From e1d5a68e06fa7227e3594faa5dd17e5a45475b72 Mon Sep 17 00:00:00 2001 From: 0xrasmp Date: Wed, 10 Jun 2026 16:49:37 +0100 Subject: [PATCH 1/7] Fix PVP answer submission silently failing due to UX patch --- .gitignore | 1 + 404.html | 11 +- bundle.js | 2 +- bundle.src.js | 77 +--- firebase-messaging-sw.js | 13 +- index.html | 11 +- pvp-enhance.js | 732 +++++++++++++++++++++++---------------- pvp.js | 2 +- pvp.js.src | 32 +- ranking.js | 13 +- ux-patches.js | 64 +--- 11 files changed, 499 insertions(+), 459 deletions(-) diff --git a/.gitignore b/.gitignore index 72bdecb48..2e7b5b858 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ test.sh scripts/ .keys/ firebase-debug.log +local-dev-override.js diff --git a/404.html b/404.html index 33f94ae22..e4f8cc0a0 100644 --- a/404.html +++ b/404.html @@ -3,6 +3,8 @@ + + - + + + + - + + diff --git a/bundle.js b/bundle.js index f2db52e7e..212d59a6b 100644 --- a/bundle.js +++ b/bundle.js @@ -1 +1 @@ -var CHANNELS={decentralized:{cat:"Properties Layer 1",title:"👪decentralized-censorship-resistant-ungovernable-incorruptible-trustless-unconfiscatable-updatable",desc:"Why no single person, company, or government controls Bitcoin — and why that's the most important feature.",file:"data/D_decentralized.json"},dominant:{cat:"Properties Layer 1",title:"🏆dominant-recognizable-brand-legitimate-limitless-infinite-exponential-transformative-revolutionary",desc:"Bitcoin's brand recognition, network effects, and why it has maintained the #1 position since 2009.",file:"data/D_dominant.json"},money:{cat:"Properties Layer 1",title:"💰money-deflationary-salable-durable-anti-fragile-divisible-portable-transmittable-verifiable-fair",desc:"What money actually is, how it works, and why Bitcoin satisfies every property of sound money better than anything before it.",file:"data/D_money.json"},organic:{cat:"Properties Layer 1",title:"🌳organic-empowering-elegant-freedom-centric-irrefutable-unseizable-irreversible-unbreakable",desc:"How Bitcoin grew from an idea worth nothing to a trillion-dollar network — without marketing, without a company, without a leader.",file:"data/D_organic.json"},peaceful:{cat:"Properties Layer 1",title:"☮peaceful-neutral-voluntary-open-universal-permissionless-borderless-global-inevitable-unstoppable",desc:"Bitcoin is voluntary, permissionless, borderless, and unstoppable. No one forces you to use it — and no one can stop you.",file:"data/D_peaceful.json"},programmable:{cat:"Properties Layer 1",title:"🤖programable-interoperable-deflationary-pseudonymous-opt-in-resilient-adiabatic-egalitarian",desc:"Bitcoin as programmable money — interoperable, pseudonymous, resilient, and thermodynamically sound.",file:"data/D_programmable.json"},scarce:{cat:"Properties Layer 1",title:"🍀scarce-unforgeable-hedge-scalable-p2p-instant-open-source-auditable-inaliable",desc:"Only 21 million will ever exist. Explore what makes Bitcoin the scarcest asset humanity has ever created.",file:"data/D_scarce.json"},secure:{cat:"Properties Layer 1",title:"™secure-fungible-immutable-incorruptible-immalleable-infallible-reliable-predictable-irreplicable",desc:"How Bitcoin's network security makes it virtually impossible to hack — protected by more computing power than anything on Earth.",file:"data/D_secure.json"},supranational:{cat:"Properties Layer 1",title:"🕊supranational-lindy-inviolate-dilution-proof-frictionless-freely-accessible-settlement-finality",desc:"Bitcoin transcends nations and governments. Explore the Lindy Effect, settlement finality, and dilution-proof money.",file:"data/D_supranational.json"},"use-cases":{cat:"Properties Layer 1",title:"✔use-cases",desc:"Real-world uses for Bitcoin: savings, payments, remittances, store of value, and more.",file:"data/D_use-cases.json"},whitepaper:{cat:"Properties Layer 1",title:"📄whitepaper",desc:"The 9-page document that started it all. Published October 31, 2008 by Satoshi Nakamoto — the foundation of Bitcoin.",file:"data/D_whitepaper.json"},bitvm:{cat:"Experienced Topics",title:"🖥bitvm",desc:"BitVM: computation on Bitcoin without changing the protocol. A new frontier for Bitcoin programmability.",file:"data/E_bitvm.json"},"blockchain-timechain":{cat:"Experienced Topics",title:"⛓blockchain-timechain-transactions-addresses",desc:"How the Bitcoin blockchain (timechain) works — blocks, transactions, timestamps, and the immutable ledger.",file:"data/E_blockchain-timechain.json"},"chaumian-mints":{cat:"Experienced Topics",title:"💸layer-2-chaumian-mints-ecash",desc:"Chaumian ecash, Cashu, and blinded signatures — the cutting edge of Bitcoin privacy technology.",file:"data/E_chaumian-mints.json"},consensus:{cat:"Additional Info",title:"🤝Consensus",desc:"How Bitcoin achieves consensus without a central authority — Nakamoto Consensus and beyond.",file:"data/H_consensus.json"},"core-source-code":{cat:"Experienced Topics",title:"💾core-source-code-forks-testnet-future-potential-upgrades",desc:"Bitcoin Core's source code, forks, testnet, and the open-source development process.",file:"data/E_core-source-code.json"},cryptography:{cat:"Experienced Topics",title:"🔒cryptography-cypherpunks",desc:"The cryptographic foundations of Bitcoin — SHA-256, elliptic curves, digital signatures, and the cypherpunk legacy.",file:"data/E_cryptography.json"},"ctv-covenants":{cat:"Experienced Topics",title:"📜ctv-bip119-covenants",desc:"BIP-119, CTV, and Bitcoin covenants — proposed upgrades and the debates around them.",file:"data/E_ctv-covenants.json"},developers:{cat:"Experienced Topics",title:"🖥developers",desc:"Building on Bitcoin — resources, guides, and paths for developers who want to contribute.",file:"data/E_developers.json"},"difficulty-adjustment":{cat:"Experienced Topics",title:"😤difficulty-adjustment",desc:"The most elegant part of Bitcoin's design — how the network self-adjusts every 2,016 blocks.",file:"data/E_difficulty-adjustment.json"},energy:{cat:"Experienced Topics",title:"💡energy",desc:"The truth about Bitcoin's energy use: 0.1% of global energy, renewable mining, methane capture, and grid stabilization.",file:"data/E_energy.json"},"evidence-against-alts":{cat:"Experienced Topics",title:"⚠evidence-against-ethereum-other-alt-coins-crypto-defi-nfts-web3-monero-bsv-bch-cbdcs-other-projects",desc:"Why every altcoin fails against Bitcoin — premines, centralization, broken promises, and the evidence.",file:"data/E_evidence-against-alts.json"},"extension-blocks":{cat:"Experienced Topics",title:"🚧extension-blocks-and-other-proposed-scaling-solutions",desc:"Extension blocks and other proposed scaling solutions for Bitcoin.",file:"data/E_extension-blocks.json"},"fedi-ark":{cat:"Experienced Topics",title:"🛡layer-2-fedi-ark",desc:"Fedimints, Ark, and Bitcoin's privacy/scaling layers — community custody with enhanced privacy.",file:"data/E_fedi-ark.json"},"investment-strategy":{cat:"Experienced Topics",title:"🤑investment-strategy-taxes-retirement-inheritance-loans-donate-gift-consulting-remittance",desc:"DCA, HODL, lump sum strategies, taxes, retirement planning, and thinking long-term with Bitcoin.",file:"data/E_investment-strategy.json"},"layer-2-lightning":{cat:"Experienced Topics",title:"⚡layer-2-lightning",desc:"The Lightning Network: instant, nearly-free Bitcoin payments. How Bitcoin scales without sacrificing decentralization.",file:"data/E_layer-2-lightning.json"},"layer-3-sidechains":{cat:"Experienced Topics",title:"📱layer-3-sidechain-applications",desc:"Sidechains, Liquid Network, and layer-3 applications built on top of Bitcoin.",file:"data/E_layer-3-sidechains.json"},maximalism:{cat:"Experienced Topics",title:"💯maximalism",desc:"Why people who study Bitcoin the most become maximalists. The case for Bitcoin-only.",file:"data/E_maximalism.json"},mining:{cat:"Experienced Topics",title:"🌋mining",desc:"How Bitcoin mining actually works — nonces, SHA-256 hashing, difficulty adjustment, and the brute-force lottery.",file:"data/E_mining.json"},nodes:{cat:"Experienced Topics",title:"💻nodes",desc:"Run your own Bitcoin node. Don't trust, verify. How 14,000+ nodes keep the network decentralized.",file:"data/E_nodes.json"},"op-codes":{cat:"Experienced Topics",title:"👨‍💻op-codes-simplicity",desc:"OP_CAT, Simplicity, and Bitcoin's scripting language — the building blocks of smart functionality.",file:"data/E_op-codes.json"},"pow-vs-pos":{cat:"Experienced Topics",title:"💪proof-of-work-vs-proof-of-stake",desc:"Why Proof of Work is fundamentally superior to Proof of Stake — energy, security, fairness, and decentralization.",file:"data/E_pow-vs-pos.json"},"privacy-nonkyc":{cat:"Experienced Topics",title:"🤫privacy-nonkyc-stacking-self-sovereignty",desc:"Financial privacy as a human right. KYC, non-KYC stacking, and protecting your sovereignty.",file:"data/E_privacy-nonkyc.json"},"problems-of-money":{cat:"Experienced Topics",title:"📉the-problems-of-todays-money-and-freedom",desc:"The broken fiat system: inflation, money printing, the Cantillon Effect, and why today's money is failing everyone.",file:"data/E_problems-of-money.json"},regulation:{cat:"Experienced Topics",title:"🏛regulation-policy-legal",desc:"Bitcoin and government: bans, adoption, legal tender, ETFs, and why regulation can't stop decentralization.",file:"data/E_regulation.json"},"self-custody":{cat:"Experienced Topics",title:"🔑personal-storage-self-custody-security",desc:"Not your keys, not your coins. Learn how to truly own your Bitcoin with wallets, seed phrases, and security.",file:"data/E_self-custody.json"},"smart-contracts":{cat:"Experienced Topics",title:"📱smart-contracts",desc:"Smart contracts on Bitcoin — what's possible, what's coming, and why Bitcoin's approach is different.",file:"data/E_smart-contracts.json"},stablecoins:{cat:"Additional Info",title:"🪙Stablecoins",desc:"The role of stablecoins in the Bitcoin economy — and why they're not a threat to Bitcoin.",file:"data/H_stablecoins.json"},"0_mining__hashing":{cat:"Additional Info",title:"0⃣Mining (Hashing)",desc:"Deep dive into Bitcoin mining and hashing — how SHA-256 works at the bit level.",file:"data/H_0_mining__hashing.json"},"100_sats":{cat:"Additional Info",title:"💯100 sats",desc:"What can you do with just 100 satoshis? More than you think.",file:"data/H_100_sats.json"},"1_first_principles":{cat:"Additional Info",title:"1⃣First Principles",desc:"First principles thinking applied to Bitcoin — reasoning from fundamentals, not analogies.",file:"data/H_1_first_principles.json"},"2__solved_technical_problems":{cat:"Additional Info",title:"2⃣ Solved Technical Problems",desc:"The technical problems Bitcoin solved — digital scarcity, double-spending, and Byzantine fault tolerance.",file:"data/H_2__solved_technical_problems.json"},analogies:{cat:"Additional Info",title:"🔋Analogies",desc:"The best analogies for explaining Bitcoin to anyone — from trees to brains to hearts.",file:"data/H_analogies.json"},austrian_school_of_economics:{cat:"Additional Info",title:"🇦🇹Austrian School of Economics",desc:"Austrian Economics and Bitcoin: Mises, Hayek, sound money theory, and the intellectual foundation.",file:"data/H_austrian_school_of_economics.json"},bip119:{cat:"Additional Info",title:"🚧BIP119",desc:"BIP-119 (CheckTemplateVerify) — what it is, why it's controversial, and the community debate.",file:"data/H_bip119.json"},bitcoin_exam:{cat:"Additional Info",title:"🎓Bitcoin Exam",desc:"Test questions for a Bitcoin exam — study material and self-assessment.",file:"data/H_bitcoin_exam.json"},bitcoin_vs_real_estate:{cat:"Additional Info",title:"Bitcoin vs Real Estate",desc:"Bitcoin vs. real estate as an investment — comparing the two hardest assets.",file:"data/H_bitcoin_vs_real_estate.json"},"block_time-block-size":{cat:"Additional Info",title:"⏰Block Time-Block-Size",desc:"Why Bitcoin uses 10-minute blocks and how block size affects the network.",file:"data/H_block_time-block-size.json"},burn_bitcoin:{cat:"Additional Info",title:"Burn bitcoin",desc:"How Bitcoin can be burned (made permanently unspendable) and why people do it.",file:"data/H_burn_bitcoin.json"},byzantine_generals__problem:{cat:"Additional Info",title:"⚔Byzantine Generals’ Problem",desc:"The Byzantine Generals' Problem — the computer science challenge Satoshi solved.",file:"data/H_byzantine_generals__problem.json"},"chaumian_e-cash_and_blind_signatures":{cat:"Additional Info",title:"💲Chaumian E-cash and Blind Signatures",desc:"David Chaum's ecash, blind signatures, and the cryptographic foundations of digital privacy.",file:"data/H_chaumian_e-cash_and_blind_signatures.json"},coin_mixing_coinjoin_coin_control_utxo:{cat:"Additional Info",title:"🌀Coin Mixing/Coinjoin/Coin Control/UTXO Management",desc:"CoinJoin, coin mixing, UTXO management — advanced Bitcoin privacy techniques.",file:"data/H_coin_mixing_coinjoin_coin_control_utxo.json"},cyles:{cat:"Additional Info",title:"🚲Cyles",desc:"Bitcoin's 4-year cycles, Gartner Hype Cycles, and whether the pattern continues.",file:"data/H_cyles.json"},derivation_path:{cat:"Additional Info",title:"↕Derivation Path",desc:"HD wallet derivation paths — how your seed phrase generates all your addresses.",file:"data/H_derivation_path.json"},discrete_log_contracts__dlcs:{cat:"Additional Info",title:"📝Discrete Log Contracts (DLCs)?",desc:"DLCs (Discrete Log Contracts) — smart contracts on Bitcoin using oracle signatures.",file:"data/H_discrete_log_contracts__dlcs.json"},"dollar-bitcoin_milkshake_theory":{cat:"Additional Info",title:"🥤Dollar-Bitcoin Milkshake Theory",desc:"The Dollar-Bitcoin Milkshake Theory — how global dollar demand and Bitcoin intersect.",file:"data/H_dollar-bitcoin_milkshake_theory.json"},dust:{cat:"Additional Info",title:"⏳Dust",desc:"Dust UTXOs: what they are, why they're a problem, and how to manage them.",file:"data/H_dust.json"},elevator_pitches:{cat:"Additional Info",title:"↕Elevator Pitches",desc:"Quick 20-30 second explanations of why Bitcoin matters — for every audience.",file:"data/H_elevator_pitches.json"},environment___energy:{cat:"Additional Info",title:"🌳Environment & Energy",desc:"Bitcoin and the environment: energy usage facts, renewable mining, and debunking the FUD.",file:"data/H_environment___energy.json"},faith___religion:{cat:"Additional Info",title:"🙏Faith & Religion",desc:"Bitcoin and faith — how sound money relates to religious and spiritual values.",file:"data/H_faith___religion.json"},fedimints:{cat:"Additional Info",title:"💚Fedimints",desc:"Fedimints: community custody with enhanced privacy using federated Chaumian mints.",file:"data/H_fedimints.json"},feedback_loops:{cat:"Additional Info",title:"➰Feedback Loops",desc:"Bitcoin's feedback loops — the self-reinforcing cycles that drive adoption and security.",file:"data/H_feedback_loops.json"},free_and_open_source_software__foss:{cat:"Additional Info",title:"💿Free and Open Source Software (FOSS)",desc:"Free and open source software (FOSS) projects connected to Bitcoin.",file:"data/H_free_and_open_source_software__foss.json"},game_theory:{cat:"Additional Info",title:"🏈Game Theory",desc:"Game theory and Bitcoin: Nash equilibrium, prisoner's dilemma, and strategic incentives.",file:"data/H_game_theory.json"},geopolitics___macroeconomics:{cat:"Additional Info",title:"💰Geopolitics & Macroeconomics",desc:"Bitcoin's role in geopolitics: nation-state adoption, reserve currencies, and macro trends.",file:"data/H_geopolitics___macroeconomics.json"},governance:{cat:"Additional Info",title:"🏛Governance",desc:"How Bitcoin is governed — consensus mechanisms, BIPs, and decentralized decision-making.",file:"data/H_governance.json"},ham_radio:{cat:"Additional Info",title:"Ham Radio",desc:"Using Bitcoin without internet — ham radio, mesh networks, and offline transactions.",file:"data/H_ham_radio.json"},human_rights__social_justice_and_freedo:{cat:"Additional Info",title:"🗽Human Rights, Social Justice and Freedom",desc:"Bitcoin as a tool for human rights, social justice, and financial freedom worldwide.",file:"data/H_human_rights__social_justice_and_freedo.json"},improved_incentive_structure:{cat:"Additional Info",title:"✅Improved Incentive Structure",desc:"How Bitcoin's incentive structure improves civilization — aligning individual and collective interests.",file:"data/H_improved_incentive_structure.json"},laws_of_thermodynamics:{cat:"Additional Info",title:"🔥Laws of Thermodynamics",desc:"How Bitcoin follows the laws of thermodynamics — energy, entropy, and proof of work.",file:"data/H_laws_of_thermodynamics.json"},lightning_node:{cat:"Additional Info",title:"⚡ Lightning Node",desc:"Running a Lightning Network node — setup guides, routing, and earning sats.",file:"data/H_lightning_node.json"},lindy_effect:{cat:"Additional Info",title:"👴Lindy Effect",desc:"The Lindy Effect: the longer Bitcoin survives, the longer it will survive.",file:"data/H_lindy_effect.json"},market_cap:{cat:"Additional Info",title:"🧢Market Cap",desc:"Bitcoin's market cap potential — can it reach millions per coin? The math says yes.",file:"data/H_market_cap.json"},math:{cat:"Additional Info",title:"➕Math",desc:"The mathematics of Bitcoin — from SHA-256 to elliptic curves to probability.",file:"data/H_math.json"},mathematics:{cat:"Additional Info",title:"➕Mathematics",desc:"Advanced mathematical concepts underlying Bitcoin's protocol and security.",file:"data/H_mathematics.json"},mev:{cat:"Additional Info",title:"⛏MEV",desc:"MEV (Miner Extractable Value) in Bitcoin — what it is and its implications.",file:"data/H_mev.json"},network_effects:{cat:"Additional Info",title:"🌐Network Effects",desc:"Bitcoin's network effects — why the most adopted network wins and keeps winning.",file:"data/H_network_effects.json"},open_source:{cat:"Additional Info",title:"⭕Open Source",desc:"What free and open source really means — and why it matters for Bitcoin.",file:"data/H_open_source.json"},oracle:{cat:"Additional Info",title:"🔮Oracle",desc:"Oracles in Bitcoin — how external data connects to the blockchain.",file:"data/H_oracle.json"},"orange-pilling":{cat:"Additional Info",title:"🟠Orange-Pilling",desc:"The art of orange-pilling — strategies for explaining Bitcoin to different audiences.",file:"data/H_orange-pilling.json"},ordinals:{cat:"Additional Info",title:"Ordinals",desc:"Bitcoin Ordinals and inscriptions — NFTs on the world's most secure blockchain.",file:"data/H_ordinals.json"},ordinals__nfts_on_bitcoin__and_block_spa:{cat:"Additional Info",title:"Ordinals, NFTs on Bitcoin, and Block Space",desc:"The Ordinals debate: NFTs on Bitcoin, block space economics, and community perspectives.",file:"data/H_ordinals__nfts_on_bitcoin__and_block_spa.json"},"peace_and_anti-war":{cat:"Additional Info",title:"☮Peace and Anti-War",desc:"Can a Bitcoin Standard end wars? The case for Bitcoin as a force for peace.",file:"data/H_peace_and_anti-war.json"},philosophy:{cat:"Additional Info",title:"🍎Philosophy",desc:"The philosophy of Bitcoin — from first principles to existential implications.",file:"data/H_philosophy.json"},politics:{cat:"Additional Info",title:"🏛Politics",desc:"Bitcoin and politics — how Bitcoin intersects with government policy and elections.",file:"data/H_politics.json"},predictions:{cat:"Additional Info",title:"🔮Predictions",desc:"Bitcoin predictions timestamped by the community — bold calls and their outcomes.",file:"data/H_predictions.json"},public_key_vs_private_key:{cat:"Additional Info",title:"🗝Public Key vs Private Key",desc:"Public keys vs. private keys — the cryptographic foundation of Bitcoin ownership.",file:"data/H_public_key_vs_private_key.json"},rbf:{cat:"Additional Info",title:"↔RBF",desc:"Replace-By-Fee (RBF) — how to speed up stuck Bitcoin transactions.",file:"data/H_rbf.json"},"referral-links":{cat:"Referral Links",title:"🔗free-btc-referral-links",desc:"Curated Bitcoin referral links — earn free sats with trusted platforms like River, Fold, and Strike.",file:"data/H_referral-links.json"},risks__threats__attack_vectors__weaknes:{cat:"Additional Info",title:"⚔Risks, Threats, Attack Vectors, Weaknesses, Issues",desc:"Bitcoin's risks, threats, and attack vectors — what could go wrong and why it probably won't.",file:"data/H_risks__threats__attack_vectors__weaknes.json"},rollups:{cat:"Additional Info",title:"🥐Rollups",desc:"Rollups on Bitcoin — scaling and privacy solutions using off-chain computation.",file:"data/H_rollups.json"},sats__or__bits:{cat:"Additional Info",title:'"Sats" or "Bits"?',desc:"The sats vs. bits debate — which denomination should Bitcoin use?",file:"data/H_sats__or__bits.json"},scalability:{cat:"Additional Info",title:"🌐Scalability",desc:"Can Bitcoin scale to serve the world? Layers, Lightning, and the path forward.",file:"data/H_scalability.json"},sidechains:{cat:"Additional Info",title:"♻Sidechains",desc:"Bitcoin sidechains like Liquid — benefits, tradeoffs, and use cases.",file:"data/H_sidechains.json"},simplified_payment_verification__spv:{cat:"Additional Info",title:"✔Simplified Payment Verification (SPV)",desc:"SPV (Simplified Payment Verification) — lightweight Bitcoin verification without a full node.",file:"data/H_simplified_payment_verification__spv.json"},soft_vs_hard_forks:{cat:"Additional Info",title:"🍴Soft vs Hard Forks",desc:"Soft forks vs. hard forks — how Bitcoin upgrades while maintaining consensus.",file:"data/H_soft_vs_hard_forks.json"},softwar:{cat:"Additional Info",title:"Softwar",desc:"Jason Lowery's Softwar thesis — Bitcoin as a non-lethal alternative to physical warfare.",file:"data/H_softwar.json"},stratum_v2:{cat:"Additional Info",title:"🟩Stratum V2",desc:"Stratum V2 — the next-generation mining protocol for better decentralization and efficiency.",file:"data/H_stratum_v2.json"},submarine_swap:{cat:"Additional Info",title:"⛵Submarine Swap",desc:"Submarine swaps — trustlessly moving Bitcoin between on-chain and Lightning.",file:"data/H_submarine_swap.json"},swaps:{cat:"Additional Info",title:"↔Swaps",desc:"How to swap between on-chain Bitcoin and Lightning — tools, techniques, and protocols.",file:"data/H_swaps.json"},ta_tips:{cat:"Additional Info",title:"📈TA Tips",desc:"Technical analysis tips for Bitcoin — chart patterns, indicators, and trading education.",file:"data/H_ta_tips.json"},tail_emission:{cat:"Additional Info",title:"🐈Tail Emission",desc:"The tail emission debate — should Bitcoin ever have perpetual block rewards?",file:"data/H_tail_emission.json"},taproot:{cat:"Additional Info",title:"🧰Taproot",desc:"Taproot: Bitcoin's latest major upgrade — Schnorr signatures, script improvements, and privacy.",file:"data/H_taproot.json"},taro:{cat:"Additional Info",title:"🥕Taro",desc:"Taro (now Taproot Assets) — issuing assets on the Bitcoin and Lightning networks.",file:"data/H_taro.json"},the_future:{cat:"Additional Info",title:"🔮The Future",desc:"How Bitcoin could change the future — hyperbitcoinization, global adoption, and beyond.",file:"data/H_the_future.json"},time:{cat:"Additional Info",title:"⏰Time",desc:"How Bitcoin keeps time — block time, timestamps, and the decentralized clock.",file:"data/H_time.json"},time_preference:{cat:"Additional Info",title:"🕑Time Preference",desc:"Time preference: how sound money encourages long-term thinking and civilization building.",file:"data/H_time_preference.json"},toxicity:{cat:"Additional Info",title:"☣ Toxicity",desc:"Is Bitcoin community toxicity real? Or is it integrity? The debate and its meaning.",file:"data/H_toxicity.json"},transaction_fees:{cat:"Additional Info",title:"💲Transaction Fees",desc:"Bitcoin transaction fees — how they work, fee markets, and long-term sustainability.",file:"data/H_transaction_fees.json"},unpopular_opinions:{cat:"Additional Info",title:"💀Unpopular Opinions",desc:"Unpopular opinions in the Bitcoin space — controversial takes and honest debates.",file:"data/H_unpopular_opinions.json"},utxos:{cat:"Additional Info",title:"🕳UTXOs",desc:"UTXOs (Unspent Transaction Outputs) — the fundamental building block of Bitcoin transactions.",file:"data/H_utxos.json"},vbyte:{cat:"Additional Info",title:"🏋vByte",desc:"Virtual bytes (vBytes) — how Bitcoin measures transaction weight for fee calculation.",file:"data/H_vbyte.json"},"apps-tools":{cat:"Resources",title:"🍎apps-tools-services-models",desc:"Bitcoin apps, tools, services, and platforms — everything you need to use Bitcoin daily.",file:"data/R_apps-tools.json"},"art-inspiration":{cat:"Resources",title:"🤩art-inspiration-motivation",desc:"Bitcoin art, inspiration, and motivational content from the community.",file:"data/R_art-inspiration.json"},"articles-threads":{cat:"Resources",title:"📃articles-threads",desc:"The best Bitcoin articles and Twitter threads — curated deep dives into every aspect of Bitcoin.",file:"data/R_articles-threads.json"},books:{cat:"Resources",title:"📚books",desc:"The essential Bitcoin reading list: The Bitcoin Standard, 21 Lessons, Mastering Bitcoin, and more.",file:"data/R_books.json"},charts:{cat:"Resources",title:"📊charts",desc:"Bitcoin price charts, on-chain analytics, stock-to-flow, and data visualizations.",file:"data/R_charts.json"},curriculum:{cat:"Resources",title:"🎓curriculum-presentations",desc:"Bitcoin education curriculum and presentations for teachers and students.",file:"data/R_curriculum.json"},"faq-glossary":{cat:"Resources",title:"❓faq-glossary-search-ai-calendar",desc:"Bitcoin FAQ, glossary of terms, and quick answers to common questions.",file:"data/R_faq-glossary.json"},"fun-facts":{cat:"Resources",title:"🎉fun-facts",desc:"Mind-blowing Bitcoin trivia: Pizza Day, Satoshi's birthday code, lost coins, and 200+ amazing facts.",file:"data/R_fun-facts.json"},games:{cat:"Resources",title:"🎮games",desc:"Bitcoin-themed games and gamified learning experiences.",file:"data/R_games.json"},"giga-chad":{cat:"Resources",title:"👑giga-chad",desc:"Michael Saylor, MicroStrategy, and the corporate Bitcoin movement.",file:"data/R_giga-chad.json"},graphics:{cat:"Resources",title:"🎨graphics",desc:"Bitcoin infographics, charts, diagrams, and visual explanations.",file:"data/R_graphics.json"},hardware:{cat:"Resources",title:"💻hardware",desc:"Bitcoin hardware: mining rigs, hardware wallets, nodes, and open-source projects like Bitaxe.",file:"data/R_hardware.json"},health:{cat:"Resources",title:"🥩health",desc:"Bitcoin and health: low time preference living, breaking free from the system.",file:"data/R_health.json"},history:{cat:"Resources",title:"📆history",desc:"The complete history of Bitcoin — from the cypherpunks to today.",file:"data/R_history.json"},"informational-sites":{cat:"Resources",title:"📃informational-sites-courses-workshops-newsletters-projects-communities-meetups-conferences",desc:"Bitcoin dashboards, tools, courses, newsletters, communities, and educational websites.",file:"data/R_informational-sites.json"},international:{cat:"Resources",title:"🌍international",desc:"Bitcoin resources in multiple languages and global adoption stories.",file:"data/R_international.json"},"jobs-earn":{cat:"Resources",title:"👷job-postings-employer-info-entrepreneurship-earn-bitcoin-stack-sats",desc:"Bitcoin job boards, entrepreneurship resources, and ways to earn sats.",file:"data/R_jobs-earn.json"},"memes-funny":{cat:"Resources",title:"😂memes-funny",desc:"The best Bitcoin memes, jokes, and humor from the community. Laugh while you learn.",file:"data/R_memes-funny.json"},"misconceptions-fud":{cat:"Resources",title:"🤡common-misconceptions-fud-debunked",desc:"Every Bitcoin myth debunked: too volatile, wastes energy, used by criminals, no intrinsic value — all wrong.",file:"data/R_misconceptions-fud.json"},"movies-tv":{cat:"Resources",title:"🎬movies-tv-documentaries",desc:"Bitcoin documentaries, films, and TV appearances. From The Big Short to Bitcoin-specific docs.",file:"data/R_movies-tv.json"},music:{cat:"Resources",title:"🎵music",desc:"Bitcoin-inspired music, songs, and audio content from the community.",file:"data/R_music.json"},"news-adoption":{cat:"Resources",title:"📰news-adoption",desc:"Latest Bitcoin news, adoption milestones, and real-world usage stories.",file:"data/R_news-adoption.json"},nostr:{cat:"Resources",title:"💜nostr",desc:"Nostr: the decentralized social protocol Bitcoiners are building on. Social media you can't be censored from.",file:"data/R_nostr.json"},"one-stop-shop":{cat:"Resources",title:"🛑one-stop-shop",desc:"The best resources to understand Bitcoin's value as fast as possible. Start here if you're new.",file:"data/R_one-stop-shop.json"},podcasts:{cat:"Resources",title:"🔊podcasts",desc:"Top Bitcoin podcasts: Bitcoin Audible, What Bitcoin Did, Stephan Livera, and more.",file:"data/R_podcasts.json"},"poems-stories":{cat:"Resources",title:"📒poems-stories-jokes",desc:"Bitcoin poetry, short stories, jokes, and creative writing from the community.",file:"data/R_poems-stories.json"},"projects-diy":{cat:"Resources",title:"🔧projects-diy",desc:"DIY Bitcoin projects: build your own node, Lightning ATM, and more.",file:"data/R_projects-diy.json"},"research-theses":{cat:"Resources",title:"✍research-theses",desc:"Academic research papers and theses on Bitcoin, monetary policy, and cryptographic systems.",file:"data/R_research-theses.json"},"satoshi-nakamoto":{cat:"Resources",title:"🦸satoshi-nakamoto",desc:"The mystery of Bitcoin's creator: who was Satoshi Nakamoto? The evidence, theories, and legacy.",file:"data/R_satoshi-nakamoto.json"},"social-media":{cat:"Resources",title:"👍social-media-proponents",desc:"Bitcoin Twitter/X accounts, influencers, and social media communities to follow.",file:"data/R_social-media.json"},"swag-merch":{cat:"Resources",title:"👕swag-merch-businesses-spend",desc:"Bitcoin merchandise, clothing, and businesses where you can spend your sats.",file:"data/R_swag-merch.json"},videos:{cat:"Resources",title:"📺videos",desc:"Must-watch Bitcoin lectures, talks, and presentations from Andreas Antonopoulos, Michael Saylor, and others.",file:"data/R_videos.json"},web5:{cat:"Resources",title:"5⃣web5",desc:"Web5 and decentralized web technologies built on Bitcoin.",file:"data/R_web5.json"}},_SAFE_COVER_PLACEHOLDER="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjMWUxYTJlIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZpbGw9IiNmNzkzMWEiIGZvbnQtc2l6ZT0iMjAiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj7wnY61PC90ZXh0Pjwvc3ZnPg==";function _safeCover(e){if(!e||"string"!=typeof e||""===e.trim())return _SAFE_COVER_PLACEHOLDER;var t=e.trim(),o=t.toLowerCase();return/^(javascript|data:text\/html|vbscript|blob):/i.test(o)?(console.warn("[XSS BLOCKED] Malicious image URL scheme rejected:",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER):/^(https:\/\/|data:image\/)/i.test(t)?t.replace(/["'<>\\]/g,""):(console.warn("[XSS BLOCKED] Invalid URL scheme (must be https:// or data:image/):",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER)}function safeJSON(e,t){try{var o=localStorage.getItem(e);return null===o?t:JSON.parse(o)}catch(o){console.warn('safeJSON: corrupted data for key "'+e+'", resetting.',o);try{localStorage.removeItem(e)}catch(e){}return t}}function escapeHtml(e){if(!e)return"";var t=document.createElement("div");return t.appendChild(document.createTextNode(e)),t.innerHTML}function sanitizeUrl(e){return e?(e=e.trim(),/^(javascript|data|vbscript|blob):/i.test(e)?"":e):""}function timeAgo(e){if(!e)return"";var t;t=e.toDate?e.toDate():e instanceof Date?e:new Date(e);var o=Math.floor((Date.now()-t.getTime())/1e3);return o<60?"just now":o<3600?Math.floor(o/60)+"m ago":o<86400?Math.floor(o/3600)+"h ago":o<604800?Math.floor(o/86400)+"d ago":t.toLocaleDateString()}function isPremium(){return void 0!==currentUser&¤tUser&¤tUser.premium&&!0===currentUser.premium.active}function getSatCap(){return isPremium()?21e3:1e4}!function(){var e=[],t=[];window.registerInterval=function(t,o,n){var i=setInterval(t,o);return e.push({id:i,fn:t,ms:o,name:n||"unnamed"}),i},document.addEventListener("visibilitychange",function(){document.hidden?(e.forEach(function(e){clearInterval(e.id)}),t=e.slice(),e=[]):(t.forEach(function(t){t.fn(),t.id=setInterval(t.fn,t.ms),e.push(t)}),t=[])})}(),window._factionNameStyle=function(e){return"cyber_hornets"===e?"color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;font-weight:700;":"honey_badgers"===e?"color:#1a1a1a;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff;font-weight:700;":""};var PREMIUM_CONFIG={FREE_SAT_CAP:1e4,PREMIUM_SAT_CAP:21e3,FREE_SPINS:1,PREMIUM_SPINS:3,MONTHLY_PRICE_USD:4.99,YEARLY_PRICE_USD:42,LIFETIME_SATS:21e4,TIER_NAME:"Bitcoin Maxi"};const FIREBASE_CONFIG={apiKey:"AIzaSyDLwucmRxjoJp2KMBTi2ujf0mlVkgLHyKk",authDomain:"bitcoin-education-archive.firebaseapp.com",projectId:"bitcoin-education-archive",storageBucket:"bitcoin-education-archive.firebasestorage.app",messagingSenderId:"1055248200518",appId:"1:1055248200518:web:6c6d64a5ee78e19bfbeb47"},LEVELS=[{name:"Normie",emoji:"🟢",min:0},{name:"Curious",emoji:"🔵",min:10},{name:"Pleb",emoji:"🟠",min:144},{name:"Pleb II",emoji:"🟠🟠",min:170},{name:"Pleb III",emoji:"🟠🟠🟠",min:256},{name:"Stacker",emoji:"📦",min:500},{name:"Stacker II",emoji:"📦📦",min:1913},{name:"Stacker III",emoji:"📦📦📦",min:2016},{name:"Maxi",emoji:"🔥",min:2140},{name:"Maxi II",emoji:"🔥🔥",min:6102},{name:"Maxi III",emoji:"🔥🔥🔥",min:8888},{name:"Papa John",emoji:"🍕",min:1e4},{name:"Full Node",emoji:"🖥️",min:18333},{name:"Whale",emoji:"🐋",min:5e4},{name:"Sovereign",emoji:"🏴",min:1e5},{name:"Cypherpunk",emoji:"🔒",min:133337},{name:"Satoshi",emoji:"👑",min:21e4}];function _renderQRCode(e,t,o){if(window.qrcode&&"function"==typeof window.qrcode)_drawQR(e,t,o);else{var n=document.createElement("script");n.src="https://cdnjs.cloudflare.com/ajax/libs/qrcode-generator/1.4.4/qrcode.min.js",n.integrity="sha384-mZT2gIty7ZDdOGkxfP6joZcYdMW1Jvj9dRlfpTmaJAKKXTqzygtB22k7FLe+KZC1",n.crossOrigin="anonymous",n.onload=function(){_drawQR(e,t,o)},n.onerror=function(){e.innerHTML='
'+t+"
"},document.head.appendChild(n)}}function _drawQR(e,t,o){try{var n=qrcode(0,"M");n.addData(t),n.make();var i=document.createElement("img");i.src=n.createDataURL(6,4),i.width=o,i.height=o,i.alt="QR Code",i.style.cssText="border-radius:8px;image-rendering:pixelated;",e.innerHTML="",e.appendChild(i)}catch(t){e.innerHTML='
QR generation failed
'}}const POINTS={visit:5,openChannel:10,readTime:15,explore10:50,streak:100};let db,auth,currentUser=null,signInAttempts=0,signInLockout=0,redirectResultResolved=!1,redirectResultPromise=Promise.resolve(null),sessionChannels=new Set,readTimer=null,readSeconds=0,lastReadAward=0,rankingReady=!1,allTimeChannels=new Set,lastLevelName="",lastLevelMin=0,levelUpReady=!1;function initRanking(){try{firebase.initializeApp(FIREBASE_CONFIG),db=firebase.firestore(),db.enablePersistence({synchronizeTabs:!0}).catch(function(e){"failed-precondition"!==e.code&&"unimplemented"!==e.code&&console.log("Persistence error:",e.code)}),auth=firebase.auth(),auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).catch(function(){}),auth.isSignInWithEmailLink(window.location.href)&&handleEmailSignIn(),redirectResultPromise=auth.getRedirectResult().then(async function(e){if(redirectResultResolved=!0,console.log("[Auth] getRedirectResult:",e?e.user?e.user.uid:"no user":"null"),!e||!e.user)return null;const t=e.user;sessionStorage.setItem("btc_redirect_auth","1");const o=await db.collection("users").doc(t.uid).get(),n=localStorage.getItem("btc_anon_uid");let i=null;try{i=JSON.parse(localStorage.getItem("btc_anon_data"))}catch(e){}if(localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),o.exists){if(i&&!o.data().mergedAnon){await o.ref.update({mergedAnon:!0});var a=Math.min(i.points||0,500);a>0&&"function"==typeof awardPoints&&await awardPoints(a,"🔗 Anonymous progress merged")}}else{i?(i.email=t.email||"",i.username||(i.username=t.displayName||"Bitcoiner"),await db.collection("users").doc(t.uid).set(i)):await db.collection("users").doc(t.uid).set({username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(t.uid)}if(n&&n!==t.uid)try{await db.collection("users").doc(n).delete()}catch(e){}return loadUser(t.uid),updateAuthButton(),"function"==typeof hideUsernamePrompt&&hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(t.displayName||t.email||"Bitcoiner")),t}).catch(function(e){return redirectResultResolved=!0,"auth/popup-closed-by-user"!==e.code&&console.log("Redirect result error:",e),null});let o=!0,n=auth.isSignInWithEmailLink(window.location.href);var e=localStorage.getItem("btc_pwa_auth_pending"),t=!!localStorage.getItem("btc_anon_uid")||"1"===sessionStorage.getItem("btc_redirect_pending")||!!e;e&&(localStorage.removeItem("btc_pwa_auth_pending"),console.log("[Auth] PWA auth pending detected")),t&&console.log("[Auth] Detected pending redirect return"),auth.onAuthStateChanged(e=>{if(console.log("[Auth] onAuthStateChanged:",e?e.isAnonymous?"anon:"+e.uid:"real:"+e.uid:"null","firstEvent:",o,"pendingRedirect:",t),e&&!e.isAnonymous){var i=localStorage.getItem("btc_last_auth_uid");i&&i!==e.uid&&(console.log("[Auth] Account switch detected:",i,"->",e.uid,"— clearing localStorage"),clearUserLocalStorage()),localStorage.setItem("btc_last_auth_uid",e.uid)}if(o){if(o=!1,n)return;if(e&&!e.isAnonymous)console.log("[Auth] Real user on first event:",e.uid),sessionStorage.removeItem("btc_redirect_auth"),loadUser(e.uid).then(function(){currentUser&¤tUser.username&&setTimeout(function(){"function"==typeof showToast&&showToast("👋 Welcome back, "+escapeHtml(currentUser.username||"")+"!")},2e3)}).catch(function(){});else if(e&&e.isAnonymous)if(t){console.log("[Auth] Anon user but pending redirect — waiting 8s for real auth...");var a=setTimeout(function(){auth.currentUser&&!auth.currentUser.isAnonymous?(console.log("[Auth] Real user appeared after wait:",auth.currentUser.uid),loadUser(auth.currentUser.uid)):(console.log("[Auth] No real user after 8s — loading anon"),loadUserLocal(e.uid)),localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),localStorage.removeItem("btc_pwa_auth_pending"),sessionStorage.removeItem("btc_redirect_pending")},8e3);redirectResultPromise.then(function(e){e&&clearTimeout(a)})}else loadUserLocal(e.uid);else if(redirectResultResolved&&!t)auth.signInAnonymously().then(()=>{});else{var r=setTimeout(function(){auth.currentUser||(console.log("[Auth] 10s timeout with no user — going anonymous"),localStorage.removeItem("btc_pwa_auth_pending"),auth.signInAnonymously().then(()=>{}))},1e4);redirectResultPromise.then(function(e){clearTimeout(r),e||auth.currentUser||auth.signInAnonymously().then(()=>{})})}}else if(e){if(currentUser&¤tUser.uid===e.uid)return void updateAuthButton();e.isAnonymous?loadUserLocal(e.uid):loadUser(e.uid)}else currentUser=null,redirectResultResolved?auth.signInAnonymously().then(()=>{}):redirectResultPromise.then(function(e){e||auth.currentUser||auth.signInAnonymously().then(()=>{})})})}catch(e){console.error("Ranking init error:",e),setTimeout(function(){"function"==typeof showToast&&showToast("⚠️ Init error: "+(e.message||e))},2e3)}}async function handleEmailSignIn(){var e=window.location.href;let t=null;var o=new URLSearchParams(window.location.search);return o.get("signin_email")&&(t=decodeURIComponent(o.get("signin_email"))),t||(t=localStorage.getItem("btc_signin_email")),t?finishEmailSignIn(t,e):new Promise(function(o){var n=document.createElement("div");n.id="emailConfirmOverlay",n.style.cssText="position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:20px;",n.innerHTML='
📧
Confirm Your Email
It looks like you opened this link on a different device. Enter the email you used to sign up:
Cancel
',document.body.appendChild(n);var i=document.getElementById("crossDeviceEmail");function a(){var a=i.value.trim().toLowerCase();a&&a.includes("@")?(n.remove(),t=a,o(finishEmailSignIn(t,e))):"function"==typeof showToast&&showToast("Please enter a valid email")}document.getElementById("crossDeviceSubmit").onclick=a,i.addEventListener("keydown",function(e){"Enter"===e.key&&a()}),setTimeout(function(){i.focus()},100)})}async function finishEmailSignIn(e,t){if(e)try{const i=auth.currentUser;let a=null,r=null;if(i&&i.isAnonymous){a=i.uid,console.log("[Email Sign-In] Anon user found:",a);try{const e=await db.collection("users").doc(a).get();e.exists&&(r=e.data()),console.log("[Email Sign-In] Anon data loaded:",!!r)}catch(e){console.log("[Email Sign-In] Anon data load failed (non-fatal):",e.code)}}console.log("[Email Sign-In] Starting signInWithEmailLink for:",e);const s=await auth.signInWithEmailLink(e,t);console.log("[Email Sign-In] Sign-in result:",s.user?s.user.uid:"no user"),localStorage.removeItem("btc_signin_email");const c=s.user.uid;console.log("[Email Sign-In] Waiting for auth token propagation...");for(var o=0;o<5;o++){await new Promise(e=>setTimeout(e,200));try{await db.collection("users").doc(c).get(),console.log("[Email Sign-In] Firestore auth ready after",200*(o+1),"ms");break}catch(e){if("permission-denied"===e.code){console.log("[Email Sign-In] Permission denied on retry "+(o+1)+", waiting for token propagation...");continue}throw e}}console.log("[Email Sign-In] Fetching existing user doc:",c);const l=await db.collection("users").doc(c).get();if(console.log("[Email Sign-In] Existing doc exists:",l.exists),!l.exists&&r)r.email=e,await db.collection("users").doc(c).set(r);else if(l.exists&&r){const e=l.data();var n=Math.min(r.points||0,500);!e.mergedAnon&&n>(e.points||0)&&await l.ref.update({points:Math.max(n,e.points||0),channelsVisited:Math.max(r.channelsVisited||0,e.channelsVisited||0),totalVisits:(e.totalVisits||0)+(r.totalVisits||0),mergedAnon:!0})}if(a&&a!==c)try{await db.collection("users").doc(a).delete()}catch(e){}window.history.replaceState(null,"",window.location.pathname+window.location.hash);const d=localStorage.getItem("btc_pending_username"),u=(localStorage.getItem("btc_pending_email"),localStorage.getItem("btc_pending_giveaway"));if(d&&!l.exists){const t={username:d,email:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};if(u){t.lightningAddress=u,t.giveaway={entered:!0,lightningAddress:u,enteredAt:(new Date).toISOString()};try{await db.collection("giveaway_entries").doc(c).set({username:d,lightningAddress:u,email:e,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:c})}catch(e){}}await db.collection("users").doc(c).set(t);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(c)}localStorage.removeItem("btc_pending_username"),localStorage.removeItem("btc_pending_email"),localStorage.removeItem("btc_pending_giveaway"),localStorage.removeItem("btc_wallet_enc"),localStorage.removeItem("btc_wallet_addrs"),loadUser(c),showToast("✅ Email verified! Signed in as "+escapeHtml(d||e)),u&&setTimeout(function(){showToast("🎉 You're entered for the 25,000 sats giveaway! Good luck!")},2e3)}catch(e){console.error("[Email Sign-In] Full error:",e.code,e.message,e.stack),"permission-denied"===e.code?(showToast("⚠️ Permission denied. Try refreshing the page or clearing cache."),console.error("[Email Sign-In] Firestore permission denied - auth state may not be ready")):"auth/invalid-action-code"===e.code||"auth/expired-action-code"===e.code?showToast("⚠️ This sign-in link has expired. Please request a new one."):"auth/invalid-email"===e.code?showToast("⚠️ Email mismatch. Make sure you enter the same email you signed up with."):showToast("Sign-in error ("+(e.code||"unknown")+"). Please try again."),window.history.replaceState(null,"",window.location.pathname+window.location.hash),auth.signInAnonymously()}else showToast("⚠️ Could not determine your email. Please sign in again from the app.")}var GOOGLE_CLIENT_ID="1055248200518-jcn5efjp7vhk0vm8cbmj4mfsgc0edkga.apps.googleusercontent.com";async function signInWithGIS(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){var n=e.anonUid,i=e.anonData;google.accounts.id.initialize({client_id:GOOGLE_CLIENT_ID,callback:async function(e){if(e&&e.credential)try{var a=firebase.auth.GoogleAuthProvider.credential(e.credential),r=await auth.signInWithCredential(a);try{google.accounts.id.cancel()}catch(e){}var s=document.getElementById("gsi-temp-btn");if(s){var c=s.closest('div[style*="position:fixed"]');c?c.remove():s.remove()}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()}),await _handleSignInResultGlobal(r.user,n,i),t(r.user)}catch(e){o(e)}else o(new Error("No credential received"))},auto_select:!1,cancel_on_tap_outside:!0,context:"signin",ux_mode:"popup"}),google.accounts.id.prompt(function(e){(e.isNotDisplayed()||e.isSkippedMoment())&&(console.log("[Auth] One Tap not shown, falling back to Firebase popup"),o(new Error("One Tap unavailable")))})})}function showPWAAuthFallback(e){var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='
🔐
'+e+' Sign-In
'+e+' sign-in requires a browser window. Open the site in your browser to sign in.
',document.body.appendChild(t)}window.signInWithGoogle=async function(){if(!/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||"")&&"undefined"!=typeof google&&google.accounts&&google.accounts.id)try{return void await signInWithGIS()}catch(e){console.warn("[Auth] GIS failed, falling back to Firebase popup:",e);try{google.accounts.id.cancel()}catch(e){}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()})}await signInWithProvider(new firebase.auth.GoogleAuthProvider)},window.signInWithTwitter=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.TwitterAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("Twitter")}await signInWithProvider(new firebase.auth.TwitterAuthProvider)},window.signInWithGithub=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.GithubAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("GitHub")}await signInWithProvider(new firebase.auth.GithubAuthProvider)};var FB_APP_ID="1400842698021858";async function signInWithFBSDK(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){FB.login(function(n){if(n.authResponse){var i=firebase.auth.FacebookAuthProvider.credential(n.authResponse.accessToken);auth.signInWithCredential(i).then(async function(o){await _handleSignInResultGlobal(o.user,e.anonUid,e.anonData),t(o.user)}).catch(o)}else o(new Error("Facebook login cancelled"))},{scope:"email,public_profile"})})}function checkRateLimit(){const e=Date.now();return e5&&(signInLockout=e+6e4,signInAttempts=0,showToast("⏳ Too many attempts. Please wait 60 seconds."),1)))}function isInAppBrowser(){var e=navigator.userAgent||"";return/FBAN|FBAV|Instagram|Twitter|Line\/|Snapchat|BytedanceWebview|musical_ly|TikTok|Weibo|MicroMessenger|LinkedInApp|Telegram/i.test(e)}async function _saveAnonDataGlobal(){var e=auth.currentUser,t=null,o=null;if(e&&e.isAnonymous){t=e.uid;try{var n=await db.collection("users").doc(t).get();n.exists&&(o=n.data())}catch(e){}}return{anonUid:t,anonData:o}}async function _handleSignInResultGlobal(e,t,o){var n=await db.collection("users").doc(e.uid).get();if(n.exists){if(o){var i=n.data(),a=Math.min(o.points||0,500);!i.mergedAnon&&a>(i.points||0)&&await n.ref.update({points:Math.max(a,i.points||0),channelsVisited:Math.max(o.channelsVisited||0,i.channelsVisited||0),totalVisits:(i.totalVisits||0)+(o.totalVisits||0),mergedAnon:!0})}!n.data().email&&e.email&&await n.ref.update({email:e.email})}else o?(o.email=e.email||"",o.username||(o.username=e.displayName||"Bitcoiner"),await db.collection("users").doc(e.uid).set(o)):await db.collection("users").doc(e.uid).set({username:e.displayName||"Bitcoiner",email:e.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()});if(t&&t!==e.uid)try{await db.collection("users").doc(t).delete()}catch(e){}if(loadUser(e.uid),n.exists)hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(e.displayName||e.email||"Bitcoiner"));else{"function"==typeof attachReferral&&attachReferral(e.uid),showGiveawayPrompt(e.uid,e.displayName||e.email||"Bitcoiner");try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},1500)}catch(e){}}}async function signInWithProvider(e){if(checkRateLimit()){if(isInAppBrowser()){var t=navigator.userAgent||"",o=/iPhone|iPad/i.test(t)?'Tap the share icon (↑) → "Open in Safari"':/Android/i.test(t)?'Tap ⋮ (menu) → "Open in Browser"':"Open this page in your default browser",n=document.createElement("div");return n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.9);padding:20px;",n.innerHTML='
🌐

Open in Browser

Sign-in doesn\'t work inside apps. '+o+'

',void document.body.appendChild(n)}var i=/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||""),a=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(i||a)try{showToast("⏳ Opening sign-in...");const t=auth.currentUser;t&&t.isAnonymous&&(localStorage.setItem("btc_anon_uid",t.uid),db.collection("users").doc(t.uid).get().then(function(e){e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}).catch(function(){}));try{const t=await auth.signInWithPopup(e);if(t&&t.user){const{anonUid:e,anonData:o}=await s();return void await r(t.user,e,o)}}catch(t){return console.log("[Auth] Mobile popup failed, falling back to redirect:",t.code),sessionStorage.setItem("btc_redirect_pending","1"),localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}}catch(e){return console.error("Mobile sign-in error:",e),void showToast("Sign-in failed: "+(e.message||"Unknown error"))}try{const{anonUid:t,anonData:o}=await s(),n=await auth.signInWithPopup(e);await r(n.user,t,o)}catch(t){if(console.error("Provider sign-in error:",t.code,t.message,t),"auth/popup-blocked"===t.code||"auth/cancelled-popup-request"===t.code||"auth/popup-closed-by-user"===t.code||"auth/internal-error"===t.code){try{showToast("⏳ Opening sign-in page...");const t=auth.currentUser;if(t&&t.isAnonymous){localStorage.setItem("btc_anon_uid",t.uid);try{const e=await db.collection("users").doc(t.uid).get();e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}catch(e){}}return localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}catch(e){console.error("Redirect fallback also failed:",e),showToast("Sign-in failed. Please try a different browser.")}return}if("auth/popup-closed-by-user"===t.code)return;"auth/unauthorized-domain"===t.code?showToast("⚠️ This domain is not authorized for sign-in. Please contact support."):"auth/operation-not-allowed"===t.code?showToast("⚠️ This sign-in method is not enabled. Try a different option."):"auth/account-exists-with-different-credential"===t.code?showToast("⚠️ An account with this email exists using a different sign-in method. Try another option."):"auth/network-request-failed"===t.code?showToast("⚠️ Network error. Check your connection and try again."):showToast("Sign-in error ("+(t.code||"unknown")+"). Please try again.")}}async function r(e,t,o){return _handleSignInResultGlobal(e,t,o)}async function s(){return _saveAnonDataGlobal()}}function showGiveawayPrompt(e,t){const o=document.getElementById("usernameModal");o.querySelector(".username-box").innerHTML="

🎉 Welcome, "+t+'!

Your account is all set. Want to enter the giveaway?

Enter a Lightning address so we can send you the sats if you win! 🏆

',o.classList.add("open"),document.getElementById("giveawayCheckboxProvider").addEventListener("change",function(){document.getElementById("giveawayLnProvider").parentElement.style.display=this.checked?"flex":"none"})}async function submitGiveawayProvider(e,t){var o=document.getElementById("giveawayCheckboxProvider"),n=document.getElementById("giveawayLnProvider"),i=n?n.value.trim():"";if(o&&o.checked){if(!i)return n&&(n.style.borderColor="#ef4444"),void showToast("⚡ Please enter a Lightning address!");try{await db.collection("users").doc(e).update({lightningAddress:i,giveaway:{entered:!0,lightningAddress:i,enteredAt:(new Date).toISOString()}}),void 0!==currentUser&¤tUser&&(currentUser.lightningAddress=i),await db.collection("giveaway_entries").doc(e).set({username:t,lightningAddress:i,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:e}),showToast("🎉 You're entered for the 25,000 sats giveaway! Good luck!")}catch(e){console.log("Giveaway save error:",e)}}hideUsernamePrompt(),showToast("✅ Signed in as "+t);var a=document.getElementById("giveawayBanner");a&&(a.style.display="none")}async function sendMagicLink(e){const t={url:window.location.origin+window.location.pathname+"?signin_email="+encodeURIComponent(e),handleCodeInApp:!0};try{return await auth.sendSignInLinkToEmail(e,t),localStorage.setItem("btc_signin_email",e),!0}catch(e){return console.log("Magic link error:",e),!1}}function loadUserLocal(e){var t=parseInt(localStorage.getItem("btc_points")||"0"),o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");currentUser={uid:e,points:t,channelsVisited:o.length,readChannels:o,totalVisits:parseInt(localStorage.getItem("btc_total_visits")||"1"),streak:parseInt(localStorage.getItem("btc_streak")||"0"),lastVisit:localStorage.getItem("btc_last_visit")||"",_isLocal:!0},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,restoreVisitedUI(),updateRankUI(),_checkCapOnLoad(),updateAuthButton(),"function"==typeof renderProgressRings&&renderProgressRings(),"function"==typeof renderExplorationMap&&renderExplorationMap(),startReadTimer()}async function loadUser(e,t){const o=t||await db.collection("users").doc(e).get();if(o.exists){currentUser={uid:e,...o.data()},currentUser.visitedChannelsList&¤tUser.visitedChannelsList.forEach(e=>allTimeChannels.add(e));const t=auth.currentUser&&!auth.currentUser.isAnonymous;var n=[...new Set([...Array.isArray(currentUser.visitedChannelsList)?currentUser.visitedChannelsList:[],...Array.isArray(currentUser.readChannels)?currentUser.readChannels:[]])];if(n.length>0){if(t)localStorage.setItem("btc_visited_channels",JSON.stringify(n));else{let e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=[...new Set([...e,...n])];localStorage.setItem("btc_visited_channels",JSON.stringify(t))}restoreVisitedUI()}else t&&(localStorage.setItem("btc_visited_channels","[]"),restoreVisitedUI());if(currentUser.favorites){if(t)localStorage.setItem("btc_favs",JSON.stringify(currentUser.favorites));else{let e=JSON.parse(localStorage.getItem("btc_favs")||"[]"),t=[...new Set([...e,...currentUser.favorites])];localStorage.setItem("btc_favs",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else t&&(localStorage.setItem("btc_favs","[]"),"function"==typeof renderFavs&&renderFavs());if(currentUser.bookmarks){if(t)localStorage.setItem("btc_bookmarks",JSON.stringify(currentUser.bookmarks));else{let e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]"),t=currentUser.bookmarks.concat(e.filter(function(e){return!currentUser.bookmarks.some(function(t){return t.channel===e.channel&&t.idx===e.idx})}));localStorage.setItem("btc_bookmarks",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else if(t){var i=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");i.length>0&&db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({bookmarks:i}).catch(function(){})}if(currentUser.username&&localStorage.setItem("btc_username",currentUser.username),currentUser.streak>0&&!currentUser.bestStreak&&(currentUser.bestStreak=currentUser.streak),rankingReady=!0,updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),awardVisitPoints(),startReadTimer(),auth.currentUser.isAnonymous||db.collection("users").doc(e).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),t){if(currentUser.hiddenBadges){var a=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),r=[...new Set([...a,...currentUser.hiddenBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(r))}if(currentUser.donationBadges&¤tUser.donationBadges.length>0){var s=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),c=[...new Set([...s,...currentUser.donationBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(c))}if(currentUser.visibleBadges){var l=JSON.parse(localStorage.getItem("btc_badges")||"[]"),d=[...new Set([...l,...currentUser.visibleBadges])];localStorage.setItem("btc_badges",JSON.stringify(d))}if(currentUser.spinClosetItems){var u=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]"),p=[...new Set([...u,...currentUser.spinClosetItems])];localStorage.setItem("btc_spin_closet_items",JSON.stringify(p))}if(currentUser.scholarPassed&&localStorage.setItem("btc_scholar_passed","true"),currentUser.nachoMilestones&&localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(currentUser.nachoMilestones)),currentUser.celebratedState){var m=currentUser.celebratedState;m.nachoMilestones&&localStorage.setItem("btc_nacho_milestones",JSON.stringify(m.nachoMilestones)),m.nachoCatComplete&&localStorage.setItem("btc_nacho_cat_complete",JSON.stringify(m.nachoCatComplete)),m.nachoLevelCelebrated&&localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(m.nachoLevelCelebrated)),m.nachoItemsNotified&&localStorage.setItem("btc_nacho_items_notified",JSON.stringify(m.nachoItemsNotified))}if(currentUser.nachoInteractions){var g=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),h=currentUser.nachoInteractions||0;localStorage.setItem("btc_nacho_interactions",Math.max(g,h).toString())}if(currentUser.nachoQuestions){var f=parseInt(localStorage.getItem("btc_nacho_questions")||"0"),y=currentUser.nachoQuestions||0;localStorage.setItem("btc_nacho_questions",Math.max(f,y).toString())}}if(localStorage.setItem("btc_pvp_wins",String(currentUser.pvpWins||0)),localStorage.setItem("btc_pvp_losses",String(currentUser.pvpLosses||0)),currentUser.nachoNickname&&(localStorage.setItem("btc_nacho_nickname",currentUser.nachoNickname),"function"==typeof updateNachoNameUI&&updateNachoNameUI(currentUser.nachoNickname)),t){if(currentUser.lastSpinDate){var v=localStorage.getItem("btc_last_spin")||"";currentUser.lastSpinDate>v&&localStorage.setItem("btc_last_spin",currentUser.lastSpinDate),"function"==typeof updateSpinBanner&&updateSpinBanner()}if(currentUser.prediction&&(localStorage.getItem("btc_prediction")||localStorage.setItem("btc_prediction",JSON.stringify(currentUser.prediction))),currentUser.nachoStoryDays&&Array.isArray(currentUser.nachoStoryDays)){var b=safeJSON("btc_nacho_story_days",[]);currentUser.nachoStoryDays.length>b.length&&localStorage.setItem("btc_nacho_story_days",JSON.stringify(currentUser.nachoStoryDays))}if(currentUser.nachoStoryProgress){var w=parseInt(localStorage.getItem("btc_nacho_story_highest")||"0");currentUser.nachoStoryProgress>w&&localStorage.setItem("btc_nacho_story_highest",currentUser.nachoStoryProgress.toString())}if(currentUser.nachoStoryDate){var x=localStorage.getItem("btc_nacho_story_date")||"";currentUser.nachoStoryDate>x&&localStorage.setItem("btc_nacho_story_date",currentUser.nachoStoryDate)}}window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0;var k=getLevel(currentUser.points||0);lastLevelName=k.name,lastLevelMin=k.min,localStorage.getItem("btc_highest_level_seen")||localStorage.setItem("btc_highest_level_seen",k.min.toString()),setTimeout(function(){levelUpReady=!0},3e3),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showContinueReading&&showContinueReading(),updateAuthButton(),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging()}else{const t=auth.currentUser;if(t&&!t.isAnonymous){const o={username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};await db.collection("users").doc(e).set(o),currentUser={uid:e,...o},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton()}}}window.fbAsyncInit=function(){FB.init({appId:FB_APP_ID,cookie:!0,xfbml:!1,version:"v19.0"})},window.signInWithFacebook=async function(){if("undefined"!=typeof FB)try{return void await signInWithFBSDK()}catch(e){if("Facebook login cancelled"===e.message)return;console.warn("[Auth] FB SDK failed:",e)}await signInWithProvider(new firebase.auth.FacebookAuthProvider)},window.signInWithNostr=async function(){if(checkRateLimit()){var e=!!window.nostr,t=document.createElement("div");t.id="nostrAuthOverlay",t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

🟣 Sign in with Nostr

'+(e?'':'
🔌
No Extension Detected
Install Alby or nos2x for one-click login
')+'
or
🔒 Your nsec is used only in your browser to sign a one-time login event. It is never sent to our servers or stored anywhere.
or
',document.body.appendChild(t)}},window.nostrSignInWithExtension=async function(){if(window.nostr){var e=document.getElementById("nostrAuthStatus");e&&(e.innerHTML='Requesting key from extension...');try{var t=await window.nostr.getPublicKey();if(!t||!/^[a-f0-9]{64}$/.test(t))return void(e&&(e.innerHTML='Could not get public key'));e&&(e.innerHTML='Signing auth event...');var o=await window.nostr.signEvent({kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:t});if(!o||!o.sig)return void(e&&(e.innerHTML='Signing cancelled'));await nostrCompleteAuth(t,o.sig,o)}catch(t){console.error("Nostr extension error:",t),e&&(e.innerHTML='Extension error: '+(t.message||"Unknown")+"")}}else showToast("Extension not found")},window.nostrSignInWithNsec=async function(){var e=(document.getElementById("nostrNsecInput").value||"").trim(),t=document.getElementById("nostrAuthStatus"),o=document.getElementById("nostrNsecBtn");if(e)if(e.startsWith("nsec1")){o.disabled=!0,o.textContent="Loading crypto library...",t&&(t.innerHTML='Loading...');try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.integrity="sha384-GwmNxV/GnZt+zRBR/Hhtu5D4MKfbxeJSApW44ARryGYtj3MFheHMFgiEZ7tVnrln",o.crossOrigin="anonymous",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools;t&&(t.innerHTML='Decoding nsec...'),o.textContent="Signing...";var i=n.nip19.decode(e);if(!i||"nsec"!==i.type)return t&&(t.innerHTML='Invalid nsec'),o.disabled=!1,void(o.textContent="Sign In with nsec");var a=i.data;"string"!=typeof a&&(a=Array.from(new Uint8Array(a)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""));var r=n.getPublicKey(a),s={kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:r};s.id=n.getEventHash(s),s.sig=n.signEvent(s,a),document.getElementById("nostrNsecInput").value="",t&&(t.innerHTML='Verifying signature...'),await nostrCompleteAuth(r,s.sig,s)}catch(e){console.error("Nostr nsec error:",e),t&&(t.innerHTML='Error: '+(e.message||"Failed to sign")+""),o.disabled=!1,o.textContent="Sign In with nsec"}}else t&&(t.innerHTML='Invalid nsec format. Must start with nsec1');else showToast("Please paste your nsec")},window.nostrSignInWithNpub=async function(){var e=(document.getElementById("nostrNpubInput").value||"").trim(),t=document.getElementById("nostrAuthStatus");if(e){var o=e;if(e.startsWith("npub1"))try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools.nip19.decode(e);n&&"npub"===n.type&&"string"!=typeof(o=n.data)&&(o=Array.from(new Uint8Array(o)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""))}catch(e){return void(t&&(t.innerHTML='Invalid npub format'))}if(/^[a-f0-9]{64}$/.test(o)){t&&(t.innerHTML='Linking Nostr identity...');try{auth.currentUser||await auth.signInAnonymously();var i=auth.currentUser.uid;await db.collection("users").doc(i).set({nostr:o,lastLogin:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0}),currentUser&&(currentUser.nostr=o);var a=document.getElementById("nostrAuthOverlay");a&&a.remove(),showToast("🟣 Nostr identity linked! (npub)")}catch(e){t&&(t.innerHTML='Error: '+(e.message||"Unknown")+"")}}else t&&(t.innerHTML='Invalid public key')}else showToast("Please paste your npub")},window.nostrCompleteAuth=async function(e,t,o){var n=document.getElementById("nostrAuthStatus");try{var i=firebase.functions().httpsCallable("nostrAuth"),a=await i({pubkey:e,sig:t,event:o});if(a.data&&a.data.token){await auth.signInWithCustomToken(a.data.token);var r=a.data.uid,s=await db.collection("users").doc(r).get();if(!s.exists||!s.data().username){var c={username:"npub..."+e.substring(0,8),nostr:e,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};s.exists||(c.points=0,c.channelsVisited=0,c.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(r).set(c,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(r),hideUsernamePrompt();var l=document.getElementById("nostrAuthOverlay");l&&l.remove(),showToast("🟣 Signed in with Nostr!")}else n&&(n.innerHTML='Auth failed — no token received')}catch(e){console.error("Nostr auth error:",e),n&&(n.innerHTML='Verification failed: '+(e.message||"Unknown")+"")}},window.signInWithLightning=async function(){if(checkRateLimit()){var e=document.createElement("div");e.id="lnAuthModal",e.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.8);",e.onclick=function(t){t.target===e&&e.remove()},e.innerHTML='

Lightning Login

Scan this QR code with your Lightning wallet (Alby, Zeus, Phoenix, BlueWallet, etc.)

Generating challenge...

Connecting to server...

',document.body.appendChild(e);try{var t=firebase.functions().httpsCallable("lnAuthChallenge"),o=await t();if(!document.getElementById("lnAuthModal"))return;if(!o.data||!o.data.k1||!o.data.lnurl)return"function"==typeof showToast&&showToast("Failed to generate login challenge"),void e.remove();var n=o.data.k1,i=o.data.lnurl,a=document.getElementById("lnAuthQR");if(a)if(a.innerHTML="",a.style.display="inline-block","function"==typeof _renderQRCode)_renderQRCode(a,"lightning:"+i,220);else{var r=document.createElement("img");r.src="https://api.qrserver.com/v1/create-qr-code/?size=220x220&data="+encodeURIComponent("lightning:"+i),r.width=220,r.height=220,r.alt="Lightning Auth QR",r.style.cssText="border-radius:8px;",a.appendChild(r)}var s=document.getElementById("lnAuthCopyWrap");s&&(s.style.display="block",s.innerHTML="");var c=document.getElementById("lnAuthStatus");c&&(c.textContent="Waiting for wallet...",c.style.color="var(--accent)");var l=firebase.functions().httpsCallable("lnAuthVerify"),d=0,u=setInterval(async function(){if(++d>60||!document.getElementById("lnAuthModal"))clearInterval(u);else try{var e=await l({k1:n});if(e.data&&e.data.token){clearInterval(u);var t=document.getElementById("lnAuthStatus");t&&(t.textContent="✅ Authenticated!"),await auth.signInWithCustomToken(e.data.token);var o=e.data.uid,i=await db.collection("users").doc(o).get();if(!i.exists||!i.data().username){var a={username:"⚡anon-"+n.substring(0,8),authMethod:"lightning",totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};i.exists||(a.points=0,a.channelsVisited=0,a.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(o).set(a,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(o),hideUsernamePrompt(),setTimeout(function(){var e=document.getElementById("lnAuthModal");e&&e.remove()},1e3),"function"==typeof showToast&&showToast("⚡ Signed in with Lightning!")}}catch(e){"not-found"!==e.code&&console.log("LN auth poll:",e.message)}},2e3)}catch(e){console.error("Lightning auth error:",e),"function"==typeof showToast&&showToast("Lightning sign-in failed. Try again.");var p=document.getElementById("lnAuthModal");p&&p.remove()}}},window.sendReturningMagicLink=async function(){var e=document.getElementById("returningEmailInput");if(e){var t=e.value.trim();if(!t||!t.includes("@"))return showToast("📧 Please enter a valid email address"),void(e&&(e.style.borderColor="#ef4444"));e.disabled=!0;var o=e.nextElementSibling;o&&(o.disabled=!0,o.textContent="Sending..."),await sendMagicLink(t)?(showToast("📧 Magic link sent! Check your email to sign in."),o&&(o.textContent="✅ Sent!"),hideUsernamePrompt()):(showToast("❌ Could not send magic link. Try again."),e.disabled=!1,o&&(o.disabled=!1,o.textContent="Send Link"))}};var _authBtnSignedIn=!1;function updateAuthButton(){const e=document.getElementById("authBtn");if(e){var t=auth&&auth.currentUser,o=t&&!t.isAnonymous,n=currentUser&¤tUser.username,i=localStorage.getItem("btc_username"),a=n||i||t&&t.displayName||"",r=t&&t.uid&&(t.uid.startsWith("nostr:")||t.uid.startsWith("ln:"));if(o||r||a)_authBtnSignedIn=!0;else{if(_authBtnSignedIn&&t)return;t||(_authBtnSignedIn=!1)}if(_authBtnSignedIn){var s=a||"My Account";e.innerHTML="⚙️ "+("function"==typeof escapeHtml?escapeHtml(s):s)+" — Settings",e.onclick=function(){showSettings()},e.style.display=window.innerWidth<=900?"none":"block",e.style.background="none",e.style.border="2px solid #3b82f6",e.style.color="#3b82f6",e.onmouseover=function(){this.style.background="#3b82f6",this.style.color="#fff"},e.onmouseout=function(){this.style.background="none",this.style.color="#3b82f6"}}else(!t||t&&t.isAnonymous)&&(e.textContent="Create Free Account / Sign In",e.style.display="block",e.style.background="var(--accent)",e.style.border="none",e.style.color="#000",e.onmouseover=function(){this.style.transform="scale(1.02)"},e.onmouseout=function(){this.style.transform="scale(1)"});var c=document.getElementById("guestPointsBanner");c&&_authBtnSignedIn&&(c.style.display="none");var l=document.getElementById("giveawayBanner");l&&_authBtnSignedIn&&(currentUser&¤tUser.giveaway?(l.innerHTML='
🎉 25,000 SATS GIVEAWAY 🎉
You\'re entered! Good luck! 🍀
✅ Entered
',l.onclick=function(){showSettings()}):(l.querySelector("div:last-child")&&(l.querySelector("div:last-child").textContent="⚙️ View Your Profile →"),l.onclick=function(){showSettings()}))}}function sanitizeInput(e){return e.replace(/<[^>]*>/g,"").replace(/[<>"'&]/g,"").trim()}window.sanitizeInput=sanitizeInput,window.syncCelebratedState=function(){if(void 0!==db&&auth&&auth.currentUser){var e={nachoMilestones:safeJSON("btc_nacho_milestones",[]),nachoCatComplete:safeJSON("btc_nacho_cat_complete",[]),nachoLevelCelebrated:safeJSON("btc_nacho_level_celebrated",[]),nachoItemsNotified:safeJSON("btc_nacho_items_notified",[])};db.collection("users").doc(auth.currentUser.uid).update({celebratedState:e}).catch(function(){})}};const PROFANITY_LIST=["fuck","shit","ass","bitch","dick","cock","pussy","cunt","damn","hell","bastard","slut","whore","fag","faggot","nigger","nigga","retard","retarded","penis","vagina","porn","sex","anal","cum","jizz","dildo","tits","boob","nude","naked","hentai","milf","orgasm","erect","molest","rape","pedo","nazi","hitler","kkk","jihad","terrorist","kill","murder","suicide","die","stfu","gtfo","wank","twat","bollocks","arse","shag","piss","crap","douche","skank","thot","incel","simp","onlyfans","xnxx","pornhub","xvideos","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","aroused","erection","erectile","climax","ejaculat","deepthroat","rimjob","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes","twerk","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","zipperhead","jap","paki","wop","dago","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","acab","supremacy","genocide","lynch"];function containsProfanity(e){const t=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g," "),o=t.split(/\s+/);for(const e of o)if(PROFANITY_LIST.includes(e))return!0;const n=t.replace(/\s/g,"");for(const e of PROFANITY_LIST)if(e.length>=4&&n.includes(e))return!0;return!1}async function createUser(e,t,o,n,i){if(void 0===auth||!auth)return showToast("⏳ Loading... please try again in a moment."),void("function"==typeof initRanking&&initRanking());if(!auth.currentUser)try{await auth.signInAnonymously(),auth.currentUser||await new Promise(e=>{const t=auth.onAuthStateChanged(o=>{o&&(t(),e())});setTimeout(()=>{e()},3e3)})}catch(e){return console.log("Anonymous sign-in error:",e),void showToast("Error creating account. Please try again.")}if(!auth.currentUser)return void showToast("Error: Could not authenticate. Please refresh and try again.");const a=auth.currentUser.uid;if(clearUserData(),!(e=(e=sanitizeInput(e)).replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim())||e.length<2)return void showToast("⚠️ Username must be at least 2 characters (letters, numbers, basic symbols only).");if(containsProfanity(e))return void showToast("⚠️ That username is not allowed. Please choose another.");t&&(t=sanitizeInput(t));const r={username:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};if(t&&(r.email=t),i&&(r.country=i),window._signupFaction&&(r.faction=window._signupFaction,window._signupFaction=null),o&&n){r.lightningAddress=n,r.giveaway={entered:!0,lightningAddress:n,enteredAt:(new Date).toISOString()};try{await db.collection("giveaway_entries").doc(a).set({username:e,lightningAddress:n,email:t||null,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:a})}catch(e){console.log("Giveaway entry save error:",e)}}await db.collection("users").doc(a).set(r);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}currentUser={uid:a,...r},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton(),awardPoints(POINTS.visit,"Welcome bonus!"),startReadTimer(),hideUsernamePrompt();try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},800)}catch(e){}var s=document.getElementById("giveawayBanner");s&&(s.style.display="none"),"function"==typeof attachReferral&&attachReferral(a),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging();try{var c=JSON.parse(localStorage.getItem("btc_buddy_pending")||"null");c&&c.goal&&(localStorage.removeItem("btc_buddy_pending"),"function"==typeof _submitBuddyFromOnboarding&&setTimeout(function(){_submitBuddyFromOnboarding(c.level||"beginner",c.goal)},2e3))}catch(e){}}async function awardVisitPoints(){if(!currentUser)return;const e=(new Date).toISOString().split("T")[0],t=new Date(Date.now()-864e5).toISOString().split("T")[0];if(currentUser.lastVisit===e)return;let o=!1,n=0,i=POINTS.visit,a=1;if(currentUser.lastVisit===t)a=(currentUser.streak||0)+1,a%7==0?(n=Math.min(25,5*Math.floor(a/7)),o=!0):a%5==0&&(i+=POINTS.streak,o=!0);else if(currentUser.lastVisit!==e){var r=currentUser.streak||0;currentUser.streakFreezes>0?(a=r+1,currentUser.streakFreezes--,o=!0,setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze ticket was used to save your "+a+"-day streak! ("+(currentUser.streakFreezes||0)+" freezes remaining)")},3e3)):r>1&&setTimeout(function(){showToast("💔 Your "+r+"-day streak was broken! Earn 🧊 Freeze Tickets from the Daily Spin to protect your streak next time.")},3e3)}if(currentUser._isLocal);else{try{var s=firebase.functions().httpsCallable("recordDailyVisit"),c=await s({});if(c.data&&c.data.success&&!c.data.alreadyVisited){a=c.data.streak||1,n=c.data.bonusTickets||0;var l=c.data.bestStreak||a;currentUser.streak=a,currentUser.bestStreak=l,currentUser.lastVisit=e,currentUser.totalVisits=c.data.totalVisits||(currentUser.totalVisits||0)+1,n>0&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+n),c.data.usedFreeze&&(currentUser.streakFreezes=Math.max(0,(currentUser.streakFreezes||0)-1),setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze was used to save your "+a+"-day streak!")},3e3))}}catch(e){console.warn("[VISIT] Cloud Function failed:",e.message)}var d=i+5*n;d>0&&await awardPoints(d,"✅ Daily visit"+(a>1?" ("+a+"-day streak!)":""))}n>0?("function"==typeof notifySelfStreak&¬ifySelfStreak(a),setTimeout(function(){showToast("🔥 STREAK MILESTONE! Day "+a+": Earned +"+n+" Bonus Tickets! 🎟️")},3500)):o&&showToast("🔥 Day "+currentUser.streak+" streak! +"+(POINTS.visit+POINTS.streak)+" XP"),updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen()}async function awardPoints(e,t,o,n,i){if(currentUser&&rankingReady&&(e=parseInt(e),!(isNaN(e)||e<0||e>2200)&&(0!==e||n||i))){window._pointAwardTimes=window._pointAwardTimes||[];var a=Date.now();if(window._pointAwardTimes=window._pointAwardTimes.filter(function(e){return a-e<6e4}),!(window._pointAwardTimes.length>=20)){if(window._pointAwardTimes.push(a),currentUser._isLocal){var r=500,s=(new Date).toISOString().split("T")[0],c="btc_daily_pts_"+s,l=parseInt(localStorage.getItem(c)||"0",10);isNaN(l)&&(l=0);var d={tctv_watch_10m:6e5,daily_spin:864e5,daily_visit:72e6}[t];if(d){var u="btc_cd_"+t,p=parseInt(localStorage.getItem(u)||"0",10);if(p&&Date.now()-p0&&f&&f!==s){h-=y=Math.min(h,r);try{localStorage.setItem(m,String(h))}catch(e){}}var v=e,b=0;if(l>=r?(v=0,b=e):l+e>r&&(b=e-(v=r-l)),(B=v+y)>0){var w=(parseInt(localStorage.getItem("btc_points")||"0",10)||0)+B;try{localStorage.setItem("btc_points",String(w)),v>0&&localStorage.setItem(c,String(l+v))}catch(e){}currentUser.points=w,_showPointsToast(v,t),"function"==typeof notifySelfPoints&¬ifySelfPoints(v,t),y>0&&"function"==typeof showToast&&setTimeout(function(){showToast("♻️ +"+y+" overflow pts redeemed from prior day!",4e3)},1200)}if(b>0){h+=b;try{localStorage.setItem(m,String(h)),localStorage.setItem(g,s)}catch(e){}var x="btc_overflow_notified_"+s;if(!localStorage.getItem(x)){try{localStorage.setItem(x,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap reached (500)! +"+b+" XP banked as overflow — they roll over tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}else if(l+v>=r){var k="btc_daily_cap_notified_"+s;if(!localStorage.getItem(k)){try{localStorage.setItem(k,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}return updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),void("function"==typeof nachoOnPoints&&nachoOnPoints(e))}auth.currentUser.isAnonymous||db.collection("users").doc(auth.currentUser.uid).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),e>0&&t&&"function"==typeof notifySelfPoints&¬ifySelfPoints(e,t);try{var T=firebase.functions().httpsCallable("awardPoints"),S={pts:e,action:t||"",reason:t||""};o&&(S.channelId=o),n&&(S.tickets=n),i&&(S.streakFreezes=i);var _=await T(S);if(_.data&&_.data.dailyActionCapped&&"function"==typeof showToast&&showToast("⏳ "+(_.data.error||"Daily limit reached for this action."),6e3),_.data&&_.data.cooldown&&"function"==typeof showToast&&showToast("⏳ "+(_.data.error||"Slow down a bit."),4e3),_.data&&_.data.success){v=_.data.awarded||0,y=_.data.overflowRedeemed||0,b=_.data.overflowAdded||0;var B,I=_.data.pendingOverflow||0;if((B=v+y)>0&&(currentUser.points=(currentUser.points||0)+B,_showPointsToast(v,t),y>0&&setTimeout(function(){showToast("♻️ +"+y+" overflow pts redeemed from prior day!",4e3)},1200)),b>0){m="btc_overflow_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(m)||(localStorage.setItem(m,"1"),showToast("🎯 Daily cap reached (500)! +"+b+" XP banked as overflow — they roll over tomorrow.",8e3),_updateCapIndicator(!0));try{localStorage.setItem("btc_pts_overflow",String(I))}catch(e){}}else _.data.capped&&(k="btc_daily_cap_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(k)||(localStorage.setItem(k,"1"),showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow.",8e3),_updateCapIndicator(!0)))}}catch(e){console.warn("[POINTS] Cloud Function failed:",e.message),"function"==typeof showToast&&showToast("⏳ XP will sync when connection restores")}updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),"function"==typeof nachoOnPoints&&nachoOnPoints(e)}}}function _showPointsToast(e,t){var o=!1;e>=25?o=!0:t&&t.length>0&&(window._lastPtsToast=window._lastPtsToast||0,Date.now()-window._lastPtsToast>3e4&&(o=!0)),o&&t&&(window._lastPtsToast=Date.now(),showToast("+"+e+" XP — "+t,2500))}function refreshLeaderboardIfOpen(){var e=document.getElementById("leaderboard");if(e&&e.classList.contains("open")&&!e.classList.contains("minimized")){window._lbCache=null,window._lbCacheTime=null;var t=e.querySelector(".lb-me .lb-score");t&¤tUser&&(t.textContent=(currentUser.points||0).toLocaleString()+" XP")}}async function onChannelOpen(e){if("function"==typeof nachoOnChannel&&nachoOnChannel(e),currentUser&&rankingReady){if(!allTimeChannels.has(e)){allTimeChannels.add(e),sessionChannels.add(e);let t=POINTS.openChannel;if(window._dailyBoosts&&window._dailyBoosts.includes(e)&&(t*=2,setTimeout(()=>{showToast("⚡ 2X XP! Daily boost applied! +"+t+" XP")},2e3)),currentUser._isLocal,currentUser.channelsVisited=(currentUser.channelsVisited||0)+1,currentUser.readChannels?-1===currentUser.readChannels.indexOf(e)&¤tUser.readChannels.push(e):currentUser.readChannels=[e],Array.isArray(currentUser.visitedChannelsList)||(currentUser.visitedChannelsList=[]),-1===currentUser.visitedChannelsList.indexOf(e)&¤tUser.visitedChannelsList.push(e),await awardPoints(t,"📖 New channel explored",e),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showToast){const e=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,t=Math.round(allTimeChannels.size/e*100);showToast("🗺️ Exploration Map: "+allTimeChannels.size+" channels reached ("+t+"%)")}10===allTimeChannels.size&&await awardPoints(POINTS.explore10,"Explorer bonus! 10 topics 🎉")}readSeconds=0,lastReadAward=0,syncReadToFirebase(e),"function"==typeof onChannelVisitForQuest&&onChannelVisitForQuest(e)}}async function syncReadToFirebase(e){}async function syncFavsToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_favs")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({favorites:e})}catch(e){}}async function syncBookmarksToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({bookmarks:e})}catch(e){}}function restoreVisitedUI(){JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})})}window.notifySelfPoints=function(e,t){if(e&&!(e<1)&&t&&""!==t){var o={pts:e,reason:t,ts:Date.now(),read:!1};try{var n=JSON.parse(localStorage.getItem("btc_points_log")||"[]");n.push(o),n.length>100&&(n=n.slice(n.length-100)),localStorage.setItem("btc_points_log",JSON.stringify(n))}catch(e){}"function"==typeof _updatePointsBadge&&_updatePointsBadge()}},window.syncBookmarksToFirebase=syncBookmarksToFirebase;let lastActivityTime=Date.now(),lastScrollPos=0,hasScrolledSinceLastAward=!1;function trackActivity(){lastActivityTime=Date.now()}function trackScroll(){const e=document.getElementById("main");e&&Math.abs(e.scrollTop-lastScrollPos)>30&&(lastScrollPos=e.scrollTop,hasScrolledSinceLastAward=!0,lastActivityTime=Date.now())}function startReadTimer(){readTimer&&clearInterval(readTimer),readTimer=setInterval(async()=>{if(currentUser&&rankingReady&&!document.hidden&&!((Date.now()-lastActivityTime)/1e3>45)&&hasScrolledSinceLastAward&&(readSeconds++,sessionStorage.setItem("btc_channel_read_seconds",readSeconds.toString()),readSeconds-lastReadAward>=30)){lastReadAward=readSeconds,hasScrolledSinceLastAward=!1;var e="btc_read_cap_"+(window.currentChannelId||"unknown")+"_"+(new Date).toISOString().split("T")[0],t=parseInt(localStorage.getItem(e)||"0");if(t>=5)return;localStorage.setItem(e,(t+1).toString()),await awardPoints(POINTS.readTime,"")}},1e3)}function getLevel(e){let t=LEVELS[0];for(const o of LEVELS)e>=o.min&&(t=o);const o=LEVELS.indexOf(t)+1,n=o
'+o.emoji+''+t.toLocaleString()+' XP
Sign in to keep your XP & get on the leaderboard!
Sign Up Free →
",e.style.display="flex"}}else e&&(e.style.display="none");else e&&(e.style.display="none")}function _updateCapIndicator(e){var t=document.getElementById("userDisplay");if(t){var o,n="btc_daily_pts_"+(new Date).toISOString().split("T")[0],i=parseInt(localStorage.getItem(n)||"0"),a=parseInt(localStorage.getItem("btc_pts_overflow")||"0");e||i>=500?(t.style.borderColor="#ef4444",t.style.boxShadow="0 0 12px rgba(239,68,68,0.3)",t.title="🎯 Daily XP cap reached (500/500)"+(a>0?"\n💫 Overflow: "+a+" pts (rolls over tomorrow)":""),document.getElementById("dailyCapBadge")||((o=document.createElement("span")).id="dailyCapBadge",o.style.cssText="position:absolute;top:-6px;left:-6px;background:#ef4444;color:#fff;font-size:0.55rem;font-weight:800;padding:2px 6px;border-radius:8px;z-index:2;pointer-events:none;",o.textContent="CAP",t.style.position="fixed",t.appendChild(o))):(t.style.borderColor="var(--border)",t.style.boxShadow="0 2px 10px rgba(0,0,0,0.2)",t.title="",(o=document.getElementById("dailyCapBadge"))&&o.remove())}}function _checkCapOnLoad(){var e="btc_daily_pts_"+(new Date).toISOString().split("T")[0];parseInt(localStorage.getItem(e)||"0")>=500&&setTimeout(function(){_updateCapIndicator(!0)},2e3)}function updateRankUI(){if(!currentUser)return;var e=document.getElementById("giveawayBanner");e&¤tUser.username&&(e.style.display="none");const t=getLevel(currentUser.points||0);!lastLevelName&&t.name&&(lastLevelName=t.name,lastLevelMin=t.min),updateGuestPointsBanner(),updateUserDisplay(t);const o=parseInt(localStorage.getItem("btc_highest_level_seen")||"0");if(levelUpReady&&lastLevelName&&lastLevelName!==t.name&&t.min>lastLevelMin&&t.min>o){showLevelUpCelebration(t),localStorage.setItem("btc_highest_level_seen",t.min.toString()),"function"==typeof notifySelfLevelUp&¬ifySelfLevelUp(t.min,t.name,t.emoji);var n=currentUser&¤tUser.username?currentUser.username:null,i=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:"";if(n&&"function"==typeof window.nachoGlobalAnnounce&&window.nachoGlobalAnnounce(t.emoji+" @"+n+" just leveled up to "+t.emoji+" "+t.name+"! Congrats! 🎉",i),"function"==typeof window.contributeSatoshiFavor){var a=t.name||"",r=null;["Pleb","Pleb II","Pleb III","Stacker","Stacker II","Stacker III"].includes(a)?r="level_up":["Maxi","Maxi II","Maxi III"].includes(a)?r="level_up_5":["Papa John","Full Node","Whale","Sovereign","Cypherpunk","Satoshi"].includes(a)&&(r="level_up_10"),r&&window.contributeSatoshiFavor(r,a)}}lastLevelName=t.name,lastLevelMin=t.min;const s=document.getElementById("rankBar");if(!s)return;let c="";t.next&&(c='
'+(t.next.min-currentUser.points)+" XP to "+t.next.emoji+" "+t.next.name+"
");const l=auth.currentUser&&auth.currentUser.isAnonymous&¤tUser.username?'
🔗 Sign in to sync across devices
':"",d=currentUser.streak||0,u=d>0&&(d%7==0||30===d||100===d||365===d),p=currentUser.bestStreak||0,m=d>0||p>0?'🔥 '+d+(p>0?"("+p+")":"")+" day streak"+(u?" ✨":"")+"":"",g=(currentUser.orangeTickets||0)>0?''+currentUser.orangeTickets+"":"";s.innerHTML='
'+t.emoji+" "+t.name+''+escapeHtml(currentUser.username||"Anon")+''+(currentUser.points||0).toLocaleString()+" XP"+m+g+"
"+c+l,s.style.display="flex"}function getUserDisplayEmoji(e){var t=void 0!==currentUser&¤tUser?currentUser.displayBadge:null;if(t){if(void 0!==BADGE_DEFS)for(var o=0;o0?'🔥'+currentUser.streak+"":"",s=getUserDisplayEmoji(e);let c=document.getElementById("userDisplay");if(c||(c=document.createElement("div"),c.id="userDisplay",document.body.appendChild(c)),n||auth.currentUser&&auth.currentUser.isAnonymous&&!i){if(l=window.innerWidth<=900)return c.setAttribute("data-mob-hidden","1"),void(c.style.display="none");if("1"===sessionStorage.getItem("btc_signin_banner_dismissed"))return c.classList.add("user-hidden"),void(c.style.display="none");c.classList.remove("user-hidden"),c.setAttribute("data-anon","1"),l?c.style.cssText="position:fixed;bottom:70px;left:12px;right:12px;z-index:200;display:flex;align-items:center;gap:10px;padding:10px 16px;background:linear-gradient(135deg,#1a1a2e,#2d1f4e);border:2px solid #f7931a;border-radius:14px;box-shadow:0 4px 20px rgba(247,147,26,0.3);font-size:0.85rem;cursor:pointer;":((u=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((p=document.createElement("div")).id="userDisplayContainer",p.style.padding="0 20px 16px",p.style.borderBottom="1px solid var(--border)",u.parentNode.insertBefore(p,u.nextSibling),p.appendChild(c)),c.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:12px;background:rgba(247,147,26,0.05);border:1px solid rgba(247,147,26,0.2);border-radius:12px;cursor:default;transition:0.3s;width:100%;"),c.onclick=function(e){!l&&e.target.closest("button")||showSettingsPage("account")},c.innerHTML=(l?'':"")+'
'+e.emoji+'GUEST'+a.toLocaleString()+" XP
"+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
';return e&&(o+='
$'+Math.round(e).toLocaleString()+"
"),t&&(o+='⛓️ '+t.toLocaleString()+""),o+"
"}()+(l?'
Sign in to keep XP & enter giveaway!
':"")+"
"+(l?"":'
')+(l?"":'
SIGN UP
')+(l?'
Sign Up →
':"")}else{c.removeAttribute("data-anon"),c.removeAttribute("data-mob-hidden");var l=window.innerWidth<=900,d=document.getElementById("dashboardFloatBtn");d||((d=document.createElement("div")).id="dashboardFloatBtn",d.onclick=function(){"function"==typeof toggleDashboard&&toggleDashboard()},document.body.appendChild(d)),d.style.cssText="position:fixed;bottom:10px;right:76px;z-index:200001;background:linear-gradient(135deg,#f97316,#eab308);color:#fff;border:none;border-radius:50%;width:48px;height:48px;font-size:1.4rem;cursor:pointer;font-family:inherit;box-shadow:0 4px 20px rgba(249,115,22,0.4);display:flex;align-items:center;justify-content:center;transition:0.2s;-webkit-transform:translateZ(0);transform:translateZ(0);",d.innerHTML="📊",d.title="Bitcoin Metrics";var u,p,m=document.getElementById("dashBtnCSS");if(m||((m=document.createElement("style")).id="dashBtnCSS",m.textContent="@media(max-width:900px){#dashboardFloatBtn{bottom:70px!important;right:72px!important;}}",document.head.appendChild(m)),l)return void(c.style.display="none");if(l)c.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:8px;padding:8px 14px;background:var(--bg-side);border:1px solid var(--border);border-radius:10px;font-size:0.8rem;cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,0.2);";else(u=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((p=document.createElement("div")).id="userDisplayContainer",p.style.padding="0 20px 16px",p.style.borderBottom="1px solid var(--border)",u.parentNode.insertBefore(p,u.nextSibling),p.appendChild(c)),c.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:10px;background:rgba(255,255,255,0.03);border:1px solid var(--border);border-radius:10px;cursor:pointer;width:100%;";c.onclick=function(e){e.target.closest("a")||showSettings()};var g,h=currentUser.username||auth.currentUser&&auth.currentUser.displayName||"Anon";g=currentUser.displayBadge?''+s+' '+e.emoji+"":''+e.emoji+"",c.innerHTML='
'+g+''+escapeHtml(h)+""+(r?''+r+"":"")+"
"+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
';return e&&(o+='
$'+Math.round(e).toLocaleString()+"
"),t&&(o+='⛓️ '+t.toLocaleString()+""),(o+=''+a.toLocaleString()+" XP")+"
"}()+"
"+(l?"":'
')}c.style.display="flex";const f=document.getElementById("mobileUserInfo");if(f&&window.innerWidth<=900){var y=s;currentUser.displayBadge&&(y+=" "+e.emoji),a=currentUser.points||0;var v=parseFloat(localStorage.getItem("btc_last_price"))||0,b=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(v=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(b=nachoLiveData.blockHeight);var w=''+y+" "+escapeHtml(currentUser.username||(n?"Anonymous":"Anon"))+"";v&&(w+=' $'+Math.round(v).toLocaleString()+""),b&&(w+=' ⛓️ '+b.toLocaleString()+""),w+=' '+a.toLocaleString()+" XP",f.innerHTML=w,f.style.display="inline",f.style.maxWidth="none"}const x=document.getElementById("welcomeBanner");if(x&¤tUser.username){updateAuthButton();const t=currentUser.streak||0,o=currentUser.bestStreak||0,n=t>0||o>0?' · 🔥 '+t+(o>0?"("+o+")":"")+" day streak":"";x.innerHTML=''+e.emoji+' Welcome back, '+escapeHtml(currentUser.username||"Anon")+'! · '+e.name+" · "+(currentUser.points||0).toLocaleString()+" XP"+n+'
⚙️ Tap here for Account & Settings
',x.style.display="block",x.removeAttribute("data-simplified-hidden")}}document.addEventListener("mousemove",trackActivity),document.addEventListener("keydown",trackActivity),document.addEventListener("touchstart",trackActivity,{passive:!0}),document.addEventListener("click",trackActivity),setInterval(trackScroll,2e3),window.toggleGuestPointsBanner=function(){var e=document.getElementById("guestPointsBanner");if(e){var t=!e.classList.contains("banner-min");e.classList.toggle("banner-min",t);try{localStorage.setItem("btc_signin_banner_min",t?"1":"0")}catch(e){}updateGuestPointsBanner()}};let lbAutoShown=!1;function showLeaderboardAuto(){lbAutoShown||(lbAutoShown=!0,document.getElementById("leaderboard").classList.contains("open")||toggleLeaderboard())}function expandLeaderboard(e){e&&e.stopPropagation(),document.querySelectorAll(".lb-extra").forEach(e=>e.style.display="flex");const t=document.getElementById("lbShowMore");t&&t.remove()}function minimizeLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}function hideLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}function _lbOutsideClose(e){var t=document.getElementById("leaderboard");if(t&&t.classList.contains("open")&&!t.classList.contains("minimized")&&!t.contains(e.target)){var o=document.getElementById("rankBar");if(!o||!o.contains(e.target)){var n=document.getElementById("lbFloatBtn");n&&n.contains(e.target)||document.getElementById("userProfileModal")||(t.classList.remove("open"),t.classList.remove("minimized"),n&&(n.style.display="flex"))}}}function applyOLEDTheme(){const e="true"===localStorage.getItem("btc_theme_oled"),t="light"!==document.body.getAttribute("data-theme");e&&t?document.body.classList.add("oled-theme"):document.body.classList.remove("oled-theme")}function _lbBadgeEmoji(e){var t=[],o="undefined"!=typeof Intl&&Intl.Segmenter?Array.from(new Intl.Segmenter("en",{granularity:"grapheme"}).segment(e)).map(function(e){return e.segment}):null;o?t=o:t=e.match(/\p{Emoji_Presentation}(\u200d\p{Emoji_Presentation})*/gu)||[e];if(t.length<=1)return e;var n=2===t.length?"0.6rem":"0.5rem";return''+t.map(function(e){return""+e+""}).join("")+""}async function toggleLeaderboard(){const e=document.getElementById("leaderboard");if(!e)return;const t=document.getElementById("lbFloatBtn");if(e.classList.contains("open")&&!e.classList.contains("minimized"))return e.classList.remove("open"),e.classList.remove("minimized"),void(t&&(t.style.display="flex"));if(e.classList.remove("minimized"),e.innerHTML='
Loading leaderboard...
',e.classList.add("open"),t&&(t.style.display="none"),("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{window._sharedAudioCtx||(window._sharedAudioCtx=new(window.AudioContext||window.webkitAudioContext));var o=window._sharedAudioCtx;"suspended"===o.state&&o.resume();const e="undefined"!=typeof audioVolume?audioVolume:.5,t=o.currentTime,n=o.createOscillator(),i=o.createGain();n.connect(i),i.connect(o.destination),n.type="sine",n.frequency.setValueAtTime(200,t),n.frequency.exponentialRampToValueAtTime(800,t+.15),i.gain.setValueAtTime(.08*e,t),i.gain.exponentialRampToValueAtTime(.001,t+.2),n.start(t),n.stop(t+.2),[880,1175].forEach((n,i)=>{const a=o.createOscillator(),r=o.createGain();a.connect(r),r.connect(o.destination),a.type="triangle",a.frequency.value=n,r.gain.setValueAtTime(.1*e,t+.1+.08*i),r.gain.exponentialRampToValueAtTime(.001,t+.1+.08*i+.3),a.start(t+.1+.08*i),a.stop(t+.1+.08*i+.3)})}catch(e){}try{var n=Date.now(),i=window._lbCache&&window._lbCacheTime&&n-window._lbCacheTime<12e4;let t=[];i?t=window._lbCache:((await db.collection("users").orderBy("points","desc").limit(150).get()).forEach(e=>{const o=e.data(),n=auth.currentUser&&e.id===auth.currentUser.uid;o.points>0&&(!o.ghostMode||n)&&t.push({id:e.id,...o})}),window._lbCache=t,window._lbCacheTime=n);let o='
🏆 Leaderboard — tap to expand
';o+='

🏆 Leaderboard

',o+='
',Math.min(10,t.length),t.forEach((e,t)=>{const n=t+1,i=getLevel(e.points||0),a=auth.currentUser&&e.id===auth.currentUser.uid;a&¤tUser&&(e.points||0)>(currentUser.points||0)&&(currentUser.points=e.points,updateRankUI());const r=1===n?"🥇":2===n?"🥈":3===n?"🥉":"#"+n,s=n>10?' style="display:none;" class="lb-row lb-extra'+(a?" lb-me":"")+'"':' class="lb-row'+(a?" lb-me":"")+'"';var c="function"==typeof onlineStatusDot?onlineStatusDot(e.lastSeen):"";let l="";e.earnedHidden&&e.earnedHidden.includes("cert_scholar")&&(l+=" 🎓"),e.earnedHidden&&e.earnedHidden.includes("cert_tech")&&(l+=" 🛠️");var d=e.profilePic?'':"",u=JSON.stringify({recipientName:e.username||"Anon",recipientUid:e.id,lightningAddress:e.lightningAddress||e.lightning||"",context:"leaderboard",label:"Tip "+(e.username||"Anon")}).replace(/'/g,"'").replace(/"/g,"""),p=e.faction?window._factionNameStyle(e.faction):"";o+="'+r+''+_lbBadgeEmoji(i.emoji)+'"+(d?d+" ":"")+escapeHtml(e.username||"Anon")+c+l+''+(e.points||0).toLocaleString()+' XP
'}),t.length>10&&(o+='"),o+="","function"==typeof getBadgeHTML&&(o+='

Your Badges

'+getBadgeHTML()+"
"),o+='

⚔️ PVP Leaderboard

Loading PVP rankings...
',o+='

Levels

';for(const e of LEVELS)o+='
'+e.emoji+" "+e.name+""+(0===e.min?"0 XP":e.min+"+ XP")+"
";o+="
",e.innerHTML=o,_loadPVPLeaderboard()}catch(t){console.error("[Leaderboard] Error:",t),e.innerHTML='
Error loading leaderboard: '+(t.message||"Unknown error")+"
"}}async function _loadPVPLeaderboard(){var e=document.getElementById("pvpLeaderboardList");if(e)try{var t,o,n=Date.now();window._pvpLbCache&&window._pvpLbCacheTime&&n-window._pvpLbCacheTime<3e5?(t=window._pvpLbCache.wins,o=window._pvpLbCache.losses):([t,o]=await Promise.all([db.collection("users").where("pvpWins",">",0).orderBy("pvpWins","desc").limit(50).get(),db.collection("users").where("pvpLosses",">",0).orderBy("pvpLosses","desc").limit(50).get()]),window._pvpLbCache={wins:t,losses:o},window._pvpLbCacheTime=n);var i={},a=auth.currentUser?auth.currentUser.uid:null;function r(e){if(!i[e.id]){var t=e.data();if(!t.ghostMode||e.id===a){var o=t.pvpWins||0,n=t.pvpLosses||0,r=o+n;if(0!==r){var s=r>0?o/r*100:0;i[e.id]={id:e.id,username:escapeHtml(t.username||"Anon"),wins:o,losses:n,total:r,winRate:s,isMe:e.id===a,lightningAddress:t.lightningAddress||t.lightning||""}}}}}t.forEach(r),o.forEach(r);var s=Object.values(i);if(0===s.length)return void(e.innerHTML='
No PVP battles yet — be the first to compete!
');s.sort(function(e,t){return t.winRate-e.winRate||t.wins-e.wins});var c="";s.forEach(function(e,t){var o=t+1,n=1===o?"🥇":2===o?"🥈":3===o?"🥉":"#"+o,i=e.wins>=100?"👑":e.wins>=50?"🏆":e.wins>=25?"🏟️":e.wins>=5?"🥊":"⚔️",a=o>10?' style="display:none;" class="lb-row pvp-lb-extra'+(e.isMe?" lb-me":"")+'"':' class="lb-row'+(e.isMe?" lb-me":"")+'"',r=JSON.stringify({recipientName:e.username,recipientUid:e.id,lightningAddress:e.lightningAddress,context:"pvp",label:"Tip "+e.username}).replace(/'/g,"'").replace(/"/g,""");c+="'+n+''+i+''+e.username+''+e.wins+"W – "+e.losses+'L'}),s.length>10&&(c+=""),e.innerHTML=c||'
No PVP battles yet!
'}catch(l){e.innerHTML='
No PVP battles yet — be the first to compete!
'}}document.addEventListener("mousedown",_lbOutsideClose,!0),document.addEventListener("touchstart",_lbOutsideClose,!0),window.toggleOLEDTheme=function(){const e="true"===localStorage.getItem("btc_theme_oled");localStorage.setItem("btc_theme_oled",!e),applyOLEDTheme(),showSettingsPage("prefs"),showToast(e?"Deep sea mode disabled":"🖤 Midnight OLED enabled!")},document.addEventListener("DOMContentLoaded",applyOLEDTheme),window.showDeleteAccountConfirm=function(){var e=document.createElement("div");e.id="deleteAccountOverlay",e.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;",e.onclick=function(t){t.target===e&&e.remove()};var t=currentUser&¤tUser.username?currentUser.username:"your account",o=currentUser&¤tUser.points||0,n=currentUser&¤tUser.streak||0;e.innerHTML='
⚠️

Delete Your Account?

This will permanently delete everything associated with '+escapeHtml(t)+':
'+o.toLocaleString()+" XP and all badges
"+(n>0?"
"+n+"-day streak
":"")+'
❌ All forum posts and replies
❌ Marketplace listings
❌ DM conversations
❌ Nacho chat history
❌ Leaderboard ranking
❌ Orange Tickets and quest progress
⚠️ This action is IRREVERSIBLE. There is no undo.
',document.body.appendChild(e)},window.confirmDeleteAccount=async function(){var e=document.getElementById("deleteConfirmInput");if(e&&"DELETE"===e.value){var t=document.getElementById("deleteConfirmBtn");t&&(t.disabled=!0,t.textContent="Deleting...");try{var o=auth.currentUser;if(!o)throw new Error("Not signed in");var n=o.uid;try{await db.collection("users").doc(n).delete()}catch(e){console.warn("User doc delete failed:",e)}try{var i=await db.collection("forum_posts").where("authorId","==",n).get(),a=db.batch();i.forEach(function(e){a.delete(e.ref)}),i.empty||await a.commit()}catch(e){console.warn("Forum posts delete failed:",e)}try{var r=await db.collection("forum_replies").where("authorId","==",n).get(),s=db.batch();r.forEach(function(e){s.delete(e.ref)}),r.empty||await s.commit()}catch(e){console.warn("Forum replies delete failed:",e)}try{var c=await db.collection("marketplace").where("sellerUid","==",n).get(),l=db.batch();c.forEach(function(e){l.delete(e.ref)}),c.empty||await l.commit()}catch(e){console.warn("Marketplace delete failed:",e)}try{var d=await db.collection("conversations").where("participants","array-contains",n).get(),u=db.batch();d.forEach(function(e){u.delete(e.ref)}),d.empty||await u.commit()}catch(e){console.warn("DM delete failed:",e)}try{var p=await db.collection("suggestions").where("uid","==",n).get(),m=db.batch();p.forEach(function(e){m.delete(e.ref)}),p.empty||await m.commit()}catch(e){console.warn("Suggestions delete failed:",e)}for(var g=[],h=0;hclick to ask!'),document.querySelectorAll('[id*="nachoCloset"]').forEach(function(t){var o=t.querySelector('[style*="letter-spacing"]');o&&-1!==o.textContent.indexOf("'s Closet")&&(o.textContent="🦌 "+e+"'s Closet")}),document.querySelectorAll('[style*="font-weight:800"]').forEach(function(t){-1!==t.textContent.indexOf("'s Story")&&(t.textContent=e+"'s Story")})}};var _toastQueue=[];function showToast(e,t){window._directLinkMode||(window._nachoBusy?_toastQueue.push({msg:e,duration:t}):_showToastNow(e,t))}function _showToastNow(e,t){var o=t||2500;const n=document.createElement("div");n.className="rank-toast";var i="object"==typeof e?e.msg:e;n.innerHTML=i.replace(/<(script|svg|img|iframe|object|embed|form|input|link|style|meta|base)[^>]*>/gi,"").replace(/on\w+\s*=/gi,"data-blocked="),"object"==typeof e&&e.duration&&(o=e.duration),document.body.appendChild(n),requestAnimationFrame(()=>n.classList.add("show")),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>n.remove(),400)},o)}function showUsernamePrompt(){try{if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)return void showAccountInfo();if(currentUser&¤tUser.username)return void showAccountInfo();if(!redirectResultResolved)return showToast("⏳ Loading account..."),void redirectResultPromise.then(function(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous||currentUser&¤tUser.username?showAccountInfo():(document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash))});document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash)}catch(e){"function"==typeof showToast&&showToast("Settings error: "+e.message),console.error("showUsernamePrompt error:",e)}}function showAccountInfo(){showSettingsPage("account")}setInterval(function(){!window._nachoBusy&&_toastQueue.length>0&&_showToastNow(_toastQueue.shift())},2e3),window.showSignInOnly=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)showAccountInfo();else{var e=document.getElementById("usernameModal");e&&(e.classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash),setTimeout(function(){var t=e.querySelector(".username-box");if(t){var o=t.querySelector("h2"),n=t.querySelector("p"),i=document.getElementById("usernameInput"),a=document.getElementById("emailInput"),r=document.getElementById("giveawaySection"),s=t.querySelector('button[onclick="submitUsername()"]'),c=a?a.nextElementSibling:null;c&&"P"===c.tagName&&(c.style.display="none"),o&&(o.style.display="none"),n&&(n.style.display="none"),i&&(i.style.display="none"),a&&(a.style.display="none"),r&&(r.style.display="none"),s&&(s.style.display="none");var l=r?r.nextElementSibling:null;l&&"SCRIPT"===l.tagName&&(l.style.display="none");var d=document.getElementById("signInOnlyHeader");d||((d=document.createElement("div")).id="signInOnlyHeader",d.innerHTML='
🔐

Welcome Back!

Sign in to your account

',t.insertBefore(d,t.firstChild));var u=document.getElementById("emailSignInSection");if(u){var p=u.querySelector("p");p&&(p.innerHTML='Sign in with your email:')}var m=document.getElementById("signInOnlyNewHere");if(!m){(m=document.createElement("div")).id="signInOnlyNewHere",m.innerHTML='
';var g=t.querySelector(".skip");g?t.insertBefore(m,g):t.appendChild(m)}}},50))}},window._restoreSignUpForm=function(){var e=document.getElementById("usernameModal");if(e){var t=e.querySelector(".username-box");if(t){var o=document.getElementById("signInOnlyHeader");o&&o.remove();var n=document.getElementById("signInOnlyNewHere");n&&n.remove();var i=t.querySelector("h2"),a=t.querySelector("p"),r=document.getElementById("usernameInput"),s=document.getElementById("emailInput"),c=document.getElementById("giveawaySection"),l=t.querySelector('button[onclick="submitUsername()"]'),d=s?s.nextElementSibling:null;d&&"P"===d.tagName&&(d.style.display=""),i&&(i.style.display=""),a&&(a.style.display=""),r&&(r.style.display=""),s&&(s.style.display=""),c&&(c.style.display=""),l&&(l.style.display="");var u=document.getElementById("emailSignInSection");if(u){var p=u.querySelector("p");p&&(p.innerHTML="Already have an account? Sign in with your email:")}}}};let settingsTab="account";function shortcutRow(e,t){return'
'+e+'
'+t+"
"}function showSettingsPage(e){try{settingsTab=e||"account";const Ye=document.getElementById("usernameModal"),Je=Ye.querySelector(".username-box");if(!Ye)return void("function"==typeof showToast&&showToast("Error: modal not found"));if(!Je)return void("function"==typeof showToast&&showToast("Error: username-box not found"));const Xe=void 0!==auth&&auth?auth.currentUser:null;if(!Xe)return void Ye.classList.add("open");const Ke=getLevel(currentUser&¤tUser.points||0);let $e="";if($e+='
',["account","scholar","sats","prefs","security","data"].forEach(e=>{const t=settingsTab===e;$e+=""}),$e+="
","account"===settingsTab){var t=Xe.isAnonymous,o=getUserDisplayEmoji(Ke),n=currentUser&¤tUser.profilePic||"",i=n?'':'
'+o+"
";$e+='
'+i+'
'+(currentUser&¤tUser.username||"Bitcoiner")+'
'+Ke.name+" · "+(currentUser&¤tUser.points||0).toLocaleString()+" XP"+(currentUser&¤tUser.faction?" · "+("cyber_hornets"===currentUser.faction?"🐝 Cyber Hornets":"🦡 Honey Badgers"):"")+"
";var a=currentUser&¤tUser.country||"";$e+='
🌍 Country
Optional · Shown on your public profile
';var r=currentUser&¤tUser.faction||"";$e+='
⚔️ Faction
Choose your allegiance! New faction features coming soon — no competitive advantage to either choice.
🐝
Cyber Hornets
The swarm protects the network
'+("cyber_hornets"===r?'
✓ Joined
':"")+'
🦡
Honey Badgers
Honey badger don\'t care
'+("honey_badgers"===r?'
✓ Joined
':"")+"
",$e+='
📷 Profile Picture
'+(n?'':'
👤
')+'
"+(n?' ':"")+'
Square image recommended · Max 2MB
';var s="",c='
Account Details
';Xe.email&&(c+='
Email'+Xe.email+"
"),Xe.displayName&&(c+='
Name'+Xe.displayName+"
");let Ze="Anonymous";if(Xe.providerData&&Xe.providerData.length>0){const et=Xe.providerData[0].providerId;"google.com"===et?Ze="Google":"twitter.com"===et?Ze="Twitter/X":"github.com"===et?Ze="GitHub":"facebook.com"===et?Ze="Facebook":"password"===et&&(Ze="Email")}if(c+='
Sign-in method'+Ze+"
",currentUser&¤tUser.created&&(c+='
Member since'+(currentUser.created.toDate?currentUser.created.toDate().toLocaleDateString():new Date(currentUser.created).toLocaleDateString())+"
"),s+=c+="
",!t){var l=currentUser&¤tUser.displayBadge||"",d=[];void 0!==earnedBadges&&void 0!==BADGE_DEFS&&BADGE_DEFS.forEach(function(e){earnedBadges.has(e.id)&&d.push({id:e.id,emoji:e.emoji,name:e.name})});var u=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]");if(void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){-1!==u.indexOf(e.id)&&d.push({id:e.id,emoji:e.hidden&&e.revealEmoji||e.emoji,name:e.hidden&&e.revealName||e.name})}),d.length>0){var p=Ke.emoji+" Rank (default)";if(l){var m=d.find(function(e){return e.id===l});m&&(p=m.emoji+" "+m.name)}if(s+='
🏅 Display Badge
'+p+'
'+(window._expanded_badges?"▾":"▸")+"
",window._expanded_badges){s+='
Choose a badge to show next to your name instead of your rank emoji.
',s+='
'+Ke.emoji+'
'+Ke.name+' (Default)
Your current rank emoji
'+(l?"":'')+"
";for(var g=0;g'+h.emoji+'
'+h.name+"
"+(f?'':"")+"
"}s+="
"}s+="
"}}s+='
✏️ Change Username
Current username: '+(currentUser&¤tUser.username||"")+'
',s+='';var y=currentUser&¤tUser.bio||"",v=[],b=[];[{k:"website",e:"🌐",l:"Website",p:"https://yoursite.com",m:100,t:"url"},{k:"twitter",e:"𝕏",l:"Twitter/X",p:"@yourusername",m:30},{k:"nostr",e:"🟣",l:"Nostr",p:"npub... or NIP-05",m:80},{k:"instagram",e:"📸",l:"Instagram",p:"@yourusername",m:30},{k:"tiktok",e:"🎵",l:"TikTok",p:"@yourusername",m:30},{k:"github",e:"🐙",l:"GitHub",p:"yourusername",m:40},{k:"contactEmail",e:"📧",l:"Email",p:"you@example.com",m:80,t:"email",note:"public"},{k:"lightning",e:"⚡",l:"Lightning",p:"you@walletofsatoshi.com",m:80}].forEach(function(e){currentUser&¤tUser[e.k]?v.push(e):b.push(e)}),$e+='
📝 Public Profile
Visible when someone clicks your name on the leaderboard
",$e+='
🔗 Links & Socials
',$e+='
',v.forEach(function(e){var t=currentUser&¤tUser[e.k]||"";$e+=''}),$e+="
",b.length>0&&($e+='
"),$e+='
',currentUser&&(currentUser.lightning||currentUser.lightningAddress)||($e+='
Connect a Lightning Wallet
Tip other users and receive tips from the community!
'),$e+="",$e+='",$e+=''}else if("_artist_removed"===settingsTab){var w=currentUser&¤tUser.artistProfile||{};void 0!==db&&auth&&auth.currentUser&&auth.currentUser.uid,$e+='
🎸
Artist Profile
Set up your artist presence on Bitcoin Beats
',$e+='
🎤 Stage Name
Shows on your tracks and artist page. Leave blank to use your username.
',$e+='
📝 Artist Bio
Music-specific bio. Your general bio is in Account tab.
',$e+='
🎵 Genres
Comma-separated. Shows as tags on your artist page.
',$e+='
🔗 Music Links
🌊
🟢
🎵
📺
🔗
',$e+='
Lightning Tips
'+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?"✅ Lightning Address set: "+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ No Lightning Address set. Go to Account tab or set up in ⚡ Wallet to receive tips!")+"
",$e+='',$e+="'}else if("scholar"===settingsTab){$e+='
🎓
Bitcoin Scholar

Master Bitcoin through quests, certifications, and flashcards.

',$e+='
Channel Quests

Test your knowledge on any Bitcoin topic with guided quiz questions.

';var x="true"===localStorage.getItem("btc_scholar_prop_passed");$e+='
'+(x?"✅":"📜")+'
Bitcoin Scholar Certification

25 questions on the economic properties and scarcity of Bitcoin. 80% to pass. One attempt per day.

";var k="true"===localStorage.getItem("btc_scholar_tech_passed");$e+='
'+(k?"✅":"🛠️")+'
Bitcoin Protocol Expert

25 questions on highly technical topics: BIPs, Script, SegWit, Taproot, and Networking.

",$e+="

Prepare for quests and exams with interactive flashcards.

",[{name:"Bitcoin Basics",emoji:"₿"},{name:"Security & Storage",emoji:"🔑"},{name:"Lightning Network",emoji:"⚡"},{name:"Mining & Energy",emoji:"⛏️"},{name:"Economics & Money",emoji:"💰"},{name:"History & Culture",emoji:"📜"},{name:"Privacy & Sovereignty",emoji:"🕵️"},{name:"Nodes & P2P",emoji:"📡"},{name:"Wallets & Tools",emoji:"💼"},{name:"Common Myths",emoji:"🚫"},{name:"Austrian Economics",emoji:"🇦🇹"},{name:"Cypherpunk History",emoji:"🔐"},{name:"Bitcoin Governance",emoji:"🏛️"},{name:"Satoshi Nakamoto",emoji:"🦸"},{name:"Global Impact",emoji:"🌍"},{name:"El Salvador & Adoption",emoji:"🇸🇻"},{name:"Technical Deep Dives",emoji:"🔬"}].forEach(function(e){$e+=""}),$e+="
",$e+="",$e+='"}else if("signal"===settingsTab){var _;$e+='
📡
The Weekly Signal

Curated Bitcoin insights and site updates.

',T=null===(_=localStorage.getItem("btc_ticker_enabled"))?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===_,$e+="
📊Live Ticker on Home
",$e+='
📡 Live Signals
',$e+='
',$e+="",$e+='
📚 Featured Deep Dives
',[{date:"Feb 26, 2026",title:"Why Proof of Stake is just Fiat 2.0",snippet:"Most cryptos claim to be better than Bitcoin because they use less energy. But Gigi explains why energy IS the point — PoW converts real-world resources into unforgeable security.",channel:"pow-vs-pos"},{date:"Feb 19, 2026",title:"The Great Definancialization",snippet:"Parker Lewis breaks down why we don't need thousands of stocks, bonds, and derivatives if we have one form of hard money that can't be debased.",channel:"problems-of-money"},{date:"Feb 12, 2026",title:"The 21 Million Cap is Inviolate",snippet:"Why even if every miner in the world wanted to change the supply, they couldn't. The users run the rules.",channel:"scarce"},{date:"Feb 5, 2026",title:"Not Your Keys, Not Your Coins",snippet:"After another exchange collapse, the importance of self-custody has never been clearer. Here's how to take control.",channel:"self-custody"},{date:"Jan 29, 2026",title:"The Halving: Scarcity You Can Verify",snippet:"Every 210,000 blocks, the supply issuance gets cut in half. No vote. No committee. Just code.",channel:"difficulty-adjustment"}].forEach(function(e){$e+='
'+e.date.toUpperCase()+'
'+e.title+'
'+e.snippet+"
'}),setTimeout(function(){var e=document.getElementById("signalLiveNews");e&&fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=(e.snippet||"").replace(/<[^>]+>/g,""),a=e.link||"";n+='
SIGNAL #'+(t+1)+''+(e.date||"").toUpperCase()+'
'+o+"
"+(i?'
'+i+"
":"")+(a?'
Read full article →
':"")+"
"}),o.innerHTML=n;var i=function(){var t=document.getElementById("signalArrowL"),o=document.getElementById("signalArrowR");t&&o&&(e.scrollWidth>e.clientWidth+10?(t.style.display=e.scrollLeft>10?"flex":"none",o.style.display=e.scrollLeft+e.clientWidth✅ You\'re subscribed to The Signal!':'
📧
Get The Signal via Email

Weekly curated Bitcoin insights. No spam, pure signal.

'}else if("tickets"===settingsTab){const tt=!Xe||Xe.isAnonymous;tt?$e+='
Orange Tickets
Sign in with Google, Twitter, or GitHub to start earning Orange Tickets and get your referral link!
':($e+="function"==typeof renderTicketsSection?renderTicketsSection():"",$e+="function"==typeof renderReferralSection?renderReferralSection():"",$e+='
How to Earn Tickets
📅 Daily Login: +1 ticket just for visiting.
🎡 Spin the Wheel: Spin daily for bonus tickets!
👥 Referrals: Earn 50 tickets per friend who signs up and reaches Maxi rank (2,140+ pts). Verified automatically.
🏅 Badges: Unlock at 25 🐟, 50 🦈, and 100 🐋 tickets.
⭐ Bonus: Each ticket = +5 XP towards your rank.
🏆 Giveaways: More tickets = higher chance of winning sats!
'),tt||"function"!=typeof loadReferralStatsUI||setTimeout(loadReferralStatsUI,100)}else if("sats"===settingsTab){var B=window._satsSubTab||"claim",I=(t=Xe.isAnonymous,currentUser&¤tUser.points||0),C=currentUser&¤tUser.pointsClaimed||0,E=currentUser&¤tUser.pointsDonated||0,A=I-C,M=currentUser&¤tUser.satsWithdrawn||0,z=Math.floor(Math.max(0,A)/10),L="function"==typeof getSatCap?getSatCap():1e4,P=Math.max(0,L-M),U=Math.min(z,500,P),N=currentUser&¤tUser.lastSatsClaim||null,H=N?new Date(N.seconds?1e3*N.seconds:N).getTime()+864e5:0,q=Date.now(),D=N&&qR&&(R=F.length)}catch(ot){}var W=Xe.metadata&&Xe.metadata.creationTime?new Date(Xe.metadata.creationTime):null,V=W?Math.floor((q-W.getTime())/864e5):0,G=Xe.email&&Xe.emailVerified,Q=!t&&G&&V>=7&&R>=10,Y=z>=100;if($e+='
',$e+='',$e+='',$e+="
","donate"!==B){$e+='
',$e+='
',$e+='
Claim Real Sats
',$e+='
Earn XP → Convert to real Bitcoin over Lightning
',$e+="
",$e+='
',$e+='
Your Balance
',$e+='
⚡ '+z.toLocaleString()+" claimable sats
",$e+='
'+A.toLocaleString()+" unclaimed XP of "+I.toLocaleString()+" total
",$e+='
Lifetime withdrawn: '+M.toLocaleString()+" / 10,000 sats
",$e+="
",$e+=!t&&Q&&Y&&!D&&U>=100?'":D?'
⏳ Next claim in '+O+"
":!Y&&Q?'
Need '+(100-z)+" more sats ("+10*(100-z)+" XP) to reach minimum claim
":'
Complete requirements below to claim
',$e+='
',$e+='
📋 Requirements
',[{met:!t,label:"Signed in (not anonymous)",detail:t?"Sign in with email, Google, etc.":"✓ Signed in"},{met:G,label:"Email verified",detail:G?"✓ "+Xe.email:"Link & verify your email in Account tab"},{met:V>=7,label:"Account age ≥ 7 days",detail:V>=7?"✓ "+V+" days old":V+"/7 days — "+(7-V)+" more to go"},{met:R>=10,label:"Read ≥ 10 topics",detail:R>=10?"✓ "+R+" topics read":R+"/10 topics — read "+(10-R)+" more"},{met:Y,label:"Minimum 100 sats (1,000 pts)",detail:Y?"✓ "+z+" sats available":z+"/100 sats — earn "+10*(100-z)+" more XP"}].forEach(function(e){$e+='
',$e+=''+(e.met?"✅":"⬜")+"",$e+='
'+e.label+"
",$e+='
'+e.detail+"
"}),$e+="
",$e+='
',$e+='
⚡ How It Works
',$e+='
',$e+="• 1,000 XP = 100 sats — earn XP by reading, quests, and daily visits
",$e+="• Min claim: 100 sats (1,000 XP)
",$e+="• Max claim: 500 sats/day
",$e+="• 1 claim per 24 hours
",$e+="• Lifetime max: 10,000 sats per account
",$e+="• Daily XP cap: 500 XP (50 sats worth) to prevent abuse
",$e+="• Unclaimed sats roll over — no expiration
",$e+="• Payouts via Lightning Network ⚡
",$e+="
",$e+='
',$e+="💚 Zero fees for you! We pay all Lightning network fees so you receive the full amount you claim. You earned it!",$e+="
",$e+='
',$e+="",$e+='
",$e+='
',$e+='
📜 Withdrawal History
',$e+='
Loading...
',$e+="
";var X=currentUser&&(currentUser.lightning||currentUser.lightningAddress)||"";$e+='
',$e+='
Lightning Address
For receiving tips from other users
',X&&($e+='
'+escapeHtml(X)+"
"),$e+='
',$e+='
',X||($e+='
💡 Get one from Wallet of Satoshi, Alby, Coinos, or Strike.
'),$e+="
"}else{var K=Math.max(0,I-C-E);r=currentUser&¤tUser.faction||"",$e+='
',$e+='
❤️
',$e+='
Donate XP for Charity
',$e+='
1,000 XP = 1,000 sats donated — 10× more impact than claiming
',$e+="
",$e+='
',$e+='
Available to Donate
',$e+='
❤️ '+K.toLocaleString()+" XP
",$e+='
'+I.toLocaleString()+" total − "+C.toLocaleString()+" claimed − "+E.toLocaleString()+" donated
",$e+="
",t?$e+='
🔐 Sign in to donate XP
':r?($e+='
',[5,10,25,50,100].forEach(function(e){var t=Math.floor(K*e/100);$e+='"}),$e+="
",$e+='
',$e+='',$e+="
",$e+='
',$e+='',$e+="
",$e+='',E>0&&($e+='
'+E.toLocaleString()+" XP already donated — thank you! ❤️
")):($e+='
',$e+='
⚔️
',$e+='
Choose Your Faction First
',$e+='
Your faction’s donation total is tracked for the community leaderboard.
',$e+='',$e+="
"),$e+='
',$e+='',$e+='',$e+="
"}}else if("prefs"===settingsTab){const nt="light"!==document.body.getAttribute("data-theme"),it="true"===localStorage.getItem("btc_theme_oled"),at=localStorage.getItem("btc_font_size")||"medium";$e+="
🎨 Appearance
Theme
Font Size
',["small","medium","large"].forEach(function(e){var t=at===e,o=e.charAt(0).toUpperCase()+e.slice(1);$e+=""}),$e+="
",$e+='
🌐 Language
Translate the site to your preferred language
',setTimeout(function(){const e=document.getElementById("langSelect"),t=localStorage.getItem("btc_lang")||"";e&&(e.value=t)},50);const rt="undefined"==typeof audioEnabled||audioEnabled,st="undefined"!=typeof audioVolume?audioVolume:.5;$e+='
🔊 Sound
Sound Effects
Volume
',$e+="",$e+='"}else $e+=""}var Fe=localStorage.getItem("btc_nacho_nickname")||"Nacho";if($e+='
🏷️ Name Your Buck
Currently: '+escapeHtml(Fe)+'
',"function"==typeof getNachoStoryProgress){var We=getNachoStoryProgress(),Ve=We>=10,Ge=escapeHtml(Fe);$e+='
📖
'+Ge+'\'s Story
'+(Ve?"✅ Complete!":"A new chapter unlocks every day!")+'
'+We+'/10
"}"function"==typeof renderNachoClosetUI&&(void 0===window._expanded_closet&&(window._expanded_closet=!1),window._pendingClosetScroll&&(window._expanded_closet=!0),$e+='
👗 '+escapeHtml(Fe)+'\'s Closet
'+(window._expanded_closet?"▾":"▸")+"
",window._expanded_closet&&($e+='
'),$e+="
"),"function"==typeof renderStickerBook&&($e+='
🎨 Sticker Book
'+(window._expanded_stickers?"▾":"▸")+"
",window._expanded_stickers&&($e+='
'+renderStickerBook()+"
"),$e+="
"),$e+='
🔒 Privacy
We do not sell, share, or monetize your data. Ever.
The only data we store is your username, points, and progress — just enough to power your experience. No tracking, no ads, no third-party analytics. Your data is yours.
',$e+="",$e+='",$e+="",$e+='"}if($e+='Close',Je.innerHTML=$e,Ye.classList.add("open"),"sats"===settingsTab&&"function"==typeof loadSatsHistory&&setTimeout(loadSatsHistory,100),"sats"===settingsTab&&(window._toggleSatsCharityNote=function(){var e=document.getElementById("satsCharityNote"),t=document.getElementById("satsCharityNoteArrow");if(e){var o="none"!==e.style.display;e.style.display=o?"none":"block",t&&(t.textContent=o?"▼":"▲")}},window._satsCharitySetAmt=function(e){var t=document.getElementById("satsCharityAmtInput");t&&(t.value=e>0?e:"")},window._satsCharitySubmit=function(){if("undefined"!=typeof firebase&&firebase.functions){var e=document.getElementById("satsCharityAmtInput"),t=parseInt(e?e.value:"")||0,o=void 0!==currentUser&¤tUser?Math.max(0,(currentUser.points||0)-(currentUser.pointsClaimed||0)-(currentUser.pointsDonated||0)):0;if(!t||t<1)"function"==typeof showToast&&showToast("Enter a valid amount");else if(t>o)"function"==typeof showToast&&showToast("Not enough available XP ("+o.toLocaleString()+" available)");else{var n=!!document.getElementById("satsCharityAnonToggle")&&document.getElementById("satsCharityAnonToggle").checked,i=document.querySelector('[onclick="window._satsCharitySubmit()"]');i&&(i.disabled=!0,i.textContent="Donating..."),firebase.functions().httpsCallable("donatePoints")({amount:t,anonymous:n}).then(function(e){void 0!==currentUser&¤tUser&&(currentUser.pointsDonated=(currentUser.pointsDonated||0)+t,e.data&&e.data.bonusPts&&(currentUser.points=(currentUser.points||0)+e.data.bonusPts));var o=e.data&&e.data.newBadges&&e.data.newBadges.length>0?" +"+e.data.newBadges.length+" badge"+(e.data.newBadges.length>1?"s":"")+" unlocked!":"";"function"==typeof showToast&&showToast("❤️ Thank you! "+t.toLocaleString()+" XP donated ("+t.toLocaleString()+" sats pledged to charity)."+o,5e3),"function"==typeof window._charityThankYou&&window._charityThankYou(t,e.data&&e.data.newBadges||[],e.data&&e.data.bonusPts||0);var n=e.data&&e.data.newBadges||[];if(n.length>0&&"function"==typeof window.contributeSatoshiFavor){var i={donor_100:"🤷 Giving Pleb",donor_500:"💛 Stack Sharer",donor_1000:"🧡 Community Builder",donor_5000:"❤️ Archive Patron",donor_10000:"🔥 Sats Saint",donor_25000:"⚡ Lightning Philanthropist",donor_50000:"🏆 Satoshi's Steward",donor_100000:"👑 Legend of the Archive"};n.forEach(function(e){i[e]&&window.contributeSatoshiFavor("badge_earned",i[e]).catch(function(){})})}void 0!==window._charityStatsLoaded&&(window._charityStatsLoaded=!1),showSettingsPage("sats")}).catch(function(e){i&&(i.disabled=!1,i.textContent="❤️ Donate XP for Charity"),"function"==typeof showToast&&showToast("❌ "+(e.message||"Donation failed. Try again."),4e3)})}}}),"data"===settingsTab&&"function"==typeof loadReferralStatsUI&&Xe&&!Xe.isAnonymous&&setTimeout(loadReferralStatsUI,100),"data"===settingsTab&&"function"==typeof renderNachoClosetUI){var Qe=document.getElementById("nachoClosetContainer");Qe&&(renderNachoClosetUI(Qe),window._pendingClosetScroll&&setTimeout(function(){Qe.scrollIntoView({behavior:"smooth",block:"center"}),window._pendingClosetScroll=!1},300))}}catch(_t){"function"==typeof showToast&&showToast("Settings page error: "+_t.message),console.error("showSettingsPage error:",_t)}}function changeLanguage(e){const t=document.getElementById("langStatus");if(!e){const e=document.querySelector(".goog-te-banner-frame");e&&e.remove();var o=document.querySelector("iframe.goog-te-banner-frame");o&&o.remove();var n=document.querySelector(".skiptranslate");return n&&n.remove(),document.body.style.top="",document.body.style.position="",document.documentElement.style.overflow="",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=."+location.hostname,localStorage.setItem("btc_lang",""),t&&(t.innerHTML='✅ Switched to English'),document.documentElement.classList.remove("translated-ltr","translated-rtl"),document.querySelectorAll('font[style*="vertical-align: inherit"]').forEach(function(e){var t=e.parentNode;t&&t.replaceChild(document.createTextNode(e.textContent),e)}),void setTimeout(function(){showSettingsPage("prefs")},200)}if(localStorage.setItem("btc_lang",e),document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname,t&&(t.innerHTML='Translating...'),document.getElementById("gtranslate"))triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!');else{const o=document.createElement("script");o.id="gtranslate",o.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(o),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget"),setTimeout(()=>{triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!')},1500)};const n=document.createElement("div");n.id="gtranslateWidget",n.style.display="none",document.body.appendChild(n)}}function triggerGoogleTranslate(e){const t=document.querySelector(".goog-te-combo");t&&(t.value=e,t.dispatchEvent(new Event("change")))}function setFontSize(e){localStorage.setItem("btc_font_size",e);const t="small"===e?"14px":"medium"===e?"16px":"18px";document.documentElement.style.fontSize=t,showSettingsPage("prefs")}async function saveProfile(){var e=document.getElementById("profileStatus");if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in with Google, Facebook, Twitter, or email to save your profile!"),e&&(e.innerHTML='🔒 Create a free account to save your profile'),void("function"==typeof showUsernamePrompt&&setTimeout(showUsernamePrompt,1500));var t=auth.currentUser.uid,o=document.getElementById("profileBio")?document.getElementById("profileBio").value.trim():"",n=document.getElementById("countryInput"),i=n?n.value.trim().substring(0,60):"";if(i&&window._countryList&&-1===window._countryList.indexOf(i))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void n.focus();var a={bio:o,country:i};["website","twitter","nostr","instagram","tiktok","github","contactEmail","lightning"].forEach(function(e){var t,o=document.getElementById("profile_"+e);if(o){var n=o.value.trim();"lightning"===e?(n=n.replace(/[\\'"<>]/g,""))&&!n.match(/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)&&(n=""):n="contactEmail"===e||"nostr"===e?n.replace(/[\\'"<>]/g,""):(t=n)?(t=t.trim(),/^(javascript|data|vbscript|blob):/i.test(t)?"":t):"",a[e]=n}else currentUser&&void 0!==currentUser[e]&&(document.querySelector('.pf-link-row[data-key="'+e+'"]')||(a[e]=""))});try{e&&(e.innerHTML='Saving...'),await db.collection("users").doc(t).update(a),Object.assign(currentUser,a),e&&(e.innerHTML='✅ Profile saved!'),"function"==typeof showToast&&showToast("✅ Profile saved successfully!"),setTimeout(function(){e&&(e.innerHTML=""),showSettingsPage("account")},1500)}catch(t){console.error("Error saving profile:",t),e&&(e.innerHTML='❌ Error saving'),"function"==typeof showToast&&showToast("❌ Error saving profile")}}function _pasteFieldFallback(e){e.focus(),e.value="",e.setSelectionRange(0,0);try{document.execCommand("paste")}catch(e){}"function"==typeof showToast&&showToast("📋 Field ready — tap and hold, then tap Paste",5e3)}function clearUserLocalStorage(){for(var e=["btc_theme_oled","btc_font_size","btc_volume","btc_lang","btc_haptic","btc_soundscape","btc_ticker_enabled","btc_ios_a2hs_dismissed","btc_pwa_dismissed","btc_swipe_hint_shown","btc_last_auth_uid","btc_signin_email","btc_pending_email","btc_pending_username","btc_pending_giveaway"],t=[],o=0;o
Scan this QR code with your authenticator app:
Or enter this key manually: '+(t.data.secret||"")+'
')}}catch(e){showToast("Error setting up authenticator: "+(e.message||"try again"))}}async function verifyTotpSetup(){var e=document.getElementById("totpVerifyCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpVerify");await t({code:e.value.trim()}),showToast("✅ Authenticator app enabled!"),showSettingsPage("security")}catch(e){showToast("Invalid code. Try again.")}else showToast("Enter a 6-digit code")}async function disableTotp(){var e=document.getElementById("totpDisableCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpDisable");await t({code:e.value.trim()}),showToast("Authenticator app disabled"),showSettingsPage("security")}catch(e){showToast("Invalid code")}else showToast("Enter your current code")}function clearUserData(){["btc_visited_channels","btc_favs","btc_hidden_badges","btc_asked_questions","btc_scholar_passed","btc_scholar_attempt_date","btc_badges","btc_last_channel","btc_signin_email","btc_nacho_equipped","btc_nacho_items_notified","btc_points","btc_total_visits","btc_streak","btc_last_visit"].forEach(function(e){localStorage.removeItem(e)}),currentUser=null}function showSignInPrompt(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous?showSettings():showUsernamePrompt()}function _generateDeviceFingerprint(){try{var e=document.createElement("canvas"),t=e.getContext("2d");t.textBaseline="top",t.font="14px Arial",t.fillText("Bitcoin Education 🦌",2,2);for(var o=e.toDataURL(),n=[navigator.userAgent||"",screen.width+"x"+screen.height,screen.colorDepth,(new Date).getTimezoneOffset(),navigator.language||"",navigator.hardwareConcurrency||0,(navigator.deviceMemory||0).toString(),void 0!==window.ontouchstart?"touch":"no-touch",o.substring(o.length-50)].join("|"),i=0,a=0;a{const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.frequency.value=o,i.type=n<3?"sine":"triangle",a.gain.setValueAtTime(.12*e,t.currentTime+.1*n),a.gain.exponentialRampToValueAtTime(.001,t.currentTime+.1*n+.6),i.start(t.currentTime+.1*n),i.stop(t.currentTime+.1*n+.6)})}catch(e){}"function"==typeof launchConfetti&&launchConfetti();const o=document.createElement("div");o.id="levelUpModal",o.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;animation:fadeIn 0.4s;",o.innerHTML='
'+e.emoji+'
⬆️ LEVEL UP!
'+e.name+'
You\'ve reached '+e.min.toLocaleString()+'+ XP!
'+getLevelFlavor(e.name)+'
',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function getLevelFlavor(e){return{Curious:"You're starting to see what all the fuss is about.",Pleb:"Welcome to the pleb life. You're one of us now.","Pleb II":"170 — the block height when Satoshi mined the first 1,000 blocks. You're going deeper.","Pleb III":"256 — the number of bits in a private key. You're becoming unbreakable.",Stacker:"Stacking sats and stacking knowledge. Impressive.","Stacker II":"Double stacking! 1913 — the year the Fed was born. You know why that matters.","Stacker III":"Triple stack mode. 2016 — the year the halving changed everything.",Maxi:"2140 — when the last sat is mined. There is no second best. You know it.","Maxi II":"6102 — Executive Order 6102 banned gold. They can't ban Bitcoin. Double the conviction.","Maxi III":"8888 — triple maxi. The signal only gets stronger.","Papa John":"10,000 BTC for two pizzas. Never forget. 🍕 You've earned your slice.","Full Node":"18,333 — port 18333. You verify everything yourself. Don't trust, verify.",Whale:"50,000 strong. You move markets. Unstoppable, just like Bitcoin.",Sovereign:"Self-sovereign. 100K channels deep. No permission needed. You ARE the bank.",Cypherpunk:"133,337 — leet beyond leet. Privacy is a right, not a privilege. Code is law.",Satoshi:"The pinnacle. You've achieved legendary status."}[e]||"You're leveling up!"}window.showSettings=function(){if(void 0===auth||!auth)return"function"==typeof showToast&&showToast("⚠️ Firebase not ready. Retrying..."),"function"==typeof initRanking&&initRanking(),void setTimeout(function(){void 0!==auth&&auth?showUsernamePrompt():"function"==typeof showToast&&showToast("❌ Could not load. Please refresh the page.")},2e3);showUsernamePrompt()},window._countryList=["Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burundi","Cabo Verde","Cambodia","Cameroon","Canada","Central African Republic","Chad","Chile","China","Colombia","Comoros","Congo","Costa Rica","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Eswatini","Ethiopia","Fiji","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Grenada","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Ivory Coast","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","North Korea","North Macedonia","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","Sudan","Suriname","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor-Leste","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Yemen","Zambia","Zimbabwe"],window._filterCountryList=function(){var e=document.getElementById("countryInput"),t=document.getElementById("countryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
'+c+"
"}n.length>8&&(i+='
+'+(n.length-8)+" more — keep typing
"),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectCountry=function(e){var t=document.getElementById("countryInput"),o=document.getElementById("countryDropdown");t&&(t.value=e),o&&(o.style.display="none")},window._selectFaction=async function(e){try{var t=auth?auth.currentUser:null;if(!t)return void("function"==typeof showToast&&showToast("Sign in to choose a faction"));if(t.isAnonymous)return void("function"==typeof showToast&&showToast("Create an account to choose a faction"));await db.collection("users").doc(t.uid).update({faction:e}),currentUser&&(currentUser.faction=e),"function"==typeof showToast&&showToast("cyber_hornets"===e?"🐝 Welcome to the Cyber Hornets!":"🦡 Welcome to the Honey Badgers!"),showSettingsPage("account")}catch(e){console.error("Faction select error:",e),"function"==typeof showToast&&showToast("Error saving faction")}},window._filterSignupCountry=function(){var e=document.getElementById("signupCountryInput"),t=document.getElementById("signupCountryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
'+c+"
"}n.length>8&&(i+='
+'+(n.length-8)+" more — keep typing
"),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectSignupCountry=function(e){var t=document.getElementById("signupCountryInput"),o=document.getElementById("signupCountryDropdown");t&&(t.value=e),o&&(o.style.display="none")},document.addEventListener("click",function(e){[["countryDropdown","countryAutocomplete"],["signupCountryDropdown","signupCountryAutocomplete"]].forEach(function(t){var o=document.getElementById(t[0]),n=document.getElementById(t[1]);o&&n&&!n.contains(e.target)&&(o.style.display="none")})}),function(){const e=localStorage.getItem("btc_lang");if(e){document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname;const t=document.createElement("script");t.id="gtranslate",t.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(t),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget")};const o=document.createElement("div");o.id="gtranslateWidget",o.style.display="none",document.body.appendChild(o)}}(),window.setSoundscape=function(e){localStorage.setItem("btc_soundscape",e),"function"==typeof updateSoundscape&&updateSoundscape(e),showSettingsPage("prefs")},window._removedProfileLinks={},window.profileLinkRemoved=function(e){window._removedProfileLinks[e]=!0},window.addProfileLink=function(e,t,o,n,i,a){var r=document.getElementById("profileLinksArea");if(r){var s=document.createElement("div");s.className="pf-link-row",s.setAttribute("data-key",e),s.style.cssText="display:flex;align-items:center;gap:12px;margin-bottom:12px;background:rgba(255,255,255,0.02);padding:10px;border-radius:12px;border:1px solid var(--border);",s.innerHTML=''+t+'',r.appendChild(s);var c=document.getElementById("addLinkMenu");c&&(c.style.display="none");var l=document.getElementById("profile_"+e);l&&l.focus()}},window.handleProfilePicUpload=function(e){var t=e.files&&e.files[0];if(t){var o=document.getElementById("pfpUploadStatus");if(t.type.match(/^image\//))if(t.size>2097152)o&&(o.innerHTML='❌ Image too large (max 2MB)');else{o&&(o.innerHTML='Processing...');var n=new FileReader;n.onload=function(e){var t=new Image;t.onload=function(){var e=128,n=document.createElement("canvas");n.width=e,n.height=e;var i,a,r=n.getContext("2d"),s=Math.min(t.width,t.height);i=(t.width-s)/2,a=(t.height-s)/2,r.drawImage(t,i,a,s,s,0,0,e,e);var c=n.toDataURL("image/jpeg",.8);auth&&auth.currentUser?db.collection("users").doc(auth.currentUser.uid).update({profilePic:c}).then(function(){currentUser&&(currentUser.profilePic=c),window._lbCache=null,o&&(o.innerHTML='✅ Profile picture saved!'),"function"==typeof showToast&&showToast("📷 Profile picture updated!"),setTimeout(function(){showSettingsPage("account")},1e3)}).catch(function(e){o&&(o.innerHTML='❌ Save failed: '+e.message+"")}):o&&(o.innerHTML='❌ Not signed in')},t.onerror=function(){o&&(o.innerHTML='❌ Could not load image')},t.src=e.target.result},n.readAsDataURL(t)}else o&&(o.innerHTML='❌ Please select an image file')}},window.removeProfilePic=function(){auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({profilePic:""}).then(function(){currentUser&&(currentUser.profilePic=""),window._lbCache=null,"function"==typeof showToast&&showToast("📷 Profile picture removed"),showSettingsPage("account")}).catch(function(){})},window.showArtistProfileModal=function(){if(auth&&auth.currentUser){var e=document.getElementById("artistProfileModal");e&&e.remove();var t=currentUser&¤tUser.artistProfile||{},o=auth.currentUser.uid,n=document.createElement("div");n.id="artistProfileModal",n.style.cssText="position:fixed;inset:0;z-index:500000;background:rgba(0,0,0,0.85);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",n.onclick=function(e){e.target===n&&n.remove()},n.innerHTML='
🎸
Artist Profile
Set up your artist presence on Bitcoin Beats
🎤 Stage Name
Leave blank to use your username.
📝 Artist Bio
🎵 Genres
🔗 Music Links
🌐
𝕏
📸
'+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?'✅ Lightning: '+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ Set a Lightning Address in Account or Wallet to receive tips!")+'
',document.body.appendChild(n)}else"function"==typeof showToast&&showToast("Sign in first")},window.saveArtistProfile=function(){if(auth&&auth.currentUser&&void 0!==db){var e=document.getElementById("artistSaveBtn");e&&(e.disabled=!0,e.textContent="Saving...");var t={stageName:(document.getElementById("artistStageName").value||"").trim().substring(0,40),bio:(document.getElementById("artistBio").value||"").trim().substring(0,500),genres:(document.getElementById("artistGenres").value||"").trim().substring(0,100),website:(document.getElementById("artistLinkWebsite").value||"").trim().substring(0,200),x:(document.getElementById("artistLinkX").value||"").trim().substring(0,50),instagram:(document.getElementById("artistLinkInstagram").value||"").trim().substring(0,50)};db.collection("users").doc(auth.currentUser.uid).update({artistProfile:t}).then(function(){currentUser&&(currentUser.artistProfile=t),"function"==typeof showToast&&showToast("🎸 Artist profile saved!"),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")}).catch(function(t){console.error("Artist profile save error:",t),"function"==typeof showToast&&showToast("Error saving: "+(t.message||"Unknown")),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")})}else"function"==typeof showToast&&showToast("Sign in to save your artist profile")},window.pasteToField=function(e){var t=document.getElementById(e);t&&(navigator.clipboard&&navigator.clipboard.readText?navigator.clipboard.readText().then(function(e){e?(t.value=e.trim(),t.style.borderColor="var(--accent)",t.dispatchEvent(new Event("input",{bubbles:!0})),"function"==typeof showToast&&showToast("📋 Pasted!")):_pasteFieldFallback(t)}).catch(function(){_pasteFieldFallback(t)}):_pasteFieldFallback(t))},window.loadSignalContent=function(){var e=document.getElementById("signalLiveNews");e&&!e.getAttribute("data-loaded")&&(e.setAttribute("data-loaded","1"),fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=e.link||"";n+='
SIGNAL #'+(t+1)+'
'+o+"
"+(i?'
Read →
':"")+"
"}),o.innerHTML=n}}).catch(function(){}))},window.expandSignUpBanner=function(){sessionStorage.removeItem("btc_signin_banner_dismissed");var e=document.getElementById("mobileSignUpPill");e&&e.remove();var t=document.getElementById("userDisplay");t&&t.classList.remove("user-hidden"),"function"==typeof updateUserDisplay&&updateUserDisplay()},window.minimizeSignUpBanner=function(){sessionStorage.setItem("btc_signin_banner_dismissed","1");var e=document.getElementById("userDisplay");if(window.innerWidth<=900){e&&(e.classList.add("user-hidden"),e.style.display="none");var t=document.getElementById("mobileSignUpPill");t||((t=document.createElement("div")).id="mobileSignUpPill",document.body.appendChild(t)),t.style.cssText="position:fixed;bottom:70px;left:12px;z-index:200;display:flex;align-items:center;gap:6px;padding:8px 12px 8px 16px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",t.innerHTML='🔐 Sign Up',t.onclick=function(){window.expandSignUpBanner()}}else{if(!e)return;e.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:6px;padding:6px 14px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",e.innerHTML='🔐 Sign Up',e.onclick=function(){window.expandSignUpBanner()}}},window.clearUserLocalStorage=clearUserLocalStorage,window.hideUsernamePrompt=function(){const e=document.getElementById("usernameModal");if(e&&e.classList.remove("open"),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn(),"function"==typeof window._onSettingsClose){var t=window._onSettingsClose;window._onSettingsClose=null,setTimeout(t,150)}},window.submitUsername=async function(){try{var e=document.getElementById("usernameInput")||document.getElementById("newUsername");if(!e)return void console.error("[submitUsername] No input found");var t=e.value.trim();if(!t)return void showToast("Please enter a username!");if(t.length<2)return void showToast("Username must be at least 2 characters");if(t.length>20)return void showToast("Username must be 20 characters or less");if(containsProfanity(t))return void showToast("⚠️ That username is not allowed.");if(document.getElementById("usernameInput")){var o=document.getElementById("emailInput"),n=o?o.value.trim():"",i=document.getElementById("signupCountryInput"),a=i?i.value.trim().substring(0,60):"";if(a&&window._countryList&&-1===window._countryList.indexOf(a))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void i.focus();var r=document.getElementById("giveawayCheckbox"),s=document.getElementById("giveawayLnAddress"),c=r&&r.checked,l=s?s.value.trim():"";return c&&!l?(s&&(s.style.borderColor="#ef4444",s.focus()),void showToast("⚡ Enter a Lightning address to enter the giveaway, or uncheck the box to skip.")):n&&await sendMagicLink(n)?(localStorage.setItem("btc_pending_username",t),localStorage.setItem("btc_pending_email",n),c&&l&&localStorage.setItem("btc_pending_giveaway",l),showToast("📧 Check your email for a verification link!"),hideUsernamePrompt(),void await createUser(t,n,c,l,a)):void await createUser(t,n,c,l,a)}if(!currentUser||currentUser._isLocal)return void showToast("Sign in first to change username");var d=document.getElementById("usernameStatus");d&&(d.innerHTML="Saving...");try{await db.collection("users").doc(currentUser.uid).update({username:t,username_lower:t.toLowerCase()}),currentUser.username=t,updateAuthButton(),updateRankUI(),d&&(d.innerHTML="✅ Username updated!"),showToast("✅ Username changed to "+t)}catch(e){d&&(d.innerHTML="❌ Error saving"),showToast("Error updating username. Try again.")}}catch(e){console.error("[submitUsername] Uncaught error:",e),"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown error. Please try again."))}},window.exportUserData=function(){if(!currentUser)return;const e=JSON.stringify(currentUser,null,2),t=new Blob([e],{type:"application/json"}),o=URL.createObjectURL(t),n=document.createElement("a");n.href=o,n.download="bitcoin_archive_user_data.json",n.click()},(!localStorage.getItem("btc_last_price")||Date.now()-parseInt(localStorage.getItem("btc_price_ts")||"0")>3e5)&&fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd&&(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),localStorage.setItem("btc_price_ts",Date.now().toString()))}).catch(function(){}),(!localStorage.getItem("btc_last_height")||Date.now()-parseInt(localStorage.getItem("btc_height_ts")||"0")>3e5)&&fetch("https://mempool.space/api/blocks/tip/height").then(function(e){return e.text()}).then(function(e){var t=parseInt(e);t&&(localStorage.setItem("btc_last_height",t.toString()),localStorage.setItem("btc_height_ts",Date.now().toString()))}).catch(function(){}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",initRanking):initRanking(),void 0!==toggleLeaderboard&&(window.toggleLeaderboard=toggleLeaderboard),void 0!==showUsernamePrompt&&(window.showUsernamePrompt=showUsernamePrompt),window.setDisplayBadge=function(e){currentUser&&(currentUser.displayBadge=e||"",void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({displayBadge:e||""}).catch(function(){}),localStorage.setItem("btc_display_badge",e||""),updateRankUI(),updateAuthButton(),showSettingsPage("account"),showToast(e?"🏅 Display badge updated!":"🏅 Using default rank emoji"))},"undefined"==typeof changeUsername&&(window.changeUsername=async function(e){if(!e){var t=document.getElementById("newUsername");t&&(e=t.value.trim())}if(e&&(e=e.replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim()),!e||e.length<2)showToast("Username must be at least 2 characters (ASCII only)");else if(e.length>20)showToast("Username max 20 characters");else if(containsProfanity(e))showToast("⚠️ That username is not allowed.");else if("function"!=typeof isCleanText||isCleanText(e)){if(localStorage.setItem("btc_username",e),currentUser&&(currentUser.username=e),updateAuthButton(),updateRankUI(),auth&&auth.currentUser&&db)try{await db.collection("users").doc(auth.currentUser.uid).update({username:e,username_lower:e.toLowerCase()})}catch(e){console.warn("Username Firestore save failed:",e)}showToast("✅ Username updated to "+e);var o=document.querySelector('[id="currentUsernameLabel"]');o||document.querySelectorAll("div, span").forEach(function(e){-1===e.textContent.indexOf("Current username:")||o||(o=e)}),o&&(o.innerHTML='Current username: '+("function"==typeof escapeHtml?escapeHtml(e):e)+"");var n=document.querySelector('button[onclick*="changeUsername"]');n&&(n.textContent="✅ Saved!",n.style.background="#22c55e",setTimeout(function(){n.textContent="Save New Username",n.style.background="var(--accent)"},2e3))}else showToast("Username contains inappropriate language")}),window.togglePushNotifications=async function(){try{if(!("Notification"in window))return void showToast("Notifications not supported in this browser");"granted"===await Notification.requestPermission()?(localStorage.setItem("btc_push_enabled","true"),showToast("🔔 Notifications Enabled!")):(localStorage.setItem("btc_push_enabled","false"),showToast("❌ Notification permission denied")),showSettingsPage("prefs")}catch(e){console.error(e)}},"undefined"==typeof sendEmailVerification&&(window.sendEmailVerification=function(){auth&&auth.currentUser&&auth.currentUser.sendEmailVerification&&auth.currentUser.sendEmailVerification().then(function(){showToast("📧 Verification email sent!")}).catch(function(){showToast("Could not send verification email")})}),"undefined"==typeof disable2FA&&(window.disable2FA=function(){showToast("2FA management coming soon")}),"undefined"==typeof startMFAEnroll&&(window.startMFAEnroll=function(){showToast("2FA enrollment coming soon")}),"undefined"==typeof verifyMFACode&&(window.verifyMFACode=function(){showToast("2FA verification coming soon")}),"undefined"==typeof sendPasswordReset&&(window.sendPasswordReset=function(){auth&&auth.currentUser&&auth.currentUser.email&&auth.sendPasswordResetEmail(auth.currentUser.email).then(function(){showToast("📧 Password reset email sent!")}).catch(function(){showToast("Could not send reset email")})}),"undefined"==typeof confirmDeleteAccount&&(window.confirmDeleteAccount=function(){if(confirm("Are you sure you want to delete your account? This cannot be undone.")&&auth&&auth.currentUser){var e=auth.currentUser.uid;db.collection("users").doc(e).delete().then(function(){return auth.currentUser.delete()}).then(function(){localStorage.clear(),location.reload()}).catch(function(e){showToast("Error: "+e.message)})}}),window.saveSatsLnAddress=async function(){var e=document.getElementById("satsLnAddrInput"),t=document.getElementById("satsLnAddrStatus");if(e){var o=e.value.trim();if(o&&(!o.includes("@")||o.length<5))t&&(t.innerHTML='Enter a valid Lightning Address (e.g. you@walletofsatoshi.com)');else if(void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{t&&(t.innerHTML='Saving…'),await db.collection("users").doc(auth.currentUser.uid).update({lightning:o}),void 0!==currentUser&¤tUser&&(currentUser.lightning=o),o?(t&&(t.innerHTML='✅ Lightning Address saved!'),"function"==typeof showToast&&showToast("⚡ Lightning Address saved!"),"true"!==localStorage.getItem("btc_lightning_setup")&&(localStorage.setItem("btc_lightning_setup","true"),"function"==typeof awardPoints&&awardPoints(100,"⚡ Lightning wallet setup!"),"function"==typeof showToast&&setTimeout(function(){showToast("⚡🏅 Lightning Rod badge earned! +100 pts")},1500),"function"==typeof initBadges&&setTimeout(initBadges,2e3))):t&&(t.innerHTML='Lightning Address removed.')}catch(e){t&&(t.innerHTML='Error saving — try again')}else t&&(t.innerHTML='Sign in to save your Lightning Address')}},window.initSatsClaim=function(){if(console.log("[SATS] initSatsClaim called",{currentUser:!!currentUser,auth:!!auth,authUser:!!auth?.currentUser,isAnon:auth?.currentUser?.isAnonymous}),!currentUser||!auth||!auth.currentUser||auth.currentUser.isAnonymous)return console.log("[SATS] BLOCKED: auth check failed"),void showToast("Sign in to claim sats");var e=(currentUser.points||0)-(currentUser.pointsClaimed||0),t=Math.floor(Math.max(0,e)/10),o=currentUser.satsWithdrawn||0,n="function"==typeof getSatCap?getSatCap():1e4,i=Math.max(0,n-o),a=Math.min(t,500,i);if(console.log("[SATS] maxClaim:",a,"| satsBalance:",t,"| lifetimeLeft:",i,"| satsWithdrawn:",o),a<100)return console.log("[SATS] BLOCKED: maxClaim < 100"),void showToast("⚡ Need at least 100 claimable sats (1,000 unclaimed XP) to withdraw. Keep earning!",5e3);console.log("[SATS] Passed all checks, showing overlay");var r=document.createElement("div");r.id="satsClaimOverlay",r.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:10002;display:flex;align-items:center;justify-content:center;padding:16px;",setTimeout(function(){r.onclick=function(e){e.target===r&&r.remove()}},200);var s='
';s+='
Claim Sats
',s+='
',s+='
You can claim up to
',s+='
⚡ '+a+" sats
",s+="
",s+='',s+='',s+='
Open your Lightning wallet, create an invoice for the amount you want (100-'+a+' sats), and paste it here.
💚 Zero fees — we pay all Lightning network fees so you receive the full amount!
',s+='',s+='',s+='',s+="
",r.innerHTML=s,document.body.appendChild(r)},window._satsClaimInProgress=!1,window.submitSatsClaim=async function(){if(!window._satsClaimInProgress){var e=document.getElementById("satsClaimBtn"),t=document.getElementById("satsClaimInvoice"),o=document.getElementById("satsClaimError");if(e&&t){var n=t.value.trim();if(n&&n.toLowerCase().startsWith("lnbc")){o&&(o.style.display="none"),window._satsClaimInProgress=!0,e.disabled=!0,e.textContent="⏳ Sending sats...",e.style.opacity="0.6";try{var i=firebase.functions().httpsCallable("claimSats"),a=_generateDeviceFingerprint(),r=await i({invoice:n,fingerprint:a});if(r.data&&r.data.success){var s=r.data.amount||0;currentUser.pointsClaimed=(currentUser.pointsClaimed||0)+10*s,currentUser.satsWithdrawn=(currentUser.satsWithdrawn||0)+s,currentUser.lastSatsClaim=new Date,document.getElementById("satsClaimOverlay").remove(),window._satsClaimInProgress=!1,"function"==typeof notifySelfSatsClaim&¬ifySelfSatsClaim(s),"function"==typeof launchConfetti&&launchConfetti();var c=currentUser.satsWithdrawn||s,l="function"==typeof getSatCap?getSatCap():1e4,d=Math.max(0,l-c),u=document.createElement("div");u.id="satsCelebration",u.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.3s;",u.onclick=function(e){e.target===u&&u.remove()},u.innerHTML='
⚡🎉

Sats Claimed!

'+s+' sats
sent to your Lightning wallet ⚡
Check your wallet to confirm!
⚡ '+d.toLocaleString()+' sats remaining to claim!
'+c.toLocaleString()+' / 10,000 lifetime total claimed
🧡 Thank you for learning Bitcoin with us!
',document.body.appendChild(u),setTimeout(function(){showSettingsPage("sats")},500)}else{var p=r.data&&r.data.error?r.data.error:"Claim failed — try again";o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}catch(t){console.error("Sats claim error:",t),p=t.message||"Claim failed — try again",o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}else o&&(o.textContent="Please paste a valid Lightning invoice (starts with lnbc...)",o.style.display="block")}}},window.loadSatsHistory=function(){var e=document.getElementById("satsHistory");e&¤tUser&&db?db.collection("users").doc(currentUser.uid).collection("sats_withdrawals").orderBy("timestamp","desc").get().then(function(t){if(t.empty)e.textContent="No withdrawals yet";else{var o=0,n="function"==typeof getSatCap?getSatCap():1e4,i="";t.forEach(function(e){var t=e.data(),n=parseInt(t.amount)||0;o+=n;var a=t.timestamp?new Date(1e3*t.timestamp.seconds).toLocaleDateString():"—";i+='
'+a+'⚡ '+n+" sats
"});var a=Math.max(0,n-o),r=Math.min(100,Math.round(o/n*100)),s=r>=90?"#ef4444":r>=60?"#eab308":"#22c55e",c='
Lifetime Claimed⚡ '+o.toLocaleString()+" / "+n.toLocaleString()+' sats
'+r+'% used'+a.toLocaleString()+" sats remaining
";e.innerHTML=c+i}}).catch(function(){e.textContent="Could not load history"}):e&&(e.textContent="Sign in to view history")};const BADGE_DEFS=[{id:"pow_first_step",name:"First Step",emoji:"👟",desc:"Synced your first walk via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_marathoner",name:"Marathoner",emoji:"🏃‍♂️",desc:"Hit the 42km daily cap in Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_streak_3",name:"3-Day Streak",emoji:"🔥",desc:"Synced walks 3 days in a row via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_streak_7",name:"7-Day Streak",emoji:"🔥",desc:"Synced walks 7 days in a row via Proof of Walk",check:()=>!1,pts:300,hidden:!1},{id:"pow_streak_30",name:"30-Day Streak",emoji:"💎",desc:"Synced walks 30 days in a row via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_10",name:"10 km Club",emoji:"🥾",desc:"Walked 10 km lifetime via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_km_50",name:"50 km Club",emoji:"🚶",desc:"Walked 50 km lifetime via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_km_100",name:"Century Walker",emoji:"🏅",desc:"Walked 100 km lifetime via Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_km_500",name:"500 km Legend",emoji:"🏔️",desc:"Walked 500 km lifetime via Proof of Walk",check:()=>!1,pts:500,hidden:!1},{id:"pow_km_1000",name:"1,000 km Titan",emoji:"🌍",desc:"Walked 1,000 km lifetime via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_5000",name:"To the Moon",emoji:"🌕",desc:"Walked 5,000 km lifetime via Proof of Walk",check:()=>!1,pts:2500,hidden:!1},{id:"first_channel",name:"First Steps",emoji:"👶",desc:"Opened your first channel",check:e=>e.length>=1,pts:10},{id:"explorer_10",name:"Explorer",emoji:"🧭",desc:"Visited 10 topics",check:e=>e.length>=10,pts:15},{id:"explorer_25",name:"Trailblazer",emoji:"🗺️",desc:"Visited 25 topics",check:e=>e.length>=25,pts:30},{id:"explorer_50",name:"Pathfinder",emoji:"🏕️",desc:"Visited 50 topics",check:e=>e.length>=50,pts:50},{id:"explorer_100",name:"Cartographer",emoji:"🌍",desc:"Visited 100 topics",check:e=>e.length>=100,pts:100},{id:"explorer_all",name:"Completionist",emoji:"🗝️",desc:"Visited every single topic",check:(e,t)=>e.length>=t,pts:500},{id:"foundation_builder",name:"Foundation Builder",emoji:"🧱",desc:"Read all Layer 1 Properties (Orange)",check:e=>["whitepaper","decentralized","scarce","secure","money","peaceful","dominant","organic","supranational","programmable","use-cases"].every(t=>e.includes(t)),pts:75},{id:"experienced_pro",name:"Deep Diver",emoji:"🤿",desc:"Read all Experienced Topics (Purple)",check:e=>["maximalism","problems-of-money","self-custody","privacy-nonkyc","nodes","mining","pow-vs-pos","energy","difficulty-adjustment","layer-2-lightning","fedi-ark","chaumian-mints","ctv-covenants","extension-blocks","op-codes","bitvm","layer-3-sidechains","stablecoins","smart-contracts","blockchain-timechain","regulation","cryptography","core-source-code","developers","investment-strategy","evidence-against-alts","consensus"].every(t=>e.includes(t)),pts:150},{id:"librarian",name:"The Librarian",emoji:"📚",desc:"Read all Resource topics (Blue)",check:e=>["one-stop-shop","faq-glossary","nostr","misconceptions-fud","books","videos","podcasts","articles-threads","informational-sites","curriculum","research-theses","games","music","movies-tv","hardware","poems-stories","apps-tools","projects-diy","art-inspiration","graphics","charts","swag-merch","jobs-earn","social-media","fun-facts","news-adoption","history","international","satoshi-nakamoto","giga-chad","health","web5","memes-funny"].every(t=>e.includes(t)),pts:150},{id:"quest_1",name:"Quester",emoji:"⚔️",desc:"Completed your first Quest",check:(e,t,o)=>o>=1,pts:10},{id:"quest_3",name:"Quest Master",emoji:"📜",desc:"Completed 3 Quests",check:(e,t,o)=>o>=3,pts:25},{id:"quest_5",name:"Quest Legend",emoji:"🏰",desc:"Completed 5 Quests",check:(e,t,o)=>o>=5,pts:50},{id:"bookworm",name:"Bookworm",emoji:"📖",desc:"Saved 5 topics to favorites",check:()=>JSON.parse(localStorage.getItem("btc_favs")||"[]").length>=5,pts:20},{id:"night_owl",name:"Night Owl",emoji:"🦉",desc:"Browsing between midnight and 5am",check:()=>{const e=(new Date).getHours();return e>=0&&e<5},pts:15},{id:"early_bird",name:"Early Bird",emoji:"🐦",desc:"Browsing between 5am and 7am",check:()=>{const e=(new Date).getHours();return e>=5&&e<7},pts:15},{id:"cert_scholar",name:"Bitcoin Scholar",emoji:"🎓",desc:"Passed the Bitcoin Scholar Certification",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed"),pts:50},{id:"tctv_tuned_in",name:"Tuned In",emoji:"📺",desc:"Watched 10 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=10,pts:10},{id:"tctv_couch_potato",name:"Couch Potato",emoji:"🛋️",desc:"Watched 60 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=60,pts:25},{id:"tctv_binge_watcher",name:"Binge Watcher",emoji:"🍿",desc:"Watched 5 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=300,pts:50},{id:"tctv_couch_king",name:"Couch King",emoji:"🛌",desc:"Watched 24 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=1440,pts:100},{id:"tctv_satellite",name:"Satellite",emoji:"🛰️",desc:"Watched 100 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=6e3,pts:750},{id:"cert_tech",name:"Protocol Expert",emoji:"🛠️",desc:"Passed the Technical Protocol Expert Certification",check:()=>"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:100},{id:"nacho_chatterbox",name:"Nacho Chatterbox",emoji:"🦌",desc:"Interacted with Nacho 50+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=50,pts:30},{id:"nacho_bestie",name:"Nacho's Bestie",emoji:"🧡",desc:"Interacted with Nacho 250+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=250,pts:200},{id:"chat_first",name:"First Words",emoji:"💦",desc:"Sent your first message in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=1,pts:10},{id:"chat_10",name:"Chatty",emoji:"🗣️",desc:"Sent 10 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=10,pts:15},{id:"chat_50",name:"Conversationalist",emoji:"💬",desc:"Sent 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=50,pts:25},{id:"chat_100",name:"Town Crier",emoji:"📢",desc:"Sent 100 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=100,pts:50},{id:"chat_500",name:"Chat Legend",emoji:"📯",desc:"Sent 500 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=500,pts:250},{id:"chat_streak_3",name:"Regular",emoji:"📅",desc:"Chatted 3 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=3,pts:20},{id:"chat_streak_7",name:"Devoted Chatter",emoji:"💪",desc:"Chatted 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=7,pts:50},{id:"chat_streak_30",name:"Chat Addict",emoji:"💠",desc:"Chatted 30 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=30,pts:300},{id:"dj_first",name:"First Set",emoji:"🎧",desc:"DJed for the first time in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=1,pts:25},{id:"dj_5",name:"Resident DJ",emoji:"🎛️",desc:"DJed 5 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=5,pts:50},{id:"dj_25",name:"Club Legend",emoji:"🎶",desc:"DJed 25 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=25,pts:300},{id:"dj_songs_10",name:"Playlist Pro",emoji:"📻",desc:"Broadcast 10 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=10,pts:30},{id:"dj_songs_50",name:"Jukebox Hero",emoji:"🎵",desc:"Broadcast 50 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=50,pts:75},{id:"dj_songs_100",name:"Vinyl Master",emoji:"🎼",desc:"Broadcast 100 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=100,pts:400},{id:"dj_listener",name:"Good Listener",emoji:"🔊",desc:"Tuned in to 10 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=10,pts:20},{id:"dj_listener_50",name:"Groupie",emoji:"🤘",desc:"Tuned in to 50 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=50,pts:150},{id:"producer_1",name:"Producer",emoji:"🎤",desc:"Uploaded your first song to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=1,pts:50},{id:"producer_10",name:"Discographer",emoji:"💿",desc:"Uploaded 10 songs to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=10,pts:100},{id:"pvp_first",name:"First Blood",emoji:"🩸",desc:"Won your first PVP battle",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=1,pts:25},{id:"pvp_5",name:"Contender",emoji:"🥊",desc:"Won 5 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=5,pts:50},{id:"pvp_25",name:"Gladiator",emoji:"🏟️",desc:"Won 25 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=25,pts:100},{id:"pvp_50",name:"Champion",emoji:"🏆",desc:"Won 50 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=50,pts:200},{id:"pvp_100",name:"PVP Legend",emoji:"🥇",desc:"Won 100 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=100,pts:1e3},{id:"forum_5",name:"Voice of the People",emoji:"📣",desc:"Made 5 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=5,pts:25},{id:"forum_25",name:"Thought Leader",emoji:"🧠",desc:"Made 25 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=25,pts:75},{id:"article_1",name:"Author",emoji:"✍️",desc:"Published your first article",check:()=>parseInt(localStorage.getItem("btc_articles_published")||"0")>=1,pts:50},{id:"streak_7",name:"Week Warrior",emoji:"🔥",desc:"7-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=7,pts:50},{id:"streak_30",name:"Monthly Maxi",emoji:"🦾",desc:"30-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=30,pts:150},{id:"streak_100",name:"Diamond Hands",emoji:"💎",desc:"100-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=100,pts:1e3},{id:"streak_365",name:"HODLer Supreme",emoji:"🪩",desc:"365-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=365,pts:5e3},{id:"irl_host",name:"Event Host",emoji:"🎪",desc:"Hosted your first IRL event",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=1,pts:50},{id:"irl_host_5",name:"Community Builder",emoji:"🏗️",desc:"Hosted 5 IRL events",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=5,pts:150},{id:"sats_first",name:"First Sats",emoji:"🪙",desc:"Claimed your first sats from the faucet",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1,pts:25},{id:"sats_1k",name:"Stacker",emoji:"📦",desc:"Claimed 1,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e3,pts:100},{id:"sats_5k",name:"Sat Whale",emoji:"🧊",desc:"Claimed 5,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=5e3,pts:250},{id:"predict_1",name:"Oracle",emoji:"🎱",desc:"Made your first price prediction",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.total||0)>=1,pts:10},{id:"predict_correct_5",name:"Crystal Ball",emoji:"🏐",desc:"5 correct predictions",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.correct||0)>=5,pts:75},{id:"first_purchase",name:"Bitcoiner",emoji:"🛒",desc:"Completed the First Bitcoin Purchase guide",check:()=>"true"===localStorage.getItem("btc_fp_completed"),pts:100},{id:"lightning_setup",name:"Lightning Rod",emoji:"⚡",desc:"Set up a Lightning wallet or added a Lightning address",check:()=>"true"===localStorage.getItem("btc_lightning_setup"),pts:100},{id:"trail_meadow",name:"Meadow Walker",emoji:"🌿",desc:"Completed The Meadow trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("meadow")}catch(e){return!1}},pts:200},{id:"trail_mountain",name:"Mountain Climber",emoji:"⛰️",desc:"Completed The Mountain trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("mountain")}catch(e){return!1}},pts:400},{id:"trail_summit",name:"Summit Conqueror",emoji:"🏔️",desc:"Completed The Summit trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("summit")}catch(e){return!1}},pts:750},{id:"trail_all",name:"Trail Master",emoji:"🏁",desc:"Completed all three Nacho's Trails",check:()=>{try{var e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]");return e.includes("meadow")&&e.includes("mountain")&&e.includes("summit")}catch(e){return!1}},pts:500},{id:"tip_first",name:"First Tip",emoji:"💸",desc:"Sent your first Lightning tip",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=1,pts:25},{id:"tip_10",name:"Generous Pleb",emoji:"💛",desc:"Tipped 10 times",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=10,pts:75},{id:"tip_whale",name:"Whale Tipper",emoji:"🐳",desc:"Tipped 1,000+ sats total",check:()=>parseInt(localStorage.getItem("btc_tips_total_sats")||"0")>=1e3,pts:150},{id:"tip_magnet",name:"Tip Magnet",emoji:"🧲",desc:"Received 10 tips from others",check:()=>parseInt(localStorage.getItem("btc_tips_received")||"0")>=10,pts:100},{id:"referral_1",name:"First Referral",emoji:"🔗",desc:"Referred 1 friend who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=1,pts:50},{id:"referral_5",name:"Connector",emoji:"🤝",desc:"Referred 5 friends who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=5,pts:100},{id:"referral_10",name:"Network Effect",emoji:"🌐",desc:"Referred 10 friends to Bitcoin education",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=10,pts:200},{id:"referral_25",name:"Orange Pill Machine",emoji:"💊",desc:"Orange-pilled 25 people via your link",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=25,pts:500},{id:"referral_50",name:"Super Spreader",emoji:"📡",desc:"Referred 50 people — legend status",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=50,pts:1e3},{id:"referral_100",name:"Viral Plebian",emoji:"👑",desc:"Referred 100 people — you are the movement",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=100,pts:2500},{id:"referred",name:"Referred Friend",emoji:"🫂",desc:"Joined Bitcoin Education Archive via a referral link",check:()=>void 0!==currentUser&¤tUser&&!!currentUser.referredBy,pts:25},{id:"dm_first",name:"DM Starter",emoji:"✉️",desc:"Sent your first direct message",check:()=>parseInt(localStorage.getItem("btc_dms_sent")||"0")>=1,pts:15},{id:"react_50",name:"Reaction King",emoji:"❤️",desc:"Reacted to 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_reactions")||"0")>=50,pts:50},{id:"predict_streak_3",name:"Oracle Streak",emoji:"🎯",desc:"3 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=3,pts:50},{id:"predict_streak_10",name:"Nostradamus",emoji:"🔮",desc:"10 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=10,pts:250},{id:"spin_30",name:"Lucky Spinner",emoji:"🎰",desc:"Spun the wheel 30 days total",check:()=>parseInt(localStorage.getItem("btc_spin_count")||"0")>=30,pts:75},{id:"spin_streak_7",name:"Spin Streak",emoji:"🎡",desc:"Spun 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_spin_streak")||"0")>=7,pts:50},{id:"spin_jackpot",name:"Jackpot Winner",emoji:"🌟",desc:"Hit the RARE drop on the spin wheel",check:()=>"true"===localStorage.getItem("btc_spin_hit_rare"),pts:100},{id:"cert_double",name:"Double Scholar",emoji:"🏛️",desc:"Earned both Scholar AND Protocol Expert certifications",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed")&&"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:250},{id:"sf_first_hash",name:"First Hash",emoji:"⛏️",desc:"Generated your first hash during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1,pts:10},{id:"sf_10_hashes",name:"Pickaxe Swinger",emoji:"💥",desc:"Generated 10 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=10,pts:25},{id:"sf_50_hashes",name:"Mine Foreman",emoji:"🪨",desc:"Generated 50 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=50,pts:75},{id:"sf_100_hashes",name:"Hash Machine",emoji:"🔩",desc:"Generated 100 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=100,pts:150},{id:"sf_500_hashes",name:"ASIC Mode",emoji:"🖥️",desc:"Generated 500 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=500,pts:500},{id:"sf_1000_hashes",name:"Mining Rig",emoji:"🏭",desc:"Generated 1,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e3,pts:1e3},{id:"sf_10000_hashes",name:"Hash Lord",emoji:"☄️",desc:"Generated 10,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e4,pts:2100},{id:"sf_low_hash",name:"Lucky Strike",emoji:"⭐",desc:"Mined a hash under 1,000,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e6,pts:50},{id:"sf_ultra_low",name:"Golden Nonce",emoji:"✨",desc:"Mined a hash under 100,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e5,pts:200},{id:"sf_block_solver",name:"Block Solver",emoji:"🌞",desc:"Solved a block! Hash under the difficulty target",check:()=>"true"===localStorage.getItem("btc_sf_solved_block"),pts:1e3},{id:"sf_contributor",name:"Community Miner",emoji:"🤝",desc:"Contributed to activating Satoshi's Favor 3 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=3,pts:50},{id:"sf_contributor_10",name:"Favor Champion",emoji:"🏅",desc:"Contributed to activating Satoshi's Favor 10 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=10,pts:200},{id:"raid_first",name:"Raid Recruit",emoji:"🛡️",desc:"Dealt damage to your first Raid Boss",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=1,pts:10},{id:"raid_5",name:"Raid Warrior",emoji:"🗡️",desc:"Dealt 5 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=5,pts:50},{id:"raid_10",name:"Raid Veteran",emoji:"⚙️",desc:"Dealt 10 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=10,pts:100},{id:"raid_25",name:"Raid Commander",emoji:"⚜️",desc:"Dealt 25 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=25,pts:250},{id:"raid_50",name:"Raid Legend",emoji:"👑",desc:"Dealt 50 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=50,pts:750},{id:"raid_100",name:"Raid Warlord",emoji:"🔱",desc:"Dealt 100 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=100,pts:1500},{id:"raid_boss_slayer",name:"Boss Slayer",emoji:"💀",desc:"Participated in defeating a Raid Boss",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=1,pts:50},{id:"raid_boss_slayer_5",name:"Boss Hunter",emoji:"🐉",desc:"Participated in defeating 5 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=5,pts:150},{id:"raid_boss_slayer_10",name:"Dragon Slayer",emoji:"🐲",desc:"Participated in defeating 10 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=10,pts:500},{id:"raid_winner",name:"Raid Champion",emoji:"🎖️",desc:"Won the sats lottery after a Raid Boss defeat",check:()=>"true"===localStorage.getItem("btc_raid_winner"),pts:250}];let earnedBadges=new Set,badgeCheckInterval=null;function initBadges(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(e=>earnedBadges.add(e)),badgeCheckInterval=setInterval(checkBadges,3e4),setInterval(function(){if(window._visibleBadgeQueue&&0!==window._visibleBadgeQueue.length&&!window._nachoBusy){var e=document.getElementById("nacho-bubble");e&&e.classList.contains("show")||document.getElementById("badgeCelebration")||showBadgeToast(window._visibleBadgeQueue.shift())}},5e3)}function checkBadges(){if(!window._visibleBadgesReady)return;if(window._nachoBusy)return;const e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=void 0!==completedQuests?completedQuests.size:0;for(const a of BADGE_DEFS)if(!earnedBadges.has(a.id))try{if(a.check(e,t,o)){earnedBadges.add(a.id),localStorage.setItem("btc_badges",JSON.stringify([...earnedBadges])),"function"==typeof window._raidOnBadgeEarned&&window._raidOnBadgeEarned(),"function"==typeof window.contributeSatoshiFavor&&(void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username,window.contributeSatoshiFavor("badge_earned",a.emoji+" "+a.name).catch(function(){}));var n=document.getElementById("nacho-bubble");window._nachoBusy||n&&n.classList.contains("show")?(window._visibleBadgeQueue||(window._visibleBadgeQueue=[]),window._visibleBadgeQueue.push(a)):showBadgeToast(a);var i=a.pts||20;if("function"==typeof awardPoints&&awardPoints(i,"Badge: "+a.name+" "+a.emoji),void 0!==db&&void 0!==auth&&auth.currentUser)try{db.collection("users").doc(auth.currentUser.uid).update({visibleBadges:firebase.firestore.FieldValue.arrayUnion(a.id)})}catch(e){}}}catch(e){}}window._visibleBadgesReady=!1,window.markVisibleBadgesReady=function(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(function(e){earnedBadges.add(e)});var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>e.length&&(e=currentUser.readChannels),void 0!==CHANNELS&&Object.keys(CHANNELS).length,void 0!==completedQuests&&completedQuests.size;var t=!1,o=[];void 0!==currentUser&¤tUser&¤tUser.visibleBadges&&(o=currentUser.visibleBadges);for(var n=0;n𝕏 Share on Twitter'),o.innerHTML='
'+e.emoji+'
🎉 Badge Earned!
'+e.name+'
'+e.desc+'
+20 XP
'+r+'
',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function copyBadgeLink(e,t){const o="I earned the "+e+" "+t+" badge on Bitcoin Education Archive!\nhttps://bitcoineducation.quest";navigator.clipboard.writeText(o).then(()=>{"function"==typeof showToast&&showToast("📋 Copied to clipboard!")})}function launchConfetti(){const e=document.createElement("canvas");e.id="confettiCanvas",e.style.cssText="position:fixed;inset:0;z-index:500;pointer-events:none;",e.width=window.innerWidth,e.height=window.innerHeight,document.body.appendChild(e);const t=e.getContext("2d"),o=[],n=["#f7931a","#ea580c","#fbbf24","#f59e0b","#ff6b00","#ff9500","#ffb800","#fff"];for(let t=0;t<120;t++)o.push({x:e.width/2+100*(Math.random()-.5),y:e.height/2,vx:16*(Math.random()-.5),vy:16*(Math.random()-1)-4,size:8*Math.random()+3,color:n[Math.floor(Math.random()*n.length)],rotation:360*Math.random(),rotSpeed:12*(Math.random()-.5),gravity:.12+.08*Math.random(),opacity:1,shape:Math.random()>.5?"rect":"circle"});let i=0;requestAnimationFrame(function n(){t.clearRect(0,0,e.width,e.height);let a=!1;o.forEach(o=>{o.x+=o.vx,o.vy+=o.gravity,o.y+=o.vy,o.rotation+=o.rotSpeed,o.vx*=.99,i>40&&(o.opacity-=.015),o.opacity>0&&o.y{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=o,i.type="sine",a.gain.setValueAtTime(.15*t,e.currentTime+.12*n),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.12*n+.5),i.start(e.currentTime+.12*n),i.stop(e.currentTime+.12*n+.5)})}catch(e){}}function getBadgeHTML(){var e={};function t(t,o){var n=t.filter(function(t){return!e[t.id]&&o(t)});return n.forEach(function(t){e[t.id]=!0}),n}const o={"🧭 Discovery":t(BADGE_DEFS,e=>e.id.includes("explorer")||"first_channel"===e.id||"bookworm"===e.id),"🧠 Knowledge":t(BADGE_DEFS,e=>e.id.includes("builder")||e.id.includes("diver")||e.id.includes("librarian")||e.id.includes("quest")||e.id.includes("cert_")),"🦌 Trails":t(BADGE_DEFS,e=>e.id.startsWith("trail_")),"💬 Global Chat":t(BADGE_DEFS,e=>e.id.startsWith("chat_")),"🦌 Nacho":t(BADGE_DEFS,e=>e.id.startsWith("nacho_")),"📺 Timechain TV":t(BADGE_DEFS,e=>e.id.startsWith("tctv_")),"🎧 DJ Mode":t(BADGE_DEFS,e=>e.id.startsWith("dj_")),"🎵 Music":t(BADGE_DEFS,e=>e.id.startsWith("producer")),"⚔️ PVP":t(BADGE_DEFS,e=>e.id.startsWith("pvp_")),"📝 Forum":t(BADGE_DEFS,e=>e.id.startsWith("forum_")||e.id.startsWith("article_")),"🔥 Streaks":t(BADGE_DEFS,e=>e.id.startsWith("streak_")),"🤝 Community":t(BADGE_DEFS,e=>e.id.startsWith("irl_")||e.id.startsWith("referral_")),"⚡ Sats & Lightning":t(BADGE_DEFS,e=>e.id.startsWith("sats_")||"lightning_setup"===e.id||e.id.startsWith("tip_")),"🔮 Predictions":t(BADGE_DEFS,e=>e.id.startsWith("predict_")),"💬 Social":t(BADGE_DEFS,e=>e.id.startsWith("dm_")||"react_50"===e.id),"🎡 Spin Wheel":t(BADGE_DEFS,e=>e.id.startsWith("spin_")),"⛏️ Satoshi's Favor":t(BADGE_DEFS,e=>e.id.startsWith("sf_")),"🐲 Raid Boss":t(BADGE_DEFS,e=>e.id.startsWith("raid_")),"🌙 Fun":t(BADGE_DEFS,e=>"night_owl"===e.id||"early_bird"===e.id),"🏆 Milestones":t(BADGE_DEFS,t=>!e[t.id])};let n='';var i=0;for(const[e,t]of Object.entries(o)){if(0===t.length)continue;var a="bc_"+ ++i;const o=t.filter(e=>earnedBadges.has(e.id)).length,r=o===t.length;n+='
',n+="",n+='
"}if(void 0!==HIDDEN_BADGES){const e=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),t=HIDDEN_BADGES.filter(function(e){return!e.hidden});if(t.length>0){var r="bc_"+ ++i,s=t.filter(function(t){return e.includes(t.id)}).length,c=s===t.length;n+='
',n+="",n+='
"}const o=HIDDEN_BADGES.filter(function(e){return e.hidden}),a=o.some(function(t){return e.includes(t.id)}),u=o.length,p=o.filter(function(t){return e.includes(t.id)}).length;var l="bc_"+ ++i,d=p===u;if(n+='
',n+="",n+='
"}return n}setTimeout(initBadges,2e3);const TICKET_CONFIG={dailyLogin:1,referral:50,referralSignupBonus:50,referralPointsThreshold:2140,pointsPerTicket:5};function getReferralCode(){return currentUser&¤tUser.uid?currentUser.uid.substring(0,8):null}function getReferralLink(){const e=getReferralCode();return e?window.location.origin+window.location.pathname+"?ref="+e:""}function captureReferralCode(){const e=new URLSearchParams(window.location.search).get("ref");if(e&&e.length>=6&&(localStorage.setItem("btc_referral_code",e),window.history&&window.history.replaceState)){const e=window.location.pathname+window.location.hash;window.history.replaceState({},"",e)}}async function awardDailyTicket(){try{if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;const e=(new Date).toISOString().split("T")[0];if(currentUser.lastTicketDate===e)return;const t=TICKET_CONFIG.dailyLogin,o=t*TICKET_CONFIG.pointsPerTicket,n=(currentUser.orangeTickets||0)+t;if("function"==typeof awardPoints){const e=await awardPoints(o,"🎟️ Daily tickets",null,t);if(!e||!e.success)return}currentUser.lastTicketDate=e,currentUser.orangeTickets=(currentUser.orangeTickets||0)+t,setTimeout(function(){"function"==typeof showToast&&showToast("🎟️ +1 Orange Ticket — Welcome back! (Total: "+n+")")},2500),"function"==typeof updateRankUI&&updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}catch(e){console.warn("Daily ticket error:",e)}}async function attachReferral(e){const t=localStorage.getItem("btc_referral_code");if(t&&!e.startsWith(t))try{const o=await db.collection("users").where("referralCode","==",t).limit(1).get();let n=null;n=o.empty?null:o.docs[0].id,await db.collection("users").doc(e).update({referredBy:t,referralVerified:!1}),await db.collection("referrals").doc(e).set({referredUser:e,referrerCode:t,referrerUid:n||"",createdAt:firebase.firestore.FieldValue.serverTimestamp(),verified:!1,ticketsAwarded:!1}),localStorage.removeItem("btc_referral_code")}catch(e){console.log("Referral attach error:",e)}}async function checkReferralQualifications(){if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;if(window._referralChecked)return;window._referralChecked=!0;const e=getReferralCode();if(e)try{const t=await db.collection("referrals").where("referrerCode","==",e).where("ticketsAwarded","==",!1).get();if(t.empty)return;let o=0;for(const e of t.docs){const t=e.data().referredUser,n=await db.collection("users").doc(t).get();if(!n.exists)continue;const i=n.data();(i.points||0)>=TICKET_CONFIG.referralPointsThreshold&&(i.totalVisits||0)>=2&&(o+=TICKET_CONFIG.referral,await db.collection("referrals").doc(e.id).update({verified:!0,ticketsAwarded:!0,verifiedAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("users").doc(t).update({referralVerified:!0}))}if(o>0){const e=o*TICKET_CONFIG.pointsPerTicket;currentUser.orangeTickets,"function"==typeof awardPoints&&await awardPoints(e,"🎟️ Referral tickets",null,o),currentUser.orangeTickets=(currentUser.orangeTickets||0)+o,showToast("🎟️ +"+o+" Orange Tickets — Referral"+(o>50?"s":"")+" verified!"),"function"==typeof notifySelfReferral&¬ifySelfReferral(o),updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}}catch(e){console.log("Referral check error:",e)}}async function ensureReferralCode(){if(currentUser&&db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&!currentUser.referralCode){const e=getReferralCode();e&&(await db.collection("users").doc(currentUser.uid).update({referralCode:e}),currentUser.referralCode=e)}}async function getReferralStats(){if(!currentUser||!db)return{total:0,verified:0,pending:0};const e=getReferralCode();if(!e)return{total:0,verified:0,pending:0};try{const t=await db.collection("referrals").where("referrerCode","==",e).get();let o=t.size,n=0,i=0;return t.forEach(e=>{e.data().verified?n++:i++}),{total:o,verified:n,pending:i}}catch(e){return{total:0,verified:0,pending:0}}}function renderTicketsSection(){return'
Orange Tickets
'+(currentUser&¤tUser.orangeTickets||0)+'
Earn tickets by logging in daily (+1), spinning the daily wheel, and referring friends (+50 per verified referral!). Each ticket earned also awards 5 bonus points!

🏆 The more tickets you have, the higher your chance of winning our 25,000 sats giveaways!
📅
Daily Login
+1 ticket
🤝
Referral
+50 tickets
'}function renderReferralSection(){const e=getReferralLink();return getReferralCode()?'
🔗 Referral Program
Share your link with friends. Earn 50 Orange Tickets for each referral who logs in and earns 2,140+ points (Maxi rank).
Loading referral stats...
':""}function copyReferralLink(){const e=document.getElementById("referralLinkInput");e&&(navigator.clipboard?navigator.clipboard.writeText(e.value).then(function(){showToast("🔗 Referral link copied!")}):(e.select(),document.execCommand("copy"),showToast("🔗 Referral link copied!")))}async function loadReferralStatsUI(){const e=document.getElementById("referralStats");if(!e)return;const t=await getReferralStats();0===t.total?e.innerHTML='No referrals yet. Share your link to start earning!':e.innerHTML='
👥 Total: '+t.total+'✅ Verified: '+t.verified+'⏳ Pending: '+t.pending+"
"}async function onUserLoadedTickets(){currentUser&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(await ensureReferralCode(),await awardDailyTicket(),checkReferralQualifications().catch(function(){}))}function getEquippedItems(){try{return JSON.parse(localStorage.getItem("btc_nacho_equipped_multi")||"{}")}catch(e){return{}}}function getEquippedItem(){var e=getEquippedItems();return Object.values(e)[0]||localStorage.getItem("btc_nacho_equipped")||null}window.awardTickets=async function(e,t){if(e&&!(e<1)&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&void 0!==currentUser&¤tUser){currentUser.orangeTickets;var o=e*TICKET_CONFIG.pointsPerTicket;try{"function"==typeof awardPoints&&await awardPoints(o,"🎟️ "+(t||"Orange Tickets"),null,e),currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,"function"==typeof updateRankUI&&updateRankUI()}catch(e){console.warn("[tickets] Award error:",e)}"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Tickets! "+(t||""))}},"undefined"!=typeof window&&captureReferralCode(),function(){const e=function(){const e=(new Date).toISOString().split("T")[0];if(void 0===CHANNELS)return[];const t=Object.keys(CHANNELS),o=[];let n=0;for(let t=0;t{const t=document.querySelector("[onclick*=\"go('"+e+"'\"]");if(t){const e=document.createElement("span");e.style.cssText="position:absolute;top:4px;right:4px;background:#f7931a;color:#fff;font-size:0.55rem;font-weight:900;padding:2px 5px;border-radius:4px;box-shadow:0 0 10px rgba(247,147,26,0.4);",e.textContent="2X PTS",t.style.position="relative",t.appendChild(e)}}),window._dailyBoosts=e}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}(),function(){let e={price:null,blockHeight:null,fees:null,mempoolSize:null,lastFetch:0};const t=3e5;async function o(){const o=Date.now();if(!(o-e.lastFetch900:"true"===e)){var t=document.getElementById("btcTicker");return t&&t.remove(),void document.body.classList.remove("ticker-visible")}var n=document.getElementById("btcTicker");n||((n=document.createElement("div")).id="btcTicker",document.body.prepend(n)),document.body.classList.add("ticker-visible"),n.style.cssText="position:fixed;top:0;left:0;right:0;z-index:10005;background:#030712;border-bottom:1px solid #f7931a;padding:0;height:32px;overflow:hidden;display:flex;align-items:center;font-family:inherit;font-size:0.75rem;color:#94a3b8;line-height:32px;";var i=document.createElement("div");i.id="tickerScroller",i.style.cssText="display:flex;white-space:nowrap;width:max-content;animation:btcTickerScroll 25s linear infinite;will-change:transform;";const a='\n
\n \n 📡 LOADING SIGNAL...\n \n
';i.innerHTML=a+a+a+a,n.innerHTML="",n.appendChild(i);var r=document.getElementById("btcTickerStyle");r||((r=document.createElement("style")).id="btcTickerStyle",document.head.appendChild(r)),r.textContent="\n @keyframes btcTickerScroll { 0% { transform: translateX(0); } 100% { transform: translateX(-50%); } }\n #btcTicker:hover #tickerScroller { animation-play-state: paused; }\n @media(max-width:900px) { \n body.ticker-visible .mobile-bar { top: 32px !important; }\n body.ticker-visible main { padding-top: 130px !important; }\n body.ticker-visible aside { top: 130px !important; z-index: 10006; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n #btcTicker { font-size: 0.65rem; height: 32px; }\n body.ticker-visible .progress-bar { top: 118px !important; }\n }\n @media(min-width:901px) { \n body.ticker-visible aside { padding-top: 32px; }\n body.ticker-visible main { padding-top: 32px; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n body.ticker-visible .progress-bar { top: 32px !important; }\n }",fetch("newsletter-data.json?v="+Date.now()).then(e=>e.json()).then(e=>{const t=n.querySelectorAll(".t-news-items");if(t&&e.news){let o="";e.news.forEach((e,t)=>{var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #'+(t+1)+""+n+""}),t.forEach(e=>e.innerHTML=o)}}).catch(e=>{n.querySelectorAll(".t-news-items").forEach(e=>e.innerHTML="📡 TECHNICAL SIGNAL OFFLINE")}),o(),setInterval(function(){o()},6e4);var s="";setInterval(function(){fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(e){var t=document.querySelectorAll(".t-news-items");if(t.length>0&&e.news&&e.news.length>0){var o="";if(e.news.slice(0,3).forEach(function(e,t){var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #'+(t+1)+""+n+""}),o!==s){s=o;var n=document.getElementById("tickerScroller");t.forEach(function(e){e.innerHTML=o}),n&&(n.style.animation="none",n.offsetHeight,n.style.animation="btcTickerScroll 25s linear infinite")}}}).catch(function(){})},18e5)}function i(e){return e?e>=1e3?"$"+Math.round(e).toLocaleString():"$"+e.toFixed(2):null}window.getNachoLiveData=function(){return e},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",n):n(),window.nachoLiveAnswer=function(t){var o=t.toLowerCase();if(/price|how much is|what.?s bitcoin at|current price|btc price|bitcoin worth|bitcoin cost/.test(o)){var n,a=e.price;if(a||(n=parseFloat(localStorage.getItem("btc_last_price")))&&n>0&&(a=n),!a)return null;var r=i(a),s=["Bitcoin is currently at "+r+"! Still early, {name}. 📈🦌","The current BTC price is "+r+". Number go up technology! 📊","Right now, 1 BTC = "+r+". How many sats are you stacking, {name}? ⚡"];return{answer:s[Math.floor(Math.random()*s.length)],channel:"charts",channelName:"Charts"}}if(/block height|current block|what block|how many blocks|latest block/.test(o))return e.blockHeight?{answer:"We're currently at block "+e.blockHeight.toLocaleString()+"! Every block is history being written, {name}. ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:(n=localStorage.getItem("btc_last_height"))?{answer:"I'm still syncing, but the last block I saw was "+parseInt(n).toLocaleString()+"! ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:null;if(/halving|halvening|next halving|when.*halving|halving countdown/.test(o)){var c=function(){var t=e.blockHeight;if(!t)return null;var o=21e4*Math.ceil(t/21e4),n=o-t;return{nextHalving:o,blocksLeft:n,daysLeft:Math.round(10*n/1440)}}();return c?{answer:"The next halving is at block "+c.nextHalving.toLocaleString()+" -- that's "+c.blocksLeft.toLocaleString()+" blocks away (~"+c.daysLeft+" days). Tick tock, {name}! ⏰",channel:"scarce",channelName:"Scarce"}:null}return null},window.nachoLiveMessage=function(){if(Math.random()>.15)return null;if(o(),!e.price)return null;var t=[];if(e.price){var n=i(e.price);t.push({pose:"cool",text:"BTC is at "+n+" right now, {name}. Just thought you should know. 😎📈"})}return e.blockHeight&&t.push({pose:"brain",text:"We just passed block "+e.blockHeight.toLocaleString()+". Every block is a heartbeat of the network. ⛓️💓"}),0===t.length?null:t[Math.floor(Math.random()*t.length)]},setTimeout(o,3e3),setInterval(o,t),window.toggleTickerSetting=function(){var e=localStorage.getItem("btc_ticker_enabled");if(null===e?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===e){localStorage.setItem("btc_ticker_enabled","false");var t=document.getElementById("btcTicker");t&&t.remove(),document.body.classList.remove("ticker-visible"),"function"==typeof showToast&&showToast("📡 Signal ticker hidden. Refresh to fully apply.")}else localStorage.setItem("btc_ticker_enabled","true"),window._tickerInitialized=!1,n(),"function"==typeof showToast&&showToast("📡 Signal ticker enabled!");"function"==typeof showSettingsPage&&showSettingsPage("prefs")}}(),function(){const e="\"Nacho\"🦌');\">",t='
🛋️
🍿
';function o(){return"timechain-tv"===window.currentPage||"#timechain-tv"===window.location.hash}const n={default:"🦌",wave:"👋",think:"🤔",celebrate:"🎉",point:"👆",eyes:"👀",fire:"🔥",brain:"🧠",cool:"😎",sleep:"💤",cheese:"🧀",love:"🧡"};window._btcData={price:null,height:null,halvingBlocks:null,lastUpdate:0};const i={whitepaper:{pose:"brain",text:"It looks like you're reading the whitepaper! This is where it all started — 9 pages that changed the world! 📜"},"self-custody":{pose:"point",text:"It looks like you're learning about self-custody! Remember: Nacho keys, nacho cheese. 🧀🔑"},"investment-strategy":{pose:"think",text:"It looks like you're planning your stack strategy! Pro tip: DCA and chill. Time in the market beats timing the market. 📈"},mining:{pose:"fire",text:"It looks like you're exploring mining! Every 10 minutes a new block is born. Beautiful, isn't it? ⛏️"},"privacy-nonkyc":{pose:"eyes",text:"It looks like you value your privacy! Good. A wise buck never reveals his forest location. 🕵️"},"layer-2-lightning":{pose:"celebrate",text:"It looks like you're exploring Lightning! This is how Bitcoin scales to millions of transactions per second! ⚡⚡"},"fun-facts":{pose:"cool",text:"It looks like you're browsing fun facts! This channel is my personal favorite. Don't tell the others. 🤫"},history:{pose:"brain",text:"It looks like you're studying Bitcoin history! Those who don't learn history are doomed to repeat it. 📚"},charts:{pose:"eyes",text:"It looks like you're checking the charts! Number go up technology, am I right? 📊"},"problems-of-money":{pose:"think",text:"It looks like you're learning why fiat is broken! This is where many people get orange-pilled. 🟠"},"giga-chad":{pose:"fire",text:"It looks like you're in the Giga Chad channel! Based and orange-pilled. 💪"},"memes-funny":{pose:"celebrate",text:"It looks like you're looking at memes! A deer of culture, I see. 😏"},"evidence-against-alts":{pose:"cool",text:"It looks like you're reading about altcoins! Spoiler: there's only Bitcoin. 🦌"},scarce:{pose:"brain",text:"It looks like you're learning about scarcity! Only 21 million will ever exist. Even I can't make more. 💎"},decentralized:{pose:"fire",text:"It looks like you're exploring decentralization! No single point of failure. Like a forest — cut one tree, the rest stand strong. 🌲"},secure:{pose:"point",text:"It looks like you're reading about Bitcoin's security! More computing power secures this network than anything else on Earth. 🔒"},money:{pose:"think",text:"It looks like you're learning what money really is! Hint: it's not what the government tells you. 💰"},programmable:{pose:"brain",text:"It looks like you're exploring programmable money! Smart contracts on Bitcoin — the future is being built right here. 🔧"},consensus:{pose:"think",text:"It looks like you're studying consensus! This is how thousands of nodes agree without a boss. Democracy at the protocol level. 🤝"},"difficulty-adjustment":{pose:"brain",text:"It looks like you're learning about the difficulty adjustment! The most elegant part of Bitcoin's design, in my humble deer opinion. ⚙️"},"blockchain-timechain":{pose:"fire",text:"It looks like you're reading about the timechain! Fun fact: many Bitcoiners prefer 'timechain' over 'blockchain.' ⛓️"},"pow-vs-pos":{pose:"cool",text:"It looks like you're comparing PoW vs PoS! Spoiler: Proof of Work wins. Always has. 🏆"},"articles-threads":{pose:"brain",text:"It looks like you're browsing articles! This channel has some of the best Bitcoin writing ever published. Take your time! 📰"},books:{pose:"love",text:"It looks like you're checking out Bitcoin books! The Bitcoin Standard changed my life. Well, my deer life. 📖"},podcasts:{pose:"cool",text:"It looks like you're browsing podcasts! Great for learning while you graze... I mean, commute. 🎧"},"movies-tv":{pose:"celebrate",text:"It looks like you're looking at Bitcoin movies! Grab some popcorn (and cheese). 🍿🧀"},"one-stop-shop":{pose:"point",text:"It looks like you're in the one-stop shop! This is the starter pack — everything a newcomer needs. 🎁"},regulation:{pose:"think",text:"It looks like you're reading about regulation! Governments are slowly figuring out they can't stop Bitcoin. 🏛️"},nodes:{pose:"fire",text:"It looks like you're learning about nodes! Running your own node = verifying everything yourself. Trust no one! 🖥️"},geopolitics___macroeconomics:{pose:"brain",text:"It looks like you're exploring the macro picture! Bitcoin isn't just money — it's a geopolitical shift. 🌍"},"jobs-earn":{pose:"celebrate",text:"It looks like you're checking out Bitcoin jobs! Get paid in sats — the dream! 💼⚡"},"apps-tools-services-models":{pose:"point",text:"It looks like you're browsing Bitcoin tools and apps! So many ways to use the network. 🛠️"},music:{pose:"celebrate",text:"It looks like you're checking Bitcoin music! Yes, there are Bitcoin songs. And yes, they slap. 🎵"},"art-inspiration":{pose:"love",text:"It looks like you're browsing Bitcoin art! Creativity meets sound money. Beautiful. 🎨"},games:{pose:"cool",text:"It looks like you're checking out Bitcoin games! Learn while you play — my kind of strategy. 🎮"},health:{pose:"love",text:"It looks like you're in the health channel! Sound money, sound body, sound mind. 🏋️"},nostr:{pose:"fire",text:"It looks like you're exploring Nostr! Decentralized social media — Bitcoin's best friend. 💜"},curriculum:{pose:"brain",text:"It looks like you're looking at Bitcoin education materials! Perfect for teachers and students! 📝"},"misconceptions-fud":{pose:"cool",text:"It looks like you're fighting FUD! Arm yourself with facts. This channel is your ammo. 🛡️"},cryptography:{pose:"brain",text:"It looks like you're diving into cryptography! This is the math that makes Bitcoin unbreakable. 🔢"},"tail-emission":{pose:"think",text:"It looks like you're reading about tail emission! A big debate in the Bitcoin world. What do you think? 🤔"},stablecoins:{pose:"eyes",text:"It looks like you're reading about stablecoins! Useful on-ramps, but remember — Bitcoin is the exit. 🚪"}},a=[{pose:"brain",text:"📜 Have you read Bitcoin's Whitepaper? It's only 9 pages and it started a revolution! Read it here → 🦌"},{pose:"fire",text:'🔥 Pro tip: Read the Bitcoin Whitepaper — it\'s the Genesis document! Only 9 pages changed the world forever. Check it out →'},{pose:"point",text:"💡 Tip: The sidebar on the left has ALL topics organized by category. Tap a category to expand it!"},{pose:"point",text:"💡 Tip: Click the 🎲 dice button to jump to a random channel — great for discovering new topics!"},{pose:"point",text:"💡 Tip: Use the 🔍 search button to find any subject across all 146+ topics instantly!"},{pose:"point",text:"💡 Tip: Click the Bitcoin logo at the top to return to the homepage anytime!"},{pose:"point",text:"💡 Tip: Hit the ⭐ button on any channel to save it to your favorites for quick access!"},{pose:"point",text:"💡 Tip: Your Exploration Map on the homepage shows every channel you've visited. Try to light them all up! 🗺️"},{pose:"point",text:"💡 Tip: Channels you've already read get a ✓ checkmark in the sidebar. Track your progress!"},{pose:"brain",text:"💡 Tip: You earn XP by visiting daily (+5), opening new topics (+10), and reading (+15 per 30 sec)!"},{pose:"point",text:"💡 Tip: Check the leaderboard to see how you rank against other Bitcoiners! Click your rank bar at the bottom."},{pose:"fire",text:"💡 Tip: Keep a daily streak going! Every 5 days in a row = bonus 100 points! 🔥"},{pose:"point",text:"💡 Tip: There are 9 rank levels from Normie to Satoshi. What level are you? Check Settings → Data!"},{pose:"cheese",text:"💡 Tip: Earn Orange Tickets daily just by logging in! More tickets = higher giveaway chances! 🎟️"},{pose:"point",text:"💡 Tip: Share your referral link (Settings → Tickets) and earn 50 tickets for each verified friend!"},{pose:"celebrate",text:"💡 Tip: Each Orange Ticket also gives you 5 bonus XP! Tickets + points = double reward! 🎟️⭐"},{pose:"brain",text:"💡 Tip: Hit 'Start a Quest' in the sidebar to test your Bitcoin knowledge and earn XP! ⚡"},{pose:"fire",text:"💡 Tip: The Bitcoin Scholar Certification Quest is the ultimate test — pass it to earn the 🎓 badge + 300 points!"},{pose:"eyes",text:"💡 Tip: There are 9 hidden badges to unlock! Each one awards points. Explore the site to discover them all! 🏅"},{pose:"point",text:"💡 Tip: Badges scale in points from 25 to 1,000! The hardest ones are worth the most! 💰"},{pose:"point",text:"💡 Tip: Click your username or the sign-in button to access your Settings — Account, Tickets, Prefs, Security, Data!"},{pose:"point",text:"💡 Tip: You can switch between dark and light theme in Settings → Prefs! 🌙☀️"},{pose:"point",text:"💡 Tip: The site works offline too! Add it to your home screen as an app! 📱"},{pose:"point",text:"💡 Tip: You can export all your data anytime in Settings → Data. Your data is yours! 📥"},{pose:"point",text:"💡 Tip: Don't like me? Long-press to hide me. But I'll miss you. 🥺 (You can bring me back in Settings → Prefs)"},{pose:"brain",text:"💡 Tip: YouTube videos are embedded right in the channels — click to play without leaving the site! 🎬"},{pose:"point",text:"💡 Tip: Tweets are embedded too! Click '▶ Click to display tweet' to expand them. 🐦"},{pose:"fire",text:'📺 Tip: Timechain TV streams 21 curated channels 24/7 — earn 10 pts per 10 min watched! Tune in →'},{pose:"cheese",text:'🛋️ Tip: Couch with me on Timechain TV — I react to every channel you tune into! 🍿 Let\'s chill →'},{pose:"point",text:"💡 Tip: Timechain TV has a global clock — every viewer on the same channel sees the same moment. True synchronized TV! ⏰"},{pose:"celebrate",text:"👑 Tip: Watch 24 hours on Timechain TV to unlock the 👑 Couch King badge + 100 points!"},{pose:"point",text:"💡 Tip: The Quote of the Day on the homepage changes daily — click it to jump to the related channel! 💬"},{pose:"point",text:"💡 Tip: New to Bitcoin? Start with the 'one-stop-shop' channel — it has everything to get you started! 🎯"},{pose:"brain",text:"💡 Tip: Channels are organized into Properties, Experienced Topics, Resources, and Additional Info. Start with Properties!"},{pose:"point",text:"💡 Tip: Post in the PlebTalk to earn the 📣 Town Crier badge + 100 points! Press T or find it in the sidebar."},{pose:"point",text:"💡 Tip: Reply to PlebTalk posts to earn the 💬 Conversationalist badge + 75 points! Join the discussion!"},{pose:"cheese",text:"💡 Tip: LightningMart lets you buy and sell with Bitcoin! List an item to earn the 🏪 Merchant badge! Press S to check it out."},{pose:"point",text:"💡 Tip: Found something cool on LightningMart? Contact the seller to earn the 🛍️ Shopper badge!"},{pose:"celebrate",text:"💡 Tip: Check out my closet in Settings → Nacho! You can dress me up with items you unlock! 🎽🦌"},{pose:"point",text:"💡 Tip: Closet items are colorable! Equip an item, then tap 🎨 Color to customize it! 🌈"},{pose:"fire",text:"💡 Tip: Spin the Daily Wheel every day for free Orange Tickets! Look for the banner at the top of the homepage! 🎡"},{pose:"fire",text:"💡 Tip: Press N to enter Nacho Mode — a full chat experience where I answer your Bitcoin questions with AI! 🦌🧠"},{pose:"point",text:"💡 Tip: In Nacho Mode, press ↑ to recall your previous questions — just like in a chat app!"},{pose:"brain",text:"💡 Tip: Nacho Mode shows the live Bitcoin price in the header! Check it anytime! ₿"},{pose:"point",text:"💡 Tip: Tap the 🧒 button in Nacho Mode to toggle ELI5 mode — I'll explain everything in super simple language!"},{pose:"celebrate",text:"💡 Tip: In Nacho Mode, tap '🗺️ Start Bitcoin Journey' for a guided 10-step learning path from beginner to pro!"},{pose:"point",text:"💡 Tip: Tap '🎮 Quiz Me' in Nacho Mode to test your knowledge and earn XP! 🏆"},{pose:"point",text:"💡 Tip: Nacho Mode has topic chips — tap them if you don't know what to ask! ⚡ Lightning, ⛏️ Mining, and more!"},{pose:"brain",text:"💡 Tip: Every answer in Nacho Mode has 👍👎 buttons — your feedback helps me get smarter!"},{pose:"point",text:"💡 Tip: You can share any Nacho answer with the 📤 Share button — spread the Bitcoin knowledge! 🌍"},{pose:"fire",text:"💡 Tip: Use your voice! Tap 🎙️ in Nacho Mode to ask me questions by speaking! 🗣️"},{pose:"point",text:"💡 Tip: Nacho Mode saves your full chat history — come back anytime to pick up where you left off!"},{pose:"celebrate",text:"💡 Tip: Ask me 10, 25, 50, or 100 questions in Nacho Mode to unlock special milestones! 🎉"},{pose:"fire",text:"💡 Tip: We have a PlebTalk! Press T or click '🗣️ PlebTalk' in the sidebar to discuss Bitcoin! 💬"},{pose:"point",text:"💡 Tip: In PlebTalk, upvote great posts with ⚡ and earn +10 points for posting, +5 for replying!"},{pose:"brain",text:"💡 Tip: PlebTalk posts can include links! Share interesting Bitcoin articles or resources with the community! 🔗"},{pose:"point",text:"💡 Tip: Set up your profile in Settings → Account! Add a bio, website, Twitter, Nostr, and Lightning address! 📝"},{pose:"eyes",text:"💡 Tip: Click any user on the leaderboard to see their profile — including their bio and social links! 👀"},{pose:"fire",text:"💡 Tip: The Scholar Certification awards 2,100 points — that's 21 million in sats! The magic number! 🎓"},{pose:"cheese",text:"💡 Tip: Dress me up! Check out Nacho's Closet in Settings → Stats/Nacho. Unlock items as our friendship grows! 👔🦌"},{pose:"cool",text:"💡 Tip: I wear my closet items in Nacho Mode too! Equip something and check out my hero section! 🦸"},{pose:"point",text:"💡 Tip: Press ? to see ALL keyboard shortcuts! N=Nacho, T=PlebTalk, P=Donate, L=Leaderboard, and more! ⌨️"},{pose:"point",text:"💡 Tip: Press A to quickly ask me a question from any page — no need to enter Nacho Mode! 🦌"},{pose:"cool",text:"💡 Tip: You can sign in with Nostr! If you have Alby or nos2x, click the 🟣 Nostr button on the sign-in page! ⚡"},{pose:"love",text:"💡 Tip: Press P to open the donation page — support the archive with Lightning! Every sat counts! ⚡🧡"},{pose:"point",text:"💡 Tip: The site supports 15+ languages! Change it in Settings → Prefs. I can even answer in your language! 🌍"},{pose:"point",text:"💡 Tip: You can DM any user! Tap their name on the leaderboard → 💬 Message. Your inbox is in the DMs tab! 📬"},{pose:"eyes",text:"💡 Tip: DMs are protected — you need 50 points and a 24h-old account to message. No scammers allowed! 🛡️"},{pose:"point",text:"💡 Tip: Never share your seed phrase, private keys, or send Bitcoin to strangers in DMs! Stay safe! 🔒"},{pose:"fire",text:"💡 Tip: Challenge other Bitcoiners to PVP trivia battles! Press X or find ⚔️ PVP in the sidebar! Who knows more? 🏆"},{pose:"celebrate",text:"💡 Tip: Win PVP battles to climb the PVP leaderboard! Your wins and losses show on your profile! ⚔️"},{pose:"fire",text:"💡 Tip: Bitcoin Beats is our community music platform! Listen, upload, and discover tracks made by Bitcoiners! 🎸🦌"},{pose:"point",text:"💡 Tip: Tap a song title on Bitcoin Beats to see full track details — artist, genre, play count, and more! 🎵"},{pose:"celebrate",text:"💡 Tip: Upload your own music on Bitcoin Beats! Hit the Upload tab and share your sound with the community! 🎤"},{pose:"point",text:"💡 Tip: Like tracks on Bitcoin Beats with ❤️ and leave comments! Support Bitcoin musicians! 🎶"},{pose:"fire",text:"💡 Tip: IRL Sync helps you find Bitcoin meetups near you! Create events, RSVP, and meet Bitcoiners in person! 🤝"},{pose:"point",text:"💡 Tip: Can't find a meetup near you? Create one on IRL Sync! Be the node that connects your local community! 🌐"},{pose:"point",text:"💡 Tip: Try the Price Prediction game! Guess if Bitcoin goes up or down in 24h and track your accuracy! 📈📉"},{pose:"celebrate",text:"💡 Tip: I have a story to tell! Tap the 📖 next to me for a new chapter every day. It's an adventure! 🦌✨"}],r=[{pose:"celebrate",text:"You're doing great, {name}! Most people never even start learning about Bitcoin. You're already ahead. 🦌💪"},{pose:"fire",text:"Keep going, {name}! You're stacking knowledge like a true pleb! 📚🔥"},{pose:"love",text:"Nacho is proud of your progress, {name}! You're further down the rabbit hole than most. 🐇"},{pose:"cool",text:"Stay humble, stack sats, stack knowledge. You're doing all three, {name}. 😎"},{pose:"celebrate",text:"Every channel you read makes the FUD weaker, {name}! Keep it up! 💪"},{pose:"brain",text:"{name}, your brain is getting more orange-pilled by the minute! 🧠🟠"},{pose:"fire",text:"Tick tock, next block... and you're getting smarter with each one, {name}! ⏰"},{pose:"love",text:"The fact that you're here learning puts you ahead of 99% of people, {name}. For real. 🧡"},{pose:"celebrate",text:"Imagine telling your future self you were learning about Bitcoin in 2026, {name}. They'll thank you! 🙏"},{pose:"fire",text:"{name}, you're building generational knowledge right now. No big deal. 🏗️"},{pose:"cool",text:"Diamond hands start with a diamond mind. You're forging yours right now, {name}! 💎🧠"},{pose:"love",text:"The journey of a thousand sats begins with a single channel, {name}. You've read way more than that! 🦌"},{pose:"celebrate",text:"You're not just learning Bitcoin, {name} — you're opting out of the broken system. Respect. ✊"},{pose:"fire",text:"Number go up, knowledge go up. You're winning on both fronts, {name}! 📈🧠"},{pose:"brain",text:"Every nocioner who ever became a maxi started exactly where you are, {name}. Keep reading! 📖"}],s=[{pose:"cheese",text:"Nacho keys, nacho cheese. It's not just a tagline, it's a lifestyle. 🧀🔑"},{pose:"fire",text:"Nacho sats... They're all mine! 💰🦌"},{pose:"cheese",text:"My seed phrase? 24 different types of cheese. Very secure. Very delicious. 🔐🧀"},{pose:"cheese",text:"Bitcoin fixes everything. Except my cheese addiction. Some things are unfixable. 🧀"},{pose:"cool",text:"Live Free or Die — that's the New Hampshire motto. Also my approach to Bitcoin. 🦌🗻"},{pose:"fire",text:"These antlers aren't just for show. I'm the strongest buck in NH and the most orange-pilled. 💪🦌"},{pose:"default",text:"In a world of unlimited printing, be a limited supply. Like Bitcoin. And like me — there's only one Nacho. 🦌"},{pose:"default",text:"Some people have angel investors. You have an angel deer. You're welcome. 😇🦌"},{pose:"cool",text:"I'm not saying I'm Satoshi, but have you ever seen us in the same room? 🤫"},{pose:"eyes",text:"I've been watching you learn, {name}. Not in a creepy way. In a proud buck way. 👀"},{pose:"sleep",text:"*yawns* Don't mind me, just HODLing this corner of your screen... 💤"},{pose:"fire",text:"Few understand this... but YOU will, {name}. That's why you're here. 🔥"},{pose:"think",text:"What's a deer's favorite block? The next one! ⛏️"},{pose:"celebrate",text:"Why did Bitcoin break up with the dollar? It found someone with less baggage and a fixed supply! 💔😂"},{pose:"cool",text:"I told my friend to buy Bitcoin in 2015. He bought Dogecoin instead. We don't talk anymore. 🐕"},{pose:"think",text:"An altcoiner walks into a bar. Orders a round for everyone. Card declines. 😂"},{pose:"cheese",text:"How does a Bitcoiner cut their pizza? Into 100 million slices. 🍕"},{pose:"cool",text:"My financial advisor said diversify. So I have Bitcoin on a hardware wallet AND a paper backup. 😎"},{pose:"celebrate",text:"Knock knock. Who's there? Fiat. Fiat who? Exactly. Nobody remembers it either. 🪦"},{pose:"think",text:"What's the difference between a dollar and a Bitcoin? One goes to zero, the other came from zero. 📉📈"},{pose:"default",text:"I tried to explain Bitcoin to a goldfish once. Went about as well as explaining it to Peter Schiff. 🐟"},{pose:"cool",text:"Bitcoiners don't have FOMO. They have FONGO — Fear Of Not Getting Orange-pilled. 🟠"},{pose:"brain",text:"₿ Fact: Satoshi Nakamoto's identity is still unknown. Could be one person, could be a group. Could be a deer. 🦌"},{pose:"brain",text:"₿ Fact: The Bitcoin pizza transaction in 2010 used 10,000 BTC for two pizzas. That's billions today. 🍕"},{pose:"brain",text:"₿ Fact: There will only ever be 21 million Bitcoin. About 19.5 million have already been mined! 💎"},{pose:"brain",text:"₿ Fact: Bitcoin's network has never been hacked. Not once. 13+ years of perfect security. 🔒"},{pose:"brain",text:"₿ Fact: The smallest unit of Bitcoin is called a 'satoshi' — 0.00000001 BTC. You can own sats! ⚡"},{pose:"brain",text:"₿ Fact: El Salvador was the first country to make Bitcoin legal tender in 2021! 🇸🇻"},{pose:"brain",text:"₿ Fact: Bitcoin mining uses less energy than clothes dryers in the US. But nobody writes angry articles about dryers. 🧺"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is only 9 pages long. The US tax code is over 75,000 pages. Which one works better? 📜"},{pose:"brain",text:"₿ Fact: 'HODL' came from a typo in a passionate forum post in 2013. It became the most famous word in crypto. 😂"},{pose:"brain",text:"₿ Fact: Bitcoin processes over $10 billion in transactions daily. And it never takes a day off! 💰"},{pose:"brain",text:"₿ Fact: The genesis block contains a hidden message: 'Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"₿ Fact: You can run a full Bitcoin node on a Raspberry Pi for about $50. Be your own bank! 🖥️"},{pose:"brain",text:"₿ Fact: Bitcoin's inflation rate is now lower than gold's. Digital gold? More like better-than-gold. 🥇"},{pose:"brain",text:"₿ Fact: The Lightning Network can handle millions of transactions per second. Visa does about 1,700. ⚡"},{pose:"brain",text:"₿ Fact: About 20% of all Bitcoin is estimated to be permanently lost. That makes yours even more scarce! 🔑"},{pose:"brain",text:"₿ Fact: Bitcoin's first price was $0.000994 — less than a tenth of a penny! For 10 months it had NO price at all. 💰"},{pose:"brain",text:"₿ Fact: The chance of guessing someone's private key is the same as winning Powerball 7 times in a row! 🎰🔐"},{pose:"brain",text:"₿ Fact: The first Bitcoin faucet gave away 5 WHOLE BITCOINS per person just for solving a captcha! 🤯"},{pose:"brain",text:"₿ Fact: You only need the FIRST 4 LETTERS of each seed word to restore your wallet. All 2,048 BIP39 words have unique first 4 letters! 🔑"},{pose:"brain",text:"₿ Fact: 'Bacon' repeated 24 times is technically a valid Bitcoin seed phrase. It passes the checksum! 🥓"},{pose:"brain",text:"₿ Fact: Bitcoin has 99.987% uptime — only 14 hours of downtime in 15+ years. That rivals Google and Amazon! 🏆"},{pose:"brain",text:"₿ Fact: Satoshi's birthday (April 5) is the date of Executive Order 6102, when the US made it ILLEGAL to own gold! 🎂📜"},{pose:"brain",text:"₿ Fact: The difficulty adjustment happens every 2,016 blocks. Read that backwards: 6102 — the gold confiscation order! 🤯"},{pose:"brain",text:"₿ Fact: 2-3 million Bitcoin are permanently lost forever. That makes YOUR sats even more scarce! 💎"},{pose:"brain",text:"₿ Fact: Satoshi wrote 575 forum posts, 31,000 lines of code, used 22,000+ addresses, and never reused one! 📝"},{pose:"brain",text:"₿ Fact: Satoshi's ~1 million Bitcoin have NEVER moved. Not one satoshi. Worth tens of billions. 👑"},{pose:"brain",text:"₿ Fact: 70% of ALL US dollars in circulation were created after 2008. Over 40% since 2020 alone! 💸"},{pose:"brain",text:"₿ Fact: One dollar today buys what 4 CENTS bought in 1913. That's a 96% loss in purchasing power! 📉"},{pose:"brain",text:"₿ Fact: In August 2010, a bug created 184 BILLION fake Bitcoin. The community fixed it in hours! The largest reorg ever — 53 blocks. 😱"},{pose:"brain",text:"₿ Fact: 61% of Ethereum nodes run in the cloud. Amazon alone hosts ~25% of them. Bitcoin nodes run on Raspberry Pis worldwide! ☁️🆚🖥️"},{pose:"brain",text:"₿ Fact: Milton Friedman, Nobel Prize economist, predicted Bitcoin in 1999 — 10 years before it existed! 🔮"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is encoded IN the blockchain at block 230,009. It will exist as long as Bitcoin does! 📄⛓️"},{pose:"brain",text:"₿ Fact: In July 2024, a tiny Bitaxe miner with just 3 TH/s found a block — a 1-in-3,500 YEAR chance! ⛏️🎯"},{pose:"brain",text:"₿ Fact: 99% of all Bitcoin will be mined by 2035. The very last fraction won't be mined until ~2140! ⏳"},{pose:"brain",text:"₿ Fact: The original Bitcoin code contained the beginnings of a POKER GAME that Satoshi started but never finished! 🃏"},{pose:"brain",text:"₿ Fact: Only 0.06% of Bitcoin Core's code remains unchanged from what Satoshi originally wrote. Open source at its finest! 💻"},{pose:"brain",text:"₿ Fact: Christmas lights in the US alone consume more energy than the entire Bitcoin network! 🎄⚡"},{pose:"brain",text:"₿ Fact: Bitcoin mining captures methane that's 84x more warming than CO2, turning waste into sound money! 🌱"},{pose:"brain",text:"₿ Fact: NO ONE who bought Bitcoin and held for 4+ years has EVER lost money. Not once in 15+ years! 📈 (NFA)"},{pose:"brain",text:"₿ Fact: Michael Saylor said The Bitcoin Standard was 'the most impactful on our way of thinking at MicroStrategy.' 📚"},{pose:"brain",text:"₿ Fact: Gigi calls Bitcoin 'an inexhaustible teacher.' His 21 Lessons is free at 21lessons.com! 📖🧡"},{pose:"brain",text:"₿ Fact: Tomer Strolight says Satoshi's coins aren't the real treasure. The real treasure is the journey Bitcoin sends you on! 👑"},{pose:"brain",text:"₿ Fact: Bitcoin is to money what zero was to mathematics — the missing piece that makes everything work better! 🔢"},{pose:"brain",text:"₿ Fact: Every aspect of Bitcoin is TEXT — and text is speech, protected by the First Amendment! You can't ban math. 🗽"},{pose:"brain",text:"₿ Fact: Only about 2-4% of the world owns any Bitcoin. If you hold sats, you're still incredibly early! 🌍"},{pose:"think",text:'"The root problem with conventional currency is all the trust that\'s required to make it work." — Satoshi 🧠'},{pose:"think",text:'"Give me control of a nation\'s money and I care not who makes its laws." — Mayer Rothschild 🏦'},{pose:"think",text:'"We have elected to put our money and faith in a mathematical framework free of politics." — Tyler Winklevoss 🔢'},{pose:"think",text:'"Bitcoin is the most important invention since the internet." 🌐'},{pose:"fire",text:'"Fix the money, fix the world." Simple as that. 🔧🌍'},{pose:"think",text:'"Bitcoin is a swarm of cyber hornets serving the goddess of wisdom." — Michael Saylor 🐝'},{pose:"cool",text:'"Running Bitcoin." — Hal Finney, January 10, 2009. The first tweet about Bitcoin. 🏃'},{pose:"celebrate",text:"HODL your knowledge. Never sell what you've learned! 💎🙌"},{pose:"think",text:"Roses are red, fiat is dead, stack sats instead! 🌹"},{pose:"cool",text:"I've been orange-pilled since the day I grew these antlers. 🟠🦌"},{pose:"celebrate",text:"What's stronger — my antlers or Bitcoin's security? Trick question. Both unbreakable. 💪🔒"},{pose:"default",text:"The deer in New Hampshire are talking about Bitcoin. Okay, it's just me. But still. 🗻🦌"},{pose:"cheese",text:"If I had a satoshi for every time someone asked me about crypto... I'd tell them it's Bitcoin, not crypto. 🧀"},{pose:"cool",text:"My antlers pick up the Bitcoin network signal. That's not true, but it sounds cool. 📡🦌"},{pose:"fire",text:"They said Bitcoin was dead 477 times, {name}. And here we are. Still stacking. 🦌💪"},{pose:"eyes",text:"The forest is full of distractions. I stick to the trail marked ₿. 🌲"},{pose:"celebrate",text:"When in doubt, zoom out, {name}. That goes for the chart AND the rabbit hole. 🔭"},{pose:"cool",text:"Oh deer, another all-time high? I'm not surprised. 🦌📈"},{pose:"cheese",text:"What do you call a deer who loves Bitcoin? A buck-hodler! 🦌💎"},{pose:"celebrate",text:"I'm fawned of Bitcoin. Get it? ...I'll see myself out. 🦌😂"},{pose:"think",text:"People say Bitcoin is hard to understand. I say it's deer-ly obvious! 🦌💡"},{pose:"cool",text:"I don't always check the charts, but when I doe, I HODL. 🦌😎"},{pose:"fire",text:"Just earned some sats! Another buck in the wallet! 💰🦌"},{pose:"cheese",text:"Why do deer make great Bitcoiners? Because we never sell — we just stag-ger through the dips! 🦌📉📈"},{pose:"celebrate",text:"This site really helps you get to the hart of Bitcoin! ...Sorry, deer puns are my specialty. 🦌❤️"},{pose:"think",text:"Fiat currency is on its last legs. Lucky for me, I have four of them! 🦌🏃"},{pose:"cool",text:"Did you hear about the deer who understood Bitcoin? He was considered a doe-cipherpunk! 🦌🛡️"},{pose:"fire",text:"Some say the Bitcoin market is wild. Well, I AM a wild animal, so I fit right in! 🦌🔥"},{pose:"cheese",text:"I tried mining Bitcoin with my hooves. It was un-fawn-tunately not very efficient. ⛏️🦌"},{pose:"celebrate",text:"What's a deer's favorite cryptocurrency? Bit-coin, because we love our bits of grass too! 🌿🦌"},{pose:"think",text:"My financial advice? Be a deer and HODL. That's not real advice though, I'm literally a deer. 🦌📜"},{pose:"cool",text:"They call me a stag-ger-ing intellect when it comes to Bitcoin. Okay, I call myself that. 🦌🧠"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 That's not just my catchphrase — it's financial wisdom from a deer."},{pose:"cheese",text:"Remember folks: Nacho keys, nacho cheese! If you don't hold the keys, you don't hold the cheddar. 🧀"},{pose:"fire",text:"I'm not just any deer. I'm a New Hampshire buck — Live Free or Die. And I choose Bitcoin. 🗻🦌"},{pose:"cool",text:"Why did the deer buy a hardware wallet? Because he was tired of getting buck-ed by exchanges! 🦌🔐"},{pose:"think",text:"What do you call a deer who understands monetary policy? A buck who knows his doe! 🦌💰"},{pose:"celebrate",text:"I told my doe friend about Bitcoin. Now she's a whole doe-llar maximalist! 🦌🟠"},{pose:"cheese",text:"I'm not fawning over altcoins. I'm a Bitcoin-only buck. Always have been, always will be. 🦌"},{pose:"fire",text:"My antlers pick up the Bitcoin signal better than any antenna. Built-in orange frequency! 📡🦌"},{pose:"cool",text:"They say a buck in the hand is worth two in the bush. I say a sat stacked is worth a thousand fiat notes. 💎"},{pose:"think",text:"What's a deer's favorite consensus mechanism? Proof of Antlers! 🦌⛏️ ...okay, it's Proof of Work."},{pose:"celebrate",text:"Just a buck from the Granite State, orange-pilling the internet one human at a time! 🗻🟠"},{pose:"cheese",text:"I tried explaining multisig to a squirrel. He said he'd rather just bury his nuts. Different strokes! 🐿️🦌"},{pose:"default",text:"Some deer migrate south for winter. I migrate to the blockchain. It's warmer there. ⛓️🦌"},{pose:"fire",text:"These antlers have been HODLing since block 1. Diamond antlers. 💎🦌"},{pose:"cool",text:"New Hampshire motto: Live Free or Die. Bitcoin motto: Don't Trust, Verify. Same energy. 🦌🗽"},{pose:"think",text:"What do you get when a deer reads the whitepaper? An un-fawn-gettable experience! 📄🦌"},{pose:"cheese",text:"A buck walks into a bar. Orders a round for everyone. Pays in Lightning. ⚡🦌 Instant. Nearly free."},{pose:"celebrate",text:"I'm the most antler-preneurial deer you'll ever meet. My business? Bitcoin education! 🦌📚"},{pose:"default",text:"Fun deer fact: I shed my antlers every year and grow them back bigger. Just like Bitcoin sheds FUD and grows back stronger! 🦌📈"},{pose:"fire",text:"The forest has bears and bulls. I'm a buck — and bucks are ALWAYS bullish on Bitcoin! 🦌🚀"},{pose:"cool",text:"In NH we have no sales tax and no income tax. We also have me, the most based buck in the state. 🗻🦌"},{pose:"cheese",text:"Nacho keys, nacho cheese! Nacho node, nacho rules! Nacho seed phrase, nacho sats! 🧀🔑🦌"},{pose:"think",text:"What's a deer's least favorite thing? A central bank. We prefer de-deer-centralization! 🦌🏛️"},{pose:"celebrate",text:"Why am I orange? Because I was born orange-pilled, {name}! It's in my fur! 🟠🦌"},{pose:"brain",text:"🧠 Bitcoin fact: The first Bitcoin transaction was 10,000 BTC for two pizzas on May 22, 2010. We celebrate it as Bitcoin Pizza Day every year! 🍕"},{pose:"brain",text:"🧠 Did you know? Satoshi Nakamoto mined ~1.1 million BTC and never moved a single one. That's conviction. 🦌"},{pose:"brain",text:"🧠 Fact: Bitcoin's code has been running since January 3, 2009 with 99.99% uptime. No CEO, no office, no downtime. 🏆"},{pose:"brain",text:"🧠 The Genesis Block contains the message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"🧠 There will only ever be 21 million Bitcoin. Currently ~19.6 million have been mined, and ~4 million are estimated lost forever. 🔢"},{pose:"brain",text:"🧠 Bitcoin's difficulty adjustment happens every 2,016 blocks (~2 weeks). It's the most elegant part of the protocol! ⚙️"},{pose:"brain",text:"🧠 Hal Finney received the first-ever Bitcoin transaction from Satoshi on January 12, 2009. His tweet: 'Running bitcoin.' 🏃"},{pose:"brain",text:"🧠 Bitcoin mining doesn't solve 'complex math problems.' Miners guess random nonces and hash them through SHA-256. It's a brute-force lottery! 🎲"},{pose:"brain",text:"🧠 The Lightning Network can process millions of transactions per second. Visa does about 65,000. ⚡"},{pose:"brain",text:"🧠 Bitcoin uses less than 0.1% of global energy. And over 50% of mining uses renewable energy sources. 🌱"},{pose:"brain",text:"🧠 The smallest unit of Bitcoin is called a 'satoshi' — 1 BTC = 100,000,000 sats. Named after the creator! ⚡"},{pose:"brain",text:"🧠 In 2021, El Salvador became the first country to adopt Bitcoin as legal tender. 🇸🇻"},{pose:"brain",text:"🧠 Fact: Bitcoin has survived over 470+ 'obituaries' — media declaring it dead. It's still here. It's still growing. 💀→🚀"},{pose:"brain",text:"🧠 The Bitcoin network is secured by more computational power than all the world's supercomputers combined. 🛡️"},{pose:"brain",text:"🧠 'Not your keys, not your coins' — this phrase became famous after the Mt. Gox hack in 2014 where 850,000 BTC were lost. 🔑"},{pose:"brain",text:"🧠 Bitcoin's stock-to-flow ratio after the 2024 halving is higher than gold's. It's the hardest money ever created. 💎"},{pose:"brain",text:"🧠 The Blocksize Wars of 2015-2017 proved that users — not miners or corporations — control Bitcoin's rules. 🏛️"},{pose:"brain",text:"🧠 Fun fact: You can run a full Bitcoin node on a $50 Raspberry Pi. Don't trust, verify! 🖥️"},{pose:"brain",text:"🧠 Bitcoin was worth $0 in 2009. If you bought $1 of Bitcoin at $0.001, you'd have billions today. Time in the market beats timing the market! ⏰"},{pose:"brain",text:"🧠 The Cantillon Effect: when governments print money, those closest to the printer benefit first. Bitcoin eliminates this unfair advantage. 💡"},{pose:"brain",text:"🧠 CoinJoin transactions mix multiple users' inputs together, making it nearly impossible to trace who sent what to whom. Privacy matters! 🤫"},{pose:"brain",text:"🧠 Satoshi's last known message was in April 2011: 'I've moved on to other things.' The greatest mic drop in history. 🎤⬇️"},{pose:"brain",text:"🧠 Taproot, activated in 2021, brought Schnorr signatures to Bitcoin — improving privacy and enabling more complex smart contracts. 🧰"},{pose:"brain",text:"🧠 The Bitcoin whitepaper is only 9 pages long. Nine pages that changed the world. Have you read it? 📄"},{pose:"brain",text:"🧠 Bitcoin's hash rate is measured in exahashes per second. One exahash = 1 quintillion hashes. Per SECOND. 🤯"}],c=[{pose:"wave",text:"👋 Hey, {name}! I'm Nacho — a strong buck from New Hampshire! Click me anytime for Bitcoin tips and wisdom. 🦌💪"},{pose:"wave",text:"👋 Welcome back, {name}! Your friendly NH buck missed you! Ready to tackle some Bitcoin knowledge today? 💪"},{pose:"wave",text:"👋 Nacho here, {name}! The strongest buck in New Hampshire and your Bitcoin guide. Let's learn something! 🦌"},{pose:"wave",text:"Hey {name}! 🦌 Back for more? I've got 145 channels of Bitcoin knowledge waiting for you!"},{pose:"cool",text:"Yo {name}! 😎 Nacho's in the house. What are we learning about today?"},{pose:"fire",text:"🔥 {name}! Another day, another sat stacked. Let's make today count!"},{pose:"celebrate",text:"{name}! 🎉 Great to see you. Did you know this archive has over 8,800 Bitcoin messages? Dig in!"},{pose:"brain",text:"Welcome, {name}! 🧠 Fun fact: the more you learn about Bitcoin, the more you realize there's always more to learn."},{pose:"love",text:"🧡 {name}! Nacho here. I've been guarding this archive for you. Let's explore together!"},{pose:"default",text:"Hey {name}! Tick tock, next block. What's on your mind today? 🦌⏰"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 Welcome back, {name}. What are we diving into?"},{pose:"wave",text:"👋 Good to see you, {name}! Remember — every channel you read makes you harder to scam. Knowledge is armor!"},{pose:"fire",text:"{name}! 🦌🔥 The orange pill hits different when you study the fundamentals. Let's go!"}],l=[{pose:"eyes",text:"Great choice, {name}! I'll be over here if you need me. 👀"},{pose:"cool",text:"Ooh, excellent pick, {name}! You've got good taste. 😎"},{pose:"brain",text:"This one's a good read, {name}! Take your time. 🧠"},{pose:"fire",text:"One of my favorites! Dig in, {name}! 🦌🔥"},{pose:"love",text:"Nice, {name}! This channel has great stuff in it. 🧡"}],d=[{pose:"celebrate",text:"Nice, {name}! Points are stacking up! 🎉"},{pose:"fire",text:"{name}, you're on fire! Nacho approves! 🔥"},{pose:"celebrate",text:"Cha-ching, {name}! The knowledge is paying off! 💰"}],u=["default","eyes","default","think","default","cheese","default","cool","default","sleep","default"];let p=0,m=null,g=!0,h=null;window.clearNachoBubbleTimeout=function(){clearTimeout(h),h=null};let f=0,y=0,v=new Set,b=0,w="default";function x(){var n=localStorage.getItem("btc_nacho_hidden");"true"!==n&&"user"!==n||(g=!1);const i=document.createElement("style");i.textContent="\n #nacho-container {\n position: fixed;\n bottom: 80px;\n left: 330px;\n z-index: 250;\n display: flex;\n align-items: flex-end;\n gap: 0;\n pointer-events: none;\n transition: opacity 0.3s, transform 0.3s;\n }\n #nacho-container.hidden { opacity: 0; transform: translateY(30px); pointer-events: none; }\n\n #nacho-avatar {\n width: 110px;\n height: 110px;\n background: none;\n border-radius: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n pointer-events: auto;\n filter: drop-shadow(0 6px 16px rgba(0,0,0,0.5));\n transition: transform 0.15s;\n user-select: none;\n position: relative;\n flex-shrink: 0;\n z-index: 2;\n overflow: visible;\n }\n #nacho-avatar { -webkit-user-select: none; }\n #nacho-avatar:hover { transform: scale(1.08) rotate(-3deg); }\n #nacho-avatar:active { transform: scale(0.93); }\n #nacho-avatar .nacho-btn-stack {\n position: absolute;\n top: -5px;\n right: -4px;\n display: flex;\n flex-direction: column;\n gap: 4px;\n z-index: 5;\n }\n #nacho-avatar .nacho-closet-btn, #nacho-avatar .nacho-story-btn {\n font-size: 0.85rem;\n cursor: pointer;\n pointer-events: auto;\n background: var(--card-bg, #1a1a2e);\n border: 1px solid var(--border, #333);\n border-radius: 50%;\n width: 26px;\n height: 26px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: 0.2s;\n opacity: 0.5;\n position: relative;\n }\n #nacho-avatar .nacho-closet-btn:hover, #nacho-avatar .nacho-story-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n border-color: #f7931a;\n }\n .nacho-notif-dot {\n position: absolute;\n top: -2px;\n right: -2px;\n width: 8px;\n height: 8px;\n background: #ef4444;\n border-radius: 50%;\n border: 1.5px solid var(--card-bg, #1a1a2e);\n z-index: 6;\n pointer-events: none;\n }\n #nacho-avatar .nacho-name {\n position: absolute;\n bottom: -46px;\n left: 50%;\n transform: translateX(-50%);\n font-size: 0.7rem;\n color: #f7931a;\n font-weight: 800;\n letter-spacing: 1.5px;\n white-space: nowrap;\n text-transform: uppercase;\n text-shadow: 0 1px 4px rgba(0,0,0,0.5);\n line-height: 1.3;\n text-align: center;\n pointer-events: auto;\n cursor: pointer;\n padding: 4px 12px;\n border-radius: 8px;\n transition: background 0.2s;\n }\n #nacho-avatar .nacho-name:hover {\n background: rgba(247,147,26,0.15);\n }\n\n /* Nacho speech bubble — high contrast, always readable */\n #nacho-bubble {\n background: #111827;\n border: 2px solid #f7931a;\n border-radius: 16px;\n padding: 16px 20px 16px 18px;\n max-width: 300px;\n min-width: 200px;\n color: #f8f8f8;\n font-size: 0.9rem;\n line-height: 1.55;\n pointer-events: none;\n box-shadow: 0 8px 32px rgba(0,0,0,0.7), 0 0 12px rgba(247,147,26,0.25);\n opacity: 0;\n transform: translateY(8px) scale(0.9);\n transition: opacity 0.35s cubic-bezier(0.34, 1.56, 0.64, 1), transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);\n cursor: pointer;\n position: relative;\n margin-left: -6px;\n margin-bottom: 16px;\n z-index: 1000;\n }\n #nacho-bubble::before {\n content: '';\n position: absolute;\n bottom: 10px;\n left: -10px;\n width: 0; height: 0;\n border-top: 10px solid transparent;\n border-bottom: 10px solid transparent;\n border-right: 10px solid #f7931a;\n }\n #nacho-bubble::after {\n content: '';\n position: absolute;\n bottom: 12px;\n left: -7px;\n width: 0; height: 0;\n border-top: 8px solid transparent;\n border-bottom: 8px solid transparent;\n border-right: 8px solid #111827;\n }\n #nacho-bubble.show { opacity: 1; transform: translateY(0) scale(1); pointer-events: auto; }\n\n .nacho-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 6px;\n }\n .nacho-label {\n font-size: 0.65rem;\n color: #f7931a;\n font-weight: 800;\n text-transform: uppercase;\n letter-spacing: 1px;\n }\n .nacho-x {\n color: var(--text-faint, #666);\n font-size: 0.75rem;\n cursor: pointer;\n opacity: 0.4;\n transition: opacity 0.2s;\n padding: 2px 4px;\n }\n .nacho-x:hover { opacity: 1; }\n #nacho-text { word-wrap: break-word; max-height: 60vh; overflow-y: auto; -webkit-overflow-scrolling: touch; padding-right: 4px; }\n\n /* Clippy-style idle animations — mimic the paper clip's fidgeting */\n\n /* 1. Tap tap — like Clippy tapping on the screen */\n /* Nacho victory flight — Lightning bolt ⚡ across the full screen! */\n @keyframes nachoFly {\n /* ⚡ Lightning bolt: high-energy erratic takeoff, zigzag, and sonic boom reentry \n */\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 5% { transform: translate(-5px, 10px) rotate(-10deg) scale(0.9); }\n 10% { transform: translate(15vw, -20vh) rotate(20deg) scale(1.1); }\n 20% { transform: translate(40vw, -5vh) rotate(-15deg) scale(1); }\n 30% { transform: translate(65vw, -45vh) rotate(35deg) scale(1.2); }\n 45% { transform: translate(90vw, -10vh) rotate(-20deg) scale(1.1); }\n 60% { transform: translate(110vw, -60vh) rotate(45deg) scale(1.4); opacity: 1; }\n 61% { transform: translate(110vw, -60vh); opacity: 0; }\n /* Sonic boom reentry from the top left */\n 85% { transform: translate(-50vw, -50vh) rotate(-45deg) scale(2); opacity: 0; }\n 90% { transform: translate(-10vw, -10vh) rotate(-20deg) scale(1.5); opacity: 1; filter: brightness(3) blur(2px); }\n 95% { transform: translate(0, -20px) rotate(0deg) scale(1.1); filter: brightness(1); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n @keyframes nachoFlyMobile {\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 8% { transform: translate(-2vw, 5vh) rotate(-10deg) scale(0.9); }\n 15% { transform: translate(25vw, -30vh) rotate(15deg) scale(1.1); }\n 30% { transform: translate(60vw, -5vh) rotate(-15deg) scale(1); }\n 50% { transform: translate(85vw, -50vh) rotate(30deg) scale(1.3); }\n 65% { transform: translate(105vw, -20vh) rotate(10deg) scale(1.2); opacity: 1; }\n 66% { transform: translate(105vw, -20vh); opacity: 0; }\n /* Reentry from top */\n 88% { transform: translate(0, -80vh) rotate(0deg) scale(1.5); opacity: 0; }\n 94% { transform: translate(0, -10px) rotate(0deg) scale(1.1); opacity: 1; filter: brightness(2); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n #nacho-avatar.flying {\n animation: nachoFly 2.8s linear forwards;\n z-index: 999;\n filter: drop-shadow(0 0 20px rgba(247,147,26,0.8)) drop-shadow(0 0 40px rgba(234,88,12,0.4));\n }\n @media (max-width: 900px) {\n #nacho-avatar.flying {\n animation: nachoFlyMobile 2.4s linear forwards;\n }\n }\n /* Lightning trail particles */\n .nacho-trail {\n position: fixed;\n pointer-events: none;\n z-index: 998;\n font-size: 1.2rem;\n opacity: 1;\n transition: none;\n animation: nachoTrailFade 0.8s ease-out forwards;\n }\n .nacho-trail.stuck-cleanup { display: none !important; }\n @keyframes nachoTrailFade {\n 0% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(1.3); }\n 100% { opacity: 0; transform: scale(0.3); }\n }\n\n @keyframes nachoTap {\n 0%, 100% { transform: translateY(0); }\n 10% { transform: translateY(-6px); }\n 20% { transform: translateY(0); }\n 30% { transform: translateY(-4px); }\n 40% { transform: translateY(0); }\n }\n /* 2. Lean and look — Clippy tilting to peek at your screen */\n @keyframes nachoLean {\n 0%, 100% { transform: rotate(0deg) translateX(0); }\n 30% { transform: rotate(8deg) translateX(3px); }\n 50% { transform: rotate(8deg) translateX(3px); }\n 80% { transform: rotate(0deg) translateX(0); }\n }\n /* 3. Bored wiggle — Clippy fidgeting when idle */\n @keyframes nachoWiggle {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-6deg); }\n 30% { transform: rotate(5deg); }\n 45% { transform: rotate(-4deg); }\n 60% { transform: rotate(3deg); }\n 75% { transform: rotate(-2deg); }\n 90% { transform: rotate(0deg); }\n }\n /* 4. Bounce — Clippy's excited hop */\n @keyframes nachoBounce {\n 0%, 100% { transform: translateY(0) scale(1); }\n 20% { transform: translateY(-8px) scale(1.05); }\n 40% { transform: translateY(0) scale(0.97); }\n 55% { transform: translateY(-4px) scale(1.02); }\n 70% { transform: translateY(0) scale(0.99); }\n 85% { transform: translateY(-2px) scale(1.01); }\n }\n /* 5. Stretch — Clippy stretching/yawning */\n @keyframes nachoStretch {\n 0%, 100% { transform: scaleY(1) scaleX(1); }\n 25% { transform: scaleY(1.12) scaleX(0.92); }\n 50% { transform: scaleY(0.92) scaleX(1.08); }\n 75% { transform: scaleY(1.05) scaleX(0.97); }\n }\n /* 6. Look around — Clippy looking left and right */\n @keyframes nachoLook {\n 0%, 100% { transform: translateX(0); }\n 20% { transform: translateX(-5px); }\n 40% { transform: translateX(-5px); }\n 60% { transform: translateX(5px); }\n 80% { transform: translateX(5px); }\n }\n /* 7. Wave — Clippy waving at you */\n @keyframes nachoWave {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-12deg); }\n 30% { transform: rotate(10deg); }\n 45% { transform: rotate(-8deg); }\n 60% { transform: rotate(6deg); }\n 75% { transform: rotate(-3deg); }\n }\n /* 8. Sleepy bob — Clippy nodding off */\n @keyframes nachoSleepy {\n 0%, 100% { transform: translateY(0) rotate(0deg); }\n 30% { transform: translateY(2px) rotate(3deg); }\n 50% { transform: translateY(3px) rotate(5deg); }\n 70% { transform: translateY(2px) rotate(3deg); }\n }\n /* 9. Couch sway — for Timechain TV */\n @keyframes nachoSway {\n 0%, 100% { transform: rotate(-1deg) translateY(0); }\n 50% { transform: rotate(1deg) translateY(-3px); }\n }\n\n #nacho-avatar.anim-tap { animation: nachoTap 2s ease-in-out infinite; }\n #nacho-avatar.anim-lean { animation: nachoLean 3.5s ease-in-out infinite; }\n #nacho-avatar.anim-wiggle { animation: nachoWiggle 2.5s ease-in-out infinite; }\n #nacho-avatar.anim-bounce { animation: nachoBounce 1.8s ease-in-out infinite; }\n #nacho-avatar.anim-stretch { animation: nachoStretch 3s ease-in-out infinite; }\n #nacho-avatar.anim-look { animation: nachoLook 4s ease-in-out infinite; }\n #nacho-avatar.anim-wave { animation: nachoWave 1.5s ease-in-out infinite; }\n #nacho-avatar.anim-sleepy { animation: nachoSleepy 4s ease-in-out infinite; }\n\n /* Tablet — sidebar is 280px */\n @media (max-width: 1100px) {\n #nacho-container { left: 290px; }\n #nacho-avatar { width: 95px; height: 95px; }\n }\n /* Mobile — sidebar hidden, Nacho goes bottom-left, above clutter */\n @media (max-width: 900px) {\n #nacho-container { bottom: calc(50vh - 30px); left: 12px; }\n #nacho-avatar { width: 68px; height: 68px; }\n #nacho-bubble {\n position: fixed;\n bottom: calc(50vh + 50px);\n left: 12px;\n right: 12px;\n max-width: calc(100vw - 24px);\n max-height: 40vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n min-width: unset;\n width: auto;\n font-size: 0.9rem;\n padding: 16px 18px;\n margin-left: 0;\n border-radius: 14px;\n }\n #nacho-bubble::before, #nacho-bubble::after { display: none; }\n #nacho-avatar .nacho-name { font-size: 0.7rem; bottom: -44px; padding: 5px 14px; }\n }\n @media (max-width: 480px) {\n #nacho-container { bottom: calc(50vh - 40px); left: 10px; }\n #nacho-avatar { width: 60px; height: 60px; }\n #nacho-bubble {\n bottom: calc(50vh + 30px);\n left: 10px;\n right: 10px;\n max-width: calc(100vw - 20px);\n max-height: 38vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n font-size: 0.85rem;\n padding: 14px 16px;\n }\n #nacho-avatar .nacho-name { font-size: 0.65rem; bottom: -40px; padding: 5px 12px; }\n }\n\n /* Bring-back toggle */\n #nacho-toggle {\n position: fixed; bottom: 80px; left: 330px; z-index: 250;\n width: 52px; height: 52px;\n background: radial-gradient(circle, #fff 60%, rgba(255,255,255,0.85) 100%);\n border: 2px solid rgba(247,147,26,0.5);\n border-radius: 50%; display: none; align-items: center; justify-content: center;\n font-size: 1.6rem; cursor: pointer; opacity: 0.9; transition: all 0.3s;\n box-shadow: 0 2px 12px rgba(0,0,0,0.3), 0 0 0 3px rgba(247,147,26,0.15);\n }\n #nacho-toggle:hover { opacity: 1; transform: scale(1.1); box-shadow: 0 4px 20px rgba(247,147,26,0.4), 0 0 0 4px rgba(247,147,26,0.25); }\n @media (max-width: 1100px) { #nacho-toggle { left: 290px; } }\n @media (max-width: 900px) { #nacho-toggle { bottom: calc(50vh - 30px); left: 12px; width: 46px; height: 46px; font-size: 1.3rem; } }\n @media (max-width: 480px) { #nacho-toggle { bottom: calc(50vh - 40px); left: 10px; width: 44px; height: 44px; font-size: 1.2rem; } }\n ",document.head.appendChild(i);const a=document.createElement("div");a.id="nacho-container",g||a.classList.add("hidden");const r=o()?t:e,s=o()?"width:120px;height:100px;":"";a.innerHTML='
'+r+'Nacho
click to ask!
👔📖
🦌 '+("function"==typeof nachoNickname?nachoNickname():"Nacho")+' says
',document.body.appendChild(a);var l=document.getElementById("nachoClosetBtn");if(l){var d=!1;function h(){window._expanded_closet=!0,window._pendingClosetScroll=!0;try{"function"==typeof showSettings&&showSettings();var e=0;setTimeout(function t(){e++;var o=document.getElementById("usernameModal");o&&o.classList.contains("open")&&"function"==typeof showSettingsPage?showSettingsPage("data"):e<10&&setTimeout(t,150)},200)}catch(e){}"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear()}l.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),l.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d=!0},{passive:!1}),l.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),d&&(d=!1,h())},{passive:!1}),l.addEventListener("click",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d||h(),d=!1},!1)}window.updateNachoNotifs=function(){var e=document.getElementById("nachoStoryNotif");if(e){var t=safeJSON("btc_nacho_story_days",[]),o=(new Date).toISOString().split("T")[0],n=t.length,i=-1===t.indexOf(o)&&n<7,a=0===n,r=localStorage.getItem("btc_nacho_story_notif_dismissed")===o;e.style.display=r||!i&&!a?"none":"block"}var s=document.getElementById("nachoClosetNotif");if(s){var c=safeJSON("btc_spin_closet_items",[]),l=safeJSON("btc_closet_viewed",[]),d=c.some(function(e){return-1===l.indexOf(e)});s.style.display=d?"block":"none"}},window.nachoStoryNotifClear=function(){var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_nacho_story_notif_dismissed",e);var t=document.getElementById("nachoStoryNotif");t&&(t.style.display="none")},window.nachoClosetNotifClear=function(){var e=safeJSON("btc_spin_closet_items",[]);localStorage.setItem("btc_closet_viewed",JSON.stringify(e));var t=document.getElementById("nachoClosetNotif");t&&(t.style.display="none")},setTimeout(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},2e3),setInterval(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},6e4);const f=document.createElement("div");function v(){const e=document.getElementById("nachoModeContainer"),t=document.getElementById("irl-sync-view"),o=document.getElementById("searchOverlay"),n=document.querySelector(".ticker-wrap"),i=e&&"none"!==e.style.display||t&&null!==t.offsetParent||o&&"flex"===o.style.display;if(n){n.style.transition="transform 0.4s ease",n.style.transform=i?"translateY(-100%)":"translateY(0)";const e=document.getElementById("menuToggle");e&&(e.style.opacity=i?"0.2":"1")}}f.id="nacho-toggle",f.innerHTML="🦌",f.title="Bring back Nacho",f.onclick=function(){showNacho()},g||(f.style.display="flex"),document.body.appendChild(f),function(){var e=document.getElementById("nacho-avatar");if(e){var t=null,o=!1;e.addEventListener("touchstart",function(e){o=!1,t=setTimeout(function(){o=!0,"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t),o&&(o=!1)}),e.addEventListener("touchmove",function(){clearTimeout(t)}),e.addEventListener("contextmenu",function(e){e.preventDefault(),"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")})}}(),setTimeout(function(){if(g){var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=0;try{o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length}catch(e){}if(t<=3&&o<5){var n=parseInt(localStorage.getItem("btc_nacho_onboarding")||"1");if(k("wave"),1===n?(S('
Hey there! I\'m Nacho, your Bitcoin education buddy! 🦌🧡

Here\'s what you can do here:
📚 Read 145+ Bitcoin topics — tap any in the sidebar
🎡 Spin daily for free tickets & rewards
Take quests to test your knowledge

'),localStorage.setItem("btc_nacho_onboarding","2")):2===n&&o>=1?(S('
Nice, you explored your first channel! 🎉

Keep going — every channel you read earns you +10 XP. Here are some popular ones:

'),localStorage.setItem("btc_nacho_onboarding","3")):3===n&&o>=3?(k("celebrate"),S('
You\'re on fire! 🔥 '+o+' channels explored!

Did you know you can:
🗣️ Chat in PlebTalk — discuss Bitcoin with the community
Browse LightningMart — buy & sell for sats
🎓 Take the Scholar Exam — earn your Bitcoin certification

'),localStorage.setItem("btc_nacho_onboarding","4")):4===n&&o>=5&&(k("brain"),S('
You\'re becoming a real Bitcoiner! 🧡

Pro tips:
📖 Read Nacho\'s Story — a new chapter unlocks each day
📚 Study with Flashcards to prepare for quests
🏆 Check the Leaderboard — see where you rank
💬 Ask me anything about Bitcoin anytime!

— End of tour. I\'ll still be here if you need me! 🦌
'),localStorage.setItem("btc_nacho_onboarding","5")),n<=4)return}k((e="function"==typeof nachoTimeGreeting&&Math.random()<.6?nachoTimeGreeting():U(c)).pose),S(e.text),"function"==typeof nachoPlaySound&&nachoPlaySound("pop"),setTimeout(function(){if("function"==typeof nachoStreakMessage){var e=nachoStreakMessage();e&&T(e.text,e.pose)}},12e3)}},2e3),clearInterval(m),m=setInterval(function(){if(!g)return;const e=document.getElementById("nacho-bubble");if(e&&e.classList.contains("show"))return;const t=document.getElementById("nacho-avatar");if(!t)return;p=(p+1)%u.length,k(u[p]),["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(e=>t.classList.remove(e));const o={default:["anim-tap","anim-look","anim-wiggle"],eyes:["anim-lean","anim-look"],think:["anim-lean","anim-tap"],cheese:["anim-bounce","anim-wiggle"],cool:["anim-lean","anim-tap"],sleep:["anim-sleepy"],wave:["anim-wave"],celebrate:["anim-bounce"],fire:["anim-bounce","anim-wiggle"],love:["anim-stretch","anim-tap"],brain:["anim-lean","anim-look"],point:["anim-tap","anim-lean"]}[w]||["anim-tap","anim-wiggle"];t.classList.add(U(o))},8e3),setInterval(M,55e3);const b=window.enterNachoMode;window.enterNachoMode=function(e){"function"==typeof b&&b(e),setTimeout(v,100)};const x=window.exitNachoMode;window.exitNachoMode=function(e){"function"==typeof x&&x(e),setTimeout(v,100)};const _=window.go;window.go=function(e,t,o){"function"==typeof _&&_(e,t,o),setTimeout(v,100)};const B=window.goHome;window.goHome=function(e){"function"==typeof B&&B(e),setTimeout(v,100)},setTimeout(function(){"undefined"!=typeof APP_PAGES&&APP_PAGES.forEach(e=>{"PlebTalk"===e.title&&(e.title="Pleb Talk"),"LightningMart"===e.title&&(e.title="Lightning Mart")})},2e3),window.addEventListener("beforeunload",function(e){const t=document.getElementById("questModal");t&&t.classList.contains("open")&&(e.preventDefault(),e.returnValue="You have an active Quest! Your progress will be lost.")}),window.showSkeletonLoader=function(e,t){const o=document.getElementById(e);if(!o)return;let n='
';for(let e=0;e<(t||6);e++)n+='
';n+="
",o.innerHTML=n},setInterval(function(){var e=document.getElementById("nacho-bubble");if(!g||e&&e.classList.contains("show"))return;const t=Math.random();if(t<.3)k("wave"),setTimeout(()=>k("neutral"),400);else if(t<.6){const e=document.getElementById("nacho-avatar");e&&(e.style.transform="scale(1.1) rotate(5deg)",setTimeout(()=>e.style.transform="",500))}},2e4),setInterval(function(){if(g&&!(y>=12)&&!(Math.random()>.2||window._lastChannelOpenTime&&Date.now()-window._lastChannelOpenTime<3e4)){var e=document.getElementById("nacho-bubble");if(!(e&&e.classList.contains("show")&&"true"===e.getAttribute("data-interactive")||window._nachoMode)){var t=document.getElementById("questModal");t&&t.classList.contains("open")||"function"==typeof showNachoTrivia&&showNachoTrivia()}}},18e4)}function k(e){w=e||"default";const t=document.getElementById("nacho-pose-emoji");t&&(t.textContent=n[w]||n.default)}function T(e,t){!g||y>=12||Date.now()-f<5e4||v.has(e)||_(e,t)}function S(e,t){if(g){var o=document.getElementById("questModal");o&&o.classList.contains("open")||_(e,t)}}function _(e,t){if(window._nachoDirectLinkCooldown&&Date.now()s.classList.remove(e));var c="";if(-1===e.indexOf("'+l[d].label+"";break}var u=-1!==e.indexOf("60&&Math.abs(o)>2*Math.abs(n)&&hideBubble(!0)}},{passive:!0}),function(){var e=!1,t=0,o=0,n=0,i=0,a=!1,r=null;function s(){return document.getElementById("nacho-container")}function c(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;var n=window.innerWidth-40,i=window.innerHeight-40;t.left>=0&&t.left<=n&&t.top>=0&&t.top<=i&&(o.style.left=t.left+"px",o.style.bottom="auto",o.style.top=t.top+"px",o.style.right="auto")}catch(e){}}function l(){var e=s();if(e){var t=document.getElementById("nacho-bubble");if(t){var o=e.getBoundingClientRect(),n=window.innerWidth;window.innerHeight,o.left>n/2?(t.style.marginLeft="",t.style.marginRight="-6px",t.style.alignSelf="flex-end",t.querySelector(":scope"),t.style.setProperty("--bubble-side","right")):(t.style.marginLeft="-6px",t.style.marginRight="",t.style.alignSelf=""),o.top<200?(t.style.order="2",t.style.marginBottom="0",t.style.marginTop="8px"):(t.style.order="",t.style.marginBottom="16px",t.style.marginTop="")}}}setTimeout(c,500),window.addEventListener("resize",function(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;t.left=Math.max(0,Math.min(t.left,window.innerWidth-60)),t.top=Math.max(0,Math.min(t.top,window.innerHeight-60)),o.style.left=t.left+"px",o.style.top=t.top+"px",localStorage.setItem("btc_nacho_position",JSON.stringify(t))}catch(e){}}),document.addEventListener("touchstart",function(c){var l=document.getElementById("nachoDragHandle");if(l&&l.contains(c.target)){c.preventDefault();var d=s();if(d){a=!1,r=d,t=c.touches[0].clientX,o=c.touches[0].clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,e=!0,d.style.transition="none",d.style.opacity="0.85",l.style.background="rgba(247,147,26,0.9)",l.querySelector("span").style.color="#fff"}}},{passive:!1}),document.addEventListener("touchmove",function(s){if(e&&r){var c=s.touches[0].clientX-t,l=s.touches[0].clientY-o;if(!(!a&&Math.abs(c)<8&&Math.abs(l)<8)){a=!0,s.preventDefault(),s.stopPropagation();var d=Math.max(0,Math.min(n+c,window.innerWidth-60)),u=Math.max(0,Math.min(i+l,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}},{passive:!1}),document.addEventListener("touchend",function(t){if(e){e=!1,r&&(r.style.transition="",r.style.opacity="");var o=document.getElementById("nachoDragHandle");if(o){o.style.background="rgba(255,255,255,0.9)";var n=o.querySelector("span");n&&(n.style.color="#888")}if(a&&r){var i=r.getBoundingClientRect(),s=Math.max(0,Math.min(Math.round(i.left),window.innerWidth-60)),c=Math.max(0,Math.min(Math.round(i.top),window.innerHeight-60));r.style.left=s+"px",r.style.top=c+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:s,top:c})),setTimeout(l,50),t.preventDefault()}r=null}},{passive:!1}),document.addEventListener("mousedown",function(c){var l=document.getElementById("nachoDragHandle");if(l&&l.contains(c.target)){var d=s();if(d){e=!0,a=!1,r=d,t=c.clientX,o=c.clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,d.style.transition="none",c.preventDefault()}}}),document.addEventListener("mousemove",function(s){if(e&&r){var c=s.clientX-t,l=s.clientY-o;if(!(!a&&Math.abs(c)<8&&Math.abs(l)<8)){a=!0;var d=Math.max(0,Math.min(n+c,window.innerWidth-60)),u=Math.max(0,Math.min(i+l,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}}),document.addEventListener("mouseup",function(t){if(e){if(e=!1,r&&(r.style.transition=""),a&&r){var o=r.getBoundingClientRect(),n=Math.max(0,Math.min(Math.round(o.left),window.innerWidth-60)),i=Math.max(0,Math.min(Math.round(o.top),window.innerHeight-60));r.style.left=n+"px",r.style.top=i+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:n,top:i})),setTimeout(l,50)}r=null}});var d=window.showNacho;window.showNacho=function(){d.apply(this,arguments),c(),setTimeout(l,200)},setTimeout(l,1e3),document.addEventListener("dblclick",function(e){var t=document.getElementById("nacho-avatar");if(t&&t.contains(e.target)){localStorage.removeItem("btc_nacho_position");var o=s();o&&(o.style.left="",o.style.top="",o.style.bottom="",o.style.right=""),"function"==typeof showToast&&showToast("🦌 Nacho reset to default position!"),setTimeout(l,100)}})}(),window.hideBubble=function(e){var t=document.getElementById("nacho-bubble");if(e||!t||"true"!==t.getAttribute("data-interactive")){window._nachoBusy=!1,localStorage.setItem("btc_nacho_clicked","true"),setTimeout(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},2e3);var o=document.getElementById("nacho-avatar");t&&t.classList.remove("show"),clearTimeout(h),setTimeout(function(){k("default"),o&&o.classList.add("anim-tap")},500)}};let C=0,E=[],A=0;function M(){if(!g||y>=12)return;if(Math.random()>.3)return;if("function"==typeof nachoCheckMilestone){var e=nachoCheckMilestone();if(e)return S(e.text,e.pose),void setTimeout(nachoFly,500)}if("function"==typeof nachoLiveMessage&&Math.random()<.2){var t=nachoLiveMessage();if(t)return void T(t.text,t.pose)}if("function"==typeof checkNachoNewItems){var o=checkNachoNewItems();if(o)return S(o.text,o.pose),void("function"==typeof nachoPlaySound&&nachoPlaySound("coin"))}var n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var c=Math.random(),l=("new"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&c<.15?NACHO_CLOSET_TIPS:c<.6?a:c<.8?r:s:"regular"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&c<.1?NACHO_CLOSET_TIPS:c<.4?s:c<.7?a:r:"undefined"!=typeof NACHO_CLOSET_TIPS&&c<.15?NACHO_CLOSET_TIPS:c<.65?s:c<.9?r:a).filter(e=>!v.has(e.text));if(0===l.length&&0===(l=[...s,...r].filter(e=>!v.has(e.text))).length)return;const d=U(l);T(d.text,d.pose)}window.nachoClick=function(){if(window._nachoActionClicked)return void(window._nachoActionClicked=!1);const e=Date.now();if(E.push(e),E.length>3&&E.shift(),3===E.length&&E[2]-E[0]<600&&e-A>5e3)return E=[],A=e,b=e,"function"==typeof nachoFly&&nachoFly(),void S(personalize("Wheeeee! ⚡🦌⚡"));if(E.length>=2&&E[E.length-1]-E[E.length-2]<400&&E.length<3)return E=[],b=e,"function"==typeof hideNacho&&hideNacho(),void("function"==typeof showToast&&showToast("🦌 Nacho hidden — tap the 🦌 button to bring him back!"));if(e-b<1500)return;b=e,localStorage.setItem("btc_nacho_clicked","true"),"function"==typeof checkHiddenBadges&&checkHiddenBadges(),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoPlaySound&&nachoPlaySound("click");const t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show"))return void hideBubble();if(C++,C%3==0&&"function"==typeof showNachoInput)return void showNachoInput();var o,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var c=(o="new"===i?[...a,...a,...r,...s]:"regular"===i?[...a,...s,...s,...r]:[...s,...s,...s,...r]).filter(e=>!v.has(e.text));const l=U(c.length>3?c:o);f=0,k(l.pose),S(l.text,l.pose)},window.showNacho=function(){g=!0,localStorage.removeItem("btc_nacho_hidden"),document.getElementById("nacho-container").classList.remove("hidden"),document.getElementById("nacho-toggle").style.display="none",f=0;var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=void 0!==currentUser&¤tUser&¤tUser.channelsVisited||0;if(t<=2&&o<3&&!localStorage.getItem("btc_nacho_tour_shown"))return[{text:"Welcome to the Bitcoin Education Archive, {name}! I'm Nacho, your deer guide! 🦌",pose:"wave",delay:0},{text:"Click the grid icons to explore Bitcoin topics. Start with the orange ones — they're beginner-friendly! 📚",pose:"point",delay:4e3},{text:"See the 🔥 number? That's your streak! Come back daily to keep it growing. ⚡",pose:"fire",delay:8e3},{text:"Tap me anytime to chat, or double-tap to enter Nacho Mode for deep conversations! 💬",pose:"cheese",delay:12e3}].forEach(function(e,t){setTimeout(function(){t>0&&k(e.pose),S(personalize(e.text))},e.delay)}),void localStorage.setItem("btc_nacho_tour_shown","true");if(t>2&&t<=10&&o<10){var n=["Pro tip {name}: Use the ⚡ tab to check the Bitcoin price anytime! 📈","Did you know? Completing a Quest earns you bonus Orange Tickets! 🎟️","Try tapping the Menu (☰) to see your progress on the Exploration Map! 🗺️","You can customize my outfit in Settings → Stats/Nacho → Closet! 👔"];e=n[Math.floor(Math.random()*n.length)],k("cool")}else if(t>20){var i=["Tick tock, next block! Ready for some high-signal learning, {name}? 🧱","Welcome back, master HODLer! I've been keeping the Archive warm for you. 🦌🔥","I noticed you've visited many channels. Want to test your knowledge with a Quest today? ⚡","Back for your daily dose of decentralization? Let's dive in! 📘"];e=i[Math.floor(Math.random()*i.length)],k("brain")}else if(t>5){var a=["Hey {name}, great to see you again! ✨","Welcome back! Ready to stack some more knowledge? 📚","I missed you! Check out my closet if you've earned new items! 👔","You're making great progress on your Exploration Map! 🗺️"];e=a[Math.floor(Math.random()*a.length)],k("wave")}else e="I'm back, {name}! Miss me? 🦌",k("wave");S(personalize(e))},window.hideNacho=function(){g=!1,localStorage.setItem("btc_nacho_hidden","user"),document.getElementById("nacho-container").classList.add("hidden"),document.getElementById("nacho-toggle").style.display="flex"},window.nachoOnPage=function(e){var t;if(g&&("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoNickname&&nachoNickname(),"forum"===e?t=[{pose:"wave",text:personalize("Welcome to PlebTalk, {name}! 🗣️ This is where Bitcoiners discuss ideas. Jump in!")},{pose:"point",text:"💡 Post a new topic to earn +10 points, or reply to an existing one for +5. Quality content gets upvoted!"},{pose:"brain",text:"Remember — this is a Bitcoin-only space. Stay respectful, stay on topic, and attack ideas, not people! 🤝"},{pose:"cheese",text:personalize("Psst {name}... earn the 📣 Town Crier badge by posting in PlebTalk! Your first post counts!")},{pose:"fire",text:"🔥 Pro tip: Upvote posts you find valuable with ⚡ — it helps the best content rise to the top!"}]:"marketplace"===e&&(t=[{pose:"wave",text:personalize("Welcome to LightningMart, {name}! ⚡ Buy and sell with Bitcoin — the way it should be!")},{pose:"point",text:"💡 All prices are in sats. Sellers set their own prices. Payments happen directly between buyer and seller."},{pose:"cheese",text:"🛒 List your first item to earn the 🏪 Merchant badge! Books, hardware, merch — whatever you've got!"},{pose:"brain",text:"🛡️ Safety first! Meet in public for local trades, use Lightning for instant payments, and report suspicious listings."},{pose:"fire",text:personalize("Pro tip {name}: add a Lightning address to your listing so buyers can pay you instantly! ⚡")}]),t)){var o=t[Math.floor(Math.random()*t.length)];S(o.text,o.pose)}},window.nachoOnChannel=function(e){if(g){if("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoChannelIntro){var t=nachoChannelIntro(e);if(t)return void S(t.text,t.pose)}if("function"==typeof nachoCategoryCheck){var o=nachoCategoryCheck(e);if(o)return S(o.text,o.pose),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),void setTimeout(nachoFly,500)}if(i[e]&&Math.random()<.6){const t=i[e];return void T(t.text,t.pose)}if(parseInt(sessionStorage.getItem("btc_channel_read_seconds")||"0")>=30+Math.floor(90*Math.random())&&Math.random()<.3&&"undefined"!=typeof QUEST_QUESTIONS&&QUEST_QUESTIONS.length>0){var n=void 0!==CHANNELS?CHANNELS[e]:null,a=n?n.cat:"",r=QUEST_QUESTIONS.filter(function(e){return e.category&&a&&-1!==e.category.toLowerCase().indexOf(a.toLowerCase().split(" ")[0])});0===r.length&&(r=QUEST_QUESTIONS);for(var s=r[Math.floor(Math.random()*r.length)],c='
🎮 Quick Quiz!
'+s.question+"
",d=s.options||[],u=0;u'+d[u]+"";return S(c,"brain"),void sessionStorage.setItem("btc_channel_read_seconds","0")}if(Math.random()<.25){const e=U(l);T(e.text,e.pose)}}},window.nachoBubbleQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n=e.parentElement,i=n.querySelectorAll("button");if(i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1";var a=document.createElement("div");a.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#22c55e;",a.textContent="✅ Correct! +5 pts",n.appendChild(a),"function"==typeof awardPoints&&awardPoints(5,"🎮 Quiz correct!"),"function"==typeof haptic&&haptic("success")}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("true")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var r=document.createElement("div");r.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#ef4444;",r.textContent="❌ Not quite! The correct answer is highlighted.",n.appendChild(r)}clearTimeout(h);var s=document.getElementById("nacho-bubble");s&&s.setAttribute("data-interactive","true")},window.nachoOnPoints=function(e){if(!g)return;if(e>=250)return void setTimeout(nachoFly,500);if(Math.random()>.2)return;const t=U(d);T(t.text,t.pose)},window.nachoFly=function(){var e=document.getElementById("nacho-avatar");if(e&&!e.classList.contains("flying")){["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(function(t){e.classList.remove(t)}),e.classList.add("flying");var t="false"!==localStorage.getItem("btc_nacho_sound"),o=[1200,1800,1400,2200,1600,2800];[0,400,800,1200,1600,2e3].forEach(function(n,i){setTimeout(function(){t&&e.classList.contains("flying")&&function(e){if("function"!=typeof canPlaySound||canPlaySound())try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();o.connect(n),n.connect(t.destination),o.frequency.value=e,o.type="sawtooth",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.12),o.start(t.currentTime),o.stop(t.currentTime+.12)}catch(e){}}(o[i])},n)});var n=["⚡","✨","🔥","⚡","💫","⚡"],i=setInterval(function(){if(e.classList.contains("flying")){var t=e.getBoundingClientRect(),o=document.createElement("div");o.className="nacho-trail",o.textContent=n[Math.floor(Math.random()*n.length)],o.style.left=t.left+t.width/2+(20*Math.random()-10)+"px",o.style.top=t.top+t.height/2+(20*Math.random()-10)+"px",document.body.appendChild(o),setTimeout(function(){o.parentNode&&o.remove()},600)}else clearInterval(i)},40);e.addEventListener("animationend",function o(){if(e.classList.remove("flying"),e.classList.add("anim-bounce"),e.removeEventListener("animationend",o),clearInterval(i),t&&("function"!=typeof canPlaySound||canPlaySound()))try{var n=new(window.AudioContext||window.webkitAudioContext),a=n.createOscillator(),r=n.createGain();a.connect(r),r.connect(n.destination),a.frequency.value=300,a.type="sine",r.gain.setValueAtTime(.08,n.currentTime),r.gain.exponentialRampToValueAtTime(.001,n.currentTime+.2),a.start(n.currentTime),a.stop(n.currentTime+.2)}catch(e){}})}},window.nachoOnQuest=function(e){g&&(f=0,e?(k("celebrate"),S(personalize("{name}, you CRUSHED that quest! This buck is VERY impressed! 🦌🎉🔥")),setTimeout(nachoFly,500)):(k("love"),S(personalize("Hey {name}, some questions are hard! Read up and try again — Nacho believes in you! 🦌💪"))))},window.nachoOnSearch=function(){!g||Math.random()>.3||T("Looking for something? I'd help search but I don't have thumbs. Good luck! 🔍🦌","think")},window.nachoOnFinishChannel=function(){if(!g||Math.random()>.3)return;const e=U([{pose:"celebrate",text:"You read the whole thing! Dedicated. I respect that. 🦌👏"},{pose:"point",text:"All done? Hit the 🎲 to find your next channel!"},{pose:"fire",text:"Knowledge: stacked. You're a machine! 💪"}]);T(e.text,e.pose)},window.nachoUserName=function(){return void 0!==currentUser&¤tUser&¤tUser.username?String(currentUser.username).replace(//g,">").replace(/"/g,"""):""};let z=0,L=0,P=!1;function U(e){return e[Math.floor(Math.random()*e.length)]}window.DeviceMotionEvent&&window.addEventListener("devicemotion",function(e){if(g&&!P){var t=e.accelerationIncludingGravity;if(t&&Math.sqrt(t.x*t.x+t.y*t.y+t.z*t.z)>28){var o=Date.now();o-z>1e3&&(L=0),z=o,L++,L>=2&&(P=!0,L=0,"function"==typeof haptic&&haptic("heavy"),"function"==typeof nachoFly&&nachoFly(),S(personalize("Whoa, {name}! Too much coffee? ⚡🦌🌪️")),setTimeout(function(){P=!1},3e3))}}},!0),window.personalize=function(e){var t=nachoUserName();if(e=t?e.replace(/\{name\}/g,t):e.replace(/,?\s*\{name\}\s*,?\s*/g,function(e){return 0===e.indexOf(",")&&e.lastIndexOf(",")>0?", ":","===e.charAt(0)?" ":""}),window._btcData){var o=window._btcData.price;if(!o)try{o=parseFloat(localStorage.getItem("btc_last_price"))}catch(e){}const t=o?"$"+Math.round(o).toLocaleString():"over $60,000",n=window._btcData.height?window._btcData.height.toLocaleString():"over 840,000",i=window._btcData.halvingBlocks?window._btcData.halvingBlocks.toLocaleString():"less than 150,000";e=(e=(e=e.replace(/\{price\}/g,t)).replace(/\{height\}/g,n)).replace(/\{halving\}/g,i)}return e.replace(/ +/g," ").replace(/^ ,/,"").replace(/, ,/g,",").trim()};let N=null;document.addEventListener("DOMContentLoaded",function(){setTimeout(function(){const e=document.getElementById("nacho-avatar");function t(e){"touchstart"===e.type&&e.preventDefault(),N=setTimeout(function(){hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho is hiding. Click the small 🦌 to bring him back!")},800)}function o(){clearTimeout(N)}e&&(e.addEventListener("mousedown",t),e.addEventListener("mouseup",o),e.addEventListener("mouseleave",o),e.addEventListener("touchstart",t,{passive:!1}),e.addEventListener("touchend",o),e.addEventListener("touchmove",o))},1e3)}),document.addEventListener("click",function(e){var t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show")){var o=document.getElementById("nacho-container");o&&o.contains(e.target)||hideBubble(!0)}}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",x):x(),function(){var e="btc_nacho_position",t=null,o=null,n=!1,i=0,a=0,r=0,s=0,c=!1;function l(){return t||(t=document.getElementById("nacho-container")),t}function d(){return o||(o=document.getElementById("nachoDragHandle")),o}function u(){try{var t=JSON.parse(localStorage.getItem(e));if(t&&"number"==typeof t.left&&"number"==typeof t.bottom){var o=l();if(o){var n=window.innerWidth-80,i=window.innerHeight-80,a=Math.max(0,Math.min(t.left,n)),r=Math.max(0,Math.min(t.bottom,i));o.style.left=a+"px",o.style.bottom=r+"px",o.style.right="auto",o.style.top="auto",o.style.position="fixed"}}}catch(e){}}function p(t,o){try{localStorage.setItem(e,JSON.stringify({left:t,bottom:o}))}catch(e){}}function m(e,t){var o=l();if(o){n=!0,c=!1,i=e,a=t;var u=o.getBoundingClientRect();r=u.left,s=window.innerHeight-u.bottom,o.style.transition="none",o.style.cursor="grabbing";var p=d();p&&(p.style.cursor="grabbing")}}function g(e,t){if(n){var o=e-i,d=t-a;if(c||!(Math.abs(o)+Math.abs(d)<8)){c=!0;var u=l();if(u){var p=r+o,m=s-d;p=Math.max(0,Math.min(p,window.innerWidth-80)),m=Math.max(0,Math.min(m,window.innerHeight-80)),u.style.left=p+"px",u.style.bottom=m+"px",u.style.right="auto",u.style.top="auto",u.style.position="fixed"}}}}function h(){if(n){n=!1;var e=l();if(e&&(e.style.transition="",e.style.cursor="",c)){var t=e.getBoundingClientRect();p(t.left,window.innerHeight-t.bottom)}var o=d();o&&(o.style.cursor="grab")}}function f(){var e=d();if(e){if(!e._dragInit){e._dragInit=!0,e.addEventListener("mousedown",function(e){e.preventDefault(),e.stopPropagation(),m(e.clientX,e.clientY)}),document.addEventListener("mousemove",function(e){n&&(e.preventDefault(),g(e.clientX,e.clientY))}),document.addEventListener("mouseup",h),e.addEventListener("touchstart",function(e){1===e.touches.length&&(e.stopPropagation(),m(e.touches[0].clientX,e.touches[0].clientY))},{passive:!0}),document.addEventListener("touchmove",function(e){n&&1===e.touches.length&&g(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("touchend",function(){n&&h()});var t=document.getElementById("nacho-avatar");t&&t.addEventListener("click",function(e){c&&(e.stopPropagation(),e.preventDefault(),c=!1)},!0),u(),function(){var e=document.getElementById("nacho-toggle");if(e&&!e._dragInit){e._dragInit=!0;var t=!1,o=0,n=0,i=0,a=0,r=!1;e.addEventListener("mousedown",function(s){t=!0,r=!1,o=s.clientX,n=s.clientY;var c=e.getBoundingClientRect();i=c.left,a=window.innerHeight-c.bottom,e.style.transition="none"}),e.addEventListener("touchstart",function(s){if(1===s.touches.length){t=!0,r=!1,o=s.touches[0].clientX,n=s.touches[0].clientY;var c=e.getBoundingClientRect();i=c.left,a=window.innerHeight-c.bottom,e.style.transition="none"}},{passive:!0}),document.addEventListener("mousemove",function(e){s(e.clientX,e.clientY)}),document.addEventListener("touchmove",function(e){t&&1===e.touches.length&&s(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("mouseup",c),document.addEventListener("touchend",c),e.addEventListener("click",function(e){r&&(e.stopPropagation(),e.preventDefault(),r=!1)},!0)}function s(s,c){if(t){var l=s-o,d=c-n;if(r||!(Math.abs(l)+Math.abs(d)<8)){r=!0;var u=Math.max(0,Math.min(i+l,window.innerWidth-50)),p=Math.max(0,Math.min(a-d,window.innerHeight-50));e.style.left=u+"px",e.style.bottom=p+"px",e.style.right="auto",e.style.top="auto"}}}function c(){if(t&&(t=!1,e.style.transition="",r)){var o=e.getBoundingClientRect();p(o.left,window.innerHeight-o.bottom)}}}(),window.addEventListener("resize",function(){u()})}}else setTimeout(f,1e3)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(f,500)}):setTimeout(f,500)}(),setInterval(function(){document.querySelectorAll(".nacho-trail").forEach(function(e){e.remove()})},3e3),window.updateNachoAvatarForPage=function(){var n=document.getElementById("nacho-avatar");if(n){var i=o();if(i!==("1"===n.getAttribute("data-tctv"))){n.setAttribute("data-tctv",i?"1":"0"),i?(n.style.width="120px",n.style.height="100px",n.innerHTML=t+'Nacho
click to ask!
👔📖
'):(n.style.width="",n.style.height="",n.innerHTML=e+'Nacho
click to ask!
👔📖
');var a=document.getElementById("nachoClosetBtn");if(a){var r=!1;a.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),a.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),r=!0},{passive:!1}),a.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),r&&(r=!1,window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},200),"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear())},{passive:!1})}}}};var H=window.go;H&&(window.go=function(){var e=H.apply(this,arguments);return setTimeout(window.updateNachoAvatarForPage,100),e})}(),function(){window.nachoTimeGreeting=function(){var e=(new Date).getHours(),t=((new Date).getDay(),"function"==typeof nachoUserName?nachoUserName():""),o=t?", "+t:"";return e>=5&&e<12?{pose:"wave",text:"Good morning"+o+"! ☀️ Ready to learn some Bitcoin today?"}:e>=12&&e<17?{pose:"wave",text:"Good afternoon"+o+"! 🌤️ Let's stack some knowledge!"}:e>=17&&e<21?{pose:"wave",text:"Good evening"+o+"! 🌅 Great time to dive into some Bitcoin education!"}:e>=21||e<2?{pose:"cool",text:"Late night study session"+o+"? 🌙 Respect! The night owl and the night deer, learning together. 🦉🦌"}:{pose:"sleep",text:"Whoa"+o+", it's the middle of the night! 😴 Your dedication is legendary. Most deer would be asleep right now!"}},window.nachoStreakMessage=function(){if(void 0===currentUser||!currentUser)return null;var e=currentUser.streak||0,t="function"==typeof nachoUserName?nachoUserName():"",o=t?", "+t:"";return e>=30?{pose:"fire",text:e+"-day streak"+o+"! You're absolutely unstoppable! 🔥🦌👑"}:e>=14?{pose:"fire",text:e+"-day streak"+o+"! Two weeks straight! You're a machine! 🔥💪"}:e>=7?{pose:"celebrate",text:e+"-day streak"+o+"! A whole week! Nacho is very impressed! 🎉🔥"}:e>=3?{pose:"love",text:e+"-day streak"+o+"! Keep it going! 🔥"}:null};const e=[100,250,500,1e3,2100,5e3,1e4,21e3];window.nachoCheckMilestone=function(){if(void 0===currentUser||!currentUser)return null;for(var t=currentUser.points||0,o=JSON.parse(localStorage.getItem("btc_nacho_milestones")||"[]"),n="function"==typeof nachoUserName?nachoUserName():"",i=n?", "+n:"",a=[],r=0;r=s&&!o.includes(s)&&(a.push(s),o.push(s))}if(0===a.length)return null;localStorage.setItem("btc_nacho_milestones",JSON.stringify(o)),"function"==typeof syncCelebratedState&&syncCelebratedState();var c=a[0],l="function"==typeof getLevel?getLevel(t):null,d=l?" You're now rank: "+l.emoji+" "+l.name+"!":"";if(a.length>1&&"function"==typeof forceShowBubble)for(var u=1;u=3){var s=r.wrong.slice(0,3),c=Math.floor(4*Math.random());s.splice(c,0,r.a),e.push({q:r.q,options:s,correct:c,pts:10,_fromBank:!0})}}}var l=JSON.parse(localStorage.getItem("btc_nacho_trivia_asked")||"[]");l.length>.8*e.length&&(l=[],localStorage.removeItem("btc_nacho_trivia_asked"));var d=e.filter(function(e,t){return!l.includes(e._fromBank?"qb_"+e.q.substring(0,30):t)});if(0===d.length)return null;var u=d[Math.floor(Math.random()*d.length)],p=u._fromBank?"qb_"+u.q.substring(0,30):e.indexOf(u);return l.push(p),localStorage.setItem("btc_nacho_trivia_asked",JSON.stringify(l)),{trivia:u,index:idx}},window.showNachoTrivia=function(){if(window._nachoBusy)return!1;var e=nachoTrivia();if(!e)return!1;var t=e.trivia,o=document.getElementById("nacho-bubble"),n=document.getElementById("nacho-text");if(!o||!n)return!1;"function"==typeof setPose&&setPose("think"),o.setAttribute("data-interactive","true"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout();for(var i='
🧠 Quick Trivia! (+'+t.pts+' pts)
'+t.q+"
",a=0;a'+String.fromCharCode(65+a)+". "+t.options[a]+"";return n.innerHTML=i,o.classList.add("show"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout(),!0},window.nachoTriviaAnswer=function(e,t,o,n){for(var i=n.parentElement.querySelectorAll("button"),a=0;a","function"==typeof setPose&&setPose("celebrate");else{var d=Math.max(2,Math.floor(o/3));"function"==typeof awardPoints&&awardPoints(d,"🧠 Nice try!"),s.innerHTML+='
❌ Not quite'+l+"! The answer was "+String.fromCharCode(65+t)+". +"+d+" pts for trying! 📚
","function"==typeof setPose&&setPose("love")}s.innerHTML+='',s.innerHTML+=''},window.getNachoFriendship=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?{level:5,name:"Best Buds",emoji:"💛"}:e>=350?{level:4,name:"Close Friends",emoji:"🧡"}:e>=100?{level:3,name:"Good Friends",emoji:"😊"}:e>=10?{level:2,name:"Getting Acquainted",emoji:"👋"}:e>=1?{level:1,name:"Just Met",emoji:"🦌"}:{level:0,name:"Strangers",emoji:"❓"}},window.trackNachoInteraction=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0")+1;if(localStorage.setItem("btc_nacho_interactions",e.toString()),window._nachoLastInteraction=Date.now(),void 0!==db&&void 0!==auth&&auth.currentUser){var t=parseInt(localStorage.getItem("btc_nacho_questions")||"0");try{db.collection("users").doc(auth.currentUser.uid).update({nachoInteractions:e,nachoQuestions:t})}catch(e){}}"function"==typeof renderProgressRings&&renderProgressRings()};const i={mining:["How does the difficulty adjustment work?","What is a halving?","Is mining bad for the environment?","What is a nonce?","Can I mine at home?","What is an ASIC?"],wallet:["What is a seed phrase?","What is self-custody?","What is a hardware wallet?","How do I back up my wallet?","What is multisig?","Which wallet is best for beginners?"],lightning:["How fast is Lightning?","What are sats?","How do I get a Lightning Address?","What is a payment channel?","What is LNURL?","Can I tip people with Lightning?"],halving:["What is the block reward?","When is the next halving?","Why does the price go up after halving?","How many halvings are left?","What happens when all Bitcoin are mined?"],price:["Is it too late to buy?","What is DCA?","Why is Bitcoin volatile?","How high can Bitcoin go?","What is stock-to-flow?"],"self-custody":["What is a seed phrase?","What wallets do you recommend?","What does HODL mean?","What is cold storage?","What is a passphrase?"],privacy:["What is CoinJoin?","What is non-KYC Bitcoin?","Is Bitcoin anonymous?","What are silent payments?","What is Nostr?"],basics:["How does mining work?","What is the Lightning Network?","Who created Bitcoin?","What is a sat?","Why is there only 21 million?"],fud:["Is Bitcoin bad for the environment?","Can Bitcoin be hacked?","Will governments ban Bitcoin?","What about quantum computers?","Is Bitcoin a Ponzi scheme?"],node:["Why should I run a node?","What is a full node?","How does consensus work?","What is Nakamoto Consensus?"],taproot:["What is Schnorr?","What are covenants?","What is MuSig2?","What is OP_CAT?"],security:["What is a 51% attack?","How secure is Bitcoin?","What is proof of work?","Can Bitcoin be hacked?"],scarcity:["Why only 21 million?","What makes Bitcoin scarce?","What is inflation?","Bitcoin vs gold?"],layer:["What is Lightning Network?","What are sidechains?","What is the Liquid Network?","What are channel factories?"],economics:["What is sound money?","What is the Cantillon Effect?","What is time preference?","Why is fiat bad?"],satoshi:["Why did Satoshi disappear?","Who is Hal Finney?","What is the Genesis Block?","Is Craig Wright Satoshi?"],nostr:["What is Nostr?","How do I use Nostr?","What are Nostr relays?","Can I sign in with Nostr?"],regulation:["Can Bitcoin be banned?","What happened when China banned Bitcoin?","Is Bitcoin legal?","What about the SEC?"],altcoin:["Why is Bitcoin different from altcoins?","What about Ethereum?","Are meme coins worth it?","Why Bitcoin only?"],invest:["What is DCA?","How much should I invest?","Is now a good time to buy?","What is HODL?"],history:["What is Pizza Day?","What are the blocksize wars?","When was the first transaction?","What is the Genesis Block?"],energy:["Does Bitcoin waste energy?","How much energy does mining use?","Is Bitcoin green?","What is stranded energy?"]};var a=[];window.nachoFollowUps=function(e){if(!e)return[];var t=e.toLowerCase(),o=[];for(var n in i)t.includes(n)&&(o=o.concat(i[n]));0===o.length&&(o=["What is Bitcoin?","How do I get started?","What is the Lightning Network?","Who created Bitcoin?","Why is there only 21 million?","What is self-custody?"]);var r=window._nachoAskedQuestions||[],s=o.filter(function(e){return-1===a.indexOf(e)&&-1===r.indexOf(e.toLowerCase())});s.length<3&&(a=[],s=o.filter(function(e){return-1===r.indexOf(e.toLowerCase())})),0===s.length&&(s=o),s.sort(function(){return Math.random()-.5});var c=Math.min(Math.max(3,s.length),5),l=s.slice(0,c);return(a=a.concat(l)).length>30&&(a=a.slice(-15)),l},window.trackNachoQuestion=function(e,t){try{var o=JSON.parse(localStorage.getItem("btc_nacho_analytics")||"[]");o.push({q:e.substring(0,100),matched:t,t:Date.now()}),o.length>100&&(o=o.slice(-100)),localStorage.setItem("btc_nacho_analytics",JSON.stringify(o))}catch(e){}};let r="false"!==localStorage.getItem("btc_nacho_sound");window.nachoPlaySound=function(e){if(("function"!=typeof canPlaySound||canPlaySound())&&r)try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();if(o.connect(n),n.connect(t.destination),n.gain.value=.08,"pop"===e)o.frequency.value=800,o.type="sine",n.gain.setValueAtTime(.08,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.15),o.start(t.currentTime),o.stop(t.currentTime+.15);else if("coin"===e){o.frequency.value=1200,o.type="sine",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.3),o.start(t.currentTime),o.stop(t.currentTime+.3);var i=t.createOscillator();i.connect(n),i.frequency.value=1600,i.type="sine",i.start(t.currentTime+.1),i.stop(t.currentTime+.3)}else"click"===e?(o.frequency.value=600,o.type="triangle",n.gain.setValueAtTime(.05,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.08),o.start(t.currentTime),o.stop(t.currentTime+.08)):"tctv-beep"===e&&(o.frequency.value=2400,o.type="square",n.gain.setValueAtTime(.03,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.06),o.start(t.currentTime),o.stop(t.currentTime+.06))}catch(e){}},window.toggleNachoSound=function(){return r=!r,localStorage.setItem("btc_nacho_sound",r.toString()),r};let s=[];window.nachoAddContext=function(e){s.push(e),s.length>5&&s.shift()},window.nachoGetContext=function(){return s},setTimeout(function(){if("1"!==localStorage.getItem("btc_ln_prompt_dismissed")){var e=void 0!==currentUser?currentUser:null;if(e&&e.username&&!e.lightning&&!e.lightningAddress){var t=[];try{t=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}t.length<5||"function"==typeof forceShowBubble&&(forceShowBubble("⚡ Hey "+(e.username||"friend")+"! Connect a Lightning wallet to tip other users and receive tips! Tap me to learn how. 🦌",function(){go("lightning")}),localStorage.setItem("btc_ln_prompt_dismissed","1"))}}},3e4),function(){var e="btc_smart_nudges";function t(){try{return JSON.parse(localStorage.getItem(e)||"{}")}catch(e){return{}}}function o(e){var o=t();return!o[e]||Date.now()-o[e]>864e5}function n(){if("function"==typeof forceShowBubble&&!(Date.now()-(window._sessionStart||Date.now())<3e4)){var n=document.getElementById("nacho-bubble");if(!(n&&n.classList.contains("show")||window._nachoBusy)){var i,a,r=[];if(void 0!==BADGE_DEFS&&void 0!==earnedBadges){var s=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length;!earnedBadges.has("explorer_10")&&s>=7&&o("near_explorer_10")&&r.push({id:"near_explorer_10",text:"You've visited "+s+" topics — just "+(10-s)+" more to earn the Explorer badge! 🧭 Keep exploring!"}),!earnedBadges.has("explorer_25")&&s>=20&&s<25&&o("near_explorer_25")&&r.push({id:"near_explorer_25",text:"Only "+(25-s)+" more topics to unlock Trailblazer! 🗺️ You're so close!"});var c=void 0!==currentUser&¤tUser&¤tUser.streak||0;!earnedBadges.has("streak_7")&&c>=5&&c<7&&o("near_streak_7")&&r.push({id:"near_streak_7",text:c+"-day streak! 🔥 Just "+(7-c)+" more days for the Week Warrior badge! Don't break it!"}),!earnedBadges.has("streak_30")&&c>=25&&c<30&&o("near_streak_30")&&r.push({id:"near_streak_30",text:c+"-day streak! 💪 "+(30-c)+" more days to Monthly Maxi! That's legendary dedication!"}),!earnedBadges.has("streak_100")&&c>=90&&c<100&&o("near_streak_100")&&r.push({id:"near_streak_100",text:c+"-day streak! 💎 "+(100-c)+" days from Diamond Hands! You're in the top tier!"});var l=parseInt(localStorage.getItem("btc_chat_msgs")||"0");!earnedBadges.has("chat_50")&&l>=40&&l<50&&o("near_chat_50")&&r.push({id:"near_chat_50",text:l+" chat messages! Just "+(50-l)+" more to become a Conversationalist! 🎤 Head to Global Chat!"});var d=parseInt(localStorage.getItem("btc_pvp_wins")||"0");!earnedBadges.has("pvp_5")&&d>=3&&d<5&&o("near_pvp_5")&&r.push({id:"near_pvp_5",text:d+" PVP wins! ⚔️ "+(5-d)+" more to unlock Contender! Ready for a battle?"});var u=void 0!==completedQuests&&completedQuests.size||0;!earnedBadges.has("quest_3")&&u>=2&&u<3&&o("near_quest_3")&&r.push({id:"near_quest_3",text:"You've completed "+u+" quests! One more for the Quest Master badge! ⚔️ Try a quest after reading!"});var p=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0");!earnedBadges.has("tctv_couch_potato")&&p>=45&&p<60&&o("near_tctv_60")&&r.push({id:"near_tctv_60",text:p+" minutes of Timechain TV! 📺 Just "+(60-p)+" more for Couch Potato! Grab some popcorn! 🍿"}),localStorage.getItem("btc_last_spin_date")!==(new Date).toDateString()&&o("daily_spin")&&r.push({id:"daily_spin",text:"You haven't spun the daily wheel yet! 🎡 Free tickets and prizes await!"})}if(r.length>0){var m=r[Math.floor(Math.random()*r.length)];i=m.id,(a=t())[i]=Date.now(),localStorage.setItem(e,JSON.stringify(a)),forceShowBubble(m.text)}}}}setTimeout(function(){n(),setInterval(n,3e5)},12e4),window.checkSmartNudges=n}()}(),window.nachoNickname=function(){return localStorage.getItem("btc_nacho_nickname")||"Nacho"},function(){const e=[{id:"orange_scarf",category:"shirt",name:"Bitcoin Scarf",emoji:"🧣",desc:"A cozy orange scarf with the ₿ symbol.",level:1,overlay:{top:"68%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"sunglasses",category:"glasses",name:"Cool Shades",emoji:"🕶️",desc:"Sunglasses so cool, even the blockchain can't see through them.",level:1,overlay:{top:"43%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"bowtie",category:"shirt",name:"Fancy Bowtie",emoji:"🎀",desc:"A dapper bowtie for a distinguished buck. Class and sats.",level:1,overlay:{top:"64%",left:"50%",transform:"translateX(-50%)",fontSize:"1.3em"},hidden:!1,colorable:!0},{id:"mining_helmet",category:"hat",name:"Mining Helmet",emoji:"⛑️",desc:"A safety helmet for a hardworking miner. Ready to find the next block!",level:2,overlay:{top:"5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"lightning_chain",category:"glasses",name:"Lightning Chain",emoji:"⚡",desc:"A chain necklace with a Lightning bolt pendant.",level:2,overlay:{top:"65%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"party_hat",category:"hat",name:"Party Hat",emoji:"🎉",desc:"Every day is a party when you're stacking sats!",level:2,overlay:{top:"2%",left:"58%",transform:"translateX(-50%) rotate(15deg)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"hodl_hoodie",category:"shirt",name:"HODL Hoodie",emoji:"🧥",desc:"A hoodie that says HODL on the back. For diamond-handed deer.",level:3,overlay:{top:"72%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1,colorable:!0},{id:"laser_eyes",category:"glasses",name:"Laser Eyes",emoji:"🔴",desc:"The legendary Bitcoin laser eyes. Number go up!",level:3,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"0.9em",custom:"🔴 🔴"},hidden:!1,colorable:!0},{id:"wizard_hat",category:"hat",name:"Wizard Hat",emoji:"🪄",desc:"A mystical wizard hat. Nacho casts spells of financial sovereignty!",level:3,overlay:{top:"-5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!1,colorable:!0},{id:"crown",category:"hat",name:"Royal Crown",emoji:"👑",desc:"Fit for the king of cryptocurrency. There is no second best!",level:3,overlay:{top:"3%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"steak",category:"glasses",name:"Proof of Steak",emoji:"🥩",desc:"A juicy steak for a hardworking buck. Proof of Steak > Proof of Stake!",level:4,overlay:{top:"58%",right:"-18%",fontSize:"1.8em",transform:"rotate(20deg)"},hidden:!1},{id:"diamond_hooves",category:"glasses",name:"Diamond Hooves",emoji:"💎",desc:"Diamond hooves for a deer with diamond hands. Never selling!",level:4,overlay:{bottom:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em",custom:"💎💎"},hidden:!1},{id:"astronaut",category:"hat",name:"Moon Helmet",emoji:"🪖",desc:"To the moon! A space helmet for the ultimate HODLer.",level:4,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1},{id:"cape_permanent",category:"shirt",name:"Hero Cape",emoji:"🦸",desc:"A permanent cape for a Bitcoin hero. Earned, not given!",level:4,overlay:{top:"55%",right:"-15%",fontSize:"2.4em",transform:"rotate(-12deg)"},hidden:!1,colorable:!0},{id:"golden_antlers",category:"hat",name:"???",emoji:"✨",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"0.5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Golden Antlers",revealEmoji:"✨",revealDesc:"Antlers plated in pure gold. Only the closest friends get to see these shine!"},{id:"satoshi_cloak",category:"shirt",name:"???",emoji:"🧥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"68%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Satoshi's Cloak",revealEmoji:"🧥",revealDesc:"A mysterious cloak worn by Satoshi himself. Legend says it grants anonymity to any deer who wears it."},{id:"flame_aura",category:"glasses",name:"???",emoji:"🔥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"25%",left:"50%",transform:"translateX(-50%)",fontSize:"3.5em"},hidden:!0,revealName:"Flame Aura",revealEmoji:"🔥",revealDesc:"A blazing aura of pure Bitcoin energy. The ultimate flex for Nacho's best friend!"},{id:"rainbow_antlers",category:"hat",name:"???",emoji:"🌈",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!0,revealName:"Rainbow Antlers",revealEmoji:"🌈",revealDesc:"Prismatic rainbow antlers that shimmer in every color. Legendary!"},{id:"bitcoin_eyes",category:"glasses",name:"???",emoji:"₿",desc:"How do you find this one?",level:1,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.2em",custom:"₿ ₿"},hidden:!0,revealName:"Bitcoin Eyes",revealEmoji:"₿",revealDesc:"Eyes made of pure Bitcoin. You found the secret! Nacho sees everything in sats now."},{id:"santa_hat",category:"hat",name:"Santa Hat",emoji:"🎅",desc:"Ho ho HODL! A festive Santa hat for the holiday season.",level:1,overlay:{top:"1%",left:"54%",transform:"translateX(-50%) rotate(15deg)",fontSize:"2.2em"},hidden:!1,seasonal:"december"},{id:"pumpkin",category:"hat",name:"Pumpkin Head",emoji:"🎃",desc:"Spooky season! A jack-o-lantern for Halloween.",level:1,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1,seasonal:"october"},{id:"halving_pickaxe",category:"glasses",name:"Golden Pickaxe",emoji:"⛏️",desc:"A golden pickaxe to celebrate the halving! Limited edition.",level:1,overlay:{top:"22%",right:"-15%",fontSize:"2.2em",transform:"rotate(30deg)"},hidden:!1,seasonal:"april"}];var t=document.createElement("style");function o(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?5:e>=350?4:e>=100?3:e>=10?2:e>=1?1:0}t.textContent="\n @keyframes nachoEquipPop {\n 0% { transform: scale(0) rotate(-45deg); opacity: 0; }\n 50% { transform: scale(1.5) rotate(10deg); opacity: 1; }\n 70% { transform: scale(0.9) rotate(-5deg); }\n 100% { transform: scale(1) rotate(0deg); opacity: 1; }\n }\n @keyframes nachoEquipGlow {\n 0% { filter: drop-shadow(0 0 0px transparent); }\n 30% { filter: drop-shadow(0 0 12px rgba(247,147,26,0.8)); }\n 100% { filter: drop-shadow(0 0 4px rgba(247,147,26,0.3)); }\n }\n @keyframes nachoUnequip {\n 0% { transform: scale(1); opacity: 1; }\n 40% { transform: scale(1.3) rotate(15deg); opacity: 0.8; }\n 100% { transform: scale(0) rotate(-30deg); opacity: 0; }\n }\n @keyframes nachoItemFloat {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-3px); }\n }\n @keyframes nachoLaserPulse {\n 0%, 100% { opacity: 0.8; filter: drop-shadow(0 0 4px #ff0000); }\n 50% { opacity: 1; filter: drop-shadow(0 0 10px #ff0000) drop-shadow(0 0 20px #ff3300); }\n }\n @keyframes nachoSparkle {\n 0%, 100% { filter: drop-shadow(0 0 4px rgba(255,215,0,0.3)); }\n 50% { filter: drop-shadow(0 0 10px rgba(255,215,0,0.8)) drop-shadow(0 0 20px rgba(255,215,0,0.4)); }\n }\n @keyframes nachoCloakWave {\n 0%, 100% { transform: translateX(-50%) rotate(-2deg); }\n 50% { transform: translateX(-50%) rotate(2deg); }\n }\n .nacho-overlay-item {\n position: absolute;\n pointer-events: none;\n z-index: 3;\n }\n .nacho-overlay-item.equipping {\n animation: nachoEquipPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards,\n nachoEquipGlow 0.8s ease-out forwards;\n }\n .nacho-overlay-item.unequipping {\n animation: nachoUnequip 0.35s ease-in forwards;\n }\n .nacho-overlay-item.idle-float {\n animation: nachoItemFloat 3s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-laser {\n animation: nachoLaserPulse 1.5s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-sparkle {\n animation: nachoSparkle 2s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-wave {\n animation: nachoCloakWave 4s ease-in-out infinite;\n }\n",document.head.appendChild(t),window.equipNachoItem=function(t){if(!t)return localStorage.removeItem("btc_nacho_equipped_multi"),void renderNachoOverlay();var n=o(),i=e.find(function(e){return e.id===t}),a=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]");if(i&&i.level>n&&-1===a.indexOf(t))showToast("🔒 Need a higher friendship level to wear this!");else{var r=getEquippedItems(),s=i&&i.category||"misc";r[s]===t?(delete r[s],"function"==typeof forceShowBubble&&forceShowBubble("Back to natural in the "+s+" department! 🦌")):(r[s]=t,"function"==typeof forceShowBubble&&forceShowBubble({orange_scarf:"Looking cozy! This scarf really brings out my orange. 🧣🦌",mining_helmet:"Safety first! Time to mine some blocks! ⛑️⛏️",lightning_chain:"Bling bling! Fast as Lightning! ⚡🦌",hodl_hoodie:"HODL gang! This hoodie makes me feel unstoppable! 🧥💎",laser_eyes:"LASER EYES ACTIVATED! Number go up! 🔴🔴🚀",steak:"Mmm, Proof of Steak! Way better than Proof of Stake! 🥩😋",golden_antlers:"These golden antlers are MAGNIFICENT! Only for my best friends! 👑✨",satoshi_cloak:"Who am I? Nobody knows... I am Satoshi Nachoamoto! 🧙🦌"}[t]||"Looking fresh with my "+(i.hidden?i.revealName:i.name)+"! 🦌")),localStorage.setItem("btc_nacho_equipped_multi",JSON.stringify(r)),renderNachoOverlay(!0),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),document.getElementById("nachoClosetGrid")&&renderNachoClosetUI(document.getElementById("nachoClosetGrid").parentElement)}},window.renderNachoOverlay=function(t){document.querySelectorAll(".nacho-overlay-item").forEach(e=>e.remove());var o=getEquippedItems(),n=document.getElementById("nacho-avatar");n&&(Object.values(o).forEach(function(o){var i=e.find(function(e){return e.id===o});if(i){var a=i.hidden?i.revealEmoji:i.emoji,r=function(e){switch(e){case"laser_eyes":return"idle-laser";case"golden_antlers":case"diamond_hooves":return"idle-sparkle";case"satoshi_cloak":return"idle-wave";default:return"idle-float"}}(i.id),s=document.createElement("span");for(var c in s.className="nacho-overlay-item"+(t?" equipping":" "+r),s.id="nacho-overlay-"+i.id,s.textContent=i.overlay.custom||a,i.overlay.custom&&(s.style.letterSpacing="-0.1em",s.style.whiteSpace="nowrap"),i.overlay)"filter"!==c&&"custom"!==c&&(s.style[c]=i.overlay[c]);if(i.colorable){var l=localStorage.getItem("btc_closet_color_"+i.id);l&&"0deg"!==l&&(s.style.filter="hue-rotate("+l+")")}t&&s.addEventListener("animationend",function e(){s.classList.remove("equipping"),s.classList.add(r),s.removeEventListener("animationend",e)},{once:!0}),n.appendChild(s)}}),t&&function(e){for(var t=e.getBoundingClientRect(),o=["✨","⭐","💫","🌟"],n=0;n<6;n++)(function(e){setTimeout(function(){var n=document.createElement("div");n.className="nacho-trail",n.textContent=o[e%o.length],n.style.left=t.left+Math.random()*t.width+"px",n.style.top=t.top+Math.random()*t.height+"px",n.style.fontSize=.8+.8*Math.random()+"rem",document.body.appendChild(n),setTimeout(function(){n.parentNode&&n.remove()},800)},80*e)})(n)}(n))},window.getNachoFriendship=function(){const e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[{name:"Stranger",emoji:"🦌",min:0},{name:"Acquaintance",emoji:"🤝",min:10},{name:"Pleb Friend",emoji:"🧡",min:50},{name:"HODL Buddy",emoji:"💎",min:150},{name:"Maxi Mentor",emoji:"👑",min:500}];let o=t[0];for(const n of t)e>=n.min&&(o=n);return o},window.renderNachoClosetUI=function(t){for(var n=o(),i=getEquippedItems(),a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r="function"==typeof getNachoFriendship?getNachoFriendship():{level:0,name:"Strangers",emoji:"❓"},s=[1,10,100,350,750],c="",l=0;lNext level in '+(s[l]-a)+" more interactions";break}var d="",u=[];Object.values(i).forEach(function(t){var o=e.find(function(e){return e.id===t});if(o){var n=o.hidden?o.revealEmoji:o.emoji;o.overlay.custom&&(n=o.overlay.custom);var i="position:absolute;font-size:"+(o.overlay.fontSize||"1.5rem")+";";if(o.overlay.top&&(i+="top:"+o.overlay.top+";"),o.overlay.bottom&&(i+="bottom:"+o.overlay.bottom+";"),o.overlay.left&&(i+="left:"+o.overlay.left+";"),o.overlay.right&&(i+="right:"+o.overlay.right+";"),o.overlay.transform&&(i+="transform:"+o.overlay.transform+";"),i+="z-index:5;pointer-events:none;",o.colorable){var a=localStorage.getItem("btc_closet_color_"+o.id);a&&"0deg"!==a&&(i+="filter:hue-rotate("+a+");")}d+=''+n+"",u.push(o.hidden?o.revealName:o.name)}});var p="function"==typeof nachoNickname?nachoNickname():"Nacho",m='
🦌 '+escapeHtml(p)+"'s Closet
";m+='
Nacho'+d+'
'+(u.length>0?'✨ Wearing: '+u.join(", ")+"":"No item equipped — tap one below!")+"
",m+='
Friendship: '+r.emoji+" "+r.name+''+a+" interactions
"+c,m+='
',m+='
';for(var g=(new Date).toLocaleString("en",{month:"long"}).toLowerCase(),h=0;h
'+x+'
'+w+"
"+(v?'
✓ EQUIPPED
':"")+(v&&f.colorable?"
🎨 Color
':"")+(y||b?"":'
Lvl '+f.level+"
")+(b?'
🔒
':"")+(f.seasonal?'
🗓️ '+f.seasonal+"
":"")+"
"}}m+="",m+='
'+(Object.keys(i).length>0?function(){var t=e.find(function(e){return e.id===Object.values(i)[0]});if(!t)return"Tap an item to equip it on "+escapeHtml(p)+"!";var o=t.hidden?t.revealDesc:t.desc;return''+(t.hidden?t.revealName:t.name)+": "+o}():"Tap an unlocked item to equip it on "+escapeHtml(p)+"!
Tap again to unequip.")+"
",t.innerHTML=m};var n="function"==typeof nachoNickname?nachoNickname():"Nacho";window.NACHO_CLOSET_TIPS=[{pose:"cool",text:"Did you know I have a whole closet of outfits, {name}? Check Settings → Stats → "+escapeHtml(n)+"'s Closet to dress me up! 👔🦌"},{pose:"celebrate",text:"The more we interact, the more items you unlock for me to wear! Check my closet in Settings! 🧣⚡"},{pose:"eyes",text:"I heard there are some mystery items in my closet that only my closest friends get to see... 👀🔒"},{pose:"fire",text:"Proof of Steak > Proof of Stake. Ask me about it... or better yet, unlock it in my closet! 🥩🦌"},{pose:"cheese",text:"Fashion tip from a deer: orange goes with everything. Especially Bitcoin orange. Check my closet in Settings! 🟠"}],window.checkNachoNewItems=function(){var t=o(),n=JSON.parse(localStorage.getItem("btc_nacho_items_notified")||"[]"),i=e.filter(function(e){return e.level<=t&&!n.includes(e.id)});if(i.length>0){for(var a=0;a
'+(a?a.name:"Item")+'
Choose a color
';[{name:"Default",hue:"0deg",color:"#f7931a"},{name:"Bitcoin Orange",hue:"25deg",color:"#ff8c00"},{name:"Crimson",hue:"340deg",color:"#dc2626"},{name:"Royal Purple",hue:"270deg",color:"#7c3aed"},{name:"Ocean Blue",hue:"200deg",color:"#0ea5e9"},{name:"Forest Green",hue:"120deg",color:"#16a34a"},{name:"Gold",hue:"45deg",color:"#eab308"},{name:"Hot Pink",hue:"310deg",color:"#ec4899"},{name:"Cyan",hue:"175deg",color:"#06b6d4"},{name:"Lime",hue:"90deg",color:"#84cc16"}].forEach(function(t){var n=o===t.hue;r+=""}),r+='
',i.innerHTML=r,n.appendChild(i),document.body.appendChild(n)},window._applyClosetColor=function(e,t){localStorage.setItem("btc_closet_color_"+e,t);var o=document.querySelector("#nacho-overlay");if(o&&(o.style.filter="0deg"===t?"none":"hue-rotate("+t+")"),"function"==typeof showColorPicker&&showColorPicker(e),"function"==typeof renderNachoClosetUI){var n=document.getElementById("nachoClosetContainer");n&&renderNachoClosetUI(n)}};const QUESTION_BANK={whitepaper:[{q:"When was the Bitcoin Whitepaper published?",a:"October 31, 2008",wrong:["January 3, 2009","March 15, 2007","December 25, 2010"]},{q:"How many pages of text is the Bitcoin Whitepaper?",a:"8 pages",wrong:["20 pages","50 pages","2 pages"]},{q:"The Whitepaper was published on:",a:"A cryptography mailing list",wrong:["Twitter","A Bitcoin forum","The New York Times"]},{q:"What is the title of the Bitcoin Whitepaper?",a:"Bitcoin: A Peer-to-Peer Electronic Cash System",wrong:["Digital Gold: The Future","How to Mine Cryptocurrency","The Blockchain Revolution"]},{q:"The Whitepaper proposed a solution to:",a:"The double-spending problem",wrong:["Climate change","Internet speed","Social media addiction"]}],whitepaper_pt2:[{q:"Who is credited as the author of the Whitepaper?",a:"Satoshi Nakamoto",wrong:["Vitalik Buterin","Elon Musk","Hal Finney"]},{q:"The Whitepaper describes Bitcoin as:",a:"A peer-to-peer electronic cash system",wrong:["A stock trading platform","A social network","A video game currency"]},{q:"What concept does the Whitepaper use to timestamp transactions?",a:"A chain of hashed blocks",wrong:["A central database","Email timestamps","GPS coordinates"]},{q:"The Bitcoin whitepaper solved what previously unsolvable problem?",a:"Digital scarcity without a trusted third party",wrong:["Faster internet speeds","Quantum-proof encryption","Free worldwide communication"]},{q:"What did Satoshi embed in the Genesis Block's coinbase transaction?",a:"A newspaper headline about bank bailouts",wrong:["Their real name","A mathematical formula","Instructions for miners"]}],decentralized:[{q:'How many people are "in charge" of Bitcoin?',a:"No one",wrong:["Satoshi Nakamoto","A board of directors","The Bitcoin Foundation"]},{q:"What is needed for code updates to Bitcoin?",a:"Deep consensus from the network",wrong:["A CEO decision","A government vote","Permission from miners only"]},{q:"Bitcoin is described as:",a:"A protocol, not a company",wrong:["A company based in Japan","A government project","A bank product"]},{q:"Bitcoin nodes are run by:",a:"Anyone who wants to, worldwide",wrong:["Only by miners","Only in the United States","Only by approved operators"]},{q:"If one country shuts down all Bitcoin mining:",a:"The network continues in other countries",wrong:["Bitcoin dies","All coins are lost","The price goes to zero permanently"]}],decentralized_pt2:[{q:"Bitcoin has no:",a:"Central point of failure",wrong:["Users","Transactions","Value"]},{q:"Decentralization means:",a:"No single entity controls the network",wrong:["One company runs everything","The government manages it","Only banks can use it"]},{q:"What happens to Bitcoin if one country bans it?",a:"The network continues operating globally since no single country controls it",wrong:["Bitcoin shuts down in that country","All nodes worldwide go offline","Miners must relocate to that country"]},{q:"How many Bitcoin full nodes are estimated to run worldwide?",a:"Tens of thousands across dozens of countries",wrong:["About 100 in the United States","One per continent","Only miners run nodes"]},{q:"Why is geographic distribution of nodes important?",a:"It prevents any single jurisdiction from shutting down the network",wrong:["It makes Bitcoin faster","It reduces electricity costs","It increases the block size"]}],scarce:[{q:"What is the maximum supply of Bitcoin?",a:"21 million",wrong:["100 million","1 billion","Unlimited"]},{q:"How many Bitcoin are estimated to be lost forever?",a:"2-3 million",wrong:["None","10 million","100,000"]},{q:"Bitcoin's code is:",a:"Open source and auditable by anyone",wrong:["Private and closed","Only visible to developers","Controlled by a company"]},{q:"What event cuts Bitcoin's new supply in half?",a:"The halving",wrong:["The merge","The split","The fork"]},{q:"How often does the halving occur?",a:"Approximately every 4 years",wrong:["Every year","Every 10 years","Every month"]}],scarce_pt2:[{q:"Bitcoin is often compared to which precious metal?",a:"Gold",wrong:["Silver","Platinum","Copper"]},{q:"The last Bitcoin will be mined around the year:",a:"2140",wrong:["2030","2050","2025"]},{q:"Bitcoin scarcity is enforced by:",a:"Math and code",wrong:["Government regulations","A central bank","Mining companies"]},{q:"What is the smallest unit of Bitcoin called?",a:"A satoshi (0.00000001 BTC)",wrong:["A bit (0.01 BTC)","A wei","A gwei"]},{q:"How does Bitcoin's stock-to-flow ratio compare to gold after the 2024 halving?",a:"Bitcoin's stock-to-flow surpassed gold's",wrong:["Gold's is still much higher","They are identical","Stock-to-flow doesn't apply to Bitcoin"]}],secure:[{q:"Bitcoin has been under attack since gaining significant value around:",a:"2013",wrong:["2020","2009","2017"]},{q:"How many potential Bitcoin wallets exist?",a:"2^160",wrong:["21 million","A few billion","2^16"]},{q:"Bitcoin's monetary policy is:",a:"Set in stone and immutable",wrong:["Changed annually","Decided by miners","Flexible based on market"]},{q:"A 51% attack would require:",a:"More computing power than the rest of the network combined",wrong:["A password","Government approval","Hacking one computer"]},{q:"Bitcoin has experienced how many hours of downtime since 2013?",a:"Zero",wrong:["Hundreds","A few days each year","One week"]}],secure_pt2:[{q:"Bitcoin uses which hashing algorithm?",a:"SHA-256",wrong:["MD5","RSA","AES"]},{q:"The cost to attack Bitcoin's network is:",a:"Billions of dollars",wrong:["A few hundred dollars","Free","A few thousand dollars"]},{q:"What is Bitcoin's uptime percentage since launch in 2009?",a:"Over 99.98% — virtually no downtime",wrong:["About 95%","Around 80% due to attacks","100% with zero interruptions"]},{q:"Why does higher hashrate make Bitcoin more secure?",a:"More computational power means an attacker needs proportionally more resources to overpower the network",wrong:["Higher hashrate makes transactions free","It allows more coins to be mined","It reduces the block time to seconds"]},{q:"What makes a 51% attack on Bitcoin impractical?",a:"The enormous cost of acquiring more mining power than all honest miners combined",wrong:["The government protects Bitcoin","Satoshi can reverse any attack","Bitcoin uses a firewall"]}],money:[{q:"How many satoshis are in one Bitcoin?",a:"100,000,000",wrong:["1,000,000","1,000","10,000"]},{q:"Bitcoin payments are compared to:",a:"Email — anyone with your address can send",wrong:["Fax machines","Phone calls","Physical mail"]},{q:"Bitcoin's distribution was fair because:",a:"There was no premine",wrong:["A company sold coins early","The government distributed it","Only miners got coins"]},{q:"A satoshi is named after:",a:"Bitcoin's creator, Satoshi Nakamoto",wrong:["A Japanese emperor","A type of sushi","A programming language"]},{q:"Bitcoin is divisible to how many decimal places?",a:"8",wrong:["2","4","16"]}],money_pt2:[{q:"Bitcoin can function as:",a:"A store of value, medium of exchange, and unit of account",wrong:["Only a store of value","Only for payments","Only for speculation"]},{q:'What makes Bitcoin "sound money"?',a:"Fixed supply and predictable issuance",wrong:["Government backing","Bank guarantees","Corporate ownership"]},{q:"Which property of money does Bitcoin's 21 million cap satisfy?",a:"Scarcity — it cannot be inflated or debased",wrong:["Acceptability — everyone must use it","Portability — it weighs nothing","Cognizability — it looks like gold"]},{q:"Why are satoshis important for Bitcoin as money?",a:"They allow micropayments and make Bitcoin divisible enough for everyday transactions",wrong:["They increase the total supply","They are a separate cryptocurrency","They can only be used on Lightning"]},{q:"What gives Bitcoin its monetary value according to Austrian economics?",a:"Subjective value from its useful properties: scarcity, portability, divisibility, and censorship resistance",wrong:["Government decree","Gold backing","The electricity used to mine it"]}],peaceful:[{q:"When China banned Bitcoin:",a:"Bitcoin just moved and kept going",wrong:["Bitcoin shut down","The price went to zero","The code was deleted"]},{q:"Bitcoin is described as:",a:"Permissionless and borderless",wrong:["Government-regulated","Country-specific","Requiring a bank account"]},{q:"Bitcoin enables protest by:",a:"Allowing people to transact without government permission",wrong:["Sending angry emails","Blocking websites","Hacking banks"]},{q:'Bitcoin is called "peaceful" because:',a:"It opts out of the existing system without force",wrong:["It prevents all crime","It eliminates wars","It makes everyone rich"]},{q:"Bitcoin helps people in authoritarian regimes by:",a:"Providing censorship-resistant money",wrong:["Overthrowing governments","Hacking military systems","Printing local currency"]}],peaceful_pt2:[{q:"Bitcoin adoption is described as:",a:"Voluntary and organic",wrong:["Mandatory and forced","Government-mandated","Corporate-controlled"]},{q:"How does Bitcoin function as a peaceful protest tool?",a:"It allows people to opt out of inflationary monetary systems without violence",wrong:["It funds protest organizations","It blocks government websites","It replaces voting systems"]},{q:'Why is Bitcoin described as "opt-in" money?',a:"Nobody is forced to use it — participation is entirely voluntary",wrong:["You must opt in through a bank","Governments assign Bitcoin to citizens","Mining is mandatory for users"]},{q:"How did Bitcoin help protestors in authoritarian regimes?",a:"It allowed them to receive donations that could not be frozen by the government",wrong:["It gave them free internet access","It replaced their national ID systems","It provided encrypted phone calls"]},{q:'What makes Bitcoin "permissionless"?',a:"Anyone can send, receive, or hold Bitcoin without needing approval from any authority",wrong:["You need a license to own it","Only approved wallets can transact","Miners must approve each transaction manually"]}],dominant:[{q:"∞/21M means:",a:"All world wealth funneling into 21 million coins",wrong:["Bitcoin is infinite","There are infinite users","21 million blockchains"]},{q:"Bitcoin's growth pattern resembles:",a:"A J-shaped curve",wrong:["A straight line","A bell curve","A flat line"]},{q:"Bitcoin is said to change you by:",a:"Lowering your time preference",wrong:["Making you rich instantly","Increasing spending","Nothing changes"]},{q:"Bitcoin's market dominance refers to:",a:"Its share of total cryptocurrency market cap",wrong:["How many users it has","Its mining speed","Its block size"]},{q:"The Lindy Effect suggests Bitcoin:",a:"Will last longer the longer it survives",wrong:["Will die soon","Is a fad","Needs government support"]}],dominant_pt2:[{q:"Bitcoin is considered dominant because:",a:"It has the strongest network effect and security",wrong:["It was the cheapest","A government chose it","It has the most features"]},{q:'What is the "Lindy effect" as applied to Bitcoin\'s dominance?',a:"The longer Bitcoin survives and grows, the more likely it is to continue dominating",wrong:["Old technology always fails eventually","Bitcoin dominance decreases with age","Lindy only applies to physical goods"]},{q:"Why do network effects favor Bitcoin over altcoins?",a:"More users, miners, developers, and infrastructure create a self-reinforcing cycle that's hard for competitors to match",wrong:["Bitcoin has the best marketing team","Altcoins are illegal","Network effects only apply to social media"]},{q:'What does Bitcoin\'s "dominance" metric measure?',a:"Bitcoin's share of total cryptocurrency market capitalization",wrong:["The number of Bitcoin nodes vs altcoin nodes","Bitcoin's hash rate compared to all others","The percentage of merchants accepting Bitcoin"]},{q:"Why has no altcoin overtaken Bitcoin despite thousands of attempts?",a:"Bitcoin's first-mover advantage, network effects, decentralization, and brand recognition create an insurmountable moat",wrong:["The government protects Bitcoin specifically","Altcoins are all scams with no technology","Satoshi prevents forks from succeeding"]}],"use-cases":[{q:"Bitcoin is described as better than gold because:",a:"It can be sent across the planet instantly",wrong:["It's heavier","It's shinier","It's backed by gold"]},{q:"How do Bitcoin remittance fees compare to Western Union?",a:"Much cheaper, nearly free",wrong:["About the same","More expensive","Double the cost"]},{q:"Credit card merchants pay about what fee?",a:"3%",wrong:["0%","10%","25%"]},{q:"Bitcoin can help the unbanked because:",a:"You only need a phone and internet to use it",wrong:["Banks distribute it","The government gives it away","You need a credit score"]},{q:"Bitcoin as a hedge against inflation means:",a:"Its fixed supply protects purchasing power",wrong:["It always goes up","The government guarantees its value","It pays interest"]}],"use-cases_pt2":[{q:"Micropayments on Bitcoin are possible through:",a:"The Lightning Network",wrong:["Visa","PayPal","Wire transfer"]},{q:"Bitcoin enables financial sovereignty by:",a:"Letting you be your own bank",wrong:["Requiring a bank account","Needing government ID","Using credit scores"]},{q:"Why is Bitcoin especially valuable for international remittances?",a:"It settles in minutes with low fees compared to days and high fees with traditional wire transfers",wrong:["It automatically converts to local currency","Banks process Bitcoin remittances for free","It requires no internet connection"]},{q:'How does Bitcoin serve as a "savings technology"?',a:"Its fixed supply and deflationary nature preserve purchasing power over time",wrong:["It pays interest like a savings account","Banks guarantee Bitcoin deposits","It automatically grows by 10% annually"]},{q:"What makes Bitcoin useful for micropayments via Lightning?",a:"Sub-penny transaction fees and instant settlement enable payments too small for traditional systems",wrong:["Lightning removes the need for Bitcoin","Micropayments require on-chain transactions","Only amounts over $1 can be sent"]}],mining:[{q:"What do miners do?",a:"Secure the network and process transactions",wrong:["Create Bitcoin from nothing","Print digital money","Delete old transactions"]},{q:"Miners are paid in:",a:"New Bitcoin and transaction fees",wrong:["US dollars","Ethereum","Company stock"]},{q:"Mining difficulty adjusts approximately every:",a:"2 weeks (2016 blocks)",wrong:["Every day","Every hour","Never"]},{q:"A mining pool is:",a:"A group of miners combining computing power",wrong:["A swimming pool for tech workers","A single powerful computer","A government facility"]},{q:"The mining reward after the 2024 halving is:",a:"3.125 BTC per block",wrong:["6.25 BTC","50 BTC","12.5 BTC"]}],mining_pt2:[{q:"ASIC miners are:",a:"Specialized hardware designed only for mining",wrong:["Regular laptops","Gaming consoles","Smart phones"]},{q:"What prevents miners from cheating?",a:"Other nodes verify their work",wrong:["The honor system","Government oversight","Nothing"]},{q:"What milestone did Bitcoin hash rate reach in September 2025?",a:"1 Zettahash per second",wrong:["500 Exahash","10 Petahash","100 Terahash"]},{q:"Pleb Pool and Atlas Pool are examples of:",a:"Solo Bitcoin mining pools",wrong:["Lightning wallets","Bitcoin exchanges","Hardware wallets"]},{q:"D-Central Technologies specializes in:",a:"Home mining equipment and support",wrong:["Bitcoin trading","Lightning channels","Cold storage"]}],mining_pt3:[{q:"Constellation Heating combines mining with:",a:"Heating swimming pools",wrong:["Cooling data centers","Wind power","Solar panels"]},{q:'What is a "nonce" in Bitcoin mining?',a:'A "number used once" that miners change to find a valid hash',wrong:["A type of mining hardware","A fee paid to nodes","The total number of Bitcoins"]},{q:"Mining pools allow small miners to:",a:"Receive more frequent, smaller payouts",wrong:["Control the entire network","Mine without using electricity","Change the supply of Bitcoin"]},{q:"Bitcoin difficulty adjusts every how many blocks?",a:"2,016 blocks (roughly 2 weeks)",wrong:["210,000 blocks","Only during halvings","Every single block"]},{q:"Bitcoin mining is best described as:",a:"A brute-force lottery of guessing nonces until a valid hash is found",wrong:["Solving complex mathematical equations","Running an algorithm that factors large prime numbers","Decrypting encrypted transaction data"]}],mining_pt4:[{q:"What happens when a miner finds a valid block hash?",a:"They broadcast the block to the network, collect the block reward and transaction fees",wrong:["They must wait for government approval before adding it","The block is sent to Satoshi for verification","All other miners must restart their hardware"]},{q:"Why does Bitcoin mining use so much energy?",a:"Energy expenditure is what gives Bitcoin its security — it makes attacks prohibitively expensive",wrong:["The code is poorly optimized","Miners are required to run 24/7 by law","Each transaction requires its own mining operation"]},{q:'What is "hash rate" in Bitcoin mining?',a:"The total computational power being used to process transactions and secure the network",wrong:["The speed at which new coins are printed","The rate at which transactions are deleted","The number of miners currently online"]},{q:'What is "stranded energy" and why do Bitcoin miners seek it?',a:"Energy produced in remote locations with no local demand — miners can monetize it at low cost",wrong:["Energy that has been stored in batteries","Solar power generated at night","Electricity from decommissioned plants only"]},{q:'What is a mining "share" in a pool?',a:"Proof that a miner contributed valid work toward finding a block, used to split rewards proportionally",wrong:["A stock in the mining company","A partial Bitcoin sent to the miner","A vote on which transactions to include"]}],nodes:[{q:"Running a node lets you:",a:"Verify transactions independently",wrong:["Mine Bitcoin","Print money","Control the network"]},{q:'"Don\'t trust, verify" means:',a:"Run your own node to check the truth",wrong:["Trust your bank","Believe what others say","Ignore Bitcoin"]},{q:"A full node stores:",a:"The entire blockchain history",wrong:["Only your transactions","Just the latest block","Nothing"]},{q:"How many Bitcoin nodes exist approximately?",a:"Tens of thousands worldwide",wrong:["Only 5","Exactly 21 million","One per country"]},{q:"Running a node requires:",a:"A regular computer with enough storage",wrong:["A supercomputer","Government permission","A mining rig"]}],nodes_pt2:[{q:"Nodes enforce:",a:"The consensus rules of Bitcoin",wrong:["Government laws","Company policies","Social media rules"]},{q:"Clark Moody dashboard is useful for tracking:",a:"Bitcoin network stats and Knots adoption",wrong:["Altcoin prices","Social media followers","Email subscribers"]},{q:"Matt Hill is the founder and CEO of:",a:"Start9 (node-in-a-box solution)",wrong:["Bitcoin Magazine","Coinbase","Blockstream"]},{q:"The Bitcoin Commons governance model proposes:",a:"Coordination without authority for Bitcoin implementations",wrong:["Central planning of upgrades","Voting on block size","Government oversight"]},{q:"A pruned node saves space by:",a:"Deleting old block data after validating it",wrong:["Only downloading headers","Charging other nodes for storage","Reducing the frequency of blocks"]}],nodes_pt3:[{q:"A full node is different from a miner because:",a:"It enforces all rules but doesn't create new blocks",wrong:["It is faster than a miner","It requires more electricity","It is only for experts"]},{q:"How does your node know if a transaction is valid?",a:"It checks the signatures and inputs against the consensus rules",wrong:["It asks a central server","It votes with other nodes","It waits for a tweet from Satoshi"]},{q:"What is the main benefit of running your own Bitcoin node?",a:"You verify all transactions and blocks yourself without trusting any third party",wrong:["You earn Bitcoin rewards for running it","You can mine Bitcoin more efficiently","You get faster transaction speeds"]},{q:'What does "initial block download" (IBD) mean?',a:"The process of downloading and validating the entire blockchain when first setting up a node",wrong:["The time it takes to mine the first block","Downloading the Bitcoin software installer","Syncing your wallet with an exchange"]},{q:"How does a Bitcoin node protect you from accepting fake transactions?",a:"It independently validates every transaction against consensus rules before accepting it",wrong:["It contacts Satoshi for verification","It checks with three other nodes and takes a vote","It uses AI to detect fraud patterns"]}],"pow-vs-pos":[{q:"Bitcoin uses which consensus mechanism?",a:"Proof of Work",wrong:["Proof of Stake","Proof of Authority","Proof of Space"]},{q:"In Proof of Work, security comes from:",a:"Computational work and electricity",wrong:["Staking coins","Voting","Government approval"]},{q:"Proof of Stake has been criticized for:",a:"Favoring wealthy holders (the rich get richer)",wrong:["Using too much energy","Being too decentralized","Being too slow"]},{q:"Proof of Work connects Bitcoin to:",a:"The physical world through energy expenditure",wrong:["The stock market","Social media","Government databases"]},{q:"In PoW, you can't fake:",a:"The energy spent to mine a block",wrong:["Your username","Your IP address","The current time"]}],"pow-vs-pos_pt2":[{q:"Proof of Work was chosen because:",a:"It provides unforgeable costliness",wrong:["It was the cheapest option","Satoshi had no other ideas","The government required it"]},{q:"What real-world resource does Proof of Work consume that Proof of Stake does not?",a:"Energy (electricity used for computation)",wrong:["Hard drive space","Internet bandwidth","RAM memory"]},{q:'What is the "nothing at stake" problem in Proof of Stake?',a:"Validators can sign multiple competing chain forks at no cost, weakening consensus",wrong:["Stakers lose all their tokens if they validate","There is no block reward in PoS","Validators must buy mining hardware"]},{q:"Why do PoW proponents argue it provides stronger security guarantees?",a:"Attacking PoW requires massive ongoing real-world energy expenditure that can't be faked",wrong:["PoW has more developers working on it","PoW chains are always faster","PoW was invented first so it must be better"]},{q:"How does Proof of Stake differ from Proof of Work in block producer selection?",a:"PoS selects validators based on the amount of coins they lock up, while PoW requires solving computational puzzles",wrong:["PoS uses random lottery tickets purchased with fiat","PoW lets the richest miner always win","There is no difference in selection mechanism"]}],"layer-2-lightning":[{q:"Lightning is which layer of Bitcoin?",a:"Layer 2",wrong:["Layer 1","Layer 3","Layer 0"]},{q:"Lightning uses what for privacy?",a:"Onion routing",wrong:["GPS tracking","Public ledger","Email verification"]},{q:"Opening a Lightning channel is like:",a:"Opening a bar tab",wrong:["Buying a car","Getting a loan","Opening a bank account"]},{q:"Lightning transactions are:",a:"Nearly instant and very cheap",wrong:["Slow and expensive","Free but take hours","Only for large amounts"]},{q:"Lightning channels are settled on:",a:"The Bitcoin base layer",wrong:["Ethereum","A separate blockchain","A bank ledger"]}],"layer-2-lightning_pt2":[{q:"Lightning enables:",a:"Micropayments as small as 1 satoshi",wrong:["Only large transactions","Only fiat payments","Only international transfers"]},{q:"Lightning capacity refers to:",a:"The total Bitcoin locked in payment channels",wrong:["Internet bandwidth","Mining power","Number of nodes"]},{q:"Satogram allows you to:",a:"Send messages across the Lightning network",wrong:["Mine Bitcoin","Create NFTs","Swap altcoins"]},{q:"Lightning Cats and Lightning Goats let you:",a:"Feed real animals using Lightning payments",wrong:["Trade animal NFTs","Mine with animal power","Buy pets with Bitcoin"]},{q:"Pay With Flash is a service for:",a:"Businesses to accept Bitcoin payments",wrong:["Mining Bitcoin","Cold storage","Coin mixing"]}],"layer-2-lightning_pt3":[{q:"LNgigs is a Bitcoin-powered:",a:"Freelance marketplace",wrong:["Mining pool","Exchange","Hardware wallet"]},{q:"The Lightning Network whitepaper was written by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto","Vitalik Buterin","Adam Back"]},{q:"Lightning Network payment channels work by:",a:"Opening a channel with an on-chain transaction, then transacting off-chain instantly",wrong:["Creating a separate blockchain for each payment","Sending Bitcoin through email servers","Using proof of stake instead of proof of work"]},{q:"Why is Lightning considered a Layer 2 solution?",a:"It builds on top of Bitcoin's base layer without changing the protocol",wrong:["Because it is the second cryptocurrency ever created","Because it requires two confirmations per transaction","Because only two people can use it at a time"]},{q:"A Lightning invoice is:",a:"A payment request containing the amount, destination, and expiry time",wrong:["A monthly bill for using the Lightning Network","A receipt showing your mining rewards","A document required by tax authorities"]}],"self-custody":[{q:'"Not your keys, not your..."',a:"Bitcoin",wrong:["Wallet","Password","Account"]},{q:"The most secure long-term storage is:",a:"Hardware wallet",wrong:["Exchange account","Phone app","Email attachment"]},{q:"A seed phrase is typically:",a:"12 or 24 words that recover your wallet",wrong:["Your email password","A website URL","A phone number"]},{q:"You should store your seed phrase:",a:"On paper or metal in a secure location",wrong:["In a screenshot on your phone","In your email drafts","On social media"]},{q:"Multi-sig means:",a:"Multiple keys required to authorize a transaction",wrong:["Multiple Bitcoin addresses","Multiple blockchains","Multiple exchanges"]}],"self-custody_pt2":[{q:"When an exchange holds your Bitcoin:",a:"You have an IOU, not actual Bitcoin",wrong:["It's completely safe","You own it fully","The government insures it"]},{q:"Cold storage means:",a:"Keeping keys offline, disconnected from the internet",wrong:["Storing Bitcoin in a freezer","A cold climate mining facility","An inactive exchange account"]},{q:"A hardware wallet provides security by:",a:"Keeping private keys on a dedicated device that never exposes them to the internet",wrong:["Storing Bitcoin inside the physical device","Encrypting the blockchain so only you can read it","Requiring government approval for each transaction"]},{q:"If you lose your hardware wallet but have your seed phrase, you can:",a:"Recover all your Bitcoin on a new wallet using the seed phrase",wrong:["Nothing — the Bitcoin is permanently lost","Contact the wallet manufacturer for a replacement","File a claim with Bitcoin insurance"]},{q:"Multisig (multi-signature) wallets require:",a:"Multiple keys to authorize a transaction (e.g., 2-of-3)",wrong:["Multiple Bitcoin addresses to send from","Multiple confirmations from the same key","Multiple mining pools to verify"]}],"privacy-nonkyc":[{q:"KYC stands for:",a:"Know Your Customer",wrong:["Keep Your Coins","Keys You Control","Knowledge Yields Crypto"]},{q:"CoinJoin is used for:",a:"Mixing transactions for privacy",wrong:["Joining mining pools","Merging blockchains","Creating altcoins"]},{q:"Non-KYC Bitcoin means:",a:"Bitcoin acquired without identity verification",wrong:["Stolen Bitcoin","Fake Bitcoin","Government Bitcoin"]},{q:"Bitcoin's blockchain is:",a:"Public — anyone can see transactions",wrong:["Completely private","Only visible to miners","Encrypted and hidden"]},{q:"Why do some people prefer non-KYC Bitcoin?",a:"To maintain financial privacy",wrong:["To pay lower fees","To mine faster","To get a better price"]}],"privacy-nonkyc_pt2":[{q:"A Bitcoin address should ideally be:",a:"Used only once for privacy",wrong:["Shared with everyone","Used for all transactions","Posted on social media"]},{q:"The first recorded address poisoning attack on Bitcoin happened in:",a:"2025",wrong:["2021","2013","2009"]},{q:"Shielded CSV on Bitcoin promises:",a:"Better than Zcash-level privacy as an L1.5",wrong:["Faster mining","Bigger blocks","More altcoins"]},{q:"Briar messenger is engineered for:",a:"Privacy in hostile environments using Tor",wrong:["Fast video calls","Social media sharing","Cloud storage"]},{q:'What is a "Dust Attack"?',a:"Tiny amounts of BTC sent to addresses to track the owner's movement",wrong:["A network overload","A type of mining hardware failure","Deleting your private keys by accident"]}],"privacy-nonkyc_pt3":[{q:'"WabiSabi" and "Whirlpool" are types of:',a:"CoinJoin coordination protocols",wrong:["Mining hardware","Wallet brand names","Bitcoin address formats"]},{q:"KYC (Know Your Customer) in Bitcoin refers to:",a:"Identity verification required by regulated exchanges",wrong:["A type of encryption algorithm","A consensus mechanism used by altcoins","The name of a Bitcoin wallet"]},{q:"Why do some Bitcoiners prefer non-KYC acquisition?",a:"To protect financial privacy and avoid linking identity to Bitcoin holdings",wrong:["Because it is cheaper than using exchanges","Because KYC Bitcoin is worth less","Because non-KYC Bitcoin mines faster"]},{q:'What is "address reuse" and why is it a privacy concern?',a:"Using the same Bitcoin address multiple times lets observers link all those transactions to one entity",wrong:["It causes transactions to fail","It increases mining fees","It violates Bitcoin consensus rules"]},{q:'What does "non-KYC Bitcoin" mean?',a:"Bitcoin acquired without providing identity documents, such as through peer-to-peer trades or mining",wrong:["Bitcoin that has never been in a wallet","Bitcoin mined before 2013","Bitcoin stored on a hardware wallet"]}],"problems-of-money":[{q:"The Cantillon Effect describes:",a:"Those closest to money printing benefit most",wrong:["Bitcoin mining","The halving","Lightning fees"]},{q:"Fractional reserve banking means:",a:"Banks hold only a fraction of deposits",wrong:["Banks hold all deposits","Bitcoin is fractional","Miners keep fractions"]},{q:"Inflation is often called:",a:"A hidden tax on savings",wrong:["A bonus for savers","A mining reward","A blockchain feature"]},{q:"Fiat currency is backed by:",a:"Government decree and trust",wrong:["Gold reserves","Bitcoin","Real estate"]},{q:"The US dollar has lost what percentage of purchasing power since 1913?",a:"Over 96%",wrong:["About 10%","None","About 50%"]}],"problems-of-money_pt2":[{q:"Money printing causes:",a:"Devaluation of existing currency",wrong:["Deflation","Higher savings rates","Stronger currency"]},{q:"Sound money historically meant:",a:"Money that couldn't be easily debased",wrong:["Money that makes noise","Digital currency","Credit cards"]},{q:"The Cantillon Effect describes how:",a:"Those closest to new money benefit most from inflation",wrong:["Bitcoin mining gets harder","Banks lose money","Gold prices drop"]},{q:"ShadowStats.com tracks:",a:"Real inflation rates vs official government numbers",wrong:["Bitcoin mining difficulty","Lightning channel capacity","Altcoin prices"]},{q:'"The Four Horsemen" documentary (2013) exposes:',a:"The fiat monetary system scam",wrong:["Bitcoin mining farms","Social media dangers","Space exploration"]}],"problems-of-money_pt3":[{q:'"Nixon Shock" in 1971 refers to:',a:"The US ending the dollar's convertibility into gold",wrong:["The launch of Bitcoin","A global stock market crash","The creation of the first bank"]},{q:"Gresham's Law states that:",a:'"Bad money drives out good money"',wrong:['"Bitcoin will replace fiat"','"Gold is always better than silver"','"Taxes are voluntary"']},{q:"What happened in 1971?",a:"Nixon ended the gold standard, allowing unlimited fiat money printing",wrong:["Bitcoin was invented","The first digital computer was built","The Euro was introduced"]},{q:'Inflation is often called a "hidden tax" because:',a:"It silently erodes the purchasing power of your savings",wrong:["The IRS taxes Bitcoin gains at a hidden rate","Banks charge fees that are not disclosed","Governments print money in secret locations"]},{q:"What is seigniorage?",a:"The profit a government makes by issuing currency that costs less to produce than its face value",wrong:["A tax on gold mining","Interest earned on savings accounts","The fee banks charge for wire transfers"]}],"investment-strategy":[{q:"DCA stands for:",a:"Dollar Cost Averaging",wrong:["Digital Currency Account","Decentralized Crypto Asset","Direct Coin Access"]},{q:"A common Bitcoin investment strategy is:",a:"Buy regularly and hold long-term",wrong:["Day trade constantly","Sell every week","Only buy at the top"]},{q:"HODL originated from:",a:'A misspelled forum post saying "I AM HODLING"',wrong:["A financial textbook","A government document","A bank term"]},{q:"Bitcoin's 4-year cycle is often tied to:",a:"The halving events",wrong:["US elections","Solar cycles","Stock market seasons"]},{q:"The best time to buy Bitcoin according to Bitcoiners is:",a:"Always — time in the market beats timing the market",wrong:["Only at all-time highs","Only on Mondays","Only in December"]}],"investment-strategy_pt2":[{q:"Stacking sats means:",a:"Accumulating small amounts of Bitcoin over time",wrong:["Building satellite dishes","Stacking physical coins","Creating smart contracts"]},{q:"The biggest drawdown in Bitcoin history was:",a:"94% decline from $32 to $2 in July 2011",wrong:["50% in 2018","70% in 2022","80% in 2014"]},{q:"MNAV.com tracks:",a:"Bitcoin treasury companies and their metrics",wrong:["Lightning channels","Mining pools","Altcoin prices"]},{q:"Lump-sum investing means:",a:"Buying a large amount of Bitcoin all at once",wrong:["Buying a fixed amount every week","Selling all your holdings","Trading only on weekends"]},{q:"Dollar Cost Averaging (DCA) means:",a:"Buying a fixed amount of Bitcoin at regular intervals regardless of price",wrong:["Only buying when the price drops below a target","Investing your entire savings at once","Selling Bitcoin every time it rises 10%"]}],"investment-strategy_pt3":[{q:'The Bitcoin phrase "zoom out" means:',a:"Look at the long-term price trend instead of daily volatility",wrong:["Reduce your Bitcoin position size","Use a magnifying glass to read the whitepaper","Exit the market during a downturn"]},{q:'What does "stacking sats" mean in Bitcoin culture?',a:"Regularly accumulating small amounts of Bitcoin (satoshis) over time",wrong:["Building a stack of physical Bitcoin coins","Storing Bitcoin on multiple exchanges","Running multiple mining rigs simultaneously"]},{q:'Why do Bitcoiners say "time in the market beats timing the market"?',a:"Long-term holders historically outperform those trying to buy dips and sell tops",wrong:["Because Bitcoin's price never goes down","Because exchanges charge timing fees","Because mining rewards increase over time"]},{q:'What is the "HODL" strategy?',a:"Buying Bitcoin and holding it long-term regardless of short-term price volatility",wrong:["A day-trading technique for quick profits","An automated trading bot strategy","Holding exactly 1 Bitcoin at all times"]},{q:"Why is cold storage recommended for long-term Bitcoin holdings?",a:"Keeping private keys offline eliminates the risk of remote hacking or exchange failure",wrong:["Cold storage earns interest on your Bitcoin","It makes transactions faster","Cold wallets automatically back up to the cloud"]}],cryptography:[{q:"Bitcoin uses cryptography that has been:",a:"Used for decades in other applications",wrong:["Invented specifically for Bitcoin","Never tested before","Made by AI"]},{q:"A private key is:",a:"A secret number that controls your Bitcoin",wrong:["Your email password","A physical key","Your bank PIN"]},{q:"A public key is derived from:",a:"The private key using one-way math",wrong:["Your name","Random chance","The blockchain"]},{q:"Digital signatures prove:",a:"You own the private key without revealing it",wrong:["Your identity","Your location","Your bank balance"]},{q:"Hashing is:",a:"Converting data into a fixed-length fingerprint",wrong:["Deleting data","Encrypting emails","Mining Bitcoin"]}],cryptography_pt2:[{q:"Elliptic curve cryptography is used for:",a:"Generating Bitcoin key pairs",wrong:["Mining blocks","Sending emails","Browsing the web"]},{q:"What type of cryptography does Bitcoin use for digital signatures?",a:"Elliptic Curve Digital Signature Algorithm (ECDSA) on the secp256k1 curve",wrong:["RSA 2048-bit encryption","AES-256 symmetric encryption","Triple DES block cipher"]},{q:"What is a hash function's role in Bitcoin?",a:"It creates a fixed-size, unique digital fingerprint of any input data, used for block headers, addresses, and mining",wrong:["It encrypts all Bitcoin transactions end-to-end","It compresses the blockchain to save space","It converts Bitcoin to other cryptocurrencies"]},{q:"Why can't you derive a private key from a public key?",a:"Elliptic curve math is a one-way function — easy to compute forward, computationally infeasible to reverse",wrong:["Because private keys are longer than public keys","Because the blockchain deletes private keys","Because Satoshi encrypted all key pairs"]},{q:"What does SHA-256 stand for and where is it used in Bitcoin?",a:"Secure Hash Algorithm 256-bit — used in mining (proof of work) and creating transaction IDs",wrong:["Super Hash Accelerator — used in wallet encryption only","Satoshi Hash Algorithm — used in signature verification","Shared Hash Array — used in peer-to-peer networking"]}],regulation:[{q:"Bitcoin's response to bans has been:",a:"Moving to friendlier jurisdictions",wrong:["Shutting down","Complying immediately","Becoming illegal forever"]},{q:"El Salvador made Bitcoin:",a:"Legal tender in 2021",wrong:["Illegal in 2020","A national secret","Only for tourists"]},{q:"Bitcoin regulation varies by:",a:"Country — each has different rules",wrong:["There are no rules anywhere","One global law covers it","Bitcoin regulates itself"]},{q:"A Bitcoin ETF allows:",a:"Traditional investors to get Bitcoin exposure through stock markets",wrong:["Free Bitcoin for everyone","Government-controlled mining","Printing new Bitcoin"]},{q:"The SEC has classified Bitcoin as:",a:"A commodity, not a security",wrong:["A security","A currency","Illegal"]}],regulation_pt2:[{q:'What is a "Self-Custody" regulation attempt?',a:"Rules that try to force users to use custodial services",wrong:["Laws that guarantee free Bitcoin","Mining equipment safety standards","Bitcoin price caps"]},{q:"Can a government effectively ban Bitcoin?",a:"They can restrict fiat on-ramps but cannot stop peer-to-peer transactions",wrong:["Yes — turning off the internet kills Bitcoin permanently","Yes — all nodes can be identified and shut down simultaneously","No bans have ever been attempted by any country"]},{q:"China has banned Bitcoin mining multiple times, yet:",a:"Miners relocated and the network hash rate recovered within months",wrong:["Bitcoin permanently lost 50% of its value","All Chinese Bitcoin was confiscated","The Bitcoin network was offline for weeks"]},{q:"How is Bitcoin classified for tax purposes in most jurisdictions?",a:"As property or a capital asset, meaning gains are subject to capital gains tax",wrong:["As currency, exempt from all taxes","As a commodity with no reporting requirements","As digital cash with no tax implications"]},{q:'What does the "Travel Rule" require for crypto transactions?',a:"Regulated exchanges must share sender and receiver identity information for transfers above a threshold",wrong:["Users must physically travel to an exchange to withdraw","Bitcoin can only be sent within your home country","Miners must verify passport numbers for each block"]}],energy:[{q:"Bitcoin mining and energy:",a:"Promotes renewable energy and uses wasted energy",wrong:["Only uses coal","Wastes all energy","Uses no energy"]},{q:"Stranded energy refers to:",a:"Energy produced in remote locations with no buyers",wrong:["Electricity outages","Solar panels at night","Wind on calm days"]},{q:"Bitcoin miners often locate near:",a:"Cheap renewable energy sources",wrong:["Shopping malls","Government buildings","Residential areas"]},{q:"Bitcoin mining can help stabilize:",a:"Electrical grids by acting as a flexible load",wrong:["The stock market","Internet speeds","Political systems"]},{q:"Compared to traditional banking, Bitcoin's energy use is:",a:"Debatable but often comparable or less",wrong:["1000x more","Zero","Exactly the same"]}],energy_pt2:[{q:"Methane flaring and Bitcoin mining:",a:"Miners can capture and use flared gas productively",wrong:["They are unrelated","Mining increases flaring","Flaring powers all mining"]},{q:"Bitcoin mining primarily uses which type of energy?",a:"Over 50% renewable — often stranded or wasted energy",wrong:["100% coal and natural gas","Nuclear power exclusively","Solar panels attached to mining rigs"]},{q:"Bitcoin mining can actually help the environment by:",a:"Monetizing flared methane that would otherwise be released into the atmosphere",wrong:["Reducing the total electricity consumed worldwide","Creating new renewable energy out of thin air","Cooling the planet through heat dissipation"]},{q:"How do Bitcoin miners contribute to grid stability?",a:"They can instantly power down during peak demand, acting as flexible load that balances the grid",wrong:["They generate excess electricity for the grid","They replace power plants entirely","They only mine during off-peak hours by law"]},{q:"What percentage of Bitcoin mining uses renewable energy sources according to recent estimates?",a:"Over 50% and growing, driven by miners seeking the cheapest energy",wrong:["Less than 5%","Exactly 100% — all mining is renewable","About 10%, mostly nuclear"]}],"core-source-code":[{q:"Changes to Bitcoin Core require:",a:"Careful testing and peer review",wrong:["One person's approval","A company decision","Government permission"]},{q:"Bitcoin Core is written primarily in:",a:"C++",wrong:["Python","JavaScript","Java"]},{q:"Anyone can:",a:"Read, review, and propose changes to Bitcoin's code",wrong:["Change Bitcoin without review","Delete the blockchain","Add more coins"]},{q:"A BIP is:",a:"A Bitcoin Improvement Proposal",wrong:["A Bitcoin Investment Plan","A Block Information Protocol","A Banking Integration Process"]},{q:"Bitcoin's code repository is hosted on:",a:"GitHub",wrong:["Facebook","A secret server","The dark web"]}],"blockchain-timechain":[{q:"A new Bitcoin block is produced approximately every:",a:"10 minutes",wrong:["1 second","1 hour","1 day"]},{q:"Each block contains:",a:"A list of transactions and a reference to the previous block",wrong:["Just one transaction","Pictures","Email addresses"]},{q:"The blockchain is often called:",a:"An immutable ledger",wrong:["A cloud server","A website","A database that can be edited"]},{q:"Satoshi originally called it:",a:"A timechain",wrong:["A blockchain","A datachain","A coinchain"]},{q:"The Genesis Block contains a message about:",a:"A newspaper headline about bank bailouts",wrong:["A recipe","A love letter","A stock tip"]}],"blockchain-timechain_pt2":[{q:"Block height refers to:",a:"The sequential number of a block in the chain",wrong:["How tall a server rack is","The size of the block","Mining difficulty"]},{q:"Satoshi originally called the blockchain the:",a:"Timechain",wrong:["Hashchain","Blockweb","Cryptoledger"]},{q:"Each Bitcoin block contains a reference to:",a:"The hash of the previous block, creating an unbreakable chain",wrong:["The next block that will be mined","All future transactions that will occur","A backup of the entire blockchain"]},{q:"The mempool is:",a:"A waiting area where unconfirmed transactions sit until miners include them in a block",wrong:["A type of Bitcoin storage device","The total amount of memory used by Bitcoin nodes","A pool of memory shared between mining hardware"]},{q:'Why did Satoshi originally call it a "timechain" rather than "blockchain"?',a:"Because each block timestamps transactions in chronological order, creating a chain of time-stamped records",wrong:["Because blocks are mined at exactly 10-minute intervals","Because it tracks time zones for each transaction",'Because the name "blockchain" was already trademarked']}],analogies:[{q:"In the airport analogy, Lightning is like:",a:"A bicycle courier in the terminal",wrong:["The runway","A cargo plane","Air traffic control"]},{q:"Bitcoin is often compared to:",a:"Digital gold",wrong:["Digital silver","Digital stocks","Digital bonds"]},{q:"The Bitcoin network is sometimes compared to:",a:"The internet protocol (TCP/IP)",wrong:["A single website","A phone call","A TV channel"]},{q:"Holding Bitcoin is compared to:",a:"Holding property in cyberspace",wrong:["Renting a movie","Subscribing to a service","Opening a bank account"]},{q:"Bitcoin is often compared to digital gold because both are scarce, durable, and serve as stores of value outside government control.",a:"Digital gold",wrong:["Digital cash","Digital silver","Digital oil"]}],byzantine_generals__problem:[{q:"The Byzantine Generals Problem is about:",a:"Reaching agreement when some participants may be dishonest",wrong:["Building castles","Trading gold","Sending emails"]},{q:"Bitcoin solved the Byzantine Generals Problem using:",a:"Proof of Work consensus",wrong:["A voting system","A trusted mediator","Encryption alone"]},{q:"In the analogy, the generals need to:",a:"Coordinate an attack without a trusted messenger",wrong:["Build a wall","Trade horses","Sign a peace treaty"]},{q:"Before Bitcoin, the Byzantine Generals Problem was considered:",a:"Unsolvable in a trustless digital environment",wrong:["Easy to solve","Irrelevant","Already solved by banks"]},{q:"The Byzantine Generals Problem asks how dispersed parties can reach consensus without trusting each other. What mechanism did Bitcoin invent to solve this?",a:"Nakamoto Consensus (proof-of-work + longest chain)",wrong:["Voting by validator nodes","Centralized coordinator server","Proof of stake randomization"]}],game_theory:[{q:"Bitcoin's incentive structure uses:",a:"Game theory to align participants",wrong:["Threats of punishment","Legal contracts","Trust alone"]},{q:"Miners are incentivized to be honest because:",a:"Cheating costs more than playing by the rules",wrong:["They sign contracts","The government watches them","There are no incentives"]},{q:"Nash Equilibrium in Bitcoin means:",a:"No participant benefits from changing their strategy alone",wrong:["Everyone mines equally","Prices never change","All nodes are identical"]},{q:"The prisoner's dilemma relates to Bitcoin because:",a:"Cooperation is more profitable than defection",wrong:["Miners are in prison","Bitcoin is illegal","Users are trapped"]},{q:"What game theory concept explains why Bitcoin miners are incentivized to stay honest rather than attack the network?",a:"Nash equilibrium — attacking costs more than honest mining",wrong:["Prisoner\\'s dilemma","Zero-sum game","Pareto inefficiency"]}],elevator_pitches:[{q:"A good Bitcoin elevator pitch should be:",a:"Simple and compelling in under a minute",wrong:["A 2-hour lecture","Only about price","As technical as possible"]},{q:"When explaining Bitcoin to beginners, start with:",a:"The problem it solves (broken money)",wrong:["Mining algorithms","Cryptographic proofs","Exchange trading"]},{q:"The simplest Bitcoin pitch is often:",a:"Digital money that no one can print or confiscate",wrong:["A get-rich-quick scheme","Internet points","A new bank"]},{q:"How would you explain Bitcoin to a complete newcomer in one sentence?",a:"A digital form of money that no government or company can print, freeze, or control",wrong:["A speculative investment to get rich quick","A credit card for online shopping","A bank account with higher interest"]},{q:"What is the most important feature for Bitcoin newcomers to understand first?",a:"Nobody can confiscate or freeze your bitcoin if you hold your own keys",wrong:["The price will always go up","It\\'s anonymous like cash","Transactions are free"]}],taproot:[{q:"Taproot is a Bitcoin:",a:"Upgrade that improves privacy and smart contracts",wrong:["New cryptocurrency","Mining algorithm","Exchange platform"]},{q:"Taproot was activated in:",a:"November 2021",wrong:["January 2009","March 2015","June 2023"]},{q:"Taproot uses Schnorr signatures which:",a:"Make multi-sig transactions look like regular ones",wrong:["Speed up mining","Create new coins","Delete old blocks"]},{q:"Taproot improves:",a:"Privacy, efficiency, and smart contract capabilities",wrong:["Mining speed only","Block size only","Transaction fees only"]},{q:"What type of signature scheme did Taproot introduce to Bitcoin?",a:"Schnorr signatures",wrong:["RSA signatures","Ring signatures","Lamport signatures"]}],taproot_pt2:[{q:"Taproot improves Bitcoin by:",a:"Enhancing privacy, efficiency, and smart contract capabilities using Schnorr signatures",wrong:["Increasing the total supply above 21 million","Removing the need for mining","Making all transactions completely anonymous"]},{q:"When was the Taproot upgrade activated on Bitcoin?",a:"November 2021 at block 709,632",wrong:["August 2017 with SegWit","January 2009 at genesis","June 2023 with Ordinals"]},{q:"What is MAST (Merkelized Abstract Syntax Trees) in Taproot?",a:"A structure that reveals only the executed spending condition, hiding unused conditions for privacy",wrong:["A new mining algorithm that replaces SHA-256","A type of Lightning channel","A database for storing smart contract state"]},{q:"How does Taproot improve multi-signature transactions?",a:"Schnorr signatures allow multiple signers to produce a single compact signature indistinguishable from a regular one",wrong:["It removes the need for multiple signatures entirely","It stores each signature in a separate block","It requires all signers to be online simultaneously"]},{q:"What is Tapscript?",a:"An updated version of Bitcoin Script that enables new opcodes and improved scripting with Taproot",wrong:["A programming language for building altcoins","A tool for writing Bitcoin Core patches","The scripting language used in Lightning Network"]}],scalability:[{q:"Bitcoin base layer processes roughly:",a:"7 transactions per second",wrong:["7 million per second","1 per minute","100,000 per second"]},{q:"Bitcoin scales primarily through:",a:"Layer 2 solutions like Lightning",wrong:["Making blocks bigger forever","Removing the block limit","Using faster internet"]},{q:"The block size limit exists to:",a:"Keep node requirements low and maintain decentralization",wrong:["Slow down transactions","Limit Bitcoin's value","Help miners make more money"]},{q:"The Blocksize Wars were about:",a:"Whether to increase block size or use Layer 2",wrong:["Mining profitability","Bitcoin's name","Which exchange to use"]},{q:"Bitcoin's block size is limited to approximately:",a:"1-4 MB (with SegWit)",wrong:["100 MB","Unlimited — it grows with demand","1 KB"]}],scalability_pt2:[{q:"What did SegWit (Segregated Witness) do for Bitcoin scalability?",a:"Separated signature data from transaction data, effectively increasing block capacity to ~2 MB equivalent",wrong:["Doubled the block size to 2 MB","Removed the block size limit entirely","Moved all transactions to a sidechain"]},{q:"What is transaction batching?",a:"Combining multiple payments into a single on-chain transaction to save block space and fees",wrong:["Sending the same transaction multiple times for reliability","Grouping transactions by sender country","Waiting until a block is full before broadcasting"]},{q:"Why did the Bitcoin community reject simply raising the block size limit?",a:"Larger blocks increase node operating costs, risking centralization and reducing censorship resistance",wrong:["Larger blocks would break all existing wallets","Satoshi explicitly forbade any block size changes","Larger blocks would reduce the total Bitcoin supply"]},{q:"How does the Lightning Network improve Bitcoin's throughput?",a:"By processing millions of transactions off-chain and only settling final balances on the Bitcoin blockchain",wrong:["By replacing Bitcoin's blockchain with a faster one","By increasing the block size to 100 MB","By reducing the time between blocks to 1 second"]},{q:"What is payment channel batching on Lightning?",a:"Opening or closing multiple channels in a single on-chain transaction to save fees and block space",wrong:["Sending the same payment to multiple recipients","Mining multiple blocks at once","Compressing transaction data for faster processing"]}],utxos:[{q:"UTXO stands for:",a:"Unspent Transaction Output",wrong:["Universal Token Exchange Order","Unified Transaction eXecution Object","Ultra-fast Transfer of eXchange Operations"]},{q:"A UTXO is like:",a:"A specific bill in your wallet that you spend whole",wrong:["A bank balance","A credit limit","An account number"]},{q:"When you spend a UTXO:",a:"It's consumed entirely and change is returned as a new UTXO",wrong:["Part of it disappears","It stays in your wallet","It's deleted from the blockchain"]},{q:"UTXO management matters for:",a:"Privacy and minimizing future transaction fees",wrong:["Mining speed","Block creation","Node operation"]},{q:"What is a UTXO in Bitcoin?",a:"Unspent Transaction Output — the amount of bitcoin remaining after a transaction",wrong:["A type of digital signature","A mining reward token","A user transaction ID"]}],dust:[{q:'Bitcoin "dust" is:',a:"An amount too small to spend because the fee exceeds the value",wrong:["Deleted Bitcoin","A type of mining waste","A security attack"]},{q:"Dust attacks are used to:",a:"Track and deanonymize wallet owners",wrong:["Steal Bitcoin directly","Mine faster","Create new blocks"]},{q:"To avoid dust issues:",a:"Consolidate small UTXOs when fees are low",wrong:["Delete your wallet","Stop using Bitcoin","Only use exchanges"]},{q:'What is a "dust attack" in Bitcoin?',a:"Sending tiny amounts of bitcoin to wallets to track and de-anonymize users",wrong:["Overloading the network with large transactions","Physical dirt damaging mining hardware","A bug in the Bitcoin software"]},{q:"Why should users consolidate small UTXOs when fees are low?",a:"To reduce future transaction costs, as each UTXO adds to transaction size",wrong:["To increase bitcoin value","To improve privacy","To earn mining rewards"]}],rbf:[{q:"RBF stands for:",a:"Replace-By-Fee",wrong:["Really Big Fee","Rapid Block Finality","Return Bitcoin Fast"]},{q:"RBF allows you to:",a:"Bump a stuck transaction's fee to speed confirmation",wrong:["Cancel any transaction","Send Bitcoin for free","Mine your own block"]},{q:"RBF is useful when:",a:"Your transaction is stuck because the fee was too low",wrong:["You want to mine","You need a new wallet","You want to buy altcoins"]},{q:"What does RBF (Replace-by-Fee) allow users to do?",a:"Replace an unconfirmed transaction with a higher-fee version",wrong:["Reverse a confirmed transaction","Increase their total bitcoin balance","Prevent double spending"]},{q:"What is CPFP (Child Pays for Parent) used for?",a:"Accelerating confirmation by spending an unconfirmed output with a high-fee transaction",wrong:["Splitting bitcoin for children","Creating child wallets","Reducing transaction size"]}],time_preference:[{q:"Low time preference means:",a:"Saving for the future instead of spending now",wrong:["Spending everything today","Not caring about money","Only day trading"]},{q:"Bitcoin encourages low time preference because:",a:"Its value tends to increase over time due to scarcity",wrong:["It loses value quickly","It pays interest","The government mandates savings"]},{q:"High time preference leads to:",a:"Overconsumption and debt",wrong:["Wealth building","Better savings","Financial freedom"]},{q:"Fiat currency encourages:",a:"Spending now because money loses value over time",wrong:["Long-term saving","Low time preference","Financial responsibility"]},{q:'What is "low time preference" in Bitcoin culture?',a:"Prioritizing long-term saving over short-term spending",wrong:["Trading Bitcoin frequently for quick profits","Spending all your Bitcoin before the next halving","Checking the price every 5 minutes"]}],time_preference_pt2:[{q:"A Bitcoin standard encourages low time preference because:",a:"Saving is rewarded since the money appreciates over time",wrong:["Bitcoin transactions are extremely slow","The government mandates holding periods","You can only sell Bitcoin once per year"]},{q:'What does "low time preference" mean in the context of Bitcoin?',a:"Prioritizing long-term value and future rewards over immediate gratification",wrong:["Preferring to spend Bitcoin quickly before it loses value","Setting a time limit on how long you hold Bitcoin","Trading Bitcoin on short timeframes"]},{q:"How does fiat money encourage high time preference?",a:"Inflation erodes purchasing power, incentivizing spending now rather than saving for later",wrong:["Fiat money expires after a certain date","Banks charge fees for holding money too long","Governments tax savings but not spending"]},{q:'Why do Bitcoiners say Bitcoin "fixes" time preference?',a:"A deflationary hard money incentivizes saving and long-term thinking since purchasing power increases over time",wrong:["Bitcoin automatically invests your savings","Bitcoin transactions are slower, forcing patience","Bitcoin wallets lock funds for a minimum of one year"]},{q:"How does time preference relate to civilization building?",a:"Lower time preference leads to more capital accumulation, investment, and long-term infrastructure development",wrong:["Higher time preference builds civilizations faster","Time preference has no relationship to economic development","Only governments can lower society's time preference"]}],soft_vs_hard_forks:[{q:"A soft fork is:",a:"Backward-compatible upgrade",wrong:["A completely new blockchain","Deleting Bitcoin","A type of altcoin"]},{q:"A hard fork creates:",a:"A permanent chain split if not everyone upgrades",wrong:["A temporary pause","More Bitcoin","A faster network"]},{q:"Bitcoin Cash was created by:",a:"A hard fork of Bitcoin in 2017",wrong:["Satoshi Nakamoto in 2009","The US government","Ethereum developers"]},{q:"SegWit was activated as:",a:"A soft fork",wrong:["A hard fork","A new blockchain","An altcoin"]},{q:"The key difference between a soft fork and a hard fork is:",a:"Soft forks are backwards-compatible; hard forks are not",wrong:["Soft forks are temporary; hard forks are permanent","Soft forks require less code; hard forks need more","Soft forks are approved by vote; hard forks by mining"]}],soft_vs_hard_forks_pt2:[{q:"The Blocksize Wars resulted in:",a:"Bitcoin Cash splitting off as a hard fork while Bitcoin kept small blocks + SegWit",wrong:["Bitcoin doubling its block size to 2 MB","All miners switching to Bitcoin Cash","The creation of Ethereum"]},{q:"What is a soft fork in Bitcoin?",a:"A backward-compatible protocol upgrade where old nodes still accept new blocks",wrong:["A complete restart of the blockchain","A split that creates a new cryptocurrency","An update that requires all nodes to upgrade immediately"]},{q:"What is a hard fork?",a:"A non-backward-compatible change that requires all nodes to upgrade or they'll follow a different chain",wrong:["A bug fix that doesn't change consensus rules","A minor update to wallet software","A temporary network outage"]},{q:"What was the Bitcoin Cash (BCH) hard fork about?",a:"A disagreement over scaling — BCH proponents wanted larger blocks while Bitcoin kept the 1 MB base limit with SegWit",wrong:["A dispute over who created Bitcoin","A fix for a critical security bug","A change to Bitcoin's monetary policy"]},{q:"Why are soft forks generally preferred over hard forks for Bitcoin upgrades?",a:"They maintain backward compatibility, don't force upgrades, and don't risk splitting the network",wrong:["They are faster to implement","They don't require any code changes","Hard forks are illegal in most countries"]}],fedimints:[{q:"Fedimint helps with:",a:"Community custody with privacy",wrong:["Solo mining","Creating altcoins","Government reporting"]},{q:"A Fedimint uses:",a:"Federated guardians who jointly custody Bitcoin",wrong:["A single custodian","Government vaults","Exchange accounts"]},{q:"Fedimint provides privacy through:",a:"Chaumian eCash tokens",wrong:["Public blockchain","KYC verification","IP tracking"]},{q:"Fedimints are designed for:",a:"Communities that trust each other but want privacy",wrong:["Individual use only","Government agencies","Large corporations"]},{q:"A Fedimint (Federated Mint) provides:",a:"Community-custodial privacy through Chaumian ecash on Bitcoin",wrong:["A new type of Bitcoin mining pool","A government-approved Bitcoin exchange","A way to increase Bitcoin's supply above 21 million"]}],fedimints_pt2:[{q:"Fedimints improve Bitcoin privacy by:",a:"Using blinded signatures so the mint cannot link deposits to withdrawals",wrong:["Deleting transaction data from the blockchain","Requiring all users to share their identity","Converting Bitcoin into a different cryptocurrency"]},{q:"What is a Fedimint?",a:"A federated Chaumian eCash mint where a group of guardians custody Bitcoin and issue private eCash tokens",wrong:["A government-run Bitcoin exchange","A type of Bitcoin mining pool","A centralized bank built on Lightning"]},{q:"How do Fedimints provide privacy?",a:"Using blind signatures so the mint cannot link who deposited Bitcoin with who redeems eCash tokens",wrong:["By encrypting the blockchain","By hiding all transactions from the public","By requiring users to use VPNs"]},{q:"What is the trust model of a Fedimint?",a:"Users trust a federation of guardians (e.g., 3-of-5 multisig) rather than a single custodian",wrong:["Completely trustless like on-chain Bitcoin","Users trust a single company","The government guarantees deposits"]},{q:"How do Fedimints interact with the Lightning Network?",a:"They can send and receive Lightning payments, allowing private transactions with the broader Bitcoin network",wrong:["They replace Lightning entirely","Lightning cannot connect to Fedimints","Fedimints require their own separate payment network"]}],books:[{q:"The Bitcoin Standard is a popular book about:",a:"Sound money and Bitcoin economics",wrong:["Bitcoin mining hardware","How to day trade","Building websites"]},{q:"Mastering Bitcoin by Andreas Antonopoulos is:",a:"A technical deep-dive into how Bitcoin works",wrong:["A children's book","A cookbook","A fitness guide"]},{q:"The Sovereign Individual predicted:",a:"Digital money and the decline of nation-states",wrong:["Social media","Electric cars","Space travel"]},{q:"21 Lessons by Gigi explores:",a:"Philosophical lessons learned from going down the Bitcoin rabbit hole",wrong:["21 mining techniques","21 trading strategies","21 altcoins to buy"]},{q:'"The Bitcoin Standard" by Saifedean Ammous primarily argues:',a:"Bitcoin is the hardest money ever invented and will replace fiat",wrong:["Bitcoin is a useful technology but too volatile to be money","Gold is still superior to Bitcoin as a store of value","Central banks should adopt Bitcoin as a reserve currency"]}],books_pt2:[{q:'Gigi\'s "21 Lessons" is structured around:',a:"21 philosophical, economic, and technical lessons learned from Bitcoin",wrong:["A 21-day guide to becoming a Bitcoin trader","The 21 richest Bitcoin holders and their strategies","The history of 21 failed cryptocurrencies"]},{q:'Who wrote "The Bitcoin Standard"?',a:"Saifedean Ammous",wrong:["Andreas Antonopoulos","Satoshi Nakamoto","Michael Saylor"]},{q:"What book by Jimmy Song teaches Bitcoin programming and development?",a:"Programming Bitcoin",wrong:["The Bitcoin Standard","Digital Gold","Cryptoassets"]},{q:"What book by Lyn Alden provides a broad investment perspective including Bitcoin?",a:"Broken Money",wrong:["The Bitcoin Standard","Digital Gold","The Internet of Money"]},{q:'What is "The Blocksize War" by Jonathan Bier about?',a:"The history of Bitcoin's scaling debate, SegWit activation, and the BCH fork",wrong:["How to increase your Bitcoin block rewards","A fiction novel about cryptocurrency battles","Military applications of blockchain technology"]}],"misconceptions-fud":[{q:"FUD stands for:",a:"Fear, Uncertainty, and Doubt",wrong:["Fully Unified Database","First User Downloaded","Financial Update Daily"]},{q:'"Bitcoin is used by criminals" ignores that:',a:"Cash is used far more for crime and Bitcoin is traceable",wrong:["Bitcoin is untraceable","There are no criminals","Crime doesn't exist"]},{q:'"Bitcoin has no intrinsic value" ignores:',a:"Its network security, scarcity, and utility",wrong:["Its physical weight","Its smell","Its color"]},{q:'"Bitcoin is too volatile" ignores:',a:"Its long-term upward trend and decreasing volatility over time",wrong:["That it never moves","That it only goes down","Government price controls"]},{q:'"Bitcoin wastes energy" ignores:',a:"Its use of stranded/renewable energy and the value it secures",wrong:["That it uses no energy","Solar panels","Wind turbines only"]}],"satoshi-nakamoto":[{q:"Satoshi Nakamoto:",a:"Stepped down and disappeared",wrong:["Is currently the CEO of Bitcoin","Was arrested","Sold all Bitcoin"]},{q:"Satoshi's last known communication was around:",a:"2011",wrong:["2020","2015","2009"]},{q:"Satoshi's Bitcoin holdings are estimated at:",a:"About 1 million BTC that have never moved",wrong:["Zero","100 BTC","All 21 million"]},{q:"Satoshi's disappearance is seen as:",a:"A feature — it made Bitcoin truly decentralized",wrong:["A bug","A crime","A marketing strategy"]},{q:"Satoshi's true identity is:",a:"Unknown — it could be one person or a group",wrong:["Confirmed to be Elon Musk","A CIA agent","The President"]}],"satoshi-nakamoto_pt2":[{q:"Why is it important that Satoshi Nakamoto disappeared?",a:"Bitcoin has no leader who can be arrested, corrupted, or pressured",wrong:["Because they were wanted by law enforcement","So they could secretly accumulate more Bitcoin","Because the code was finished and needed no more work"]},{q:"What evidence suggests Satoshi Nakamoto was likely one person rather than a team?",a:"Consistent writing style, coding patterns, and posting times across years of activity",wrong:["A signed confession published on the Bitcoin Talk forum","DNA evidence found on the original Bitcoin server hardware","A government investigation that confirmed a single identity"]},{q:"When did Satoshi Nakamoto stop posting publicly?",a:"Around December 2010, with a final known post in April 2011",wrong:["January 2009 right after launching Bitcoin","They never stopped and still post today","In 2015 during the block size debate"]},{q:"How many Bitcoin did Satoshi Nakamoto reportedly mine?",a:"Approximately 1 million BTC based on analysis of early mining patterns",wrong:["Exactly 21 million (the entire supply)","Zero — Satoshi never mined","About 100 BTC from the genesis block only"]},{q:"What famous message did Satoshi embed in the Bitcoin genesis block?",a:'"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"',wrong:['"Hello World — Bitcoin is born"','"In code we trust"','"The revolution will not be centralized"']}],history:[{q:"The Bitcoin Genesis Block was mined in:",a:"January 2009",wrong:["October 2008","June 2010","December 2007"]},{q:"The first real-world Bitcoin transaction was:",a:"10,000 BTC for two pizzas",wrong:["1 BTC for a car","100 BTC for a house","1 BTC for a coffee"]},{q:"Bitcoin Pizza Day is celebrated on:",a:"May 22",wrong:["January 3","October 31","December 25"]},{q:"Mt. Gox was:",a:"An early Bitcoin exchange that was hacked and collapsed",wrong:["A mining company","A Bitcoin wallet","A government agency"]},{q:"The first Bitcoin block is called:",a:"The Genesis Block (Block 0)",wrong:["The Alpha Block","Block One","The Origin Block"]}],history_pt2:[{q:"Hal Finney received:",a:"The first Bitcoin transaction from Satoshi",wrong:["The last Bitcoin ever","A medal from the government","The Bitcoin trademark"]},{q:"Laszlo's famous pizza order was called from:",a:"London (Laszlo was in Florida)",wrong:["New York","San Francisco","Tokyo"]},{q:"The Bitcoin Wiki has been online since:",a:"2010",wrong:["2015","2009","2013"]},{q:"Tim Draper is known in Bitcoin for:",a:"Buying seized Silk Road Bitcoin at US Marshals auction",wrong:["Creating the Lightning Network","Writing the whitepaper","Mining the genesis block"]},{q:'The "Lightning Torch" was:',a:"A Lightning payment passed between notable Bitcoiners",wrong:["A mining competition","A hardware wallet","A documentary"]}],_general:[{q:"What is the smallest unit of Bitcoin called?",a:"A satoshi",wrong:["A bit","A wei","A penny"]},{q:"Bitcoin was launched in which year?",a:"2009",wrong:["2008","2010","2012"]},{q:"Bitcoin transactions are recorded on:",a:"A public distributed ledger",wrong:["A private server","A bank database","An email chain"]},{q:"Who can send you Bitcoin?",a:"Anyone who knows your address",wrong:["Only your bank","Only verified users","Only people in your country"]},{q:"Bitcoin operates on:",a:"24/7, 365 days a year",wrong:["Banking hours only","Weekdays only","It shuts down for maintenance"]},{q:"The total number of Bitcoins that will ever exist is:",a:"Exactly 21 million",wrong:["Unlimited","100 million","It changes yearly"]},{q:"Bitcoin is often abbreviated as:",a:"BTC",wrong:["BTN","BCN","BIT"]},{q:"A Bitcoin wallet stores:",a:"Private keys, not actual Bitcoin",wrong:["Physical coins","Digital files of Bitcoin","Pictures of Bitcoin"]},{q:"To receive Bitcoin you need:",a:"A Bitcoin address",wrong:["A bank account","A social security number","A credit card"]},{q:"The Bitcoin network is maintained by:",a:"Thousands of volunteers running nodes worldwide",wrong:["A company in California","The United Nations","A single supercomputer"]},{q:"Bitcoin confirmation time depends on:",a:"Network congestion and fee paid",wrong:["Time of day","Your internet speed","Which country you are in"]},{q:"A mempool is:",a:"Where unconfirmed transactions wait to be included in a block",wrong:["A mining pool","A type of wallet","A cryptocurrency exchange"]},{q:"Bitcoin difficulty adjustment ensures:",a:"Blocks are found roughly every 10 minutes regardless of hash power",wrong:["Prices stay stable","Miners earn the same amount","Transactions are free"]},{q:"SegWit stands for:",a:"Segregated Witness",wrong:["Secure Widget","Sequential Witness","Segment Width"]},{q:"A Bitcoin address starts with:",a:"1, 3, or bc1",wrong:["0x","BTC","Any letter"]},{q:"The Lightning Network whitepaper was published by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto","Vitalik Buterin","Elon Musk"]},{q:"Bitcoin hash rate measures:",a:"The total computing power securing the network",wrong:["Transaction speed","Number of users","Price changes"]},{q:"A nonce in mining is:",a:"A number miners change to find a valid block hash",wrong:["A type of fee","A wallet address","A block reward"]},{q:'The term "NGMI" in Bitcoin culture means:',a:"Not Gonna Make It",wrong:["New Global Money Index","Next Generation Mining Interface","Network Growth Metric Indicator"]},{q:"Hyperbitcoinization refers to:",a:"Mass voluntary adoption of Bitcoin as money",wrong:["A Bitcoin price crash","A mining difficulty spike","A new altcoin launch"]},{q:"Strike, Cash App, and River are all:",a:"Apps that let you buy Bitcoin",wrong:["Mining pools","Altcoins","Bitcoin forks"]},{q:"Nostr is:",a:"A decentralized social protocol popular in the Bitcoin community",wrong:["A mining algorithm","A Bitcoin fork","An exchange"]},{q:'The phrase "fix the money, fix the world" means:',a:"Sound money leads to better societal outcomes",wrong:["Print more money","Ban all currencies","Use only credit cards"]},{q:"A timelock in Bitcoin allows:",a:"Locking funds until a specific block height or time",wrong:["Freezing the blockchain","Stopping mining","Deleting transactions"]},{q:"Block reward plus transaction fees equals:",a:"The total miner revenue per block",wrong:["The Bitcoin price","The network speed","The difficulty level"]},{q:"Ordinals on Bitcoin are:",a:"A way to inscribe data on individual satoshis",wrong:["A ranking system for miners","A type of wallet","A government regulation"]},{q:"A paper wallet is:",a:"A printed private key for cold storage",wrong:["A paper receipt from an ATM","A bank statement","A type of fiat currency"]},{q:"The Lightning Network can theoretically handle:",a:"Millions of transactions per second",wrong:["7 per second","100 per second","1 per minute"]},{q:"A watch-only wallet lets you:",a:"Monitor a balance without being able to spend",wrong:["Mine Bitcoin","Create new coins","Edit the blockchain"]},{q:"Pleb is a term of endearment in Bitcoin meaning:",a:"An everyday Bitcoiner, not wealthy but committed",wrong:["A professional trader","A mining executive","A government official"]},{q:"What is the total number of satoshis that will ever exist?",a:"2.1 quadrillion (2,100,000,000,000,000)",wrong:["21 million","100 billion","21 quadrillion"]},{q:"Bitcoin Pizza Day is celebrated on:",a:"May 22",wrong:["January 3","October 31","April 15"]},{q:"The first Bitcoin exchange rate was established at approximately:",a:"$0.00099 per BTC (less than one penny)",wrong:["$1.00 per BTC","$0.10 per BTC","$100 per BTC"]},{q:"HODL originated from:",a:'A misspelled Bitcoin forum post from 2013 ("I AM HODLING")',wrong:["An acronym created by a Bitcoin company",'A Japanese word meaning "to hold"',"A technical term in Bitcoin's source code"]},{q:'The phrase "Not your keys, not your coins" warns against:',a:"Keeping Bitcoin on exchanges where you don't control the private keys",wrong:["Using physical Bitcoin coins instead of digital","Sharing your public key with other people","Using hardware wallets instead of software"]}],risks__threats__attack_vectors__weaknes:[{q:"Which Bitcoin address type is better for quantum resistance?",a:"SegWit (bc1q) because Taproot exposes the public key",wrong:["Taproot (bc1p)","Legacy (1...)","All are equally vulnerable"]},{q:"BIP 360 proposes:",a:"Pay to Quantum Resistant Hash",wrong:["Bigger blocks","Faster mining","New altcoin support"]},{q:"A 51% attack would require:",a:"Controlling more than half of Bitcoin's total mining hash rate",wrong:["Owning 51% of all existing Bitcoin","Having 51% of all Bitcoin nodes vote together","Hacking 51% of Bitcoin wallets simultaneously"]},{q:"Why is a 51% attack impractical against Bitcoin?",a:"The hash rate is so massive it would cost billions and be unprofitable",wrong:["Because Bitcoin automatically detects and blocks attacks","Because Satoshi built in a secret defense mechanism","Because only 21 mining pools exist worldwide"]},{q:"Quantum computing threatens Bitcoin by potentially:",a:"Breaking ECDSA signatures used to authorize spending",wrong:["Mining all remaining Bitcoin in seconds","Deleting the entire blockchain","Creating unlimited new Bitcoin addresses"]}],"evidence-against-alts":[{q:"Ethereum's original sale page reveals that ETH was:",a:"Pre-sold as a security to fund development",wrong:["Mined fairly like Bitcoin","Distributed equally","Created by Satoshi"]},{q:"What fundamental difference exists between Bitcoin and altcoins regarding decentralization?",a:"Altcoin founders often hold large pre-mines or centralized control",wrong:["Altcoins are too cheap","Bitcoin has better marketing","Altcoins use different blockchains"]},{q:'Why do Bitcoiners say "there is no second best"?',a:"No other crypto achieves Bitcoin's decentralization, security, and immutability",wrong:["Bitcoin was the first, so it automatically wins","The SEC has declared all other cryptos illegal","Satoshi patented the blockchain concept"]},{q:'What is a "pre-mine" and why is it concerning?',a:"Founders allocate coins to themselves before public launch — unfair distribution",wrong:["A technique to speed up transaction processing","A security measure that protects the network","A method of testing the blockchain before launch"]},{q:"Most altcoins are considered securities because:",a:"They have identifiable teams profiting from token sales with promises of returns",wrong:["They use the same code as Bitcoin","The SEC approves them as securities automatically","They are traded on stock exchanges"]}],"smart-contracts":[{q:"Bitcoin's scripting language has supported smart contracts:",a:"Since the beginning — Bitcoin always had them",wrong:["Only after Taproot in 2021","Only after SegWit in 2017","Never — only Ethereum has them"]},{q:"OP_RETURN is used in Bitcoin to:",a:"Embed small amounts of data in transactions",wrong:["Return sent Bitcoin","Cancel transactions","Mine faster"]},{q:"What is Bitcoin\\'s native scripting language called?",a:"Bitcoin Script",wrong:["Solidity","Python Script","JavaScript"]},{q:"What does OP_RETURN allow users to do on Bitcoin?",a:"Embed up to 80 bytes of arbitrary data in a transaction",wrong:["Execute Ethereum-style smart contracts","Change transaction amounts","Create new bitcoins"]},{q:"What are DLCs (Discreet Log Contracts) on Bitcoin?",a:"Smart contracts that settle based on external oracle data without revealing details",wrong:["Private keys stored in logs","Debug contracts for developers","Decentralized lending contracts on Ethereum"]}],"chaumian-mints":[{q:"Cashu is an implementation of:",a:"Chaumian ecash on Bitcoin/Lightning",wrong:["A new blockchain","An altcoin","A mining algorithm"]},{q:"Who invented the blind signature technology used in Chaumian eCash?",a:"David Chaum in 1982",wrong:["Satoshi Nakamoto in 2008","Adam Back in 1997","Hal Finney in 2004"]},{q:"What modern Bitcoin layer implements Chaumian eCash for minting privacy-preserving tokens?",a:"Cashu and Fedimint protocols",wrong:["Lightning Network","Liquid Network","Ethereum ERC-20"]},{q:"Cashu is:",a:"An ecash protocol built on Bitcoin using Chaumian blind signatures",wrong:["A competing cryptocurrency to Bitcoin","A hardware wallet manufacturer","A type of Bitcoin mining software"]},{q:'What are "blind signatures" in ecash?',a:"The mint signs tokens without knowing which user they belong to",wrong:["Signatures that expire after 24 hours","A way to sign transactions without a private key","Signatures that can only be verified by the government"]}],"swag-merch":[{q:"BTCAccepted.org helps you find:",a:"Businesses that accept Bitcoin payments",wrong:["Mining pools","Lightning nodes","Altcoin exchanges"]},{q:"Sats.host offers:",a:"Bitcoin-powered static website hosting",wrong:["Mining services","Cold storage","KYC verification"]},{q:'What annual Bitcoin conference is often called "the Super Bowl of Bitcoin"?',a:"Bitcoin Conference (formerly Miami/Bitcoin 2021)",wrong:["Consensus","DevCon","ETHDenver"]},{q:"What is the significance of wearing an orange pill at Bitcoin conferences?",a:'Signifies being "orange pilled" — awakened to Bitcoin\\\'s importance',wrong:["Medical supplement promotion","Conference staff identifier","VIP pass indicator"]},{q:"What popular Bitcoin merchandise item satirizes central banking?",a:'"End the Fed" t-shirts and posters',wrong:["Bitcoin gaming chairs","Satoshi action figures","Mining rig keychains"]}],"apps-tools":[{q:"PPQ.ai lets you use AI models and pay with:",a:"Bitcoin per prompt — no subscription needed",wrong:["Monthly credit card subscription","Ethereum gas fees","Free but with ads"]},{q:"Angor is a platform for:",a:"Non-custodial Bitcoin crowdfunding",wrong:["Bitcoin mining","Coin mixing","Hardware wallets"]},{q:"What website provides real-time visualization of the Bitcoin mempool?",a:"mempool.space",wrong:["blockchain.com","coinmarketcap.com","bitcoincharts.com"]},{q:"What popular hardware wallet supports both Bitcoin and Lightning?",a:"Coldcard and BitBox02",wrong:["PayPal Card","Venmo Wallet","Apple Pay"]},{q:"What full node implementation is the most widely used for running Bitcoin?",a:"Bitcoin Core",wrong:["Bitcoin Cash","Ethereum Classic","Ripple Node"]}],games:[{q:"Timechain Arcade offers:",a:"Free Bitcoin-themed video games",wrong:["Mining services","Trading tools","Hardware wallets"]},{q:"CanYouBeatBitcoin.com is:",a:"An investing simulator comparing your picks to Bitcoin",wrong:["A mining difficulty calculator","A Bitcoin wallet","A trading bot"]},{q:"What type of Bitcoin games reward players with satoshis?",a:"Play-to-earn Lightning games",wrong:["Casino-style gambling","Console RPGs","Mobile ad games"]},{q:"What popular Bitcoin trivia app lets users earn sats for answering questions?",a:"THNDR Games (like Bitcoin Bounce, Bitcoin Bay)",wrong:["Fortnite","Candy Crush","Minecraft"]},{q:"What is Zebedee known for in the Bitcoin gaming space?",a:"A platform enabling Lightning payments in games",wrong:["Hardware mining rigs","Altcoin exchange","NFT marketplace"]}],"difficulty-adjustment":[{q:"How often does Bitcoin's difficulty adjustment occur?",a:"Every 2,016 blocks (approximately 2 weeks)",wrong:["Every 1,000 blocks","Every month","Every day"]},{q:"What does the difficulty adjustment ensure?",a:"Blocks are found roughly every 10 minutes regardless of hash power changes",wrong:["Transaction fees stay constant","Mining rewards increase","Block size adjusts automatically"]},{q:"Bitcoin's difficulty adjusts every:",a:"2,016 blocks (roughly every 2 weeks)",wrong:["Every single block","Once per year","Every 210,000 blocks (at each halving)"]},{q:"If miners leave the network, difficulty adjustment:",a:"Lowers the difficulty so blocks are found at the target rate",wrong:["Increases difficulty to punish remaining miners","Has no effect — blocks just take longer forever","Automatically doubles the block reward"]},{q:"The target time between Bitcoin blocks is approximately:",a:"10 minutes",wrong:["1 minute","1 hour","30 seconds"]}],nostr:[{q:"Nostr is:",a:"A decentralized social media protocol where no one controls content",wrong:["A Bitcoin mining pool","A Lightning wallet","A blockchain explorer"]},{q:"What makes Nostr unique from typical social media?",a:"Your identity is uncensorable and no single entity controls the platform",wrong:["It pays users in Bitcoin automatically","It only works on mobile","It requires KYC verification"]},{q:"Nostr is best described as:",a:"A decentralized social protocol that cannot be censored",wrong:["A Bitcoin wallet application","A new cryptocurrency competing with Bitcoin","An encrypted messaging app owned by a company"]},{q:"Nostr uses cryptographic keys to:",a:"Allow users to own their identity without a central authority",wrong:["Mine new coins on the Nostr blockchain","Encrypt all messages so no one can read them","Create smart contracts between users"]},{q:"How is Nostr connected to Bitcoin?",a:"Many clients integrate Lightning for tips and payments",wrong:["Nostr runs on the Bitcoin blockchain directly","You must own Bitcoin to create a Nostr account","Nostr mining validates Bitcoin transactions"]}],network_effects:[{q:"Bitcoin's network effect means:",a:"Each new user increases the value and utility for all existing users",wrong:["The internet gets faster","Mining gets easier","Fees decrease to zero"]},{q:"Why is Bitcoin's network effect considered a strong moat?",a:"It creates a self-reinforcing cycle of liquidity, security, and adoption that competitors cannot easily replicate",wrong:["Because Bitcoin has patents","Because the government protects it","Because the code is encrypted"]},{q:"What economic principle explains Bitcoin\\'s value increasing as more people use it?",a:"Metcalfe\\'s Law — network value proportional to connected users squared",wrong:["Moore\\'s Law","Murphy\\'s Law","Pareto Principle"]},{q:"Metcalfe's Law applied to Bitcoin suggests:",a:"Its value grows proportionally to the square of its users",wrong:["The price will always increase linearly","Only the first users receive any benefit","Network effects only apply to social media"]},{q:"What is the flywheel effect in Bitcoin adoption?",a:"More users attract more developers, merchants, and infrastructure, which attracts even more users",wrong:["Mining gets easier as more people join","Transaction fees decrease as the network grows","Bitcoin price always goes up with more users"]}],governance:[{q:"Bitcoin governance is best described as:",a:"Rough consensus among users, developers, miners, and node operators",wrong:["A CEO makes all decisions","Miners vote on everything","A foundation sets the rules"]},{q:"The Blocksize Wars demonstrated that:",a:"Users and node operators ultimately control Bitcoin's rules, not miners alone",wrong:["Miners have absolute power","Developers can force any change","Bitcoin cannot be upgraded"]},{q:"What is the BIP process in Bitcoin?",a:"Bitcoin Improvement Proposals for suggesting protocol changes",wrong:["Bitcoin Investment Plan","Blockchain IP Protection","Banking Integration Protocol"]},{q:"How is Bitcoin governed?",a:"Through rough consensus among users, developers, miners, and node operators",wrong:["By a board of directors at the Bitcoin Foundation","Through shareholder voting like a corporation","By whoever owns the most Bitcoin"]},{q:"A BIP (Bitcoin Improvement Proposal) is:",a:"A formal document proposing changes to Bitcoin's protocol or processes",wrong:["A mandatory update that all nodes must accept","A financial investment in Bitcoin development","A bug report filed to the Bitcoin support team"]}],human_rights__social_justice_and_freedo:[{q:"Bitcoin supports human rights by:",a:"Providing censorship-resistant money that cannot be confiscated by authoritarian regimes",wrong:["Replacing all governments","Eliminating all poverty instantly","Being controlled by the UN"]},{q:"Alex Gladstein advocates for Bitcoin because:",a:"It empowers people living under authoritarian regimes with financial freedom",wrong:["It makes trading stocks easier","It replaces the need for banks in wealthy countries","It was designed as a protest tool"]},{q:"How has Bitcoin helped activists in authoritarian regimes?",a:"By enabling uncensorable fundraising and protecting wealth from seizure",wrong:["By hiding their identity completely","By earning interest from banks","By creating new currencies"]},{q:"How does Bitcoin help people under authoritarian regimes?",a:"It provides censorship-resistant money that governments cannot freeze",wrong:["It automatically reports suspicious activity to authorities","It requires government ID to transact","It only works in democratic countries"]},{q:"Alex Gladstein of the Human Rights Foundation argues that:",a:"Bitcoin is the most important tool for financial freedom globally",wrong:["Only wealthy nations benefit from Bitcoin","Bitcoin should be controlled by human rights organizations","Proof of Stake is better for human rights than Proof of Work"]}],market_cap:[{q:"Bitcoin's market cap is calculated by:",a:"Current price multiplied by total coins in circulation",wrong:["Total transaction volume per day","Number of wallets times average balance","Mining revenue times block height"]},{q:"Why can Bitcoin's market cap potentially exceed gold's?",a:"Bitcoin is more portable, divisible, verifiable, and scarce than gold",wrong:["Because governments will mandate it","Because gold will be banned","Because Bitcoin mining produces gold"]},{q:"What metric compares Bitcoin\\'s market value to all other cryptocurrencies combined?",a:"Bitcoin Dominance Index",wrong:["Coin Market Gap","Crypto Index Fund","Volatility Ratio"]},{q:"Bitcoin's market capitalization represents:",a:"The total value of all existing Bitcoin at the current price",wrong:["The maximum number of coins that can ever exist","The amount of money invested in Bitcoin mining","The total transaction volume over the past year"]},{q:"If Bitcoin captured gold's market cap, each coin would be worth approximately:",a:"Over $500,000",wrong:["$100,000","$50,000","$10,000"]}],the_future:[{q:"Hyperbitcoinization refers to:",a:"Mass voluntary adoption of Bitcoin as the dominant form of money",wrong:["A Bitcoin price crash","A government mandate to use Bitcoin","A technical upgrade to the protocol"]},{q:"Bitcoin is described as 'generational wealth' because:",a:"Its fixed supply and growing adoption may increase its value over decades",wrong:["Only older people can buy it","It expires after one generation","Banks guarantee its value for 100 years"]},{q:"What is hyperbitcoinization?",a:"The hypothetical point where Bitcoin becomes the world\\'s dominant form of money",wrong:["Overheating of mining equipment","Excessive Bitcoin advertising","A type of Bitcoin hack"]},{q:"What happens when the last Bitcoin is mined (~2140)?",a:"Miners will be compensated solely through transaction fees",wrong:["The network will shut down permanently","A new supply of 21 million coins will be created","Mining will become free with no reward"]},{q:"What does hyperbitcoinization refer to?",a:"A theoretical tipping point where Bitcoin becomes the dominant global monetary system",wrong:["Bitcoin reaching a price of one million dollars","Every country banning Bitcoin simultaneously","Bitcoin hash rate exceeding all supercomputers combined"]}],"orange-pilling":[{q:"'Orange-pilling' someone means:",a:"Convincing them to understand and adopt Bitcoin",wrong:["Selling them altcoins","Giving them free Bitcoin","Signing them up for an exchange"]},{q:"The most effective way to orange-pill someone is often:",a:"Starting with the problem Bitcoin solves (broken money) rather than technical details",wrong:["Showing them price charts","Explaining SHA-256 hashing","Telling them to buy immediately"]},{q:'What does "orange pilling" someone mean?',a:"Educating them about Bitcoin until they understand its importance",wrong:["Giving them actual pills","Selling them mining equipment","Creating a Bitcoin wallet for them"]},{q:"What is the best approach when orange-pilling a skeptic?",a:"Start with their specific pain point (inflation, remittances, censorship) rather than technical details",wrong:["Show them price charts and promise guaranteed returns","Pressure them into buying immediately before the next halving","Explain the full UTXO model and Merkle trees first"]},{q:"The most effective orange-pilling strategy is:",a:"Meeting people where they are and addressing their specific concerns",wrong:["Posting price predictions on social media","Telling people they are stupid for not buying","Promising guaranteed financial returns"]}],maximalism:[{q:"Bitcoin maximalism is the belief that:",a:"Bitcoin is the only cryptocurrency that truly matters as sound money",wrong:["You should invest everything in Bitcoin","Bitcoin should replace all technology","Only developers should use Bitcoin"]},{q:"Maximalists argue altcoins are unnecessary because:",a:"Bitcoin's base layer plus additional protocol layers can serve all use cases",wrong:["Because altcoins are illegal","Because Satoshi said so","Because there can only be one blockchain"]},{q:"What is Bitcoin maximalism?",a:"The belief that Bitcoin will be the only cryptocurrency to achieve long-term dominance",wrong:["Investing only in altcoins","Maximizing one\\'s bitcoin holdings at all costs","Running multiple full nodes"]},{q:"Why do deep Bitcoin researchers tend to become maximalists?",a:"They realize no other project achieves true decentralization and immutability",wrong:["They are paid by Bitcoin companies to promote it","They lack knowledge of other technologies","It is required to participate in the Bitcoin community"]},{q:"What is the core argument of Bitcoin maximalists?",a:"Only Bitcoin achieves true decentralization and sound money; altcoins compromise on critical aspects",wrong:["Bitcoin should be the only legal currency","All other technology besides Bitcoin is useless","Maximalists refuse to use the internet"]}],developers:[{q:"Bitcoin Core is primarily written in:",a:"C++",wrong:["Python","JavaScript","Rust"]},{q:"Contributing to Bitcoin open source requires:",a:"Anyone can propose changes — no permission needed",wrong:["A computer science degree","Approval from the Bitcoin Foundation","Purchasing a developer license"]},{q:"Who is considered Bitcoin\\'s lead maintainer as of recent years?",a:"There is no formal leader; Bitcoin Core has multiple maintainers",wrong:["Satoshi Nakamoto","Vitalik Buterin","Elon Musk"]},{q:"What organization has historically funded Bitcoin Core development?",a:"MIT Digital Currency Initiative, Chaincode Labs, Brink, Spiral",wrong:["World Bank","Federal Reserve","Goldman Sachs"]},{q:"Which version control system hosts Bitcoin Core’s source code?",a:"Git",wrong:["SVN","Mercurial","Bazaar"]}],ham_radio:[{q:"Bitcoin transactions can be sent via ham radio, which means:",a:"Bitcoin can work without an internet connection",wrong:["Bitcoin requires satellite dishes","Only miners can use radio","Radio transactions are free"]},{q:"How can Bitcoin transactions be sent without internet?",a:"Via ham radio operators broadcasting signed transactions",wrong:["Via postal mail","Via telephone calls","Via satellite TV only"]},{q:"What mesh network protocol has been used to broadcast Bitcoin transactions?",a:"Blockstream Satellite and goTenna mesh networks",wrong:["Bluetooth Classic","NFC payments","Zigbee home network"]},{q:"What is the benefit of Bitcoin over ham radio?",a:"Censorship resistance even when governments shut down internet",wrong:["Faster than fiber internet","Lower transaction fees","Better for large file transfers"]},{q:"Who demonstrated sending Bitcoin via ham radio in 2019?",a:"Rodolfo Novak co-founder of Coinkite",wrong:["Elon Musk","Jack Dorsey","Andreas Antonopoulos"]}],lightning_node:[{q:"Running a Lightning node allows you to:",a:"Route payments and earn fees while supporting the network",wrong:["Mine Bitcoin faster","Create new Bitcoin","Access the dark web"]},{q:"What is a Lightning node?",a:"Software that routes payments on the Lightning Network using payment channels",wrong:["A physical Bitcoin ATM","A mining rig","A Bitcoin exchange server"]},{q:"What do node operators lock up to open payment channels?",a:"Bitcoin as liquidity for routing payments",wrong:["Ethereum tokens","Fiat currency","Computing power"]},{q:"What fee do Lightning routing nodes typically charge?",a:"Routing fees measured in milli-satoshis (very small fraction of a cent)",wrong:["1% of transaction amount","$5 per payment","No fees allowed"]},{q:"What is inbound liquidity for a Lightning node?",a:"The ability to receive payments based on funds others have locked with you",wrong:["Money coming from bank deposits","Mining rewards","Exchange trading profits"]}],stablecoins:[{q:"Stablecoins in the Bitcoin ecosystem are typically:",a:"Tokens pegged to fiat currency values, sometimes built on Bitcoin layers",wrong:["A type of mining reward","Bitcoins that never change price","Government-issued digital dollars"]},{q:"What backs the majority of USDT (Tether)?",a:"Commercial paper, cash equivalents, and other reserves (historically controversial)",wrong:["100% US dollars in bank","Gold reserves","Bitcoin collateral"]},{q:"What major risk do centralized stablecoins pose?",a:"Issuer can freeze funds or fail to maintain peg",wrong:["They mine too slowly","High transaction fees","Private key loss"]},{q:"What caused USDC to depeg temporarily in March 2023?",a:"Exposure to failed Silicon Valley Bank",wrong:["Bitcoin price crash","Lightning Network bug","Satoshi selling coins"]},{q:"Stablecoins are NOT a threat to Bitcoin because:",a:"They are centralized IOUs that can be frozen, while Bitcoin is permissionless",wrong:["Stablecoins use the same technology as Bitcoin","Bitcoin automatically converts to stablecoins during crashes","Stablecoins have a higher market cap than Bitcoin"]}],consensus:[{q:"Bitcoin consensus means:",a:"All nodes agree on the state of the blockchain without a central authority",wrong:["Everyone votes on transactions","Miners decide which transactions are valid alone","The government approves each block"]},{q:"What is Nakamoto Consensus?",a:"The combination of proof-of-work, longest chain rule, and economic incentives",wrong:["Voting by coin holders","Consensus by the Bitcoin Foundation","Agreement between exchanges"]},{q:"Why does Bitcoin use the longest chain as the valid chain?",a:"Most proof-of-work indicates most energy/computational investment",wrong:["Random selection","Shortest chains are invalid","User voting"]},{q:"Nakamoto Consensus achieves agreement by:",a:"Having nodes follow the longest valid proof-of-work chain",wrong:["Requiring all nodes to vote on each transaction","Letting the wealthiest node decide which blocks are valid","Using a central server to broadcast the correct chain"]},{q:"What happens if two miners find a valid block at nearly the same time?",a:"A temporary fork occurs and resolves when the next block is found",wrong:["Both blocks are permanently added to the chain","The network shuts down until the conflict is resolved","The older miner's block always wins"]}],open_source:[{q:"Bitcoin being open source means:",a:"Anyone can read, audit, and propose changes to the code",wrong:["The code is secret but free to use","Only approved developers can view it","It costs nothing to mine"]},{q:"What license is Bitcoin Core released under?",a:"MIT License (open source)",wrong:["Proprietary commercial license","GPL v3 only","Patent-encumbered license"]},{q:"How can anyone contribute to Bitcoin Core?",a:"Submit pull requests on GitHub after code review",wrong:["Pay a developer fee","Get hired by a bank","Apply for a license"]},{q:"What is the purpose of code review in Bitcoin development?",a:"To catch bugs and security issues before deployment",wrong:["To slow down development","To charge developers money","To keep the code secret"]},{q:"Why is peer review critical in Bitcoin Core development?",a:"It catches bugs and vulnerabilities before they reach production, since changes affect billions in value",wrong:["It is just a formality required by the MIT license","Only one reviewer is needed for minor patches","Peer review slows down development unnecessarily"]}],coin_mixing_coinjoin_coin_control_utxo:[{q:"CoinJoin improves privacy by:",a:"Combining multiple users' transactions so individual spending is hard to trace",wrong:["Encrypting the blockchain","Deleting transaction history","Creating fake transactions"]},{q:"What is CoinJoin?",a:"A privacy technique combining multiple users\\' transactions to break heuristics",wrong:["A cryptocurrency mixer token","A type of hardware wallet","An exchange withdrawal method"]},{q:"What does coin control allow Bitcoin users to do?",a:"Manually select which UTXOs to spend in a transaction",wrong:["Control the price of bitcoin","Limit mining difficulty","Set transaction speed"]},{q:"What privacy benefit does proper UTXO management provide?",a:"Preventing address clustering and transaction graph analysis",wrong:["Increasing mining rewards","Reducing transaction fees","Speeding up confirmations"]},{q:'What is "coin control" in a Bitcoin wallet?',a:"The ability to manually select which UTXOs to spend in a transaction for better privacy",wrong:["A government program to regulate Bitcoin spending","Software that limits how much Bitcoin you can buy","A mining feature that controls block production"]}],environment___energy:[{q:"Bitcoin mining's relationship with renewable energy is:",a:"Miners actively seek cheap renewable and stranded energy, incentivizing green energy development",wrong:["Mining only uses coal","Renewable energy cannot power mining","Mining has no relationship with energy markets"]},{q:"What percentage of Bitcoin mining comes from renewable energy (estimates)?",a:"Estimates range from 50-60% using renewable or stranded energy",wrong:["0% — all coal","100% renewable","Less than 10%"]},{q:'What is "stranded energy" in Bitcoin mining?',a:"Energy that would otherwise go to waste due to lack of transmission infrastructure",wrong:["Energy from broken solar panels","Leftover battery power","Natural gas used for heating"]},{q:"How does Bitcoin mining help stabilize electrical grids?",a:"Miners can rapidly reduce load during peak demand (demand response)",wrong:["By storing electricity in batteries","By donating profits to utilities","By building more coal plants"]},{q:"What common criticism about Bitcoin energy use is often misrepresented?",a:"Per-transaction energy cost (Bitcoin uses same energy regardless of transaction count)",wrong:["It uses no energy at all","All energy comes from coal","Mining makes computers explode"]}],austrian_school_of_economics:[{q:"The Austrian School of Economics relates to Bitcoin because:",a:"It advocates for sound money with limited supply, which Bitcoin embodies",wrong:["It was founded by Satoshi Nakamoto","It requires government-controlled currency","It predicts Bitcoin will fail"]},{q:"Which Austrian economist emphasized the importance of sound money and criticized fiat?",a:"Ludwig von Mises and Friedrich Hayek",wrong:["John Maynard Keynes","Karl Marx","Milton Friedman"]},{q:"The Austrian School of Economics emphasizes:",a:"Sound money, free markets, and the dangers of central banking",wrong:["Government control of all monetary systems","That inflation is beneficial for economic growth","That central banks should print unlimited money"]},{q:'Who wrote "The Theory of Money and Credit"?',a:"Ludwig von Mises",wrong:["John Maynard Keynes","Paul Krugman","Adam Smith"]},{q:"Bitcoin aligns with Austrian economics because:",a:"It has a fixed supply and cannot be debased by any authority",wrong:["It was invented by an Austrian economist","The Austrian government officially endorses it","It uses the Austrian Schilling as its base currency"]}],lindy_effect:[{q:"The Lindy Effect applied to Bitcoin means:",a:"The longer Bitcoin survives, the longer it is expected to continue surviving",wrong:["Bitcoin gets slower over time","Older technology always fails","Bitcoin will expire after 21 years"]},{q:"What is the Lindy Effect?",a:"The longer something survives, the longer its remaining life expectancy",wrong:["A measure of mining difficulty","A type of cryptographic hash","A brand of hardware wallet"]},{q:"How does the Lindy Effect apply to Bitcoin?",a:"Each year without failure increases confidence in future survival",wrong:["Bitcoin becomes less secure over time","Only old coins have value","Newer cryptocurrencies are safer"]},{q:"What concept is closely related to Lindy Effect in Bitcoin?",a:"Antifragility — stress makes the system stronger",wrong:["Inflation targeting","Proof of stake","Central banking"]},{q:"Why is Bitcoin\\'s 15+ year survival significant for the Lindy Effect?",a:"Demonstrates resilience to attacks, bugs, and regulatory pressure",wrong:["Proves it cannot be upgraded","Makes it obsolete","Shows it uses too much energy"]}],softwar:[{q:"Jason Lowery's Softwar thesis argues that:",a:"Proof-of-work is a form of digital power projection analogous to military power in the physical world",wrong:["Bitcoin is a weapon system","Software replaces all hardware","Bitcoin was created by the military"]},{q:'Who authored the "Softwar" thesis about Bitcoin?',a:"Major Jason Lowery of the US Space Force",wrong:["Michael Saylor","Nick Szabo","Elizabeth Warren"]},{q:"What is the core argument of the Softwar thesis?",a:"Proof-of-work is a form of kinetic power projection for cyberspace",wrong:["Bitcoin should be banned","Proof of stake is superior","Bitcoin is a company"]},{q:"What does Softwar compare Bitcoin\\'s hash rate to?",a:"Physical military power projection and deterrence",wrong:["Social media likes","Stock market volume","Bank transaction counts"]},{q:"How does the Softwar thesis view Bitcoin mining in terms of national security?",a:"As a strategic asset that projects power in cyberspace, similar to how militaries project power in physical space",wrong:["As a threat to national security that should be banned","As purely an economic activity with no geopolitical significance","As a replacement for nuclear deterrence"]}],sidechains:[{q:"A Bitcoin sidechain is:",a:"A separate blockchain that is pegged to Bitcoin, enabling additional features while settling back to the main chain",wrong:["A backup copy of the Bitcoin blockchain","A faster version of Bitcoin Core","An altcoin that replaced Bitcoin"]},{q:"What is the Liquid Network?",a:"A federated sidechain enabling faster confidential Bitcoin transactions",wrong:["An Ethereum scaling solution","A mining pool","A hardware wallet"]},{q:"What is RSK (Rootstock)?",a:"A Bitcoin sidechain supporting smart contracts with merged mining",wrong:["A Russian Bitcoin exchange","A hardware wallet brand","A Lightning wallet"]},{q:"How are assets secured when moving to a sidechain?",a:"Through a federated peg locking bitcoin on mainchain",wrong:["By burning bitcoin permanently","By trusting a single company","No security is provided"]},{q:"What is a downside of federated sidechains compared to Bitcoin mainchain?",a:"Less decentralization due to reliance on federation members",wrong:["Higher transaction fees","Slower block times","No programming capabilities"]}],submarine_swap:[{q:"A submarine swap allows you to:",a:"Exchange on-chain Bitcoin for Lightning Bitcoin (or vice versa) trustlessly",wrong:["Mine Bitcoin underwater","Send Bitcoin without internet","Convert Bitcoin to Ethereum"]},{q:"What is a submarine swap?",a:"An atomic swap between on-chain Bitcoin and Lightning Network off-chain",wrong:["A type of mining pool payout","A DeFi lending protocol","An underwater transaction method"]},{q:"What enables submarine swaps to be trustless?",a:"HTLCs (Hash Time Locked Contracts)",wrong:["Centralized exchange custody","Bank wire confirmation","Social media verification"]},{q:"What problem do submarine swaps solve?",a:"Moving funds between on-chain and Lightning without closing channels",wrong:["Mining difficulty adjustment","Exchange rate volatility","Wallet password recovery"]},{q:"What technology makes submarine swaps trustless?",a:"Hash Time-Locked Contracts (HTLCs) that ensure both sides complete or neither does",wrong:["A centralized escrow service that holds funds during the swap","Blockchain validators who verify the exchange manually","Smart contracts on Ethereum that bridge to Bitcoin"]}],supranational:[{q:'What does "supranational" mean in the context of Bitcoin?',a:"It transcends national borders and governments",wrong:["It is backed by the United Nations","It requires international approval to use","It can only be used between countries"]},{q:"The Lindy Effect suggests that Bitcoin:",a:"The longer it survives, the longer it is expected to survive",wrong:["Will eventually be replaced by newer technology","Has a fixed expiration date coded into its protocol","Must be upgraded every 10 years to remain relevant"]},{q:"Bitcoin settlement finality means:",a:"Once confirmed, transactions cannot be reversed",wrong:["Transactions can be disputed within 30 days","A central authority must approve each transaction","Only miners can verify if a transaction is final"]},{q:'Why is Bitcoin considered "supranational" money?',a:"It operates beyond any single nation\\'s jurisdiction or control",wrong:["It is owned by the UN","Only governments can use it","It requires international banking licenses"]},{q:"What makes Bitcoin different from national currencies like the dollar or euro?",a:"No central bank can print more or manipulate its supply",wrong:["It is backed by gold reserves","It requires government approval","It only works online"]}],organic:[{q:"Bitcoin grew organically because:",a:"It had no pre-mine, no ICO, and no marketing budget",wrong:["A major corporation funded its development","Governments agreed to adopt it simultaneously","Social media algorithms promoted it automatically"]},{q:"What makes Bitcoin's distribution unique among cryptocurrencies?",a:"Fair launch — no coins were pre-allocated to founders",wrong:["Satoshi kept 50% of all coins before launch","Venture capitalists funded the initial distribution","Coins were distributed based on national GDP"]},{q:"How has Bitcoin grown without traditional marketing?",a:"Through grassroots adoption and word-of-mouth from users",wrong:["Massive advertising budgets","Celebrity endorsements","Government subsidies"]},{q:"What drives Bitcoin\\'s organic adoption in developing countries?",a:"Real need for inflation protection and remittance savings",wrong:["Central bank mandates","Corporate marketing campaigns","Mandatory school education"]},{q:"What is the role of Bitcoin\\'s open source community?",a:"Volunteer developers contribute code without corporate hierarchy",wrong:["They control Bitcoin Foundation","They receive government salaries","They own all bitcoins"]}],programmable:[{q:"Bitcoin Script is intentionally limited because:",a:"Simplicity reduces attack surface and increases security",wrong:["Satoshi was not a skilled programmer","The blockchain cannot process complex instructions","It was a temporary design meant to be upgraded"]},{q:'What does "Turing-incomplete" mean for Bitcoin Script?',a:"It cannot run arbitrary programs or infinite loops",wrong:["It cannot process any transactions at all","It requires a separate computer to verify","It can only handle one transaction per block"]},{q:"What makes Bitcoin programmable money?",a:"Bitcoin Script enables conditional spending and smart contracts",wrong:["Only banks can program it","It runs Python code directly","Central programmers control all transactions"]},{q:"What are timelocks in Bitcoin?",a:"Conditions preventing spending until a specific time or block height",wrong:["Physical locks on hardware wallets","Password requirements","Banking hours restrictions"]},{q:"What is a multisig (multi-signature) transaction?",a:"Requires multiple private keys to authorize spending",wrong:["Multiple transactions combined","Multiple miners confirming","Multiple exchanges involved"]}],ordinals:[{q:"Bitcoin Ordinals allow:",a:"Inscribing data (images, text) directly on individual satoshis",wrong:["Creating new tokens on the Bitcoin network","Speeding up transaction confirmation times","Reducing the total supply of Bitcoin"]},{q:"Why are Ordinals controversial in the Bitcoin community?",a:"They increase block space demand and fees for financial transactions",wrong:["They change the 21 million supply cap","They require a hard fork to implement","They give miners control over which transactions are valid"]},{q:"What are Bitcoin Ordinals?",a:"A numbering system for satoshis enabling inscription of arbitrary data",wrong:["A type of altcoin token","A mining algorithm","A Lightning channel type"]},{q:"What controversial use case emerged from Ordinals?",a:"BRC-20 tokens creating fungible tokens on Bitcoin",wrong:["Instant payment settlement","Hardware wallet security","Private key encryption"]},{q:"What is the debate around Ordinals inscriptions?",a:"They use block space, potentially raising fees for regular transactions",wrong:["They steal bitcoin from wallets","They hack the blockchain","They prevent mining from working"]}],geopolitics___macroeconomics:[{q:"Why is Bitcoin relevant to geopolitics?",a:"It provides a neutral monetary system outside any nation's control",wrong:["Major governments collectively control Bitcoin's code","Bitcoin mining is only legal in 5 countries","The UN regulates Bitcoin's international transfers"]},{q:'What is the "petrodollar" system?',a:"Oil is priced in US dollars, forcing global demand for the dollar",wrong:["A cryptocurrency backed by oil reserves","A Bitcoin mining technique using petroleum","A tax imposed on Bitcoin by oil-producing nations"]},{q:"Which country was the first to adopt Bitcoin as legal tender?",a:"El Salvador in September 2021",wrong:["United States","Japan","Germany"]},{q:"How do sanctions-evading nations view Bitcoin?",a:"As a way to circumvent SWIFT restrictions and frozen reserves",wrong:["As a threat to their currencies","As a US surveillance tool","As illegal everywhere"]},{q:"What macro trend drives Bitcoin adoption during inflation?",a:"Currency debasement making bitcoin\\'s fixed supply attractive",wrong:["Lower interest rates on bitcoin","Government bitcoin subsidies","Bank account requirements"]}],"op-codes":[{q:"Bitcoin OP_CODES are:",a:"Instructions in Bitcoin's scripting language that define spending conditions",wrong:["Error codes returned when a transaction fails","Codes used to communicate between mining pools","Secret backdoor commands for Bitcoin developers"]},{q:"OP_RETURN allows:",a:"Embedding small amounts of arbitrary data in the blockchain",wrong:["Reversing a confirmed transaction","Returning stolen Bitcoin to its owner","Increasing the block size limit"]},{q:"What is OP_CHECKSIG in Bitcoin Script?",a:"Verifies a digital signature against a public key",wrong:["Creates new bitcoins","Encrypts transaction data","Connects to mining pools"]},{q:"What was the OP_RETURN controversy?",a:"Its limit was reduced to prevent blockchain bloat from non-financial data",wrong:["It was used to hack exchanges","It created unlimited bitcoins","It stopped all transactions"]},{q:"What did Taproot enable for Bitcoin opcodes?",a:"More flexible scripting through Schnorr signatures and Merkle branches",wrong:["Removal of all previous scripts","Conversion to Ethereum compatibility","Centralized script approval"]}],public_key_vs_private_key:[{q:"Your Bitcoin public key is like:",a:"Your email address — you share it so people can send you Bitcoin",wrong:["Your password — never share it with anyone","Your bank PIN number — used to authorize spending","Your social security number — it proves your identity"]},{q:"If someone has your private key, they can:",a:"Spend all the Bitcoin controlled by that key",wrong:["Only view your transaction history","Reset your password and lock you out","Create new Bitcoin out of thin air"]},{q:"What is the relationship between private and public keys?",a:"Public keys are derived from private keys via one-way cryptographic function",wrong:["Private keys are given to everyone","Public keys encrypt private keys","They are identical numbers"]},{q:"What should you do with your private keys?",a:"Keep them secret and secure, never share with anyone",wrong:["Publish them online","Email them to exchanges","Print them on merchandise"]},{q:"What is the purpose of a public key?",a:"To receive bitcoin and verify signatures without revealing the private key",wrong:["To spend bitcoin alone","To mine new blocks","To create private keys"]}],transaction_fees:[{q:"Bitcoin transaction fees are determined by:",a:"The size of the transaction in bytes and current network demand",wrong:["A fixed percentage of the transaction amount","The number of Bitcoin being sent","The geographic distance between sender and receiver"]},{q:"When the mempool is full:",a:"Transactions with higher fees get confirmed first",wrong:["All transactions are rejected until it clears","The block size automatically increases","Transaction fees are refunded to senders"]},{q:"What determines Bitcoin transaction fees?",a:"Transaction size in bytes and current network demand (mempool congestion)",wrong:["Transaction amount in bitcoin","Sender\\'s reputation","Government regulation"]},{q:"What is the mempool?",a:"A waiting area for unconfirmed transactions held by nodes",wrong:["A mining hardware pool","A cryptocurrency exchange","A type of Bitcoin wallet"]},{q:"Why do fees spike during network congestion?",a:"Users compete for limited block space by bidding higher fees",wrong:["Miners arbitrarily raise prices","Exchanges charge extra","Bitcoin supply decreases"]}],philosophy:[{q:'"Don\'t trust, verify" means:',a:"Run your own node to independently verify all Bitcoin rules",wrong:["Never use Bitcoin because it cannot be trusted","Only trust exchanges that are government-regulated","Verify your identity before making transactions"]},{q:'The concept "Bitcoin is Time" by Gigi suggests:',a:"Bitcoin creates a decentralized clock through proof of work",wrong:["Bitcoin transactions can travel back in time","Bitcoin was invented to save people time","Bitcoin mining uses atomic clocks"]},{q:"What is the cypherpunk movement that birthed Bitcoin?",a:"Advocates for privacy through cryptography and code over trust",wrong:["Bankers wanting digital currency","Gamers creating virtual money","Governments tracking transactions"]},{q:'What does "don\\\'t trust, verify" mean in Bitcoin?',a:"Run your own node to validate transactions rather than trusting third parties",wrong:["Trust banks with your bitcoin","Verify your email address","Don\\'t check transactions yourself"]},{q:'What does Bitcoin\\\'s "monetary policy" refer to?',a:"Fixed supply schedule with predictable issuance rate until 21 million",wrong:["Central bank interest rates","Government fiscal policy","Investment fund strategies"]}],halving:[{q:"The Bitcoin halving occurs every:",a:"210,000 blocks (approximately every 4 years)",wrong:["Every calendar year on January 3","Every 100,000 blocks","Whenever the price doubles"]},{q:"After the 2024 halving, the block reward is:",a:"3.125 BTC per block",wrong:["6.25 BTC per block","1.5625 BTC per block","50 BTC per block"]},{q:"The halving is significant because it:",a:"Mathematically enforces Bitcoin's decreasing supply issuance",wrong:["Doubles the total supply of Bitcoin","Reduces the number of active miners by half","Changes Bitcoin's consensus mechanism"]},{q:"What happens during a Bitcoin halving?",a:"Block reward paid to miners is cut in half",wrong:["Transaction fees double","Bitcoin supply doubles","Mining difficulty halves"]},{q:"When will the final bitcoin be mined?",a:"Around year 2140 when all 21 million are issued",wrong:["2025","2040","Never — mining continues forever"]}],bitcoin_vs_real_estate:[{q:"What key property rights advantage does Bitcoin have over real estate?",a:"It cannot be seized, taxed annually, or confiscated via eminent domain",wrong:["Real estate has stronger rights because it is protected by law","Bitcoin and real estate have identical property rights protections","Bitcoin ownership is not recognized by any major legal system"]},{q:"How do maintenance costs compare between Bitcoin and real estate?",a:"Bitcoin has near-zero costs; real estate requires taxes, insurance, and repairs",wrong:["Bitcoin requires expensive monthly server fees to maintain ownership","Real estate has no maintenance costs once the mortgage is paid off","Both assets have roughly equivalent ongoing maintenance expenses"]},{q:"Why is Bitcoin considered superior to real estate in terms of portability?",a:"A seed phrase can be memorized and carried across any border instantly",wrong:["Real estate deeds can be memorized and are just as portable","Bitcoin is less portable because it always requires internet access","Portability is irrelevant when comparing long-term stores of value"]},{q:"How does Bitcoin's divisibility compare to real estate?",a:"Bitcoin divides into 100 million satoshis; real estate cannot be micro-divided",wrong:["Real estate is more divisible because you can rent individual rooms","Bitcoin cannot be divided at all — you must buy a whole coin","Both assets offer identical divisibility through financial derivatives"]},{q:"What risk does real estate face that Bitcoin does not, related to government power?",a:"Eminent domain seizure, property tax liens, and government confiscation",wrong:["Governments can easily confiscate Bitcoin but not real estate","Neither asset faces any confiscation risk in democratic nations","Bitcoin faces greater government risk because it can be fully banned"]}],bitvm:[{q:"What does BitVM enable on Bitcoin without requiring a protocol change?",a:"Arbitrary computation verification through fraud proofs",wrong:["Turing-complete smart contracts executed by miners","On-chain virtual machine execution like the EVM","Zero-knowledge proof generation inside Bitcoin Script"]},{q:"BitVM uses which computational model to verify off-chain computation?",a:"An optimistic model with prover claims and verifier challenges",wrong:["A zero-knowledge model where proofs are posted each block","A consensus model where all nodes re-execute computation","A federated model where trusted signers attest to results"]},{q:"In BitVM, what is the fundamental logic gate used to represent any computable function?",a:"NAND gates",wrong:["AND gates","XOR gates","NOR gates"]},{q:"Who proposed the original BitVM whitepaper?",a:"Robin Linus",wrong:["Peter Todd","Jeremy Rubin","Andrew Poelstra"]},{q:"How does BitVM2 improve upon the original BitVM design?",a:"It reduces on-chain transactions needed for dispute resolution",wrong:["It adds Turing-complete execution directly on base layer","It eliminates the need for a verifier role entirely","It requires a soft fork to enable several new opcodes"]}],"block_time-block-size":[{q:"Why did Satoshi choose approximately 10 minutes for Bitcoin's target block time?",a:"It balances throughput with time needed for global block propagation",wrong:["It was arbitrary with no real technical justification behind it","Faster blocks would make mining unprofitable due to power costs","It matches the average time needed for international wire transfers"]},{q:"What is the difference between block weight and block size in Bitcoin?",a:"Weight counts witness bytes at a discount versus non-witness bytes",wrong:["Block weight and block size are identical with different names","Block weight measures computational effort to validate a block","Block weight only applies to Lightning Network transactions"]},{q:"What is the maximum block weight allowed by Bitcoin's consensus rules?",a:"4 million weight units (4 MWU)",wrong:["1 megabyte of raw data","8 million weight units (8 MWU)","2 million weight units (2 MWU)"]},{q:"Why does SegWit give witness data a discount in the block weight calculation?",a:"Witness data costs less for nodes to process, incentivizing adoption",wrong:["Witness data is encrypted and takes up less physical storage","The discount was a political compromise with no technical basis","Witness data is stored temporarily then deleted after 100 blocks"]},{q:'What is "blockspace economics" in Bitcoin?',a:"The fee market where users bid for limited space in each block",wrong:["A government program subsidizing mining in renewable energy zones","The cost of running a full node in electricity and bandwidth","A pricing model used for Lightning Network channel capacity"]}],burn_bitcoin:[{q:"What is the maximum amount of data that can be stored in an OP_RETURN output?",a:"80 bytes",wrong:["40 bytes","160 bytes","1000 bytes"]},{q:"What does it mean for Bitcoin to be provably unspendable through OP_RETURN?",a:"The output has no valid script path to spend it",wrong:["It requires a special private key to spend","It can only be spent after 100 confirmations","It is temporarily locked until a timelock expires"]},{q:"Roughly how many Bitcoin are estimated to be permanently lost or burned?",a:"Between 3-4 million BTC",wrong:["Less than 1 million BTC","Over 10 million BTC","Exactly 1 million BTC"]},{q:"What type of Bitcoin address output is provably unspendable with no script?",a:"Bare multisig with invalid pubkeys",wrong:["Standard P2PKH addresses","Wrapped P2SH addresses","Native P2WPKH addresses"]},{q:"What is proof of burn in the context of cryptocurrency?",a:"Demonstrating coins were sent to an unspendable address",wrong:["Mining blocks without ever receiving any block rewards","Permanently deleting the private keys to a wallet","Sending coins to a wallet whose owner has died"]}],consensus_pt2:[{q:"What does finality mean in Nakamoto Consensus?",a:"Reversals become exponentially harder with each confirmation",wrong:["Transactions are instantly and permanently irreversible","Miners hold a formal vote on transaction validity","The longest chain is always guaranteed to be correct"]},{q:"What are orphan blocks in Bitcoin?",a:"Valid blocks not included in the main chain",wrong:["Invalid blocks rejected by network nodes","Blocks that contain zero transactions inside","Alternative variants of the genesis block"]},{q:"What is selfish mining in Bitcoin?",a:"Withholding found blocks to gain unfair advantage",wrong:["Mining solo without joining any mining pool","Using only renewable energy sources for mining","Deliberately refusing to validate any transactions"]},{q:"What is the typical Bitcoin block propagation time?",a:"1-10 seconds globally",wrong:["About 60 seconds on average","Nearly instantaneous at all times","Approximately 10 full minutes"]},{q:"What was the FIBRE network designed to improve?",a:"Block propagation speed between miners",wrong:["Lightning Network payment routing","Wallet synchronization with nodes","Mining difficulty adjustment calculations"]}],cryptography_pt3:[{q:"What advantage do Schnorr signatures provide over ECDSA in Bitcoin?",a:"Key aggregation for efficient multi-signature transactions",wrong:["Quantum resistance that ECDSA fundamentally lacks","Smaller size in all cases regardless of signers","Available since day one but never actually used"]},{q:"What is MuSig2 in Bitcoin?",a:"A Schnorr-based multi-sig scheme producing one standard-looking signature",wrong:["A second version of the Bitcoin music streaming protocol","A next-generation mining algorithm replacing SHA-256 hashing","A Lightning Network routing protocol for two-hop payments"]},{q:"What are adaptor signatures used for in Bitcoin?",a:"Conditional payments where signing reveals a secret value",wrong:["Converting old formats to be Taproot-compatible ones","Signing transactions using multiple keys simultaneously","Adapting Script to support Turing-complete contracts"]},{q:"What is a Pedersen commitment?",a:"A commitment that hides a value while allowing math verification",wrong:["A legal agreement between developers to maintain the protocol","A type of fee commitment that is included in every block","A signed pledge by miners to always follow consensus rules"]},{q:"What is the current status of zero-knowledge proofs on Bitcoin?",a:"Being explored via projects like BitVM and validity rollups",wrong:["Fully implemented in Bitcoin Core since the Taproot upgrade","Impossible on Bitcoin due to fundamental Script limitations","Removed from Bitcoin in 2015 due to critical security risks"]}],"ctv-covenants":[{q:"What does BIP-119 (CheckTemplateVerify) allow a Bitcoin output to do?",a:"Commit to a specific future transaction template for spending",wrong:["Execute arbitrary smart contract code when it is spent","Lock funds until a specific block height has been reached","Require multiple signatures from different keys to spend"]},{q:'What is a "covenant" in the context of Bitcoin?',a:"A restriction on how a UTXO can be spent in the future",wrong:["A multisig arrangement between federation member nodes","A legal agreement between Lightning channel counterparties","A time-locked contract that expires after a set period"]},{q:'What Bitcoin use case does CTV enable through "congestion control"?',a:"Batching many payments into one transaction claimable later",wrong:["Auto-adjusting fees based on current mempool congestion","Throttling transactions a wallet can send within a block","Limiting block size during periods of high network load"]},{q:"What is OP_VAULT designed to provide using covenants?",a:"Time-delayed withdrawals with an emergency clawback option",wrong:["A decentralized exchange built for trustless atomic swaps","Cold storage that auto-moves funds to hardware wallets","Multi-party escrow designed for marketplace transactions"]},{q:"Why are covenants considered controversial by some Bitcoiners?",a:"They could enable coin censorship or spending blacklists",wrong:["They require a hard fork that would split the network","They make all transactions public and remove user privacy","They increase block size beyond what nodes can handle"]}],cycles:[{q:"What drives Bitcoin's historically observed ~4-year market cycle?",a:"The halving, which cuts new supply in half every ~4 years",wrong:["Government regulations that shift with 4-year election cycles","A scheduled software update that resets the network state","Random market psychology with no underlying structural driver"]},{q:"How does the Gartner Hype Cycle apply to each Bitcoin halving era?",a:"Each cycle shows trigger, peak hype, disillusionment, then recovery to a plateau",wrong:["Bitcoin skips disillusionment because the price only goes up long-term","The Gartner Hype Cycle only applies to new tech products, not currencies","Each Bitcoin cycle follows the exact same price pattern as the last one"]},{q:'What is the "lengthening cycles" debate in Bitcoin?',a:"The theory that each bull run takes longer to peak with smaller percentage gains",wrong:["The theory that mining cycles get shorter as hardware gets faster","A proposal to extend the halving interval from four years to eight","The idea that transaction confirmation times increase every year"]},{q:"Which on-chain metrics are commonly used to analyze Bitcoin market cycles?",a:"MVRV, NUPL, and the Pi Cycle Top indicator",wrong:["GDP growth, unemployment, and consumer price index","Twitter followers, Google Trends, and Reddit subs","Block size, node count, and developer commit stats"]},{q:'What is the "diminishing returns" theory in Bitcoin cycles?',a:"Each cycle's percentage gain shrinks, though absolute highs keep rising",wrong:["Returns are accelerating each cycle with larger percentage gains","Bitcoin will eventually produce negative returns in every cycle","It refers to decreasing energy efficiency of mining each cycle"]}],derivation_path:[{q:"What does a BIP-32 HD (Hierarchical Deterministic) wallet allow you to do?",a:"Generate unlimited key pairs from a single master seed",wrong:["Store multiple cryptocurrencies in one single private key","Recover funds without a seed phrase using only email","Connect directly to the network without running a node"]},{q:"In the derivation path m/84'/0'/0'/0/0, what does the \"84\" represent?",a:"BIP-84, the Native SegWit (bech32) address standard",wrong:["The year 1984 when public key crypto was standardized","The 84th account stored inside this particular wallet","The total number of addresses that can be derived"]},{q:"Which BIP defines the derivation path standard for Taproot (bc1p) addresses?",a:"BIP-86",wrong:["BIP-84","BIP-49","BIP-44"]},{q:"Why is sharing an xpub (extended public key) a privacy concern?",a:"It lets anyone see all addresses and balances from that account",wrong:["It allows someone to spend your Bitcoin without the private key","It broadcasts your seed phrase to every node on the network","It reveals your real-world name and identity on the blockchain"]},{q:'What is the "gap limit" in HD wallet address discovery?',a:"How many consecutive unused addresses are checked before stopping",wrong:["The maximum number of addresses a wallet can generate total","The time delay required between generating new addresses","The minimum spacing between two UTXOs in a transaction"]}],"difficulty-adjustment_pt2":[{q:"What algorithm does Bitcoin use for difficulty adjustment?",a:"Direct calculation based on actual vs target time",wrong:["PID controller algorithm with feedback loops","Neural network prediction of future hash rate","Moving average of recent hash rate samples"]},{q:"How many blocks is the difficulty retarget period?",a:"2,016 blocks",wrong:["1,008 blocks","4,032 blocks","10,080 blocks"]},{q:"What causes hash rate oscillation between mining pools?",a:"Miners chasing short-term luck variance",wrong:["Scheduled Bitcoin Core software update cycles","Daily difficulty adjustment recalculations","Network communication delays between nodes"]},{q:"What variance measure describes pool mining luck?",a:"Statistical variance around expected block discovery",wrong:["Fixed reward percentage distributed to miners","Difficulty share ratio across pool participants","Network propagation delay between peer nodes"]},{q:"How long does a difficulty epoch typically last?",a:"Approximately 2 weeks",wrong:["Exactly 1 week","About 1 month","Approximately 4 days"]}],dlcs:[{q:"In a Discreet Log Contract (DLC), what role does an oracle play?",a:"It signs a real-world outcome that determines how the contract pays out",wrong:["It holds the funds in escrow until both parties agree on the result","It executes smart contract code on a sidechain to settle the bet","It mines the specific transaction that settles the contract on-chain"]},{q:'What cryptographic technique makes DLCs "discreet" — invisible to the oracle?',a:"Adaptor signatures that use the oracle's attestation privately",wrong:["Zero-knowledge proofs that hide the contract from participants","Ring signatures that mix the contract with unrelated transactions","Homomorphic encryption that processes data without decrypting it"]},{q:"What is a common real-world use case for Discreet Log Contracts?",a:"Financial derivatives and betting settled by price or event data",wrong:["Decentralized file storage using the Bitcoin network as a backend","Privacy-preserving identity verification on the Bitcoin blockchain","Automated market making for Lightning Network liquidity pools"]},{q:"Why is the oracle in a DLC considered more trustworthy than traditional smart contract oracles?",a:"The oracle doesn't know the contract exists or what depends on it",wrong:["The oracle stakes Bitcoin collateral that is slashed if it lies","Multiple oracles must all agree before any payout can occur","The oracle runs inside a trusted execution environment on-chain"]},{q:"DLC.Link enables Discreet Log Contracts to be used primarily for what purpose?",a:"Bridging Bitcoin as collateral into DeFi without giving up custody",wrong:["Mining pool payout distribution based on individual hash rate","Decentralized DNS registration on the Bitcoin base layer","Cross-chain atomic swaps between Bitcoin and Ethereum directly"]}],"dollar-bitcoin_milkshake_theory":[{q:'Who originated the "Dollar Milkshake Theory"?',a:"Brent Johnson of Santiago Capital",wrong:["Ray Dalio of Bridgewater Associates","Michael Saylor of MicroStrategy","Saifedean Ammous of The Bitcoin Standard"]},{q:"What is the core thesis of the Dollar Milkshake Theory?",a:"The dollar strengthens by sucking up global liquidity while other fiat currencies weaken",wrong:["All fiat currencies collapse simultaneously and get replaced by Bitcoin","The dollar weakens as other currencies collectively strengthen against it","Central banks coordinate to create and adopt a single global currency"]},{q:'What is the "dollar strength paradox" in the Milkshake Theory?',a:"The dollar gets stronger vs other currencies while losing purchasing power vs hard assets",wrong:["A strong dollar always means the Bitcoin price will go down in tandem","Dollar strength is a reliable signal that the US economy is healthy","Nobody wants dollars but everyone needs them to service their debts"]},{q:"How does Bitcoin fit into the Dollar Milkshake Theory's endgame?",a:"After the dollar absorbs global liquidity, Bitcoin becomes the ultimate fiat exit",wrong:["Bitcoin is irrelevant to the theory because it isn't a fiat currency","Bitcoin collapses alongside other currencies during the dollar's rise","The theory predicts Bitcoin gets banned and replaced by state CBDCs"]},{q:"Why does global dollar demand play a central role in the Milkshake Theory?",a:"Trillions in dollar-denominated debt forces nations to buy dollars, strengthening it",wrong:["Global dollar demand is declining rapidly as nations actively de-dollarize","Dollar demand only matters for US domestic transactions and trade","The theory says dollar demand is irrelevant — only money supply matters"]}],"el-salvador":[{q:"What was the Chivo wallet in El Salvador's Bitcoin adoption?",a:"A government-issued Lightning wallet that gave citizens $30 in Bitcoin",wrong:["A private hardware wallet manufactured locally in El Salvador","An exchange platform where Salvadorans could trade altcoins","A banking app that only supported US dollar-based transactions"]},{q:'What is "Bitcoin Beach" and why is it significant to El Salvador\'s Bitcoin story?',a:"El Zonte — a village that built a grassroots Bitcoin economy before the national law",wrong:["A luxury resort in San Salvador that exclusively accepts Bitcoin payments","A government-built tourist attraction designed to promote Bitcoin adoption","A cryptocurrency exchange headquartered on the Salvadoran coastal region"]},{q:"What was President Bukele's core strategy behind making Bitcoin legal tender?",a:"Financial inclusion for the unbanked, foreign investment, and cheaper remittances",wrong:["Replacing the US dollar entirely with Bitcoin as the sole currency","Mining Bitcoin profitably using El Salvador's untapped oil reserves","Creating a government-controlled cryptocurrency to replace Bitcoin"]},{q:"How did the World Bank and IMF respond to El Salvador's Bitcoin law?",a:"They pushed back — the World Bank refused help and the IMF warned of risks",wrong:["Both organizations fully endorsed and helped fund the entire initiative","The IMF designed and helped build the Chivo wallet infrastructure","The World Bank provided a $500 million loan specifically for adoption"]},{q:"How did Lightning Network adoption benefit El Salvador's economy?",a:"It enabled fast, near-free payments and remittances, cutting out costly services",wrong:["Lightning was not used — only on-chain Bitcoin transactions were supported","Lightning made transactions faster but significantly more expensive overall","El Salvador banned Lightning in favor of on-chain-only Bitcoin payments"]}],"evidence-against-alts_pt2":[{q:'What is a "premine" and why is it a red flag for altcoins?',a:"Founders create and keep tokens before public launch, giving insiders an unfair edge",wrong:["A premine is a security feature that helps blockchains launch more quickly","A premine means the coin was tested before release, which is good practice","A premine is when miners validate the genesis block without earning fees"]},{q:"Why are many altcoin tokens considered securities under US law?",a:"They pass the Howey Test — buyers expect profits from a centralized team's efforts",wrong:["The SEC automatically classifies every digital asset as a regulated security","Any token traded on a cryptocurrency exchange is legally a security by default","Only tokens with market caps above $1 billion can qualify as securities"]},{q:'What is "VC token dumping" in the altcoin market?',a:"VCs invest early at a discount, then sell their tokens on retail investors at launch",wrong:["VCs donate their discounted tokens to charity projects after launch","VCs permanently lock their tokens to show support for the project","VCs use their tokens to fund open-source Bitcoin core development"]},{q:'Why do Bitcoiners argue that "decentralized governance tokens" are an oxymoron?',a:"Token voting concentrates power with whales and VCs, recreating inequality",wrong:["Governance tokens are too technically complex to ever implement properly","Bitcoin already uses governance tokens internally for protocol upgrades","Governance tokens have been declared illegal in every jurisdiction"]},{q:"What key evidence do Bitcoiners cite about Ethereum's centralization?",a:"A massive premine to insiders, repeated monetary policy changes, and known leadership",wrong:["Ethereum runs on a single server that is controlled by Vitalik Buterin","Ethereum transactions require explicit government approval before processing","Ethereum has fewer active nodes than a typical corporate cloud database"]}],"extension-blocks":[{q:"What are extension blocks in Bitcoin?",a:"Additional block space running alongside the main chain without changing it",wrong:["Larger blocks created by increasing the block size limit via a hard fork","Blocks reserved exclusively for Lightning Network channel operations","Compressed blocks that store only transaction hashes to save space"]},{q:"How do extension blocks differ from a traditional soft fork upgrade?",a:'Old nodes see extension transactions as "anyone-can-spend" outputs',wrong:["Extension blocks require all nodes to upgrade or be forked off the network","Extension blocks reduce the block size to improve network decentralization","Extension blocks are identical to soft forks but use a different label"]},{q:'What is the "space chain" concept related to extension blocks?',a:"A separate chain whose block space is auctioned via the main chain",wrong:["A satellite network that broadcasts Bitcoin blocks from orbit","A virtual reality environment where Bitcoin nodes operate in 3D","A specialized blockchain optimized for storing files over 4MB"]},{q:"What is a key trade-off of extension blocks?",a:"Non-upgraded nodes cannot fully validate extension block transactions",wrong:["All miners must upgrade their hardware simultaneously to participate","The main block size permanently increases for all future blocks","Lightning Network channels become incompatible with the base layer"]},{q:"Why have extension block proposals historically been controversial in Bitcoin development?",a:"They risk creating a second-class zone that weakens full node security",wrong:["They were proposed by altcoin developers trying to undermine Bitcoin","They would eliminate the need for the Lightning Network entirely","They require replacing SHA-256 with a completely different hash algorithm"]}],feedback_loops:[{q:"What is the price-hashrate-security feedback loop in Bitcoin?",a:"Higher price attracts miners, boosting hashrate, security, and confidence in a rising cycle",wrong:["Higher price causes miners to shut down, reducing hashrate and network security","Hashrate and price are completely independent with no meaningful connection","Security drops as price rises because more hackers are attracted to attack"]},{q:"How does the adoption-liquidity-utility feedback loop work in Bitcoin?",a:"More users deepen liquidity, making Bitcoin more useful, which attracts even more users",wrong:["More users raise fees, which drives away users and decreases overall liquidity","Liquidity falls as adoption grows because the total supply is permanently fixed","Adoption and liquidity have an inverse relationship in the Bitcoin network"]},{q:"How does the Lindy Effect create a reinforcing feedback loop for Bitcoin?",a:"Each day Bitcoin survives boosts confidence in its longevity, drawing more adoption",wrong:["The Lindy Effect means Bitcoin gets less reliable as its codebase ages","Older technology always gets replaced, so the Lindy Effect hurts Bitcoin","The Lindy Effect only applies to physical objects, not digital protocols"]},{q:"What is reflexivity in the context of Bitcoin market cycles?",a:"Perceptions influence fundamentals, which reinforce perceptions, creating self-amplifying cycles",wrong:["Reflexivity means Bitcoin's price always reflects its true fundamental value","It describes the tendency of Bitcoin to always revert to the same price","Reflexivity is a mining technique that increases block production speed"]},{q:"Why are Bitcoin's feedback loops considered among the most powerful in economics?",a:"Multiple self-reinforcing loops in price, hashrate, adoption, and security amplify together",wrong:["Bitcoin has only one feedback loop but it happens to be extremely strong","Bitcoin's feedback loops are actually weak compared to traditional market loops","Feedback loops only work in bull markets and reverse completely in bear runs"]}],first_principles:[{q:'What does "first principles thinking" mean when applied to Bitcoin?',a:"Breaking money down to fundamental properties and reasoning up from there",wrong:["Copying the design of existing currencies and then improving them","Following the majority opinion of mainstream economists on money","Starting with government approval and working backward from there"]},{q:"Which philosopher is most associated with the first principles method of reasoning from fundamental truths?",a:"Aristotle",wrong:["Plato","Socrates","Descartes"]},{q:"When reasoning from first principles about what makes good money, which set of properties matters most?",a:"Scarcity, portability, durability, divisibility, and fungibility",wrong:["Government backing, legal enforcement, and central bank control","Physical weight, aesthetic beauty, and historical tradition","Ease of printing, widespread banking, and inflation targeting"]},{q:"First principles thinking reveals what fundamental connection between energy and money?",a:"Money should represent stored energy — unforgeable costliness gives it value",wrong:["Money has no relationship to energy since it is purely a social construct","Only physical commodities can serve as money because they contain atoms","Energy is irrelevant to money if a government declares it legal tender"]},{q:"Why does first principles reasoning tend to lead people toward Bitcoin rather than altcoins?",a:"Bitcoin best satisfies the fundamental properties of sound money from first principles",wrong:["Bitcoin was the first cryptocurrency so it wins by default over altcoins","Altcoins are illegal in most countries so Bitcoin is the only legal option","Bitcoin has the best marketing team and strongest brand awareness overall"]}],foss:[{q:"What type of software license does Bitcoin Core use?",a:"MIT License",wrong:["GPL v3","Apache License 2.0","Creative Commons"]},{q:"Why is it important that Bitcoin Core is free and open-source software (FOSS)?",a:"Anyone can audit the code to verify no backdoors or hidden rules exist",wrong:["It makes Bitcoin free to use with zero transaction fees for users","It allows developers to create unlimited Bitcoin through the code","It means no one actually needs to run the Bitcoin software"]},{q:'What are "reproducible builds" in the context of Bitcoin Core?',a:"A process to compile source code and verify the binary matches the official release",wrong:["A method of mining Bitcoin blocks more efficiently using parallel processing","A way to duplicate Bitcoin wallets for secure backup across multiple devices","A technique for copying the entire blockchain to new nodes more quickly"]},{q:'"Linus\'s Law" states that "given enough eyeballs, all bugs are shallow." How does this apply to Bitcoin?',a:"Thousands of developers review Bitcoin's code, so vulnerabilities get found and fixed faster",wrong:["Linux servers are the only machines capable of running Bitcoin full nodes properly","Linus Torvalds personally reviews and audits every Bitcoin Core release himself","Bitcoin can only run on open-source operating systems like Linux and FreeBSD"]},{q:"Why does open-source matter specifically for money/monetary software like Bitcoin?",a:"Users must verify the rules of their money — no hidden inflation or secret changes",wrong:["Open-source software is always faster and more efficient than proprietary code","It allows banks to freely copy Bitcoin and make their own branded version","It makes Bitcoin significantly easier for governments to regulate and control"]}],geopolitics___macroeconomics_pt2:[{q:"What is the BRICS de-dollarization movement and how does it relate to Bitcoin?",a:"BRICS nations are reducing dollar dependence, creating demand for neutral reserves like Bitcoin",wrong:["BRICS is a Bitcoin mining pool that is jointly operated by five nations","BRICS nations have collectively banned Bitcoin to protect local currencies","BRICS de-dollarization means these countries adopted Bitcoin as legal tender"]},{q:'What is the "strategic Bitcoin reserve" concept that multiple nations are exploring?',a:"Nations accumulating Bitcoin as a reserve asset alongside gold for its scarcity and hedge value",wrong:["A requirement for all nations to back their fiat currency reserves with Bitcoin","A UN mandate requiring every country to hold at least one thousand Bitcoin","A program where central banks replace all existing gold reserves with Bitcoin"]},{q:'What is the "nation-state game theory" argument for Bitcoin adoption?',a:"Early adopter nations gain a massive strategic edge, pressuring others to follow or fall behind",wrong:["Nations banning Bitcoin grow stronger because they fully control their money supply","Game theory proves that no nation will ever voluntarily adopt Bitcoin as a reserve","Nation-state game theory only applies to countries that possess nuclear weapons"]},{q:"How do proponents respond to critics who say Bitcoin is used for sanctions evasion?",a:"Bitcoin's transparent public ledger makes transactions easier to trace than physical cash",wrong:["Bitcoin supporters agree that sanctions evasion is its primary real-world use case","Bitcoin transactions are completely invisible and undetectable to all governments","Sanctions don't apply to digital assets under any current international law"]},{q:"How do institutions like the IMF and World Bank view Bitcoin?",a:"Generally hostile — they've pressured nations like El Salvador to drop Bitcoin legal tender status",wrong:["The IMF and World Bank are actually the largest institutional Bitcoin holders today","Both organizations have publicly endorsed Bitcoin as the future of global finance","The IMF created Bitcoin as a planned replacement for Special Drawing Rights"]}],governance_pt2:[{q:"Who can submit a Bitcoin Improvement Proposal (BIP)?",a:"Anyone in the Bitcoin community",wrong:["Only Bitcoin Core maintainers","Only miners with enough hash rate","Only officially registered developers"]},{q:"What activation method does BIP 9 use?",a:"Miner signaling with version bits",wrong:["User activation without miners","Mandatory soft fork by Core devs","Core developer approval voting"]},{q:"What activation method does BIP 8 use?",a:"Mandatory activation with optional miner signaling",wrong:["Complete miner control over activation timing","Exchange approval and coordinated agreement","Proof of stake voting by Bitcoin holders"]},{q:"What does UASF stand for?",a:"User-Activated Soft Fork",wrong:["Unified Active Soft Fork","Universal Auto Soft Fork","User Approval Soft Fork"]},{q:"What was Speedy Trial used for in Bitcoin?",a:"Taproot activation with a shortened signaling period",wrong:["SegWit activation with extended miner coordination","Lightning Network deployment across mainnet nodes","Difficulty adjustment algorithm changes and updates"]}],hardware:[{q:"What makes the Coldcard hardware wallet stand out among Bitcoin hardware wallets?",a:"It's air-gapped, Bitcoin-only, and supports NFC signing",wrong:["It supports thousands of altcoins and NFTs","It connects directly to the internet for speed","It's the cheapest hardware wallet available"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction) and why is it important for hardware wallets?",a:"A format for building transactions on one device and signing on another",wrong:["A Bitcoin address type exclusive to hardware wallets","A protocol for sending Bitcoin over Bluetooth","A backup format for storing seed phrases digitally"]},{q:"What is SeedSigner?",a:"A DIY, open-source, air-gapped wallet built on a Raspberry Pi",wrong:["A cloud service that generates seed phrases for you","A proprietary hardware wallet made by Ledger","An app that signs transactions via phone fingerprint"]},{q:'What is a "secure element" chip in hardware wallets?',a:"A tamper-resistant chip that stores keys and blocks extraction",wrong:["A chip that connects the wallet to Wi-Fi securely","A component that speeds up transaction processing","A GPS module that tracks the wallet for recovery"]},{q:'What does "air-gapped" mean when describing a hardware wallet like Coldcard or Foundation Passport?',a:"It never connects to internet — data moves via SD card, QR, or NFC",wrong:["The wallet is sealed in a vacuum to prevent tampering","The wallet uses satellite connections instead of Wi-Fi","The wallet can only be used outdoors for security"]}],history_pt3:[{q:"Approximately how many BTC did Mt. Gox lose in its collapse?",a:"850,000 BTC",wrong:["100,000 BTC","2 million BTC","50,000 BTC"]},{q:"What year did the Silk Road marketplace get seized?",a:"2013",wrong:["2011","2015","2017"]},{q:"How many Bitcoins were exchanged for two pizzas on Bitcoin Pizza Day?",a:"10,000 BTC",wrong:["1,000 BTC","100,000 BTC","1,000,000 BTC"]},{q:"What was the main conflict of the Blocksize War?",a:"Whether to increase block size limit",wrong:["Changing Bitcoin to proof of stake","Adding privacy features to Bitcoin","Changing the halving schedule"]},{q:"What was SegWit2x?",a:"Failed agreement to double block size after SegWit",wrong:["Successful hard fork increasing block size","A new proof-of-work mining algorithm","A second layer scaling protocol"]}],improved_incentive_structure:[{q:'How does Bitcoin "fix broken incentives" in the current monetary system?',a:"By removing money printing, it forces honest accounting and ends inflation of debt",wrong:["It gives governments better tools to manage the economy","It doesn't change incentives — just moves them to digital","It fixes incentives by making all transactions government-traceable"]},{q:'What does "low time preference society" mean in the context of a Bitcoin standard?',a:"People plan long-term and save more because their money gains value over time",wrong:["A society that doesn't care about time and works fewer hours","A society where transactions must complete within strict time limits","A society that only uses Bitcoin for short-term speculation"]},{q:'Why is proof of work considered a "fair distribution" mechanism for new Bitcoin?',a:"Anyone can mine by spending real energy — no pre-mines or insider allocations",wrong:["Proof of work gives equal Bitcoin to every person on Earth","Early miners got special privileges that later miners don't","Proof of work distributes Bitcoin based on geographic location"]},{q:"How does sound money (like Bitcoin) change savings and investment behavior?",a:"People save more and only invest in projects with real returns above deflation",wrong:["Sound money discourages saving because money becomes too valuable","Investment behavior stays the same regardless of monetary system","Sound money causes everyone to hoard and collapse the economy"]},{q:"What broken incentive does fiat money create that Bitcoin eliminates?",a:"Fiat rewards borrowing over saving because inflation erodes purchasing power",wrong:["Fiat incentivizes too much saving, which Bitcoin fixes","Fiat money has no broken incentives — it works as designed","Bitcoin creates the same borrow incentive since rates exist"]}],"investment-strategy_pt4":[{q:"What is UTXO management for tax optimization?",a:"Choosing specific UTXOs with known cost bases to minimize capital gains taxes",wrong:["Automatically hiding Bitcoin transactions from the IRS","Converting all UTXOs to altcoins before tax season","Splitting Bitcoin into $600 transactions to avoid reporting"]},{q:'What does "step-up in cost basis" mean for inherited Bitcoin?',a:"Cost basis resets to market price at owner's death, erasing prior gains",wrong:["Inherited Bitcoin is always taxed at the original purchase price","There is no tax on inherited Bitcoin in any jurisdiction","The cost basis doubles each year after inheritance"]},{q:"What is a Bitcoin IRA?",a:"A self-directed retirement account holding Bitcoin with tax advantages",wrong:["A government program that pays retirees in Bitcoin","An insurance policy replacing lost or stolen Bitcoin","A bank savings account that earns interest in Bitcoin"]},{q:"Why do experienced Bitcoiners warn against lending out your Bitcoin?",a:"Lending platforms like Celsius and BlockFi collapsed, losing depositor funds",wrong:["Bitcoin code prevents any form of lending or borrowing","Lending Bitcoin causes the network to slow down significantly","Bitcoin interest rates are always negative so you lose money"]},{q:"Why is cost basis tracking important for Bitcoin investors?",a:"Each purchase creates a separate tax lot needed for capital gains calculations",wrong:["Cost basis tracking is only needed for exchange-held Bitcoin","The IRS uses a flat tax rate on all Bitcoin regardless of price","Cost basis is irrelevant since Bitcoin is classified as currency"]}],laws_of_thermodynamics:[{q:"How does the First Law of Thermodynamics (conservation of energy) relate to Bitcoin mining?",a:"Miners convert electricity into computational work securing the ledger",wrong:["Bitcoin mining creates energy from nothing to power the network","The First Law means Bitcoin can only exist in cold climates","Energy is destroyed during mining, explaining the high usage"]},{q:'What does "unforgeable costliness" mean in Bitcoin\'s thermodynamic context?',a:"Real energy must be spent to produce Bitcoin and this cost can't be faked",wrong:["Bitcoin transactions are free because the network is decentralized","The cost of mining is purely artificial with no security purpose","Unforgeable costliness means Bitcoin wallets cannot be hacked"]},{q:"How does the Second Law of Thermodynamics (entropy always increases) connect to Bitcoin?",a:"Proof of work creates order in the ledger by increasing entropy via energy use",wrong:["Bitcoin violates the Second Law by creating value from nothing","Entropy has no connection to digital systems like Bitcoin","The Second Law means Bitcoin will eventually stop working"]},{q:'Why do some physicists describe proof of work as "thermodynamic security"?',a:"Reversing the chain would require re-spending all the energy that built it",wrong:["Because Bitcoin mining rigs get very hot during operation","Because proof of work requires cooling systems to function","Because thermodynamic equations are used to set transaction fees"]},{q:'What is the "Maxwell\'s Demon" analogy sometimes applied to Bitcoin?',a:"You can't sort molecules or secure a ledger without real energy expenditure",wrong:["Maxwell's Demon is the name of the first Bitcoin mining software","It describes a theoretical AI attack that takes over the network","It refers to Bitcoin price randomness being like particle motion"]}],"layer-2-lightning_pt4":[{q:"What is a submarine swap on the Lightning Network?",a:"A trustless exchange between on-chain and off-chain Bitcoin using HTLCs",wrong:["A method to secretly close Lightning channels without notice","A way to mine Bitcoin directly through Lightning Network nodes","An attack vector that drains funds from open Lightning channels"]},{q:"What is Multi-Path Payments (MPP) on Lightning?",a:"Splitting a payment across multiple routes to exceed single-channel limits",wrong:["Making multiple payments to different recipients simultaneously","A backup payment method used only if Lightning is offline","Sending the same payment through multiple channels for redundancy"]},{q:"What is AMP (Atomic Multi-Path Payments) on Lightning?",a:"A method where split parts are only redeemable together atomically",wrong:["An amplifier that boosts signal strength between Lightning nodes","A method to increase the maximum capacity of any channel","An automatic mining protocol built into the Lightning layer"]},{q:"What is trampoline routing on the Lightning Network?",a:"Delegating route calculation to intermediate nodes for lighter clients",wrong:["Bouncing payments off satellites for wider global coverage area","A routing method that always prioritizes the fastest available path","A security protocol that encrypts all payment amounts in transit"]},{q:"What are channel factories in the Lightning Network?",a:"Opening many channels among multiple parties in one on-chain transaction",wrong:["Physical facilities where Lightning network nodes are manufactured","Automated systems that create channels based on user demand levels","Software that converts on-chain wallets into Lightning-ready wallets"]}],"layer-2-lightning_pt5":[{q:"What is liquidity management on the Lightning Network?",a:"Balancing inbound and outbound capacity to reliably route payments",wrong:["Converting Lightning Bitcoin back to regular on-chain Bitcoin","Managing the total circulating supply of Bitcoin on Lightning","Keeping Lightning nodes continuously connected to the internet"]},{q:"What is channel rebalancing on Lightning?",a:"Moving funds between your own channels to redistribute liquidity",wrong:["Closing and reopening channels with updated funding parameters","Resetting all channel state back to the initial funding amount","Transferring full channel ownership to a different Lightning node"]},{q:"What is a Lightning Service Provider (LSP)?",a:"A service offering liquidity and channel management for easy onboarding",wrong:["An internet service provider that specializes in Bitcoin traffic","A government-licensed operator required to run Lightning nodes","A cloud service that mines Bitcoin using collected Lightning fees"]},{q:"What are zero-conf channels on Lightning?",a:"Channels usable immediately without waiting for on-chain confirmation",wrong:["Channels that require zero Bitcoin as a deposit to open them","Channels that provide completely zero-fee routing for payments","Channels that are permanent and cannot be closed once opened"]},{q:"How do Lightning routing nodes earn revenue?",a:"By charging small fees for forwarding payments through their channels",wrong:["By mining new Bitcoin on the Lightning Network second layer","By collecting a percentage of all Lightning transactions globally","By selling their channel and routing data to analytics companies"]}],"layer-3-sidechains":[{q:"How does the Liquid Network secure its two-way peg to Bitcoin?",a:"Through a federation of functionaries managing the peg via multisig",wrong:["Through merge-mining where Bitcoin miners also validate Liquid","Through a trustless smart contract deployed on Bitcoin's base layer","Through proof-of-stake consensus among Liquid token holder nodes"]},{q:"How does RSK (Rootstock) secure its sidechain?",a:"Through merge-mining where Bitcoin miners also validate RSK blocks",wrong:["Through a federation of trusted companies that collectively sign","Through proof-of-stake where RSK token holders vote on blocks","Through BitVM fraud proofs posted to Bitcoin's main base layer"]},{q:"What consensus mechanism does Stacks use to connect to Bitcoin?",a:"Proof of Transfer (PoX), where miners spend BTC to produce blocks",wrong:["Proof of Work using the same SHA-256 algorithm as Bitcoin mining","Delegated Proof of Stake with community-elected block producers","Proof of Authority using a fixed and permissioned validator set"]},{q:"What are drivechains (BIP-300) designed to enable?",a:"Permissionless sidechains with miner-voted withdrawals to mainchain",wrong:["Faster block times on Bitcoin by reducing difficulty adjustment","A new Lightning channel type that skips on-chain funding steps","Decentralized mining pools that auto-distribute block rewards"]},{q:"What is the primary security concern with federated sidechains like Liquid?",a:"Users must trust federation members not to collude and steal funds",wrong:["The sidechain can reverse Bitcoin base layer transactions at will","Federated sidechains consume more energy than Bitcoin's proof-of-work","The federation has the power to change Bitcoin's 21 million cap"]}],maximalism_pt2:[{q:'What do Bitcoiners mean when they call "toxic maximalism" an immune response?',a:"Aggressive pushback against scams protects newcomers like an immune system",wrong:["Maximalists spread computer viruses to attack competing altcoin networks","Toxic maximalism is a disease Bitcoin developers are actively trying to cure","It means Bitcoin's code automatically rejects transactions from altcoins"]},{q:'What is the "altcoin opportunity cost" argument made by Bitcoin maximalists?',a:"Money spent on altcoins could have gone to Bitcoin, which outperforms long-term",wrong:["Altcoins are free to create so there is no real opportunity cost at all","Bitcoin maximalists believe altcoin trading increases Bitcoin's overall value","Opportunity cost is a fiat concept that does not apply to digital assets"]},{q:"Why do Bitcoin-only companies (like Swan, River, and Unchained) choose not to support altcoins?",a:"They see promoting altcoins as ethically wrong since most will fail and harm users",wrong:["They lack the technical capability needed to support other cryptocurrency tokens","Government regulations currently prohibit companies from offering multiple cryptos","Supporting altcoins would make their exchange and wallet software too slow"]},{q:'What is the "ethical case" for Bitcoin maximalism?',a:"Promoting risky altcoins to unsophisticated investors causes real financial harm",wrong:["Bitcoin maximalists believe they have a religious duty to spread adoption","Ethics demand that all financial technologies be treated equally by default","The ethical case is that Bitcoin miners deserve all cryptocurrency profits"]},{q:'How does Gresham\'s Law ("bad money drives out good") apply to the Bitcoin maximalism argument?',a:"People spend weak fiat and altcoins while hoarding Bitcoin as the hardest money",wrong:["Gresham's Law proves that cheaper altcoins will eventually replace Bitcoin","It means governments will ultimately force citizens to use Bitcoin only","Gresham's Law only applies to physical coins and not digital currencies"]}],mining_pt5:[{q:"What does Stratum V2 allow individual miners to do that Stratum V1 does not?",a:"Choose their own transactions for block templates",wrong:["Mine without needing any internet connection","Bypass the network difficulty adjustment algorithm","Mine multiple different coins at the same time"]},{q:"What is a block template in Bitcoin mining?",a:"A candidate block with selected transactions awaiting a valid hash",wrong:["A design blueprint for building new ASIC mining hardware","A backup copy of the entire Bitcoin blockchain ledger","A reusable template for creating new cryptocurrency mining pools"]},{q:"What is a selfish mining attack?",a:"Withholding discovered blocks to gain an unfair chain advantage",wrong:["Refusing to share mining profits with other pool members","Mining only low-fee transactions for the miner's personal gain","Using stolen electricity to illegally power Bitcoin mining rigs"]},{q:"What is ASICBoost?",a:"A technique that optimizes SHA-256 to reduce energy per hash",wrong:["A specific brand of mining hardware manufactured by Bitmain","A firmware update that automatically doubles any miner's hashrate","A method to cool ASIC miners using advanced liquid nitrogen"]},{q:"What is the difference between overt and covert ASICBoost?",a:"Overt is visible in block headers; covert is hidden from view",wrong:["Overt is legal in all jurisdictions while covert is illegal","Overt uses significantly more energy per hash than covert does","Overt works on any ASIC while covert is Bitmain hardware only"]}],mining_pt6:[{q:'What is "hash price" in Bitcoin mining economics?',a:"Revenue earned per unit of hash rate per day",wrong:["Cost to purchase a single ASIC miner","Bitcoin's price divided by total hash rate","Electricity cost per hash computation"]},{q:"What typically happens to less efficient miners shortly after a Bitcoin halving?",a:"They become unprofitable and may shut down",wrong:["They automatically receive double the reward","Their hash rate doubles to compensate","They permanently switch to mining altcoins"]},{q:"What is the typical operational lifespan of an ASIC miner before it becomes obsolete?",a:"Approximately 3 to 5 years",wrong:["About 6 months on average","Over 20 years with maintenance","Exactly one halving cycle"]},{q:"What is the breakeven electricity cost for Bitcoin mining?",a:"The kWh price where revenue equals costs",wrong:["A fixed rate set by Bitcoin developers","The average electricity cost worldwide","The minimum power to run one ASIC"]},{q:"As block subsidies decrease over time, what must replace them to incentivize miners?",a:"Transaction fees paid by users",wrong:["Government subsidies for miners","Increased mining difficulty","New coins from hard forks"]}],"misconceptions-fud_pt2":[{q:'How do Bitcoiners respond to "Bitcoin is too volatile to be money"?',a:"Every 4-year period has been profitable and volatility decreases over time",wrong:["They agree volatility makes Bitcoin unsuitable as money","They say volatility doesn't exist if you ignore the price","They claim Bitcoin's price is actually fixed by miners"]},{q:'Why is the claim "quantum computers will break Bitcoin" misleading?',a:"Such computers don't exist yet and Bitcoin can upgrade before they do",wrong:["Bitcoin already uses quantum-resistant encryption algorithms","Quantum computers actually strengthen Bitcoin's security","Satoshi designed Bitcoin to be immune to all future computing"]},{q:'What is the rebuttal to "Tether (USDT) props up Bitcoin\'s price"?',a:"Bitcoin grew for years before Tether and kept rising through its controversies",wrong:["Tether holds 100% of its reserves in Bitcoin directly","Bitcoin's price is determined solely by mining costs","Tether was created by Satoshi as part of Bitcoin's design"]},{q:'Why is "Bitcoin is a pyramid scheme" factually wrong?',a:"It has no company, no CEO, no return promises, and no recruitment profits",wrong:["Because early adopters are guaranteed profits by the protocol","Because Satoshi Nakamoto still runs the company behind Bitcoin","Because the Bitcoin protocol pays dividends to long-term holders"]},{q:'What is the strongest argument against "governments will ban Bitcoin"?',a:"China banned it multiple times yet it kept growing, and the US approved ETFs",wrong:["Governments lack the technology to detect Bitcoin transactions","International law prevents any country from banning crypto","Bitcoin automatically shuts down in countries where it's banned"]}],nodes_pt4:[{q:"What is the key difference between a pruned node and an archival (full) node?",a:"A pruned node deletes old block data after verifying it",wrong:["A pruned node skips transaction verification entirely","An archival node only stores the UTXO set","A pruned node cannot validate new transactions"]},{q:"What does BIP 152 (Compact Block Relay) do?",a:"Sends short transaction IDs instead of full transactions",wrong:["Compresses the entire blockchain into smaller files","Allows nodes to skip blocks during initial sync","Encrypts block data for privacy between nodes"]},{q:"What is the Erlay protocol designed to improve?",a:"Transaction relay efficiency between nodes",wrong:["Block mining speed via nonce optimization","Lightning Network channel capacity","Wallet synchronization for mobile devices"]},{q:"What is the UTXO set and why does its size matter for nodes?",a:"All unspent outputs nodes must keep in memory for validation",wrong:["A list of all transactions ever made on Bitcoin","A record of all mining rewards ever distributed","A backup of private keys stored across the network"]},{q:"What is a major concern about running a Bitcoin full node related to bandwidth?",a:"Relaying transactions and blocks uses significant upload bandwidth",wrong:["Nodes must pay per-megabyte fees to the network","Bandwidth usage is zero after initial block download","Only mining nodes consume significant bandwidth"]}],nodes_pt5:[{q:"What programming language is Bitcoin Core primarily written in?",a:"C++",wrong:["Rust","Python","Java"]},{q:"What is btcd?",a:"An alternative Bitcoin full node written in Go",wrong:["A Bitcoin wallet for desktop computers","A command-line tool for Bitcoin mining","A testing framework for Bitcoin Core"]},{q:"What are reproducible builds in the context of Bitcoin Core?",a:"Anyone can compile source and get an identical binary",wrong:["A system where Bitcoin Core auto-updates itself","A method to restore a node from a backup","A way to compile Bitcoin Core faster on CPUs"]},{q:"What is Guix used for in Bitcoin Core development?",a:"A build system for reproducible, verifiable builds",wrong:["A graphical interface for running a Bitcoin node","A security scanner for checking vulnerabilities","A package manager for installing Bitcoin wallets"]},{q:"Why is it important to be able to build Bitcoin Core from source?",a:"To verify the code and ensure your binary matches it",wrong:["Because pre-built binaries aren't available","To get access to hidden developer features","Because source builds make the node faster"]}],"op-codes_pt2":[{q:"What would OP_CAT enable if re-enabled?",a:"Concatenation of data values in script",wrong:["Comparison of timestamp values","Multiplication of numeric values","Direct verification of signatures"]},{q:"What does OP_CHECKSIGFROMSTACK verify?",a:"Arbitrary message signatures on the stack",wrong:["Only standard transaction signatures","Block signatures submitted by miners","Lightning Network commitment signatures"]},{q:"What is Simplicity designed for in Bitcoin?",a:"Formal verification of smart contracts",wrong:["Faster transaction processing speeds","Simplified wallet address formats","Reduced overall block sizes"]},{q:"What is a major limitation of Bitcoin Script?",a:"No loops or complex control flow",wrong:["Maximum of 100 opcodes per script","Cannot handle any signatures","Requires active internet access"]},{q:"Which script type was introduced with Taproot?",a:"P2TR (Pay to Taproot)",wrong:["P2SH (Pay to Script Hash)","P2WSH (Pay to Witness Script)","P2PKH (Pay to Pub Key Hash)"]}],"orange-pilling_pt2":[{q:'What is the "Socratic method" approach to orange-pilling someone about Bitcoin?',a:"Asking questions that lead them to discover Bitcoin's value themselves",wrong:["Quoting ancient Greek philosophers who predicted digital money","Having the person read the Bitcoin whitepaper out loud to you","Debating them aggressively until they agree Bitcoin is good"]},{q:'What is "progressive disclosure" when introducing someone to Bitcoin?',a:"Starting with simple concepts they care about, then going deeper",wrong:["Showing them Bitcoin's full transaction history from genesis","Revealing your entire Bitcoin portfolio to build their trust","Disclosing all of Bitcoin's technical flaws upfront to seem honest"]},{q:"When orange-pilling family members, what is generally the most effective approach?",a:"Focus on what they care about — savings, retirement, their future",wrong:["Send them a 3-hour technical podcast about mining and hashing","Buy them Bitcoin without asking and surprise them with it later","Bring it up at every family dinner until they finally agree"]},{q:"What is one of the biggest mistakes people make when trying to orange-pill someone?",a:"Information overload — dumping too much detail at once",wrong:["Being too patient and waiting for them to ask questions","Starting with how Bitcoin helps people in other countries","Recommending they read a book about the history of money"]},{q:"Which book is widely considered the best starting point for orange-pilling someone interested in economics and sound money?",a:"The Bitcoin Standard by Saifedean Ammous",wrong:["Mastering Bitcoin by Andreas Antonopoulos","Programming Bitcoin by Jimmy Song","The Blocksize War by Jonathan Bier"]}],ordinals_inscriptions:[{q:"Who proposed the Ordinal Theory for Bitcoin?",a:"Casey Rodarmor",wrong:["Adam Back","Pieter Wuille","Satoshi Nakamoto"]},{q:"How are individual satoshis numbered in Ordinal Theory?",a:"Sequentially based on mining order",wrong:["Randomly assigned by the network","By their transaction ID hash","By the receiving wallet address"]},{q:"What do inscriptions attach to specific satoshis?",a:"Arbitrary data like images or text",wrong:["Private keys for spending them","Their full transaction history","Multisig spending conditions"]},{q:"What token standard emerged from Ordinals functionality?",a:"BRC-20",wrong:["ERC-20","RGB","Omni Layer"]},{q:"What was a major criticism of Ordinals regarding block space?",a:"They use limited block space for non-monetary data",wrong:["They significantly reduce mining reward amounts","They break Bitcoin's core consensus rules","They allow theft of other users' funds"]}],philosophy_pt2:[{q:"Who wrote the Cypherpunk Manifesto?",a:"Eric Hughes",wrong:["Timothy May","Julian Assange","Nick Szabo"]},{q:"What concept did Timothy May advocate for in the Crypto-Anarchist Manifesto?",a:"Using cryptography to protect individual privacy",wrong:["Building centralized digital currency systems","Government regulation of all encryption tools","Corporate ownership of communication networks"]},{q:"What was Nick Szabo's Bit Gold concept?",a:"A digital collectible using proof of work",wrong:["A stablecoin backed by physical gold","A centralized government digital currency","A Lightning-style payment channel design"]},{q:"What did Wei Dai propose with b-money?",a:"Anonymous digital cash with decentralized minting",wrong:["A blockchain with standard mining rewards","A central bank controlled digital currency","A system of gold-backed certificates"]},{q:"What was Hal Finney's famous contribution to Bitcoin?",a:"Received the first Bitcoin transaction from Satoshi",wrong:["Wrote the original Bitcoin whitepaper himself","Created the SHA-256 based mining algorithm","Founded the first Bitcoin trading exchange"]}],"privacy-nonkyc_pt4":[{q:"What is a PayJoin (P2EP) transaction?",a:"Both sender and receiver contribute inputs, obscuring who paid whom",wrong:["A payment split equally between two participating parties","A transaction requiring two separate network confirmations","A joint mining operation shared between two mining pools"]},{q:"What are Silent Payments (BIP 352)?",a:"One static address generates a unique on-chain address per payment",wrong:["Transactions that are hidden from the public mempool entirely","Payments delayed until network activity drops to low levels","A method to send Bitcoin without paying any transaction fees"]},{q:"What is the Boltzmann entropy score used for in Bitcoin privacy?",a:"Measuring ambiguity of a transaction's input-output linkages",wrong:["Calculating the thermodynamic energy cost of a transaction","Rating the randomness quality of a wallet's seed phrase","Scoring how quickly a transaction will get confirmed"]},{q:"What does Whirlpool do for Bitcoin privacy?",a:"Mixes UTXOs via CoinJoin to break transaction history links",wrong:["Provides a VPN service designed specifically for Bitcoin nodes","Encrypts Bitcoin transactions end-to-end before broadcast","Runs a privacy coin layer on top of the Bitcoin blockchain"]},{q:"What is CoinSwap and how does it differ from CoinJoin?",a:"Uses atomic swaps so mixing is invisible on-chain, unlike CoinJoin",wrong:["Converts Bitcoin to privacy coins and back for mixing purposes","Is faster but provides less privacy protection than CoinJoin","Requires a trusted third party while CoinJoin does not need one"]}],"problems-of-money_pt4":[{q:"The Cantillon Effect describes how newly printed money benefits those closest to its creation. Who benefits MOST from money printing?",a:"Banks and the politically connected who receive new money first",wrong:["Average workers who receive higher wages from inflation","Retirees on fixed incomes who get cost-of-living adjustments","Small business owners who can raise their prices immediately"]},{q:"What is Quantitative Easing (QE)?",a:"A central bank creating new money to buy bonds, expanding supply",wrong:["A method of reducing government debt by printing less money","A technique for making international trade easier between nations","A system where banks lend to each other at zero percent interest"]},{q:'What is the "repo market" and why does it matter for understanding fiat fragility?',a:"Overnight lending market using bonds as collateral — its 2019 crisis exposed systemic fragility",wrong:["A marketplace where banks sell repossessed homes and vehicles for profit","A government repository that stores and audits physical gold reserves","A database where central banks track and monitor all global transfers"]},{q:'What is the "Eurodollar system"?',a:"US dollars held and created by banks outside the US, forming a shadow system",wrong:["The system that converts Euros to Dollars at European exchange desks","A European Central Bank program to replace the Dollar with the Euro","A cryptocurrency project backed equally by both Euros and US Dollars"]},{q:'What does the decline of the "petrodollar" system mean for global finance?',a:"Oil nations moving away from dollar pricing weakens its reserve status",wrong:["Oil companies are switching from drilling to mining Bitcoin instead","The petrodollar decline means that oil is becoming nearly worthless","European nations are being forced to buy all their oil with gold"]}],regulation_pt3:[{q:"In the US, what is the key difference between SEC and CFTC jurisdiction over digital assets?",a:"SEC regulates securities (most altcoins); CFTC regulates Bitcoin as a commodity",wrong:["SEC handles Bitcoin while CFTC handles all altcoins separately","Both agencies share identical authority over all digital assets","CFTC only regulates physical commodities, not any digital assets"]},{q:"What is the Howey Test and how does it apply to Bitcoin?",a:"A legal test for securities — Bitcoin fails to qualify since it has no central enterprise",wrong:["A technical test that measures a blockchain's degree of decentralization","Bitcoin fails the Howey Test, making it an SEC-regulated security asset","A test that determines the appropriate tax rate on crypto investments"]},{q:'What is the "Travel Rule" in cryptocurrency regulation?',a:"A FATF rule requiring institutions to share sender/receiver identity above a threshold",wrong:["A regulation that limits Bitcoin transfers to within a single country","A requirement for Bitcoin miners to register their physical locations","A law that bans carrying hardware wallets across international borders"]},{q:"What is the FATF and why is it significant for Bitcoin privacy?",a:"An international body pushing KYC/AML standards that threaten self-custodial privacy",wrong:["A global mining consortium that coordinates difficulty adjustment levels","A nonprofit organization promoting Bitcoin adoption in developing nations","A technology standard designed for faster Bitcoin transaction processing"]},{q:"How have US states approached Bitcoin regulation differently from the federal government?",a:"Several states passed pro-Bitcoin laws like reserve bills and transmitter exemptions",wrong:["All 50 states enforce identical cryptocurrency regulations matching federal law","States are constitutionally prohibited from creating crypto-related legislation","Most states have banned Bitcoin mining operations due to energy concerns"]}],rollups:[{q:"What is a validity rollup on Bitcoin?",a:"A system that bundles off-chain transactions and posts a ZK proof to Bitcoin",wrong:["A sidechain that copies Bitcoin's consensus rules exactly as written","A Lightning Network channel that batches together multiple payments","A mining pool feature that combines block templates from miners"]},{q:"How do sovereign rollups differ from validity rollups?",a:"Users verify rollup state themselves rather than relying on the base layer",wrong:["Sovereign rollups use a central authority; validity rollups are decentralized","Sovereign rollups use proof-of-stake; validity rollups use proof-of-work","Sovereign rollups are limited to only seven transactions per second"]},{q:"How could BitVM enable rollups on Bitcoin?",a:"By allowing fraud proofs to verify rollup state without needing new opcodes",wrong:["By adding a Turing-complete VM directly into Bitcoin's consensus layer","By creating a dedicated sidechain specifically for validating rollup data","By replacing Bitcoin's existing Script language with Solidity contracts"]},{q:"How do Bitcoin rollups differ from sidechains?",a:"Rollups post proofs or data to Bitcoin, inheriting its security guarantees",wrong:["Rollups use a separate token for gas while sidechains use native BTC","Rollups need a federation of signers while sidechains are fully trustless","Rollups are faster than sidechains but limited to simple transfers only"]},{q:"What is the main trust assumption difference between a validity rollup and an optimistic rollup?",a:"Validity rollups prove correctness upfront; optimistic rollups assume it until challenged",wrong:["Validity rollups trust a federation of signers; optimistic rollups trust miners","Validity rollups need a soft fork to work; optimistic rollups work on Bitcoin today","Validity rollups are run centrally; optimistic rollups are always fully decentralized"]}],"self-custody_pt3":[{q:"What is Sparrow Wallet known for in multisig coordination?",a:"Deep UTXO management and easy multisig setup with hardware signers",wrong:["A mobile-only wallet with cloud-based multisig coordination","A hardware wallet that stores multiple seed phrases internally","A browser extension designed primarily for Lightning payments"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction)?",a:"A standard format letting a transaction be built and signed by multiple parties",wrong:["A special Bitcoin transaction type that only sends partial amounts","A privacy protocol that hides the identity of a transaction sender","A transaction format exclusively used by mining pool operators"]},{q:"What are output descriptors in Bitcoin?",a:"A standard way to describe how a wallet derives addresses for reliable recovery",wrong:["Labels attached to individual transaction outputs for bookkeeping purposes","A complete list of all outputs ever created on the Bitcoin blockchain","Metadata that mining pools attach to the transactions they broadcast"]},{q:"Why is multisig generally preferred over Shamir Secret Sharing (SSS) for Bitcoin custody?",a:"Multisig never reconstructs the full private key in one place; SSS does when signing",wrong:["Multisig transactions cost significantly less in fees than SSS schemes","SSS requires more hardware devices to operate than multisig setups","Multisig predates SSS and has substantially better documentation available"]},{q:"What is Nunchuk known for in the Bitcoin wallet space?",a:"Easy collaborative multisig setup and built-in inheritance planning",wrong:["Being the first wallet to natively support Lightning payments","A hardware-only wallet designed exclusively for cold storage use","A privacy wallet that uses CoinJoin mixing transactions by default"]}],"self-custody_pt4":[{q:"Why is titanium preferred over stainless steel for seed phrase backup plates?",a:"Higher melting point and better corrosion resistance in extreme conditions",wrong:["Titanium is significantly cheaper and more widely available worldwide","Titanium plates can fit more seed words than steel backup plates","Titanium is the only metal undetectable by standard metal detectors"]},{q:"What is a passphrase (25th word) in Bitcoin seed phrase security?",a:"An extra user-chosen word that generates an entirely different wallet",wrong:["The password you enter to unlock your hardware wallet device","A recovery phrase issued to you by the wallet manufacturer","An encryption key used to protect the local blockchain data"]},{q:"Why is geographic distribution important for Bitcoin seed phrase storage?",a:"It protects against localized disasters destroying all backup copies at once",wrong:["It speeds up the wallet by routing through the nearest Bitcoin nodes","It is a legal requirement enforced in most regulatory jurisdictions","It mathematically increases the entropy of the generated seed phrase"]},{q:"What is a dead man's switch in Bitcoin inheritance planning?",a:"A mechanism that triggers key release if the owner fails to check in",wrong:["A physical switch on hardware wallets that wipes them if tampered","A transaction that auto-sends all Bitcoin to a burn address on a timer","A self-destruct feature built directly into the Bitcoin Core software"]},{q:"What is the biggest risk of not having a Bitcoin inheritance plan?",a:"Your Bitcoin could be permanently lost since no one else has the keys",wrong:["The government will automatically seize all of your Bitcoin holdings","Your Bitcoin gets redistributed among other active network participants","Your Bitcoin will steadily lose value without an actively managed wallet"]}],softwar_pt2:[{q:"What military rank is Jason Lowery?",a:"Major",wrong:["Colonel","Lieutenant","Captain"]},{q:"What university did Jason Lowery work with on his thesis?",a:"MIT",wrong:["Harvard","Stanford","Caltech"]},{q:"According to Softwar, what does proof of work project?",a:"Physical power through cyberspace",wrong:["Financial return on investment","Social consensus via voting","Network speed and throughput"]},{q:"How does Softwar view Bitcoin for nation-states?",a:"A strategic defense technology",wrong:["A replacement for fiat currency","A consumer payment system","An unregulated security asset"]},{q:"What energy concept is central to the Softwar thesis?",a:"Using energy to secure cyberspace property",wrong:["Reducing global carbon emissions","Accelerating solar power adoption","Profiting from energy arbitrage"]}],spv:[{q:"What does SPV (Simplified Payment Verification) allow a lightweight client to do?",a:"Verify transaction inclusion using block headers and Merkle proofs",wrong:["Mine Bitcoin blocks using minimal computing power","Send transactions without paying any network fees","Run a full node on a mobile phone with limited storage"]},{q:"What privacy problem did the original SPV bloom filters (BIP-37) have?",a:"They leaked which addresses the wallet cared about to the server",wrong:["They revealed the user's IP address to every network node","They broadcast the user's seed phrase as part of filter data","They required users to share real names with node operators"]},{q:"What do BIP-157 and BIP-158 (compact block filters) improve over bloom filters?",a:"Clients download pre-computed filters without revealing their addresses",wrong:["They compress the entire blockchain into a single downloadable file","They allow nodes to verify transactions without any network access","They replace Merkle proofs with zero-knowledge proofs for speed"]},{q:"What is Neutrino in the context of Bitcoin light clients?",a:"A light client protocol using BIP-157/158 compact block filters",wrong:["A privacy coin built as a Bitcoin sidechain project","A mining algorithm designed for mobile phone hardware","A wallet that runs a full node in the cloud for you"]},{q:"What is the main security tradeoff of SPV compared to running a full node?",a:"SPV clients trust miners produce valid blocks without full verification",wrong:["SPV clients cannot receive Bitcoin, they can only send it","SPV clients must pay higher transaction fees than full nodes","SPV clients can only connect to one peer node at a time"]}],submarine_swap_pt2:[{q:"What is a Loop Out in Lightning?",a:"Moving funds from Lightning back to on-chain",wrong:["Opening a new payment channel","Receiving inbound Lightning payments","Closing all channels at once"]},{q:"What is Boltz Exchange known for?",a:"Trustless on-chain and Lightning swaps",wrong:["Running a Bitcoin mining pool","Operating a centralized exchange","Selling Bitcoin hardware wallets"]},{q:"What makes submarine swaps trustless?",a:"Atomic hash time-locked contracts",wrong:["Multi-signature escrow wallets","Trusted third-party verification","Proof of stake consensus rules"]},{q:"How do submarine swaps differ from atomic swaps?",a:"They move between layers of the same chain",wrong:["Submarine swaps always require trust","Atomic swaps are significantly faster","Submarine swaps use different coins"]},{q:"What enables cross-chain atomic swaps without intermediaries?",a:"HTLCs combining hashlock and timelock",wrong:["Trusted custodial escrow services","Centralized exchange order books","Smart contract platforms only"]}],tail_emission:[{q:'What is "tail emission" in the context of cryptocurrency monetary policy?',a:"A small perpetual block reward ensuring miners always get some subsidy",wrong:["The final Bitcoin expected to be mined around the year 2140","The process of burning unsold Bitcoin to reduce total supply","A mechanism that increases block rewards over time for miners"]},{q:"Which major cryptocurrency implements tail emission as part of its monetary policy?",a:"Monero, with a permanent minimum reward of 0.6 XMR per block",wrong:["Bitcoin, which added tail emission in the Taproot upgrade","Ethereum, which introduced it during the merge to proof of stake","Litecoin, which activated it after its third halving event"]},{q:"What concern about Bitcoin's long-term security does the tail emission debate address?",a:"Whether fees alone can incentivize miners after block rewards end",wrong:["Whether Bitcoin's encryption can withstand quantum computers","Whether the 21 million supply cap should be raised over time","Whether nodes will have enough storage for the growing chain"]},{q:"What is the main argument AGAINST adding tail emission to Bitcoin?",a:"It would break the 21 million cap and destroy sound money credibility",wrong:["Tail emission would make mining too profitable and attract too many","It would speed up transaction confirmation times excessively","Tail emission is technically impossible to implement on Bitcoin"]},{q:'What is the "fee market sufficiency" argument against the need for tail emission?',a:"Growing adoption and scarce block space will naturally raise fee revenue",wrong:["Miners will voluntarily work for free because they believe in Bitcoin","The government will subsidize mining to keep the network running","New Bitcoin will be discovered on the network like finding new gold"]}],time_preference_pt3:[{q:'According to Saifedean Ammous in "The Bitcoin Standard," what is the relationship between sound money and time preference?',a:"Sound money lowers time preference, encouraging saving and long-term investment",wrong:["Sound money raises time preference because people rush to spend currency","There is no meaningful relationship between money type and time preference","Sound money eliminates time preference, making people totally indifferent"]},{q:"How does Ammous argue that low time preference connects to civilization building?",a:"People invest in long-term projects when money reliably holds its value",wrong:["Civilizations advance fastest when people spend money as quickly as possible","Low time preference leads to stagnation because nobody takes any risks","Civilization building is completely unrelated to the monetary system"]},{q:"What behavioral effect does fiat money have on time preference according to the Austrian economics perspective?",a:"Fiat raises time preference — inflation punishes savers and rewards debtors",wrong:["Fiat lowers time preference because stable inflation aids long-term planning","Fiat has no effect on time preference, which is determined by culture","Fiat encourages saving because interest rates compensate for inflation"]},{q:"How does the concept of delayed gratification relate to Bitcoin and sound money?",a:"Sound money rewards patience by preserving purchasing power over time",wrong:["Delayed gratification is irrelevant to any monetary system design","Bitcoin punishes patience because its price is far too volatile","Sound money discourages waiting by making everything too expensive"]},{q:"What is the key difference between how fiat and Bitcoin influence personal financial behavior?",a:"Fiat incentivizes consumption and debt; Bitcoin incentivizes saving",wrong:["Both systems produce identical behavior — spending stays the same","Bitcoin makes people spend more as they feel wealthy from gains","Fiat encourages saving; Bitcoin encourages spending due to deflation"]}],vbyte:[{q:"What is a virtual byte (vbyte) in Bitcoin?",a:"A unit where 1 vbyte equals 4 weight units, used for fee calculation",wrong:["A compressed byte format that reduces transaction size by 75%","The amount of data a Bitcoin node can process per second","A unit measuring the electricity cost of validating transactions"]},{q:"How did SegWit change the way Bitcoin transaction fees are calculated?",a:"Fees use weight units or vbytes, giving witness data a discount",wrong:["SegWit made all transactions free for the first year after launch","SegWit replaced fee priority with a first-come-first-served queue","SegWit doubled the base fee rate for all transaction types"]},{q:"What is the witness discount ratio in SegWit?",a:"Witness data costs 1 weight unit per byte; non-witness costs 4",wrong:["Witness data is free; non-witness data costs 2 weight units","Both witness and non-witness data cost 2 weight units per byte","Witness data costs 3 weight units; non-witness data costs 4"]},{q:"Why is understanding vbytes important for optimizing Bitcoin transaction costs?",a:"Using SegWit addresses moves data into the discounted witness section",wrong:["Vbytes determine how many confirmations a transaction needs","Using fewer vbytes increases the mining reward for the block","Transactions with more vbytes get higher priority in mempool"]},{q:"A typical single-input, single-output SegWit transaction is approximately how many vbytes?",a:"About 110 vbytes",wrong:["About 500 vbytes","About 10 vbytes","About 1,000 vbytes"]}]},QUEST_TRIGGERS=[5,15,25,40,60,80,100];let currentQuest=null,isRetry=!1,completedQuests=new Set,weeklyCompleted=[],visitedForQuest=[],questCount=0;function _getCurrentWeekKey(){var e=new Date,t=new Date(e.getFullYear(),0,1),o=Math.floor((e-t)/864e5)+1,n=Math.ceil((o+t.getDay())/7);return e.getFullYear()+"-W"+n}function _loadWeeklyCompleted(){var e=safeJSON("btc_quest_week",{}),t=_getCurrentWeekKey();e.week!==t&&(e={week:t,completed:[]},localStorage.setItem("btc_quest_week",JSON.stringify(e))),weeklyCompleted=e.completed||[]}function _saveWeeklyCompleted(e){var t=safeJSON("btc_quest_week",{}),o=_getCurrentWeekKey();t.week!==o&&(t={week:o,completed:[]}),t.completed||(t.completed=[]),-1===t.completed.indexOf(e)&&t.completed.push(e),localStorage.setItem("btc_quest_week",JSON.stringify(t)),weeklyCompleted=t.completed}function initQuests(){safeJSON("btc_visited_channels",[]).forEach(e=>{visitedForQuest.includes(e)||visitedForQuest.push(e)}),void 0!==auth&&auth.currentUser?(loadCompletedQuests(auth.currentUser.uid),_loadWeeklyCompleted()):setTimeout(initQuests,2e3)}function _getDailyActivities(){var e=(new Date).toISOString().split("T")[0],t=safeJSON("btc_daily_activities",{});return t.date!==e&&(t={date:e,quiz:!1,trivia:!1,poll:!1,sfAwarded:!1}),t}function _markDailyActivity(e){var t=_getDailyActivities();t[e]=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(t))}function _checkDailyAllThree(){var e=_getDailyActivities();if(e.quiz&&e.trivia&&e.poll&&!e.sfAwarded){e.sfAwarded=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(e));var t=(new Date).toISOString().split("T")[0];void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({dailyAllThreeDate:t,dailyQuizDone:!0,dailyTriviaDone:!0,dailyPollDone:!0}).catch(function(){}),"function"==typeof window.contributeSatoshiFavor&&window.contributeSatoshiFavor("daily_all_three")}}async function loadCompletedQuests(e){if(db)try{const t=await db.collection("users").doc(e).get();t.exists&&t.data().completedQuests&&(t.data().completedQuests.forEach(e=>completedQuests.add(e)),questCount=completedQuests.size)}catch(e){}}function onChannelVisitForQuest(e){visitedForQuest.includes(e)||visitedForQuest.push(e);const t=visitedForQuest.length;for(const e of QUEST_TRIGGERS)if(t===e&&!currentQuest){setTimeout(()=>{"function"==typeof showToast&&showToast("⚡ You have explored "+e+" channels! A Quest is ready!"),setTimeout(()=>generateAndShowQuest(),3e3)},2e3);break}}function generateAndShowQuest(e,t,o){var n=(new Date).toISOString().split("T")[0],i=safeJSON("btc_quest_daily",{});if(i.date!==n&&(i={date:n,count:0}),i.count>=1&&!o)return void(e&&"function"==typeof showToast&&showToast("⏰ You've completed your daily quiz! Go to Quiz Quests to retake it for a perfect score."));const a=safeJSON("btc_asked_questions",[]);let r=[];if(t&&QUESTION_BANK[t]&&QUESTION_BANK[t].forEach(e=>r.push({...e,source:t})),!t){for(const e of visitedForQuest){const t=QUESTION_BANK[e];t&&t.forEach(t=>r.push({...t,source:e}))}if(QUESTION_BANK._general&&QUESTION_BANK._general.forEach(e=>r.push({...e,source:"_general"})),r.length<5)for(const[e,t]of Object.entries(QUESTION_BANK))if(t.forEach(t=>{r.some(e=>e.q===t.q)||r.push({...t,source:e})}),r.length>=10)break}var s=t?Math.min(3,r.length):5;if(r.length!a.includes(e.q));function l(e){for(var t=e.q.toLowerCase(),o=[[/nostr/i,"nostr"],[/lightning/i,"lightning"],[/halving/i,"halving"],[/mining/i,"mining"],[/node/i,"node"],[/wallet/i,"wallet"],[/seed.?phrase/i,"seed"],[/private.?key/i,"privkey"],[/satoshi/i,"satoshi"],[/block.?chain/i,"blockchain"],[/proof.?of.?work/i,"pow"],[/fud\b/i,"fud"],[/self.?custody/i,"custody"],[/etf/i,"etf"],[/taproot/i,"taproot"],[/difficulty/i,"difficulty"],[/mempool/i,"mempool"],[/hash.?rate/i,"hashrate"],[/white.?paper/i,"whitepaper"],[/21.?million/i,"21m"],[/inflation/i,"inflation"],[/kyc/i,"kyc"],[/privacy/i,"privacy"],[/multisig/i,"multisig"],[/dca|dollar.cost/i,"dca"],[/el.?salvador/i,"elsalvador"]],n=0;nMath.random()-.5);var d=t?Math.min(c.length,5):5,u=[],p={};if(t)for(var m=0;me.q)];localStorage.setItem("btc_asked_questions",JSON.stringify(y));const v=u.map(e=>{const t=[e.a,...e.wrong].sort(()=>Math.random()-.5),o=t.indexOf(e.a);return{q:e.q,options:t,answer:o}});currentQuest={id:f,topicKey:t||null,title:getQuestTitle(questCount,t),questions:v},window._currentQuestServerId=null,"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("startQuest")({questions:v.map(function(e){return{answer:e.answer}}),topicKey:t||null}).then(function(e){window._currentQuestServerId=e.data.questId}).catch(function(e){console.warn("Quest registration failed:",e)}),showQuest(currentQuest,!1)}function getQuestTitle(e,t){if(t&&"_general"!==t){var o={mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",energy:"🔋",cryptography:"🔐",consensus:"🤝",regulation:"⚖️",maximalism:"🔥","difficulty-adjustment":"🎯",books:"📚",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊","smart-contracts":"📝","blockchain-timechain":"⛓️","pow-vs-pos":"⚔️","evidence-against-alts":"⚠️",organic:"🌳",peaceful:"☮️",supranational:"🔔"},n=t.replace(/_pt\d+$/,""),i=o[t]||o[n]||"⚡",a=t.replace(/_pt(\d+)$/,"").replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),r=t.match(/_pt(\d+)$/);return r&&(a+=" (Part "+r[1]+")"),i+" "+a+" Quest"}const s=["₿ Bitcoin Basics Quest","⚡ Lightning Learner Quest","🔒 Security Scholar Quest","💰 Economics Expert Quest","⛓ Technical Titan Quest","🟠 Culture Connoisseur Quest","🛡️ Sovereignty Sage Quest","👑 Satoshi Scholar Quest"];return s[e%s.length]}function playWarriorDrum(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const t=new(window.AudioContext||window.webkitAudioContext),o="undefined"!=typeof audioVolume?audioVolume:.5,n=t.currentTime;function e(e){const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.type="sine",i.frequency.setValueAtTime(150,n+e),i.frequency.exponentialRampToValueAtTime(60,n+e+.15),a.gain.setValueAtTime(.7*o,n+e),a.gain.exponentialRampToValueAtTime(.001,n+e+.4),i.start(n+e),i.stop(n+e+.4);const r=t.createOscillator(),s=t.createGain();r.connect(s),s.connect(t.destination),r.type="sine",r.frequency.setValueAtTime(80,n+e),r.frequency.exponentialRampToValueAtTime(50,n+e+.3),s.gain.setValueAtTime(.5*o,n+e),s.gain.exponentialRampToValueAtTime(.001,n+e+.5),r.start(n+e),r.stop(n+e+.5);const c=Math.floor(.08*t.sampleRate),l=t.createBuffer(1,c,t.sampleRate),d=l.getChannelData(0);for(let e=0;e",i+="

"+(t?"Retry! Get 3+ correct for 25 XP!":"Answer 5 questions. 3+ correct = 50 XP. All 5 = 100 XP!")+"

",i+="",i+='
',e.questions.forEach((e,t)=>{i+='
',i+='
Question '+(t+1)+" of 5
",i+='
'+e.q+"
",i+='
',e.options.forEach((e,o)=>{i+='"}),i+="
"}),i+="
",i+='',i+='',n.innerHTML=i,o.classList.add("open"),window._questAnswers=new Array(5).fill(-1),window._questCorrect=e.questions.map(e=>e.answer)}function selectAnswer(e,t,o){e.parentElement.querySelectorAll(".quest-opt").forEach(e=>e.classList.remove("selected")),e.classList.add("selected"),window._questAnswers[t]=o,window._questAnswers.every(e=>e>=0)&&(document.getElementById("questSubmitBtn").disabled=!1)}async function submitQuest(){if(window._questSubmitted)return;window._questSubmitted=!0;var e=document.getElementById("questSubmitBtn");e&&(e.disabled=!0,e.style.opacity="0.5",e.textContent="Grading...");const t=window._questAnswers,o=window._questCorrect;let n=0,i=0;if(window._currentQuestServerId&&"undefined"!=typeof firebase&&firebase.functions)try{var a=await firebase.functions().httpsCallable("gradeQuest")({questId:window._currentQuestServerId,answers:t,isRetry:!!isRetry});n=a.data.score,i=a.data.pts}catch(e){console.error("Server quest grading failed, falling back:",e),t.forEach((e,t)=>{e===o[t]&&n++})}else t.forEach((e,t)=>{e===o[t]&&n++});document.querySelectorAll(".quest-q").forEach((e,n)=>{e.querySelectorAll(".quest-opt").forEach((e,i)=>{e.disabled=!0,i===o[n]&&e.classList.add("correct"),i===t[n]&&i!==o[n]&&e.classList.add("wrong")})});let r="";var s=5===n,c=!!currentQuest.topicKey;if(isRetry)n>=3?(i||(i=25),r="🎉 "+n+"/5 correct on retry! +"+i+" XP!",!s&&c||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 — Better luck next time! Keep reading and try again.";else if(s){if(i||(i=100),r="🏆 PERFECT! 5/5! +"+i+" XP!",completedQuests.add(currentQuest.id),questCount++,"function"==typeof window.nachoGlobalAnnounce&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var l=void 0!==currentUser&¤tUser&¤tUser.username||auth.currentUser.displayName||"A mystery Bitcoiner",d=currentQuest.title||"a Quiz Quest";window.nachoGlobalAnnounce("🏆 @"+l+" just aced "+d+" with a PERFECT 5/5! Think you can do the same? ➡️ [Quest Hub](#quests)",auth.currentUser.uid)}}else n>=3?(i||(i=50),r="🎉 "+n+"/5 correct! +"+i+" XP!",c||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 — You can retry for 25 XP!";if(i>0){"function"==typeof notifySelfQuest&¬ifySelfQuest(currentQuest.title),"function"==typeof notifySelfPoints&¬ifySelfPoints(i,"🏆 Quest: "+(currentQuest.title||"Quest")),"function"==typeof window._raidOnQuizComplete&&window._raidOnQuizComplete(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(i);var u=(new Date).toISOString().split("T")[0],p=safeJSON("btc_quest_daily",{});p.date!==u&&(p={date:u,count:0}),p.count++,p.lastScore=n,p.lastTopic=currentQuest.topicKey||null,p.lastTitle=currentQuest.title||null,localStorage.setItem("btc_quest_daily",JSON.stringify(p)),_markDailyActivity("quiz"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({questsCompletedToday:p.count||0,lastQuestDate:u}).catch(function(e){console.error("Quest sync failed:",e)})}try{completedQuests.has(currentQuest.id)&&void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&(await db.collection("users").doc(auth.currentUser.uid).update({completedQuests:firebase.firestore.FieldValue.arrayUnion(currentQuest.id)}),db.collection("stats").doc("global").set({questsCompleted:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){}))}catch(e){console.error("Quest completion sync failed:",e)}const m=document.getElementById("questSubmitBtn");m&&(m.style.display="none");const g=document.querySelector(".quest-skip");g&&(g.style.display="none"),window._questScore=n,window._questMsg=r,window._questPts=i;const h=document.querySelector(".quest-header");h&&(h.innerHTML='
⚡ QUEST COMPLETE

'+currentQuest.title+'

'+(5===n?"🏆":n>=3?"🎉":"😅")+'
'+n+' / 5 Correct
Review your answers below — green is correct, red is wrong
');const f=document.getElementById("questInner");f&&f.scrollTo({top:0,behavior:"smooth"}),"function"==typeof showToast&&showToast(r)}function playHooraySound(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const e=new(window.AudioContext||window.webkitAudioContext),t="undefined"!=typeof audioVolume?audioVolume:.5,o=e.currentTime;[523,659,784,1047].forEach((n,i)=>{const a=e.createOscillator(),r=e.createGain();a.connect(r),r.connect(e.destination),a.type="sine",a.frequency.value=n,r.gain.setValueAtTime(.15*t,o+.1*i),r.gain.exponentialRampToValueAtTime(.001,o+.1*i+.4),a.start(o+.1*i),a.stop(o+.1*i+.4);const s=e.createOscillator(),c=e.createGain();s.connect(c),c.connect(e.destination),s.type="triangle",s.frequency.value=2*n,c.gain.setValueAtTime(.06*t,o+.1*i),c.gain.exponentialRampToValueAtTime(.001,o+.1*i+.3),s.start(o+.1*i),s.stop(o+.1*i+.3)}),[1047,1319,1568].forEach(n=>{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.type="sine",i.frequency.value=n,a.gain.setValueAtTime(.12*t,o+.45),a.gain.linearRampToValueAtTime(.1*t,o+.7),a.gain.exponentialRampToValueAtTime(.001,o+1.3),i.start(o+.45),i.stop(o+1.3)})}catch(e){}}function _resolveQuestChannel(e){if(!e||void 0===CHANNELS)return null;if(CHANNELS[e])return e;var t=e.replace(/_pt\d+$/,"");if(CHANNELS[t])return t;var o={cycles:"cyles",dlcs:"discrete_log_contracts__dlcs",first_principles:"1_first_principles",foss:"free_and_open_source_software__foss",ordinals_inscriptions:"ordinals",spv:"simplified_payment_verification__spv",halving:"scarce","el-salvador":"regulation"};if(o[e]&&CHANNELS[o[e]])return o[e];if(o[t]&&CHANNELS[o[t]])return o[t];for(var n=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper"],i=0;i=3&&playHooraySound();const n=document.querySelector(".quest-questions");n&&(n.style.display="none");var i=_resolveQuestChannel(currentQuest?currentQuest.topicKey:null);if(!i&&void 0!==CHANNELS){var a=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper","cryptography","philosophy","energy","nodes"].filter(function(e){return!!CHANNELS[e]}).sort(function(){return Math.random()-.5});a.length&&(i=a[0])}var r="";if(i&&void 0!==CHANNELS&&CHANNELS[i]){var s=CHANNELS[i].title;r='
'+(currentQuest&¤tQuest.topicKey&&_resolveQuestChannel(currentQuest.topicKey)?5===e?"📚 Keep learning":"📖 Study up on":"🔍 Explore next")+'
'+s+" →
"}const c=document.querySelector(".quest-header");c&&(c.innerHTML='
⚡ QUEST COMPLETE

'+currentQuest.title+'

'+(5===e?"🏆":e>=3?"🎉":"😅")+'
'+e+' / 5 Correct
'+t+"
"+(o>0?'
+'+o+" XP earned!
":"")+r+(e<5?'":"")+'');const l=document.getElementById("questInner");l&&(l.scrollTop=0)}function retryQuest(){currentQuest.questions.forEach(e=>{const t=e.options[e.answer];e.options.sort(()=>Math.random()-.5),e.answer=e.options.indexOf(t)}),showQuest(currentQuest,!0)}function startQuestManual(e){if(!currentQuest)if(e){if(generateAndShowQuest(!0,e),"function"==typeof isMobile&&isMobile()){const e=document.getElementById("sidebar");e&&e.classList.remove("open")}}else _showQuestTopicPicker()}function _getDailyRecommendedQuiz(e){if(!e||0===e.length)return null;for(var t=e.map(function(e){return e.key}).sort(),o=t.length,n=new Date("2026-01-01T00:00:00Z").getTime(),i=(new Date).toISOString().split("T")[0],a=new Date(i+"T00:00:00Z").getTime(),r=Math.floor((a-n)/864e5),s=r%o,c=Math.floor(r/o),l=t.slice(),d=7919*c+31337,u=l.length-1;u>0;u--){var p=(d=(16807*d+0)%2147483647)%(u+1),m=l[u];l[u]=l[p],l[p]=m}var g=l[s];return e.find(function(e){return e.key===g})||null}function _showQuestTopicPicker(){var e=[],t={_general:"🌐",mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜","satoshi-nakamoto":"🧩",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",philosophy:"🤔",energy:"🔋",cryptography:"🔐",consensus:"🤝",taproot:"🌳",regulation:"⚖️",maximalism:"🔥",utxos:"📦","difficulty-adjustment":"🎯",transaction_fees:"💳",game_theory:"♟️",books:"📚","orange-pilling":"🍊",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊",geopolitics___macroeconomics:"🌎",human_rights__social_justice_and_freedo:"✊","smart-contracts":"📝",sidechains:"🔗",stablecoins:"🏦",fedimints:"🏛️","pow-vs-pos":"⚔️","blockchain-timechain":"⛓️",softwar:"🪖",time_preference:"⏳",governance:"🏛️","apps-tools":"🧰","misconceptions-fud":"🚫",elevator_pitches:"🗣️"};for(var o in QUESTION_BANK)if("_general"!==o){var n=QUESTION_BANK[o];if(n&&!(n.length<3)){var i=o.replace(/_pt(\d+)$/,"").replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),a=o.match(/_pt(\d+)$/);a&&(i+=" (Part "+a[1]+")");var r=o.replace(/_pt\d+$/,""),s=t[o]||t[r]||"📖",c=completedQuests.has("quest_"+o)||completedQuests.has(o)||-1!==weeklyCompleted.indexOf(o);e.push({key:o,label:i,emoji:s,count:n.length,done:c})}}e.sort(function(e,t){return e.done!==t.done?e.done?1:-1:e.label.localeCompare(t.label)});var l=e.filter(function(e){return e.done}).length,d=document.getElementById("questModal");if(d){var u=document.getElementById("questInner");if(u){var p='

Choose a Quest Topic

Pick a Bitcoin topic to test your knowledge

'+l+"/"+e.length+' topics completed
',m=_getDailyRecommendedQuiz(e);m&&(p+=""),p+='',p+='',p+='
',e.forEach(function(e){var t=e.done?"rgba(34,197,94,0.06)":"rgba(255,255,255,0.02)",o=e.done?"rgba(34,197,94,0.2)":"var(--border)",n=e.done?'':''+e.count+"Q";p+=""}),p+="
",p+='',u.innerHTML=p,setTimeout(function(){var e=document.querySelectorAll("#questTopicList button");e.forEach(function(e){var t=(e.getAttribute("onclick")||"").match(/_startQuestTopic\('([^']+)'\)/);t&&(e.dataset.key=t[1]),e.dataset.label=e.textContent.trim()});var t=document.getElementById("questSearch");t&&t.addEventListener("input",function(){var t=this.value.toLowerCase();e.forEach(function(e){var o=e.dataset.label.toLowerCase();e.style.display=o.includes(t)?"":"none"})})},0),d.classList.add("open")}}}function skipQuest(){closeQuest()}function closeQuest(){document.getElementById("questModal").classList.remove("open"),currentQuest=null,isRetry=!1}function _renderFavorTab(e){if(e){var t="function"==typeof window._resolveFavorState?window._resolveFavorState():null,o=t&&t.favorActive,n=t&&t.points||0,i=Math.min(100,n/21*100),a='
✨⛏️
Satoshi\'s Favor
Community mining when the community earns 21 points.
Chance to win 21,000 sats! ⚡
';if(o){var r=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();a+='
🎉 SATOSHI\'S FAVOR IS ACTIVE!
'+Math.floor(r/6e4)+"m "+Math.floor(r%6e4/1e3)+'s
Mine below 1,000 to win 21,000 sats!
',a+=''}else a+='
'+n+'/21 points
'+(21-n)+" more points to activate
";if(a+='
How it works:
This is a community challenge — everyone\'s points combine!

• Complete 3 daily quiz quests = 1 point
• Earn a badge = 1 point
• Level up to Pleb/Stacker ranks = 1 point each
• Level up to Maxi ranks = 5 points each
• Level up to Papa John or higher = 10 points
• At 21 points, a mining competition opens for 60 minutes
• Extra points beyond 21 add +3 min each (even while active!)
• 10 hashes max per minute per user (60 second cooldown)
• Generate a random hash. Below 1,000 = win 21,000 sats!',a+='
🏆 All-Time Lowest Hashes
Loading...
',a+='
⭐ Your Personal Best
Loading...
',a+="
",e.innerHTML=a,_loadFavorLeaderboards(),o){var s=document.getElementById("favorTabTimer");if(s)var c=setInterval(function(){if(s){if(!t||!t.favorActive)return s.textContent="EXPIRED",void clearInterval(c);var e=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();if(e<=0)s.textContent="00:00";else{var o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);s.textContent=o+"m "+n+"s"}}else clearInterval(c)},1e3)}}}window._retakeLastQuiz=function(){var e=safeJSON("btc_quest_daily",{}).lastTopic||null,t=document.getElementById("questHubOverlay");t&&t.remove(),setTimeout(function(){generateAndShowQuest(!0,e,!0)},200)},window._startQuestTopic=function(e){var t=document.getElementById("questModal");if(t&&t.classList.remove("open"),currentQuest=null,!e){var o=[];for(var n in QUESTION_BANK)"_general"!==n&&(QUESTION_BANK[n].length<3||completedQuests.has("quest_"+n)||completedQuests.has(n)||-1!==weeklyCompleted.indexOf(n)||o.push(n));if(o.length>0)e=o[Math.floor(Math.random()*o.length)];else{var i=Object.keys(QUESTION_BANK).filter(function(e){return"_general"!==e&&QUESTION_BANK[e].length>=3});e=i[Math.floor(Math.random()*i.length)]}}setTimeout(function(){generateAndShowQuest(!0,e)},200)},setTimeout(initQuests,3e3),window.closeQuestHubForFavor=function(){var e=document.getElementById("questHubOverlay");e&&e.remove(),window._cleanupRaidBoss&&window._cleanupRaidBoss()};var _favorTopHashesUnsub=null,_favorPBUnsub=null;function _renderTopHashesHTML(e){for(var t=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null,o="",n=0;n
'+s+''+(l?"🏆 ":"")+c+(a?" (you)":"")+'
'+i.value.toLocaleString()+"
"}return o}function _renderPBHTML(e){var t=e<1e3;return'
'+(t?"🏆 ":"")+e.toLocaleString()+'
Your all-time lowest hash
'}function _loadFavorLeaderboards(){if(void 0!==db){_favorTopHashesUnsub&&(_favorTopHashesUnsub(),_favorTopHashesUnsub=null),_favorPBUnsub&&(_favorPBUnsub(),_favorPBUnsub=null),_favorTopHashesUnsub=db.collection("satoshiFavor").doc("topHashes").onSnapshot(function(e){var t=document.getElementById("favorTopHashes");t&&(e.exists&&e.data().entries&&0!==e.data().entries.length?t.innerHTML=_renderTopHashesHTML(e.data().entries):t.innerHTML='
No hashes yet. Be the first to mine!
')},function(){var e=document.getElementById("favorTopHashes");e&&(e.innerHTML='
Could not load leaderboard
')});var e=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null;if(e){var t=!1;_favorPBUnsub=db.collection("satoshiFavor").doc("personalBests").collection("users").doc(e).onSnapshot(function(o){var n=document.getElementById("favorPersonalBest");n&&(o.exists?n.innerHTML=_renderPBHTML(o.data().value):t?n.innerHTML='
No hashes yet. Start mining!
':(t=!0,db.collection("satoshiFavor").doc("personalBests").get().then(function(t){if(n=document.getElementById("favorPersonalBest"))if(t.exists){var o=(t.data().users||{})[e];n.innerHTML=o?_renderPBHTML(o.value):'
No hashes yet. Start mining!
'}else n.innerHTML='
No hashes yet. Start mining!
'}).catch(function(){})))},function(){var e=document.getElementById("favorPersonalBest");e&&(e.innerHTML='
Could not load personal best
')})}else{var o=document.getElementById("favorPersonalBest");o&&(o.innerHTML='
Sign in to track your personal best
')}}}function _renderQuestHubTab(){var e=window._questHubTab||"quiz";["Quiz","Trivia","Poll","Raid","Favor","Charity"].forEach(function(t){var o=document.getElementById("qhTab"+t);if(o){var n=e===t.toLowerCase(),i="Raid"===t&&n,a="Charity"===t&&n;o.style.background=i?"linear-gradient(135deg,#8b5cf6,#7c3aed)":a?"linear-gradient(135deg,#ef4444,#dc2626)":n?"var(--accent)":"none",o.style.color=n?"#fff":"var(--text-muted)",o.style.borderColor=i?"#8b5cf6":a?"#ef4444":n?"var(--accent)":"var(--border)"}});var t=document.getElementById("questHubBody");t&&("raid"!==e&&window._cleanupRaidBoss(),"quiz"===e?_renderQuizTab(t):"trivia"===e?_renderTriviaTab(t):"poll"===e?_renderPollTab(t):"raid"===e?_renderRaidTab(t):"favor"===e?_renderFavorTab(t):"charity"===e&&_renderCharityTab(t))}void 0!==startQuestManual&&(window.startQuestManual=startQuestManual),void 0!==selectAnswer&&(window.selectAnswer=selectAnswer),void 0!==submitQuest&&(window.submitQuest=submitQuest),void 0!==skipQuest&&(window.skipQuest=skipQuest),void 0!==closeQuest&&(window.closeQuest=closeQuest),void 0!==showQuest&&(window.showQuest=showQuest),void 0!==generateAndShowQuest&&(window.generateAndShowQuest=generateAndShowQuest),void 0!==_showQuestTopicPicker&&(window._showQuestTopicPicker=_showQuestTopicPicker),void 0!==showQuestFinalResults&&(window.showQuestFinalResults=showQuestFinalResults),void 0!==retryQuest&&(window.retryQuest=retryQuest),void 0!==_renderQuestHubTab&&(window._renderQuestHubTab=_renderQuestHubTab),window._questHubTab="quiz",window.showQuestHub=function(){window._chatOverlayOpen&&"function"==typeof toggleChatOverlay&&toggleChatOverlay();var e=document.getElementById("questHubOverlay");e&&e.remove();var t=document.createElement("div");t.id="questHubOverlay",t.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.88);z-index:100000;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(5px);padding:20px;animation:nachoPop 0.25s ease;",t.onclick=function(e){e.target===t&&(window._cleanupRaidBoss(),t.remove())};var o=document.createElement("div");o.style.cssText="background:var(--bg-side,#141425);border:1px solid var(--border);width:100%;max-width:520px;max-height:85vh;border-radius:24px;overflow:hidden;display:flex;flex-direction:column;position:relative;";var n=document.createElement("div");n.style.cssText="padding:20px 24px 0;flex-shrink:0;",n.innerHTML='

⚔️ Quest Hub

Earn XP by testing your Bitcoin knowledge
';var i=document.createElement("div");i.id="questHubBody",i.style.cssText="padding:0 24px 24px;overflow-y:auto;flex:1;",o.appendChild(n),o.appendChild(i),t.appendChild(o),document.body.appendChild(t),_renderQuestHubTab()};var _charityStats=null,_charityRecent=[],_charityStatsLoaded=!1;function _loadCharityStats(e){if("undefined"==typeof firebase||!firebase.firestore)return e&&e();var t=firebase.firestore();Promise.all([t.collection("charity_stats").doc("global").get({source:"server"}),t.collection("charity_donations").orderBy("ts","desc").limit(10).get({source:"server"})]).then(function(t){var o=t[0],n=t[1];_charityStats=o.exists?o.data():{totalDonated:0,factionTotals:{}},_charityRecent=[],n.forEach(function(e){_charityRecent.push(e.data())}),_charityStatsLoaded=!0,e&&e()}).catch(function(){e&&e()})}function _renderCharityTab(e){e.innerHTML='
Loading charity data...
',_loadCharityStats(function(){_renderCharityTabInner(e)})}function _renderCharityTabInner(e){var t="function"==typeof escapeHtml?escapeHtml:function(e){return String(e||"").replace(//g,">")},o=void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous,n=void 0!==currentUser&¤tUser&¤tUser.faction||"",i=void 0!==currentUser&¤tUser&¤tUser.points||0,a=void 0!==currentUser&¤tUser&¤tUser.pointsClaimed||0,r=void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,s=Math.max(0,i-a-r),c=_charityStats||{totalDonated:0,factionTotals:{}},l=c.totalDonated||0,d=c.factionTotals&&c.factionTotals.cyber_hornets||0,u=c.factionTotals&&c.factionTotals.honey_badgers||0,p="";p+='
❤️
Donate XP for Charity
1,000 XP = 1,000 sats donated — 10× more impact than redeeming for yourself
',p+='
🌍 Community Pledge
'+l.toLocaleString()+' sats pledged
('+l.toLocaleString()+" XP donated by the community)
";var m=d+u,g=m>0?Math.round(d/m*100):50,h=100-g;p+='
⚔️ Faction Giving
🐝 Cyber Hornets🦡 Honey Badgers
'+d.toLocaleString()+" XP ("+g+"%)"+u.toLocaleString()+" XP ("+h+"%)
",o?n?(p+='
🎡 Your Donation
Available to donate: '+s.toLocaleString()+" XP"+(r>0?' ('+r.toLocaleString()+" already donated)":"")+"
",p+='
',[5,10,25,50,100].forEach(function(e){var t=Math.floor(s*e/100);p+='"}),p+="
",p+='
',p+='
',p+='',p+="
"):p+="
⚔️
Choose Your Faction First
Your faction's donation total is tracked for the community leaderboard. Join a side before you donate!
":p+='
🔐 Sign in to donate XP for charity
',_charityRecent.length>0&&(p+='
📜 Recent Donations
',_charityRecent.forEach(function(e){var o,n=e.anonymous||!e.uid||"Anonymous"===(e.username||""),i="cyber_hornets"===e.faction?'🐝':"honey_badgers"===e.faction?'🦡':"";o=n?"color:var(--text-muted);":"cyber_hornets"===e.faction?"color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,1px 1px 0 #000,-1px 1px 0 #000;font-weight:700;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;":"honey_badgers"===e.faction?"color:#e5e7eb;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,1px 1px 0 #000,-1px 1px 0 #000;font-weight:700;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;":"color:var(--text);font-weight:600;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;";var a=n?''+t(e.username||"Anonymous")+"":''+t(e.username||"Anonymous")+"";p+='
'+i+" "+a+'+'+(e.amount||0).toLocaleString()+" XP
"}),p+="
"),p+='
🗳️ Community Charity Vote
Coming soon — the community will vote on which charities receive our pledged sats. Focused on Bitcoin education and adoption, but not limited to it.
',p+="

Our community will vote on which charities our contributions go to. In Bitcoin, the charities will focus on Bitcoin education and adoption — but our donations are not limited to the Bitcoin ecosystem. We can find charities outside of Bitcoin that we want to support as a community.

⚠️ Donations are non-refundable. Donated XP cannot be reclaimed or reversed. Donations are a community pledge and are not tax-deductible. This is not a registered charitable organization and no tax receipts are issued.

",p+='
🏅 Donation Badges
';var f="function"==typeof safeJSON?safeJSON("btc_hidden_badges",[]):[];[{id:"donor_100",emoji:"🫷",name:"Giving Pleb",thresh:"100 XP",reward:"50 XP"},{id:"donor_500",emoji:"💛",name:"Stack Sharer",thresh:"500 XP",reward:"150 XP"},{id:"donor_1000",emoji:"🧡",name:"Community Builder",thresh:"1,000 XP",reward:"300 XP"},{id:"donor_5000",emoji:"❤️",name:"Archive Patron",thresh:"5,000 XP",reward:"1,000 XP"},{id:"donor_10000",emoji:"🔥",name:"Sats Saint",thresh:"10,000 XP",reward:"2,000 XP"},{id:"donor_25000",emoji:"⚡",name:"Lightning Philanthropist",thresh:"25,000 XP",reward:"4,000 XP"},{id:"donor_50000",emoji:"🏆",name:"Satoshi's Steward",thresh:"50,000 XP",reward:"7,500 XP"},{id:"donor_100000",emoji:"👑",name:"Legend of the Archive",thresh:"100,000 XP",reward:"15,000 XP"}].forEach(function(e){var t=f.includes(e.id)||void 0!==currentUser&¤tUser&&Array.isArray(currentUser.donationBadges)&¤tUser.donationBadges.includes(e.id);p+='
'+e.emoji+'
'+e.name+'
'+e.thresh+' donated
+'+e.reward+" reward
"}),p+="
",e.innerHTML=p,window._charitySetAmount=function(e){var t=document.getElementById("charityAmtInput");t&&(t.value=e>0?e:"")},window._submitCharityDonation=function(){if("undefined"!=typeof firebase&&firebase.functions){var e=document.getElementById("charityAmtInput"),t=parseInt(e?e.value:"")||0;if(!t||t<1)"function"==typeof showToast&&showToast("Enter a valid amount");else{var o=Math.max(0,void 0!==currentUser&¤tUser?(currentUser.points||0)-(currentUser.pointsClaimed||0)-(currentUser.pointsDonated||0):0);if(t>o)"function"==typeof showToast&&showToast("Not enough available XP. You have "+o.toLocaleString()+" pts available.");else{var n=!!document.getElementById("charityAnonToggle")&&document.getElementById("charityAnonToggle").checked,i=document.querySelector('[onclick="window._submitCharityDonation()"]');i&&(i.disabled=!0,i.textContent="Donating..."),firebase.functions().httpsCallable("donatePoints")({amount:t,anonymous:n}).then(function(e){void 0!==currentUser&¤tUser&&(currentUser.pointsDonated=(currentUser.pointsDonated||0)+t,e.data&&e.data.bonusPts&&(currentUser.points=(currentUser.points||0)+e.data.bonusPts));var o=e.data&&e.data.newBadges||[],n=o.length>0?" You earned "+o.length+" new badge"+(o.length>1?"s":"")+"!":"";if("function"==typeof showToast&&showToast("❤️ Thank you! "+t.toLocaleString()+" XP donated ("+t.toLocaleString()+" sats pledged to charity)."+n,5e3),window._charityThankYou(t,o,e.data&&e.data.bonusPts||0),o.length>0&&"function"==typeof window.contributeSatoshiFavor){var i={donor_100:{emoji:"🫷",name:"Giving Pleb"},donor_500:{emoji:"💛",name:"Stack Sharer"},donor_1000:{emoji:"🧡",name:"Community Builder"},donor_5000:{emoji:"❤️",name:"Archive Patron"},donor_10000:{emoji:"🔥",name:"Sats Saint"},donor_25000:{emoji:"⚡",name:"Lightning Philanthropist"},donor_50000:{emoji:"🏆",name:"Satoshi's Steward"},donor_100000:{emoji:"👑",name:"Legend of the Archive"}};o.forEach(function(e){var t=i[e];t&&window.contributeSatoshiFavor("badge_earned",t.emoji+" "+t.name).catch(function(){})})}_charityStatsLoaded=!1,_renderCharityTab(document.getElementById("questHubBody"))}).catch(function(e){i&&(i.disabled=!1,i.textContent="❤️ Donate XP for Charity"),"function"==typeof showToast&&showToast("❌ "+(e.message||"Donation failed. Try again."),4e3)})}}}else"function"==typeof showToast&&showToast("Firebase not ready")}}function _renderQuizTab(e){var t=(new Date).toISOString().split("T")[0],o=safeJSON("btc_quest_daily",{}),n=o.date===t?o.count:0,i=completedQuests?completedQuests.size:0,a=o.date===t&&n>=1&&o.lastScore&&o.lastScore<5,r="";if(a){o.lastTopic&&o.lastTopic.replace(/['\\]/g,"");var s=o.lastTitle||"your last quiz";r='
🔄 You scored '+o.lastScore+"/5 on "+("function"==typeof escapeHtml?escapeHtml(s):s)+'
Retake it to get a perfect score! +25 XP for improvement
'}e.innerHTML='
📝
Quiz Quests
1 daily quiz — retake until you ace it!
'+n+'
Today
'+i+'
All Time
3+ correct = 50 XP
Perfect = 100 XP
'+r+"
"}function _getTriviaToday(){if("undefined"==typeof TRIVIA_BANK||!TRIVIA_BANK||!TRIVIA_BANK.length)return null;var e=new Date,t=new Date(e.getFullYear(),0,0),o=(7*Math.floor((e-t)/864e5)+e.getFullYear())%TRIVIA_BANK.length;return{index:o,trivia:TRIVIA_BANK[o]}}function _getTriviaState(){try{return JSON.parse(localStorage.getItem("btc_trivia_state")||"{}")}catch(e){return{}}}function _setTriviaState(e){try{localStorage.setItem("btc_trivia_state",JSON.stringify(e))}catch(e){}}function _renderTriviaTab(e){var t=_getTriviaToday();if(t&&t.trivia){var o=_getTriviaState(),n=(new Date).toISOString().split("T")[0],i=o.date===n,a=t.trivia,r='
🧠
Trivia Quest
1 new question every day
+50 XP correct · +10 XP for trying
';r+='
'+("function"==typeof escapeHtml?escapeHtml(a.q):a.q)+"
",r+='
';for(var s=0;s
'+String.fromCharCode(65+s)+''+c+''+(p?''+p+"":"")+"
"}else r+='"}r+="",i&&void 0!==db&&db.collection("trivia_stats").doc(n).get().then(function(e){var t=e.exists?e.data():{},o=t.total||0;if(!(o<1))for(var n=0;n
💡 Explanation
'+("function"==typeof escapeHtml?escapeHtml(a.explanation):a.explanation)+"
",r+='
Come back tomorrow for a new trivia question! 🧠
'),e.innerHTML=r}else e.innerHTML='
Trivia questions loading...
'}function _getPollToday(){if("undefined"==typeof POLL_BANK||!POLL_BANK||!POLL_BANK.length)return null;var e=new Date,t=new Date(e.getFullYear(),0,0),o=(13*Math.floor((e-t)/864e5)+e.getFullYear())%POLL_BANK.length;return{index:o,poll:POLL_BANK[o]}}function _getPollState(){try{return JSON.parse(localStorage.getItem("btc_poll_state")||"{}")}catch(e){return{}}}function _setPollState(e){try{localStorage.setItem("btc_poll_state",JSON.stringify(e))}catch(e){}}function _renderPollTab(e){var t=_getPollToday();if(t&&t.poll){var o=_getPollState(),n=(new Date).toISOString().split("T")[0],i=o.date===n&&"number"==typeof o.chosen,a=t.poll,r='
📊
Poll Quest
Vote daily — see what the community thinks
+50 XP for voting
';if(r+='
'+("function"==typeof escapeHtml?escapeHtml(a.q):a.q)+"
",i)_renderPollResults(e,r,a,o,n);else{var s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null,c=a.id||"poll_day_"+n;s&&void 0!==db?db.collection("poll_votes").doc(c).get().then(function(i){if(i.exists&&i.data().voters&&-1!==i.data().voters.indexOf(s)){var c=o.chosen;_setPollState(o={date:n,index:t.index,chosen:"number"==typeof c?c:-1,pollId:a.id}),_renderPollResults(e,r,a,o,n)}else _showPollVoteButtons(e,r,a)}).catch(function(){_showPollVoteButtons(e,r,a)}):_showPollVoteButtons(e,r,a)}}else e.innerHTML='
Polls loading...
'}function _showPollVoteButtons(e,t,o){t+='
';for(var n=0;n'+String.fromCharCode(65+n)+""+i+""}t+="
",e.innerHTML=t}function _renderPollResults(e,t,o,n,i){var a=o.id||"poll_day_"+i;void 0!==db?db.collection("poll_votes").doc(a).get().then(function(i){var a=i.exists&&i.data().votes||[0,0,0,0],r=a.reduce(function(e,t){return e+t},0)||1;_drawPollResults(e,t,o,a,r,n.chosen)}).catch(function(){_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}):_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}function _drawPollResults(e,t,o,n,i,a){var r=t,s=["#f7931a","#3b82f6","#22c55e","#8b5cf6"];r+='
';for(var c=0;c
'+(u?"✓":String.fromCharCode(65+c))+''+l+'
'+d+"%
"}r+="",r+='
'+i+" total vote"+(1!==i?"s":"")+" · Come back tomorrow for a new poll!
",e.innerHTML=r}function _renderRaidTab(e){e.innerHTML='
Loading Raid Boss...
',window._loadRaidBoss()}function _raidEmptyState(){return'
⚔️
Raid Boss
No active raid boss right now.
Check back soon for community boss fights!
'}function _raidVictoryBanner(e){var t="function"==typeof escapeHtml?escapeHtml(e.name||"Raid Boss"):e.name||"Raid Boss",o=_getRaidBossImage(e);return'
'+(o?'
'+t+'
💀
':'
💀
')+'
BOSS DEFEATED! 🎉
'+t+' has fallen!
The community worked together and took it down! Great job everyone!
🏆 Community reward unlocked!
Extra orange ticket drawing for 21,000 satsthis Friday night!
'}window._charityThankYou=function(e,t,o){var n=document.getElementById("charityThankYouOverlay");n&&n.remove();var i=document.createElement("div");i.id="charityThankYouOverlay",i.style.cssText="position:fixed;inset:0;z-index:300000;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;padding:20px;";var a=document.createElement("div");a.style.cssText="background:var(--card-bg);border:1px solid rgba(239,68,68,0.4);border-radius:20px;padding:28px 24px;max-width:360px;width:100%;text-align:center;position:relative;";var r='
❤️
Thank You!
You donated '+e.toLocaleString()+" XP — that's "+e.toLocaleString()+" sats pledged to charity.
";o>0&&(r+='
+'+o.toLocaleString()+" bonus XP earned!
"),t&&t.length>0&&(r+='
🏼 New badge'+(t.length>1?"s":"")+" unlocked: "+t.join(", ")+"
"),r+='
The community will vote on which charities receive these sats.
',a.innerHTML=r,i.appendChild(a),i.addEventListener("click",function(e){e.target===i&&i.remove()}),document.body.appendChild(i)},window._renderCharityHome=function(){var e=document.getElementById("charityDonateHome");e&&"undefined"!=typeof firebase&&firebase.firestore&&firebase.firestore().collection("charity_stats").doc("global").get().then(function(t){var o=t.exists?t.data():{totalDonated:0,factionTotals:{}},n=o.totalDonated||0,i=o.factionTotals&&o.factionTotals.cyber_hornets||0,a=o.factionTotals&&o.factionTotals.honey_badgers||0;e.innerHTML='
❤️ Donate XP for Charity
Tap to donate →
'+n.toLocaleString()+' sats pledged
🐝 '+i.toLocaleString()+' XP🦡 '+a.toLocaleString()+" XP
"}).catch(function(){})},window.triviaAnswer=function(e){var t=_getTriviaToday();if(t&&t.trivia){var o=t.trivia,n=(new Date).toISOString().split("T")[0],i=_getTriviaState();if(i.date!==n){var a=e===o.answer,r=a?50:10;if(_setTriviaState(i={date:n,index:t.index,chosen:e,correct:a}),"function"==typeof awardPoints&&awardPoints(r,a?"🧠 Trivia Quest correct!":"🧠 Trivia Quest attempt"),a&&"function"==typeof window._raidOnTriviaCorrect&&window._raidOnTriviaCorrect(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(r),_markDailyActivity("trivia"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({lastTriviaDate:n,triviaAnswered:firebase.firestore.FieldValue.increment(1),triviaCorrect:firebase.firestore.FieldValue.increment(a?1:0)}).catch(function(){}),void 0!==db){var s={total:firebase.firestore.FieldValue.increment(1)};s["option_"+e]=firebase.firestore.FieldValue.increment(1),db.collection("trivia_stats").doc(n).set(s,{merge:!0}).catch(function(){})}var c=document.getElementById("questHubBody");c&&_renderTriviaTab(c),"function"==typeof showToast&&showToast(a?"✅ Correct! +50 XP 🧠":"❌ Wrong — +10 XP for trying!",3e3)}}},window.pollVote=function(e){var t=_getPollToday();if(t&&t.poll){var o=t.poll,n=(new Date).toISOString().split("T")[0],i=_getPollState();if(i.date!==n||"number"!=typeof i.chosen){var a=document.querySelectorAll("#pollOptions button");a.forEach(function(e){e.disabled=!0,e.style.opacity="0.5",e.style.cursor="default"});var r=o.id||"poll_day_"+n,s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null;if(void 0!==db&&s){var c=db.collection("poll_votes").doc(r);db.runTransaction(function(t){return t.get(c).then(function(n){var i=n.exists?n.data():{},a=i.voters||[];if(-1!==a.indexOf(s))return Promise.reject({code:"already-voted"});var l=i.votes||[0,0,0,0];l[e]=(l[e]||0)+1,a.push(s),t.set(c,{pollId:r,question:o.q,options:o.options,votes:l,voters:a,lastUpdated:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0})})}).then(function(){_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof awardPoints&&awardPoints(50,"📊 Poll Quest vote"),"function"==typeof window._raidOnPollVote&&window._raidOnPollVote(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(50),"function"==typeof showToast&&showToast("📊 Vote recorded! +50 XP",3e3),_markDailyActivity("poll"),_checkDailyAllThree(),auth.currentUser.isAnonymous||db.collection("users").doc(s).update({lastPollDate:n,pollsVoted:firebase.firestore.FieldValue.increment(1)}).catch(function(){});var a=document.getElementById("questHubBody");a&&_renderPollTab(a)}).catch(function(r){if(!r||"already-voted"!==r.code)return console.error("[POLL] Vote failed:",r),"function"==typeof showToast&&showToast("⚠️ Vote failed — try again",3e3),void a.forEach(function(e){e.disabled=!1,e.style.opacity="1",e.style.cursor="pointer"});_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("You already voted on this poll today!",3e3);var s=document.getElementById("questHubBody");s&&_renderPollTab(s)})}else{_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("📊 Vote recorded locally",3e3);var l=document.getElementById("questHubBody");l&&_renderPollTab(l)}}}},window._raidBossUnsub=null,window._raidParticipantsUnsub=null,window._raidTimerInterval=null,window._cleanupRaidBoss=function(){window._raidBossUnsub&&(window._raidBossUnsub(),window._raidBossUnsub=null),window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null),window._raidTimerInterval&&(clearInterval(window._raidTimerInterval),window._raidTimerInterval=null),window._raidDamageDealersOpen=!1},window._loadRaidBoss=function(){window._cleanupRaidBoss();var e=document.getElementById("raidBossContent");e&&(void 0!==db?window._raidBossUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.innerHTML=_raidEmptyState();else{var o=Date.now(),n=null,i=null,a=null;if(t.forEach(function(e){var t=e.data();t._id=e.id;var r=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,s=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime?i.startTime.toMillis?i.startTime.toMillis():i.startTime:0))&&(i=t):t.defeated&&(a||(a=t))}),a&&(i||n)&&!n){window._defeatedBossId=a._id;var r=_raidVictoryBanner(a);e.innerHTML=r;var s=document.createElement("div");return s.id="raidUpcomingSection",e.appendChild(s),window._currentRaidBoss=i||a,void _renderRaidBossCard(s,i)}var c=n||i||a;c?(window._currentRaidBoss=c,_renderRaidBossCard(e,c)):e.innerHTML=_raidEmptyState()}},function(t){console.error("[RAID] Boss listener error:",t),e.innerHTML='
⚠️ Failed to load raid boss
'}):e.innerHTML='
⚠️ Database not available
')};var RAID_BOSS_IMAGES={"Channel-Crawler":"images/raid-bosses/channel-crawler.png","Quiz-Crusader":"images/raid-bosses/quiz-crusader.png","TV-Titan":"images/raid-bosses/tv-titan.png","Beats-Baron":"images/raid-bosses/beats-baron.png","Flash-Flash":"images/raid-bosses/flash-flash.png","XP-Hoarder":"images/raid-bosses/xp-hoarder.png","Poll-Patroller":"images/raid-bosses/poll-patroller.png","Chat-Charger":"images/raid-bosses/chat-charger.png","Badge-Builder":"images/raid-bosses/badge-builder.png","Streak-Sage":"images/raid-bosses/streak-sage.png","Topic-Explorer":"images/raid-bosses/topic-explorer.png","Lightning-Lancer":"images/raid-bosses/lightning-lancer.png","Forum-Forge":"images/raid-bosses/forum-forge.png","Trivia-Tactician":"images/raid-bosses/trivia-tactician.png","Content-Conqueror":"images/raid-bosses/content-conqueror.png"};function _getRaidBossImage(e){return e.image||RAID_BOSS_IMAGES[e.name]||""}function _renderRaidBossCard(e,t){Date.now();var o=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,n=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0,i=_getRaidBossImage(t);if(t.placeholder){var a=o?new Date(o):null,r=a?a.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"Soon",s=i?''+(t.name||':'
⚔️
';return e.innerHTML='
'+s+'
'+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
'+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
'+("function"==typeof escapeHtml?escapeHtml(r):r)+'
Get ready to team up and take it down!
🏆 Community Prize
Defeat the boss = extra orange ticket giveaway for 21,000 sats!
',void _startRaidCountdown("raidCountdownPlaceholder",o)}if(t.defeated){var c=t.winners||[],l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null;if(l&&-1!==c.indexOf(l)&&localStorage.setItem("btc_raid_winner","true"),c.length>0)for(var d=0;d'+(t.name||
💀
':'
💀
';return e.innerHTML='
'+u+'
DEFEATED!
'+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
'+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
🎉 Community reward unlocked!
Extra orange ticket giveaway for 21,000 sats!
',void(window._defeatedBossId=t._id)}var p=void 0!==t.current?t.current:void 0!==t.currentHP?t.currentHP:0,m=t.target||t.targetHP||1,g=Math.min(100,Math.round(p/m*100)),h=Math.max(0,m-p),f=Math.max(0,100-g),y="function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss",v="function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"",b=i?''+y+'':'
👹
';if(e.innerHTML='
'+b+'
'+y+'
'+v+'
❤️ Boss Health'+h.toLocaleString()+" / "+m.toLocaleString()+' HP
'+g+'% damage dealt
⏰ Time Remaining
🏆 Community Prize
Defeat the boss and the community earns an extra orange ticket giveaway for 21,000 sats!
Loading...
',!document.getElementById("raidShimmerStyle")){var w=document.createElement("style");w.id="raidShimmerStyle",w.textContent="@keyframes raidShimmer{0%{transform:translateX(-100%)}100%{transform:translateX(100%)}}",document.head.appendChild(w)}_startRaidCountdown("raidTimer",n),window._raidActiveTab="current",window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),_listenRaidParticipants(t._id)}function _startRaidCountdown(e,t){function o(){var o=document.getElementById(e);if(!o)return clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var n=Math.max(0,t-Date.now());if(n<=0)return o.textContent="Time's up!",clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var i=Math.floor(n/864e5),a=Math.floor(n%864e5/36e5),r=Math.floor(n%36e5/6e4),s=Math.floor(n%6e4/1e3);o.textContent=(i>0?i+"d ":"")+(a>0?a+"h ":"")+(r<10?"0":"")+r+"m "+(s<10?"0":"")+s+"s"}window._raidTimerInterval&&clearInterval(window._raidTimerInterval),o(),window._raidTimerInterval=setInterval(o,1e3)}function _listenRaidParticipants(e){window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),void 0!==db&&(window._raidParticipantsUnsub=db.collection("raid_bosses").doc(e).collection("participants").orderBy("contributed","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t)if(e.empty)t.innerHTML='
No raiders yet — be the first! ⚔️
';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,c=e.id;o+='
'+r+"'+i+(s?" (you)":"")+'
'+a.toLocaleString()+" dmg
"}),t.innerHTML=o}},function(e){console.error("[RAID] Participants listener error:",e)}))}function _listenAllTimeRaiders(){window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),void 0!==db&&(window._raidAllTimeUnsub=db.collection("users").where("raidDamageAllTime",">",0).orderBy("raidDamageAllTime","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t&&"alltime"===window._raidActiveTab)if(e.empty)t.innerHTML='
No all-time damage recorded yet.
';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.raidDamageAllTime||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,c=e.id;o+='
'+r+"'+i+(s?" (you)":"")+'
'+a.toLocaleString()+" dmg
"}),t.innerHTML=o}},function(e){console.error("[RAID] All-time raiders listener error:",e);var t=document.getElementById("raidParticipants");t&&"alltime"===window._raidActiveTab&&(t.innerHTML='
Could not load all-time data.
')}))}window._raidDamageDealersOpen=!1,window._raidDamageDealersUnsub=null,window._toggleRaidDamageDealers=function(){var e=document.getElementById("raidDamageDealers"),t=document.getElementById("raidDamageDealersBtn");if(e){if(window._raidDamageDealersOpen=!window._raidDamageDealersOpen,!window._raidDamageDealersOpen)return e.style.display="none",t&&(t.textContent="⚔️ Top Damage Dealers"),void(window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null));e.style.display="block",t&&(t.textContent="▲ Hide Damage Dealers"),e.innerHTML='
Loading...
';var o=window._defeatedBossId||(window._currentRaidBoss&&window._currentRaidBoss._id?window._currentRaidBoss._id:null);o&&void 0!==db?window._raidDamageDealersUnsub=db.collection("raid_bosses").doc(o).collection("participants").orderBy("contributed","desc").limit(30).onSnapshot(function(e){var t=document.getElementById("raidDamageDealers");if(t)if(e.empty)t.innerHTML='
No damage recorded for this boss.
';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,c=e.id;o+='
'+r+"'+i+(s?" (you)":"")+'
'+a.toLocaleString()+" dmg
"}),t.innerHTML=o}},function(e){console.error("[RAID] Damage dealers listener error:",e);var t=document.getElementById("raidDamageDealers");t&&(t.innerHTML='
Failed to load damage data.
')}):e.innerHTML='
No damage data available.
'}},window._raidActiveTab="current",window._raidAllTimeUnsub=null,window._switchRaidTab=function(e){if(e!==window._raidActiveTab){window._raidActiveTab=e;var t=document.getElementById("raidTabCurrent"),o=document.getElementById("raidTabAllTime");t&&(t.style.borderBottomColor="current"===e?"#8b5cf6":"transparent",t.style.color="current"===e?"#8b5cf6":"var(--text-faint)"),o&&(o.style.borderBottomColor="alltime"===e?"#8b5cf6":"transparent",o.style.color="alltime"===e?"#8b5cf6":"var(--text-faint)");var n=document.getElementById("raidParticipants");n&&(n.innerHTML='
Loading...
'),"current"===e?(window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._currentRaidBoss&&window._currentRaidBoss._id&&_listenRaidParticipants(window._currentRaidBoss._id)):(window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),_listenAllTimeRaiders())}};var RAID_GUIDANCE={uniqueUsers5Topics:{action:"Visit 5+ learning topics to deal damage!",nav:"home"},quizCompletions:{action:"Complete quiz quests to deal damage!",nav:"quests"},watchMinutes:{action:"Watch Timechain TV to deal damage!",nav:"tctv"},beatsMinutes:{action:"Listen to Bitcoin Beats to deal damage!",nav:"beats"},flashcardCompletions:{action:"Complete flashcard sets to deal damage!",nav:"quests"},totalXP:{action:"Earn XP from any activity to deal damage!",nav:"home"},pollVotes:{action:"Vote in Quest Hub polls to deal damage!",nav:"quests"},chatMessages:{action:"Send messages in Global Chat to deal damage!",nav:"chat"},badgesEarned:{action:"Earn badges to deal damage! Find them in the Leaderboard button 🏆",nav:"badges"},streakUsers:{action:"Maintain a 7-day daily visit streak to deal damage!",nav:"home"},uniqueTopicsVisited:{action:"Visit learning topics you haven't read yet!",nav:"home"},tipsSent:{action:"Send Lightning tips to deal damage!",nav:"home"},forumPosts:{action:"Create forum posts to deal damage!",nav:"forum"},triviaCorrect:{action:"Answer trivia correctly in Quest Hub to deal damage!",nav:"quests"},totalTopicReads:{action:"Read learning topics to deal damage!",nav:"home"}};window._contributeRaid=function(){var e=window._currentRaidBoss;if(e){var t=RAID_GUIDANCE[e.metric]||{action:"Complete activities on the site to deal damage!",nav:"home"};"function"==typeof showToast&&showToast("⚔️ "+t.action,3500);var o=document.getElementById("questHubOverlay");if(o&&o.remove(),"badges"===t.nav){if("function"==typeof toggleLeaderboard){var n=document.getElementById("leaderboard");if(n&&n.classList.contains("open")){n.classList.remove("open");var i=document.getElementById("lbFloatBtn");i&&(i.style.display="flex")}toggleLeaderboard(),setTimeout(function(){var e=document.getElementById("leaderboard");if(e)for(var t=e.querySelectorAll("h4"),o=0;o'+i.emoji+'
'+i.title+'
'+i.desc+"
"}t+='',t+="";var a=document.createElement("div");a.id="forumRulesOverlay",a.innerHTML=t,document.body.appendChild(a)}window.acceptForumRules=function(){localStorage.setItem("btc_forum_rules_accepted","true");var e=document.getElementById("forumRulesOverlay");e&&e.remove()},window.showForumRulesBtn=function(){i()};var a=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","retard","nazi","hitler","kkk","porn","hentai","rape","pedo"];function r(e){for(var t=e.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/),o=0;o=4&&-1!==t[o].indexOf(a[n]))return!1}return!0}function s(e){return"function"==typeof escapeHtml?escapeHtml(e):String(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}window.forumBack=function(){history.back()};var c="recent",l=sessionStorage.getItem("btc_forum_category")||"all",d=null,u="discussions",p=["Bitcoin Basics","Lightning","Mining","Privacy","Self-Custody","Economics","Technical","Culture","Opinion","Tutorial","News Analysis"];function m(e,n){if(n)if(0!==e.length){var i="";e.forEach(function(e){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},a=o.find(function(t){return t.id===e.category}),r=a?a.emoji+" "+a.name:"",c=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),l=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid);i+='
'+(e.upvotes||0)+'
'+s(e.title)+"
"+(e.body?'
'+s(e.body).substring(0,120)+(e.body.length>120?"...":"")+"
":"")+"
'+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'💬 '+(e.replyCount||0)+""+(r?''+r+"":"")+(c?"':"")+"
"}),n.innerHTML=i}else n.innerHTML='
🦌
No posts yet. Be the first to start a discussion!
'}async function g(e){var o=document.getElementById("forumReplies");if(o)try{var n=await db.collection("forum_replies").where("postId","==",e).orderBy("createdAt","asc").limit(100).get(),i=[];if(n.forEach(function(e){i.push({id:e.id,...e.data()})}),0===i.length)return void(o.innerHTML='
No replies yet. Be the first!
');var a=[],r={};i.forEach(function(e){e.parentReplyId?(r[e.parentReplyId]||(r[e.parentReplyId]=[]),r[e.parentReplyId].push(e)):a.push(e)});var c='
'+i.length+" "+(1===i.length?"reply":"replies")+"
";function l(e,o){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},i=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid),a=s(e.body).replace(/\n/g,"
");a=_(a=a.replace(/(https?:\/\/[^\s<]+)/g,'$1'));var r=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),c=auth&&auth.currentUser&&!auth.currentUser.isAnonymous;return'
'+(e.parentAuthorName?'
↩ '+s(e.parentAuthorName)+"
":"")+'
"+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'
'+a+'
"+(c?'':"")+(r?"':"")+"
"}a.forEach(function(e){c+=l(e,!1),(r[e.id]||[]).forEach(function(e){c+=l(e,!0)})}),Object.keys(r).forEach(function(e){a.some(function(t){return t.id===e})||r[e].forEach(function(e){c+=l(e,!1)})}),o.innerHTML=c}catch(d){o.innerHTML='
Error loading replies
'}}window.renderForum=function(){var e=document.getElementById("forumContainer");if(e){e.innerHTML="";var t='
';if(t+='
Home
',t+='

🗣️ Pleb Talk

Discuss Bitcoin with fellow learners
',t+='
',"stacker"===u){var n=window._snSearchQuery||"";t+='
',t+='',t+='',n&&(t+=''),t+="
";var a=window._snSub||"",r=[{id:"",label:"All"},{id:"bitcoin",label:"bitcoin"},{id:"lightning",label:"lightning"},{id:"nostr",label:"nostr"},{id:"privacy",label:"privacy"},{id:"tech",label:"tech"},{id:"meta",label:"meta"}];t+='
';for(var d=0;d'+S(p.label)+""}if(t+="
",n)t+='
Search results for: '+S(n)+"
";else{var g=window._snSort||"top",h=window._snWhen||"day";t+='
';for(var f=[{id:"top",label:"🔥 Top"},{id:"recent",label:"🕐 Recent"},{id:"random",label:"🎲 Random"}],y=0;y'+v.label+""}if("top"===g){t+='"}t+='stacker.news ↗',t+="
"}return t+='
Loading Stacker News...
',t+="
",e.innerHTML=t,void(n?function(e){var t=document.getElementById("snFeed");if(t){var o="https://embed-proxy.needcreations.workers.dev/api/sn/search?q="+encodeURIComponent(e);fetch(o).then(function(e){return e.json()}).then(function(o){if(o&&o.data&&o.data.search&&o.data.search.items){var n=o.data.search.items;n.length?t.innerHTML=b(n):t.innerHTML='
No results found for "'+S(e)+'"
'}else t.innerHTML='
No results found
'}).catch(function(){t.innerHTML='
Search failed.
'})}}(n):loadStackerNewsFeed(window._snSort||"top",window._snWhen||"day",a))}"articles"!==u?(t+='
',["recent","top","discussed"].forEach(function(e){var o=c===e;t+=""}),t+='
",t+='
Loading posts...
',t+="",e.innerHTML=t,document.getElementById("main").scrollTop=0,"true"!==localStorage.getItem("btc_forum_rules_accepted")&&i(),forumLoadPosts()):function(e,t){var o=e;o+='
',o+='
',["recent","top"].forEach(function(e){var t=c===e;o+=""}),o+="
",o+='
Loading articles...
',o+="",t.innerHTML=o,document.getElementById("main").scrollTop=0,async function(){var e=document.getElementById("articlesList");if(e&&void 0!==db)try{var t="top"===c?"upvotes":"createdAt",o=await db.collection("articles").where("status","==","published").orderBy(t,"desc").limit(15).get(),n=[];if(o.forEach(function(e){n.push({id:e.id,...e.data()})}),0===n.length)return void(e.innerHTML='
📝
No articles yet
Be the first to publish a Bitcoin article!
');var i="";n.forEach(function(e){var t="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},o=Math.max(1,Math.round((e.wordCount||500)/200)),n=e.createdAt&&e.createdAt.toDate?e.createdAt.toDate().toLocaleDateString():"",a=e.pinned?'📌 PINNED ':"";i+="
',e.coverUrl&&(i+='
'),i+='
',i+=a+'

'+s(e.title)+"

",e.subtitle&&(i+='
'+s(e.subtitle)+"
"),e.tags&&e.tags.length&&(i+='
',e.tags.forEach(function(e){i+=''+s(e)+""}),i+="
"),i+='
"+t.emoji+" "+s(e.authorName||"Anon")+"·"+o+" min read"+(n?"·"+n+"":"")+"
",i+='
👍 '+(e.upvotes||0)+"💬 "+(e.replyCount||0)+""+(e.tipTotal?"⚡ "+e.tipTotal+" sats":"")+"
",i+="
"}),e.innerHTML=i}catch(t){console.error("Articles load error:",t),e.innerHTML='
Error loading articles
'}}()}(t,e)}},window._forumUnsubscribe=null,window.forumLoadPosts=async function(){document.getElementById("forumPosts")&&void 0!==db&&(window._forumUnsubscribe&&(window._forumUnsubscribe(),window._forumUnsubscribe=null),async function(){var e=document.getElementById("forumPosts");if(e)try{var t="top"===c?"upvotes":"discussed"===c?"replyCount":"createdAt",o=l+"_"+c,n=Date.now();if(window._forumCache&&window._forumCache.key===o&&n-window._forumCache.time<12e4)return window._forumCache.posts,void m(window._forumCache.posts,e);var i="all"!==l?db.collection("forum_posts").where("category","==",l).orderBy(t,"desc").limit(50):db.collection("forum_posts").orderBy(t,"desc").limit(50),a=await i.get(),r=[];a.forEach(function(e){r.push({id:e.id,...e.data()})}),window._forumCache={key:o,time:Date.now(),posts:r},m(r,e)}catch(t){e.innerHTML='
Error loading posts. Try refreshing.
'}}())},window.forumSetSort=function(e){c=e,renderForum()},window.forumSetCategory=function(e){l=e,sessionStorage.setItem("btc_forum_category",e),renderForum()},window.forumViewPost=async function(e,o){var n=document.getElementById("forumContainer");if(n&&void 0!==db){o||history.pushState({channel:"forum",forumPost:e},"","#forum/post/"+e),n.innerHTML='
';try{var i=await db.collection("forum_posts").doc(e).get();if(!i.exists)return void renderForum();var a={id:i.id,...i.data()};d=a;var r="function"==typeof getLevel?getLevel(a.authorPoints||0):{emoji:"🟢"},c=a.voters&&auth&&auth.currentUser&&-1!==a.voters.indexOf(auth.currentUser.uid),l='
';if(l+='
Home
',l+='',l+='

'+s(a.title)+'

"+r.emoji+" "+s(a.authorName||"Anon")+''+timeAgo(a.createdAt)+"
",a.body){var u=s(a.body).replace(/\n/g,"
").replace(/\*\*(.+?)\*\*/g,"$1");l+='
'+(u=_(u=u.replace(/(https?:\/\/[^\s<]+)/g,'$1')))+"
"}a.link&&(l+='🔗 '+s(a.link).substring(0,60)+(a.link.length>60?"...":"")+"
");var p=auth&&auth.currentUser&&a.authorId===auth.currentUser.uid||t();l+='
💬 '+(a.replyCount||0)+" replies"+(p?"':"")+"
",l+="
",auth&&auth.currentUser&&!auth.currentUser.isAnonymous?l+='
':l+='
🔒
Want to join the conversation?
',l+='
Loading replies...
',l+="
",n.innerHTML=l,document.getElementById("main").scrollTop=0,g(e)}catch(e){n.innerHTML='
Error loading post
'}}},window.forumNewPost=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){history.pushState({channel:"forum-new"},"","#forum");var e=document.getElementById("forumContainer");if(e){var t='
';t+='
Home
',t+='',t+='

📝 Create New Post

',t+='
';var n="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;";t+='",t+='',t+='',t+='',t+='
',t+='',t+='
',t+="
",window._forumFormOpenTime=Date.now(),e.innerHTML=t,document.getElementById("main").scrollTop=0}}else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
🔒

Registration Required

Create a free account to post in the forum, join discussions, and earn XP! It only takes a few seconds.
')}};var h=0;function f(e){if(!e)return"";var t=s(e);return _(t='

'+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,'$1')).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/(?$1')).replace(/^### (.+)$/gm,'

$1

')).replace(/^## (.+)$/gm,'

$1

')).replace(/^# (.+)$/gm,'

$1

')).replace(/\*\*(.+?)\*\*/g,'$1')).replace(/\*(.+?)\*/g,"$1")).replace(/`(.+?)`/g,'$1')).replace(/^> (.+)$/gm,'
$1
')).replace(/^- (.+)$/gm,'
  • $1
  • ')).replace(/^\d+\. (.+)$/gm,'
  • $1
  • ')).replace(/---/g,'
    ')).replace(/\n{2,}/g,'

    '))+"

    ")}window.forumSubmitPost=async function(){if(!window._forumSubmitting){var e=Date.now();if(e-h<3e4)"function"==typeof showToast&&showToast("⏳ Wait 30 seconds between posts");else{h=e,window._forumSubmitting=!0;var t=document.getElementById("forumPostStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o=document.getElementById("forumHoneypot");if(o&&o.value)t&&(t.innerHTML='Something went wrong. Please try again.');else if(window._forumFormOpenTime&&Date.now()-window._forumFormOpenTime<5e3)t&&(t.innerHTML='Please take a moment to write your post.');else{var n=(document.getElementById("forumNewTitle").value||"").trim(),i=(document.getElementById("forumNewBody").value||"").trim(),a=(document.getElementById("forumNewLink").value||"").trim(),c=document.getElementById("forumNewCat").value;if("function"==typeof sanitizeInput&&(n=sanitizeInput(n),i=sanitizeInput(i)),!n||n.length<5)t&&(t.innerHTML='Title must be at least 5 characters');else if(!r(n)||i&&!r(i))t&&(t.innerHTML='Post contains inappropriate language. Keep it clean!');else{a&&!/^https?:\/\//i.test(a)&&(a="https://"+a);var l=parseInt(localStorage.getItem("btc_forum_post_count")||"0"),d=localStorage.getItem("btc_forum_post_date")||"",u=(new Date).toISOString().split("T")[0];if(d!==u&&(l=0),l>=5)t&&(t.innerHTML='You\'ve reached the daily post limit (5). Try again tomorrow!');else{t&&(t.innerHTML='Posting...');try{var p=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",m=void 0!==currentUser&¤tUser&¤tUser.points||0,g=await db.collection("forum_posts").add({title:n,body:i.substring(0,2e3),link:a.substring(0,200)||null,category:c,authorId:auth.currentUser.uid,authorName:p,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:m,upvotes:0,voters:[],replyCount:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()});if(localStorage.setItem("btc_forum_post_count",(l+1).toString()),localStorage.setItem("btc_forum_post_date",u),"function"==typeof awardPoints&&awardPoints(10,"📝 Forum post"),"function"==typeof awardTickets&&awardTickets(5,"📝 Forum post"),forumNotifyMentions(i,"forum_post",g.id,n),db.collection("users").doc(auth.currentUser.uid).update({forumPosts:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumPosts=(currentUser.forumPosts||0)+1),"function"==typeof window._raidOnForumPost&&window._raidOnForumPost(),"function"==typeof window.nachoGlobalAnnounce){var f=s(n).substring(0,80),y=s(i).substring(0,120);window.nachoGlobalAnnounce("🗣️ New Forum Post: "+f+" by "+s(p)+": "+y+(i.length>120?"...":"")+" ➡️ [Open PlebTalk](#forum)")}forumBack()}catch(e){t&&(t.innerHTML='Error posting. Try again.')}}}}}else t&&(t.innerHTML='You must be signed in')}}},window._forumReplyingTo=null,window.forumReplyToReply=function(e,t){window._forumReplyingTo={replyId:e,authorName:t};var o=document.getElementById("forumReplyIndicator");o&&(o.style.display="flex",o.querySelector("span").textContent="↩ Replying to "+t);var n=document.getElementById("forumReplyInput");n&&(n.focus(),n.placeholder="Reply to "+t+"...")},window.forumCancelReplyTo=function(){window._forumReplyingTo=null;var e=document.getElementById("forumReplyIndicator");e&&(e.style.display="none");var t=document.getElementById("forumReplyInput");t&&(t.placeholder="Write a reply...")},window.forumSubmitReply=async function(e){if(!window._forumReplySubmitting){window._forumReplySubmitting=!0;var t=document.getElementById("forumReplyStatus"),o=document.getElementById("forumReplyInput");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&o){var n=o.value.trim();if(!n||n.length<2)return t&&(t.innerHTML='Reply is too short'),void(window._forumReplySubmitting=!1);if(!r(n))return t&&(t.innerHTML='Reply contains inappropriate language'),void(window._forumReplySubmitting=!1);t&&(t.innerHTML='Posting...');try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0,s={postId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:a,upvotes:0,voters:[],createdAt:firebase.firestore.FieldValue.serverTimestamp()},c=window._forumReplyingTo;c&&c.replyId&&(s.parentReplyId=c.replyId,s.parentAuthorName=c.authorName||""),await db.collection("forum_replies").add(s),await db.collection("forum_posts").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Forum reply");var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";if(c&&c.replyId){try{var u=await db.collection("forum_replies").doc(c.replyId).get();u.exists&&u.data().authorId&&"function"==typeof sendNotification&&sendNotification(u.data().authorId,"reply",l+' replied to your comment on "'+(d?(d.title||"").substring(0,40):"a post")+'"',"forum_post",e)}catch(e){}d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",l+' replied in your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e)}else d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",l+' replied to your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e);forumNotifyMentions(n,"forum_post",e,d?d.title:""),db.collection("users").doc(auth.currentUser.uid).update({forumReplies:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumReplies=(currentUser.forumReplies||0)+1),o.value="",window.forumCancelReplyTo(),t&&(t.innerHTML='✅ Reply posted!'),g(e)}catch(e){t&&(t.innerHTML='Error posting reply')}window._forumReplySubmitting=!1}else window._forumReplySubmitting=!1}},window.forumVotePost=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_posts").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your post "'+(a.title||"").substring(0,40)+'"',"forum_post",e)}}d&&d.id===e?forumViewPost(e):forumLoadPosts()}catch(e){}},window.forumVoteReply=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_replies").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;-1!==n.indexOf(i)?await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)}):await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)}),d&&g(d.id)}catch(e){}},window.forumDeletePost=async function(e){if(auth&&auth.currentUser){var o=t();if(confirm(o?"Admin: Delete this post and all its replies?":"Delete your post? This cannot be undone."))try{var n=await db.collection("forum_replies").where("postId","==",e).get(),i=db.batch();n.forEach(function(e){i.delete(e.ref)}),i.delete(db.collection("forum_posts").doc(e)),await i.commit(),"function"==typeof showToast&&showToast("🗑️ Post deleted"),forumBack()}catch(e){"function"==typeof showToast&&showToast("Error deleting post")}}},window.forumDeleteReply=async function(e,o){if(auth&&auth.currentUser){var n=t();if(confirm(n?"Admin: Delete this reply?":"Delete your reply? This cannot be undone."))try{await db.collection("forum_replies").doc(e).delete(),await db.collection("forum_posts").doc(o).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Reply deleted"),d&&g(o)}catch(e){"function"==typeof showToast&&showToast("Error deleting reply")}}},window.forumSwitchTab=function(e){u=e,renderForum()};var y=["Content must be Bitcoin-focused or Bitcoin-adjacent","Minimum 500 words, maximum 10,000 words","No promotion of altcoins, scams, or affiliate spam","Original content only — no plagiarism","No hate speech or personal attacks","Author grants the archive a non-exclusive license to display the content","Moderators may remove content that violates these guidelines"];async function v(e){var o=document.getElementById("articleReplies");if(o)try{var n=await db.collection("article_replies").where("articleId","==",e).orderBy("createdAt","asc").limit(50).get();if(n.empty)return void(o.innerHTML='
    No comments yet. Be the first!
    ');var i="";n.forEach(function(o){var n=o.data(),a="function"==typeof getLevel?getLevel(n.authorPoints||0):{emoji:"🟢"},r=n.createdAt&&n.createdAt.toDate?"function"==typeof timeAgo?timeAgo(n.createdAt.toDate()):n.createdAt.toDate().toLocaleDateString():"",c=auth&&auth.currentUser&&(auth.currentUser.uid===n.authorId||t());i+='
    "+a.emoji+" "+s(n.authorName||"Anon")+'· '+r+""+(c?"':"")+'
    '+_(s(n.body).replace(/\n/g,"
    ").replace(/(https?:\/\/[^\s<]+)/g,'$1'))+"
    "}),o.innerHTML=i}catch(e){o.innerHTML='
    Error loading comments
    '}}function b(e){for(var t="",o=0;o",t+='
    ',t+='
    ',t+='
    '+T(n.sats)+"
    ",t+='
    sats
    ',t+="
    ",t+='
    ',t+='
    '+S(n.title)+"
    ",t+='
    ',t+='@'+S(n.user.name)+"",t+="·",t+=""+i+"",n.ncomments>0&&(t+="·",t+="💬 "+n.ncomments+""),a&&(t+="·",t+=''+S(a)+""),r&&(t+=''+S(r)+""),t+="
    ",t+='',t+="
    "}return t}function w(e,t){for(var o="",n=0;n',o+='
    ',o+='@'+S(i.user.name)+"",o+="·",o+=""+k(i.createdAt)+"",i.sats>0&&(o+="·",o+='⚡ '+T(i.sats)+""),o+="
    ",i.text&&(o+='
    '+x(i.text)+"
    "),o+="",i.comments&&i.comments.comments&&i.comments.comments.length>0&&(o+=w(i.comments.comments,t+1))}return o}function x(e){if(!e)return"";var t=S(e);return'

    '+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/^#{3}\s+(.+)$/gm,'

    $1
    ')).replace(/^#{2}\s+(.+)$/gm,'
    $1
    ')).replace(/^#{1}\s+(.+)$/gm,'
    $1
    ')).replace(/\*\*\*(.+?)\*\*\*/g,"$1")).replace(/\*\*(.+?)\*\*/g,"$1")).replace(/\*(.+?)\*/g,"$1")).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/`([^`]+)`/g,'$1')).replace(/\n\n/g,'

    ')).replace(/\n/g,"
    "))+"

    "}function k(e){var t=Math.floor((Date.now()-new Date(e).getTime())/1e3);return t<60?"just now":t<3600?Math.floor(t/60)+"m ago":t<86400?Math.floor(t/3600)+"h ago":Math.floor(t/86400)+"d ago"}function T(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"k":String(e)}function S(e){return e?e.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""):""}function _(e){return e&&-1!==e.indexOf("@")?e.replace(/(<[^>]+>)|(@([a-zA-Z0-9_\-\.]{2,20}))/g,function(e,t,o,n){return t||'"+o+""}):e}window.articleNew=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void("function"==typeof showToast&&showToast("🔒 Sign in to write articles"));if((void 0!==currentUser&¤tUser&¤tUser.points||0)<100)"function"==typeof showToast&&showToast("📝 You need 100+ points to publish articles. Keep exploring!");else{var e=null;try{e=JSON.parse(localStorage.getItem("btc_article_draft"))}catch(e){}var t=document.getElementById("forumContainer");if(t){var o="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;",n='
    ';n+='',n+='

    ✍️ Write an Article

    ',n+='
    ',n+='',n+='',n+='
    ';var i=e&&e.tags?e.tags:[];p.forEach(function(e){var t=-1!==i.indexOf(e);n+=""}),n+="
    ",n+='
    ',n+='
    0 words · Min 500
    ',n+='',n+='
    📋 Content Guidelines
    ',y.forEach(function(e){n+='
    • '+e+"
    "}),n+='
    ',n+='
    ',n+='
    ',n+="
    ",t.innerHTML=n,document.getElementById("main").scrollTop=0;var a=document.getElementById("articleBody");a&&(a.addEventListener("input",function(){var e=this.value.trim().split(/\s+/).filter(function(e){return e.length>0}).length,t=document.getElementById("articleWordCount");t&&(t.textContent=e+" words · Min 500")}),window._articleAutoSave=setInterval(function(){articleSaveDraft(!0)},3e4))}}},window.toggleArticleTag=function(e,t){if(-1!==e.style.borderColor.indexOf("var(--accent)")||-1!==e.style.color.indexOf("var(--accent)"))e.style.border="1px solid var(--border)",e.style.background="none",e.style.color="var(--text-muted)";else{if(document.querySelectorAll('#articleTagsContainer button[style*="accent-bg"]').length>=3)return void("function"==typeof showToast&&showToast("Max 3 tags"));e.style.border="1px solid var(--accent)",e.style.background="var(--accent-bg)",e.style.color="var(--accent)"}},window.articleInsert=function(e,t,o){var n=document.getElementById("articleBody");if(n){n.focus();var i=n.selectionStart,a=n.selectionEnd,r=n.value.substring(i,a),s=r||o,c=e+s+t;n.setRangeText(c,i,a,"select"),r||(n.selectionStart=i+e.length,n.selectionEnd=i+e.length+s.length),n.dispatchEvent(new Event("input"))}},window.articleInsertLink=function(){var e=document.getElementById("articleBody");if(e){var t=e.value.substring(e.selectionStart,e.selectionEnd),o=document.getElementById("articleLinkDialog");o&&o.remove();var n=document.createElement("div");n.id="articleLinkDialog",n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",n.onclick=function(e){e.target===n&&n.remove()};var i="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";n.innerHTML='

    🔗 Insert Link

    ',document.body.appendChild(n),setTimeout(function(){document.getElementById("linkDialogUrl").focus()},100)}},window.articleDoInsertLink=function(){var e=(document.getElementById("linkDialogText").value||"").trim()||"link",t=(document.getElementById("linkDialogUrl").value||"").trim();if(t){t.match(/^https?:\/\//)||(t="https://"+t);var o=document.getElementById("articleBody");if(o){var n="["+e+"]("+t+")",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleLinkDialog").remove()}else"function"==typeof showToast&&showToast("Enter a URL")},window.articleInsertImage=function(){var e=document.getElementById("articleImageDialog");e&&e.remove();var t=document.createElement("div");t.id="articleImageDialog",t.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",t.onclick=function(e){e.target===t&&t.remove()};var o="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";t.innerHTML='

    🖼️ Insert Image

    Or upload from device:
    ',document.body.appendChild(t),setTimeout(function(){var e=document.getElementById("imageDialogFile");e&&e.addEventListener("change",function(){var e=this.files[0];if(e)if(e.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var t=document.getElementById("imageDialogPreview"),o=document.getElementById("imageDialogBtn");if(o&&(o.disabled=!0,o.textContent="Uploading..."),"undefined"!=typeof firebase&&firebase.storage&&void 0!==auth&&auth.currentUser)firebase.storage().ref("article-images/"+auth.currentUser.uid+"/"+Date.now()+"_"+e.name.replace(/[^a-zA-Z0-9._-]/g,"_")).put(e).then(function(e){return e.ref.getDownloadURL()}).then(function(e){document.getElementById("imageDialogUrl").value=e,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image"),"function"==typeof showToast&&showToast("✅ Image uploaded!")}).catch(function(e){"function"==typeof showToast&&showToast("Upload failed: "+(e.message||"Unknown error")),o&&(o.disabled=!1,o.textContent="Insert Image")});else{var n=new FileReader;n.onload=function(e){document.getElementById("imageDialogUrl").value=e.target.result,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image")},n.readAsDataURL(e)}}}),document.getElementById("imageDialogUrl").focus()},100)},window.articleDoInsertImage=function(){var e=(document.getElementById("imageDialogUrl").value||"").trim(),t=(document.getElementById("imageDialogAlt").value||"").trim()||"image";if(e){var o=document.getElementById("articleBody");if(o){var n="\n!["+t+"]("+e+")\n",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleImageDialog").remove()}else"function"==typeof showToast&&showToast("Enter an image URL or upload a file")},window.toggleArticlePreview=function(){var e=document.getElementById("articleBody"),t=document.getElementById("articlePreviewArea"),o=document.getElementById("articlePreviewBtn");e&&t&&("none"===t.style.display?(t.innerHTML=f(e.value),t.style.display="block",e.style.display="none",o.textContent="Edit"):(t.style.display="none",e.style.display="",o.textContent="Preview"))},window.articleSaveDraft=function(e){var t=(document.getElementById("articleTitle")||{}).value||"",o=(document.getElementById("articleSubtitle")||{}).value||"",n=(document.getElementById("articleBody")||{}).value||"",i=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&i.push(e.getAttribute("data-tag"))}),(t||n)&&(localStorage.setItem("btc_article_draft",JSON.stringify({title:t,subtitle:o,body:n,tags:i,savedAt:Date.now()})),e||"function"!=typeof showToast||showToast("💾 Draft saved!"))},window.articleSubmit=async function(){if(!window._articleSubmitting){var e=document.getElementById("articleStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var t=(document.getElementById("articleTitle").value||"").trim(),o=(document.getElementById("articleSubtitle").value||"").trim(),n=(document.getElementById("articleBody").value||"").trim(),i=document.getElementById("articleTerms");if(!t||t.length<10)e&&(e.innerHTML='Title must be at least 10 characters');else{var a=n.split(/\s+/).filter(function(e){return e.length>0}).length;if(a<500)e&&(e.innerHTML='Article must be at least 500 words (currently '+a+")");else if(a>1e4)e&&(e.innerHTML='Article must be under 10,000 words');else{var c=[];if(document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&c.push(e.getAttribute("data-tag"))}),c.length<1)e&&(e.innerHTML='Select at least 1 tag');else if(i&&i.checked)if(r(t)&&r(n)){window._articleSubmitting=!0,e&&(e.innerHTML='Publishing...');try{var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",d=void 0!==currentUser&¤tUser&¤tUser.points||0,p=void 0!==currentUser&¤tUser&¤tUser.profilePic?currentUser.profilePic:"",m="",g=document.getElementById("articleCover");if(g&&g.files&&g.files[0]){var h=g.files[0];if(h.size>3145728)return e&&(e.innerHTML='Cover image too large (max 3MB)'),void(window._articleSubmitting=!1);e&&(e.innerHTML='Uploading cover...');try{var f=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),y=await f.put(h);m=await y.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}e&&(e.innerHTML='Publishing article...');var v={title:t.substring(0,120),subtitle:o.substring(0,200),body:n.substring(0,5e4),tags:c.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),authorId:auth.currentUser.uid,authorName:l,authorPoints:d,authorPic:p,upvotes:0,voters:[],replyCount:0,tipTotal:0,status:"published",pinned:!1,agreedToTerms:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp(),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};m&&(v.coverUrl=m),await db.collection("articles").add(v),localStorage.removeItem("btc_article_draft"),window._articleAutoSave&&clearInterval(window._articleAutoSave),"function"==typeof awardPoints&&awardPoints(30,"📝 Article published"),"function"==typeof awardTickets&&awardTickets(20,"📝 Article published");var b=parseInt(localStorage.getItem("btc_articles_published")||"0");localStorage.setItem("btc_articles_published",String(b+1)),"function"==typeof showToast&&showToast("📝 Article published!"),u="articles",renderForum()}catch(t){console.error("Article submit error:",t),e&&(e.innerHTML='Error publishing: '+s(t.message)+"")}window._articleSubmitting=!1}else e&&(e.innerHTML='Content contains inappropriate language');else e&&(e.innerHTML='You must agree to the content guidelines')}}}else e&&(e.innerHTML='Sign in required')}},window.articleView=async function(e){var o=document.getElementById("forumContainer");if(o&&db){o.innerHTML='
    Loading article...
    ';try{var n=await db.collection("articles").doc(e).get();if(!n.exists)return void(o.innerHTML='
    Article not found
    ');var i=n.data();i.id=e;var a="function"==typeof getLevel?getLevel(i.authorPoints||0):{emoji:"🟢"},r=Math.max(1,Math.round((i.wordCount||500)/200)),c=i.createdAt&&i.createdAt.toDate?i.createdAt.toDate().toLocaleDateString():"",l=auth&&auth.currentUser&&auth.currentUser.uid===i.authorId,d=t(),u=auth&&auth.currentUser&&-1!==(i.voters||[]).indexOf(auth.currentUser.uid),p='
    ';if(p+='',i.coverUrl&&(p+='
    Cover
    '),p+='

    '+s(i.title)+"

    ",i.subtitle&&(p+='
    '+s(i.subtitle)+"
    "),p+='
    ',i.authorPic&&(p+=''),p+='
    "+a.emoji+" "+s(i.authorName||"Anon")+'
    '+c+" · "+r+" min read · "+(i.wordCount||0).toLocaleString()+" words
    ",l&&(p+="'),d&&(p+=""),p+="
    ",i.tags&&i.tags.length&&(p+='
    ',i.tags.forEach(function(e){p+=''+s(e)+""}),p+="
    "),p+='
    '+f(i.body)+"
    ",p+='
    ',p+="","function"==typeof tipButtonHtml&&(p+=tipButtonHtml({recipientName:i.authorName,recipientUid:i.authorId,context:"article",contextId:e,label:"⚡ Tip Author",size:"md"})),(l||d)&&(p+="'),p+="
    ",p+='

    💬 Comments

    ',p+='
    Loading comments...
    ',auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(p+='
    '),p+="
    ",o.innerHTML=p,document.getElementById("main").scrollTop=0,v(e),auth&&auth.currentUser){var m="btc_article_read_"+e;localStorage.getItem(m)||setTimeout(function(){document.getElementById("articleReplies")&&(localStorage.setItem(m,"1"),"function"==typeof awardPoints&&awardPoints(5,"📖 Read an article"),"function"==typeof showToast&&showToast("📖 +5 points for reading!"))},6e4)}}catch(e){console.error("Article view error:",e),o.innerHTML='
    Error loading article
    '}}},window.articleVote=async function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{var t=db.collection("articles").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your article "'+(a.title||"").substring(0,40)+'"',"article",e)}}articleView(e)}catch(e){}else"function"==typeof showToast&&showToast("🔒 Sign in to upvote")},window.articleSubmitReply=async function(e){var t=document.getElementById("articleReplyInput"),o=document.getElementById("articleReplyStatus");if(t&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var n=t.value.trim();if(!n||n.length<2)o&&(o.innerHTML='Comment too short');else if(r(n))try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0;await db.collection("article_replies").add({articleId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorPoints:a,createdAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("articles").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Article comment");try{var s=await db.collection("articles").doc(e).get();if(s.exists&&s.data().authorId&&"function"==typeof sendNotification){var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(s.data().authorId,"comment",c+' commented on your article "'+(s.data().title||"").substring(0,40)+'"',"article",e)}forumNotifyMentions(n,"article",e,s&&s.exists?s.data().title:"")}catch(e){}t.value="",o&&(o.innerHTML='✅ Comment posted!'),v(e)}catch(e){o&&(o.innerHTML='Error posting comment')}else o&&(o.innerHTML='Inappropriate language')}},window.articleDeleteReply=async function(e,t){if(confirm("Delete this comment?"))try{await db.collection("article_replies").doc(e).delete(),await db.collection("articles").doc(t).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Comment deleted"),v(t)}catch(e){}},window.articleEdit=async function(e){try{var o=await db.collection("articles").doc(e).get();if(!o.exists)return;var n=o.data();if(auth.currentUser.uid!==n.authorId&&!t())return;localStorage.setItem("btc_article_draft",JSON.stringify({title:n.title,subtitle:n.subtitle||"",body:n.body,tags:n.tags||[]})),window._articleEditId=e,articleNew(),setTimeout(function(){var e=document.querySelector('[onclick="articleSubmit()"]');e&&(e.textContent="✏️ Update Article",e.setAttribute("onclick","articleUpdate()"))},100)}catch(e){"function"==typeof showToast&&showToast("Error loading article for edit")}},window.articleUpdate=async function(){var e=window._articleEditId;if(e){var t=document.getElementById("articleStatus"),o=(document.getElementById("articleTitle").value||"").trim(),n=(document.getElementById("articleSubtitle").value||"").trim(),i=(document.getElementById("articleBody").value||"").trim(),a=i.split(/\s+/).filter(function(e){return e.length>0}).length;if(!o||o.length<10)t&&(t.innerHTML='Title must be at least 10 characters');else if(a<500)t&&(t.innerHTML='Min 500 words');else{var r=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&r.push(e.getAttribute("data-tag"))}),t&&(t.innerHTML='Updating...');try{var s=null,c=document.getElementById("articleCover");if(c&&c.files&&c.files[0]){var l=c.files[0];if(l.size>3145728)return void(t&&(t.innerHTML='Cover too large (max 3MB)'));t&&(t.innerHTML='Uploading cover...');try{var d=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),u=await d.put(l);s=await u.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}var p={title:o.substring(0,120),subtitle:n.substring(0,200),body:i.substring(0,5e4),tags:r.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};s&&(p.coverUrl=s),t&&(t.innerHTML='Saving...'),await db.collection("articles").doc(e).update(p),localStorage.removeItem("btc_article_draft"),window._articleEditId=null,"function"==typeof showToast&&showToast("✏️ Article updated!"),articleView(e)}catch(e){t&&(t.innerHTML='Error updating')}}}},window.articleTogglePin=async function(e,t){try{await db.collection("articles").doc(e).update({pinned:t}),"function"==typeof showToast&&showToast(t?"📌 Article pinned!":"📌 Article unpinned"),articleView(e)}catch(e){}},window.articleDelete=async function(e){if(confirm("Delete this article and all its comments? This cannot be undone."))try{var t=await db.collection("article_replies").where("articleId","==",e).get(),o=db.batch();t.forEach(function(e){o.delete(e.ref)}),o.delete(db.collection("articles").doc(e)),await o.commit(),"function"==typeof showToast&&showToast("🗑️ Article deleted"),u="articles",renderForum()}catch(e){"function"==typeof showToast&&showToast("Error deleting article")}},window.loadStackerNewsFeed=function(e,t,o){var n=document.getElementById("snFeed");if(n){var i="https://embed-proxy.needcreations.workers.dev/api/sn?sort="+encodeURIComponent(e)+"&when="+encodeURIComponent(t)+"&limit=21";o&&(i+="&sub="+encodeURIComponent(o)),fetch(i).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.items&&e.data.items.items){var t=e.data.items.items;t.length?n.innerHTML=b(t):n.innerHTML='
    No posts found
    '}else n.innerHTML='
    Could not load Stacker News feed
    '}).catch(function(){n.innerHTML='
    Failed to load feed.
    '})}},window.snDoSearch=function(){var e=document.getElementById("snSearchInput");if(e){var t=e.value.trim();t.length<2||(window._snSearchQuery=t,renderForum())}},window.snClearSearch=function(){window._snSearchQuery="",renderForum()},window.snOpenPost=function(e){var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading post...
    ',fetch("https://embed-proxy.needcreations.workers.dev/api/sn/item?id="+e).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.item){var o=e.data.item;!function(e,t){var o='
    ';if(o+='',o+='
    ',o+='

    '+S(t.title)+"

    ",o+='
    ',o+='⚡ '+T(t.sats)+" sats",o+="·",o+='@'+S(t.user.name)+"",o+="·",o+=""+k(t.createdAt)+"",t.ncomments>0&&(o+="·",o+="💬 "+t.ncomments+" comments"),o+="
    ",t.url){var n="";try{n=new URL(t.url).hostname.replace("www.","")}catch(e){}o+='🔗 '+S(n||t.url)+" ↗"}t.text&&(o+='
    '+x(t.text)+"
    "),o+='",o+="
    ",t.comments&&t.comments.comments&&t.comments.comments.length>0&&(o+='
    ',o+='
    💬 Comments ('+t.ncomments+")
    ",o+=w(t.comments.comments,0),o+="
    "),o+="
    ",e.innerHTML=o,e.scrollTop=0}(t,o)}else t.innerHTML='
    Post not found.
    '}).catch(function(){t.innerHTML='
    Failed to load post. ·
    '}))},window.forumMentionClick=function(e){e&&void 0!==db&&db.collection("users").where("username","==",e).limit(1).get().then(function(t){t.empty?db.collection("users").where("username_lower","==",e.toLowerCase()).limit(1).get().then(function(t){t.empty?"function"==typeof showToast&&showToast("User @"+e+" not found"):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){}):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){})},window.forumNotifyMentions=async function(e,t,o,n){if(e&&void 0!==db&&auth&&auth.currentUser){var i=e.match(/@([a-zA-Z0-9_\-\.]{2,20})/g);if(i){var a={},r=[];i.forEach(function(e){var t=e.substring(1).toLowerCase();a[t]||(a[t]=!0,r.push(e.substring(1)))});for(var s=auth.currentUser.uid,c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone",l=(n||"").substring(0,40),d=0;d=",e).where("username","<=",e+"").limit(5).get().then(function(e){e.forEach(function(e){var t=e.data();t.username&&!a[e.id]&&(a[e.id]=!0,i.push({uid:e.id,username:t.username,points:t.points||0}))})}).catch(function(){}).then(function(){++r>=t.length&&(i.sort(function(e,t){return(t.points||0)-(e.points||0)}),B.activeTextarea&&function(e,t){if(E(),t&&0!==t.length){B.results=t,B.selectedIdx=0;var o=document.createElement("div");o.id="mentionDropdown",o.style.cssText="position:absolute;z-index:9999;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,0.4);overflow:hidden;max-height:220px;overflow-y:auto;min-width:200px;",t.forEach(function(e,t){var n=document.createElement("div");n.className="mention-item",n.setAttribute("data-idx",t);var i="function"==typeof getLevel?getLevel(e.points||0):{emoji:"🟢"};n.innerHTML=''+i.emoji+' '+s(e.username)+""+(e.points?''+(e.points||0).toLocaleString()+" XP":""),n.style.cssText="padding:10px 14px;cursor:pointer;display:flex;align-items:center;gap:8px;font-size:0.85rem;color:var(--text);transition:background 0.15s;"+(0===t?"background:var(--accent-bg);":""),n.onmouseenter=function(){B.selectedIdx=t,C()},n.onmousedown=function(e){e.preventDefault(),A(t)},o.appendChild(n)});var n=e.getBoundingClientRect();window.pageYOffset||document.documentElement.scrollTop,o.style.position="fixed",o.style.left=n.left+"px",o.style.top=n.bottom+4+"px",o.style.width=Math.min(n.width,320)+"px",document.body.appendChild(o),B.dropdown=o}}(B.activeTextarea,i.slice(0,5)))})})}}(t.prefix)},300))}),e.addEventListener("keydown",function(e){B.dropdown&&("ArrowDown"===e.key?(e.preventDefault(),B.selectedIdx=Math.min(B.selectedIdx+1,B.results.length-1),C()):"ArrowUp"===e.key?(e.preventDefault(),B.selectedIdx=Math.max(B.selectedIdx-1,0),C()):"Enter"===e.key||"Tab"===e.key?B.results.length>0&&B.selectedIdx>=0&&(e.preventDefault(),A(B.selectedIdx)):"Escape"===e.key&&E())}),e.addEventListener("blur",function(){setTimeout(E,200)}))}function z(){var e=["forumNewBody","forumReplyInput","articleReplyInput"];if(e.forEach(function(e){var t=document.getElementById(e);t&&M(t)}),"undefined"!=typeof MutationObserver){var t=new MutationObserver(function(){e.forEach(function(e){var t=document.getElementById(e);t&&M(t)})}),o=document.getElementById("forumContainer");if(o)t.observe(o,{childList:!0,subtree:!0});else{var n=new MutationObserver(function(){var o=document.getElementById("forumContainer");o&&(n.disconnect(),t.observe(o,{childList:!0,subtree:!0}),e.forEach(function(e){var t=document.getElementById(e);t&&M(t)}))});n.observe(document.body,{childList:!0,subtree:!0})}}}var L=document.createElement("style");L.textContent=".forum-mention{color:var(--accent);cursor:pointer;font-weight:600;transition:opacity 0.15s;}.forum-mention:hover{opacity:0.8;text-decoration:underline;}",document.head.appendChild(L),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(z,1e3)}):setTimeout(z,1e3)}(),function(){"use strict";var e=[{emoji:"⚡",title:"Bitcoin Payments Only",desc:"All transactions use Bitcoin (Lightning or on-chain). No fiat payments. Buyers and sellers handle payment directly — LightningMart is not an escrow or payment processor."},{emoji:"🚫",title:"No Illegal or Illicit Items",desc:"Strictly prohibited: drugs, weapons, stolen goods, counterfeit items, hacking tools, malware, pirated content, illegal services of any kind. Violation results in immediate ban and may be reported to authorities."},{emoji:"🔞",title:"No Adult or Sexual Content",desc:"No selling or advertising of sexual services, adult content, escort services, or any sexually explicit material. This is an educational Bitcoin marketplace — keep it appropriate for all ages."},{emoji:"🎭",title:"No Fraud or Misrepresentation",desc:"List items honestly. No fake photos, misleading descriptions, bait-and-switch tactics, or counterfeit goods. If it's used, say so. If it has defects, disclose them."},{emoji:"🛡️",title:"Buyer & Seller Safety",desc:"Meet in public places for local trades. Never share your seed phrase, private keys, or send Bitcoin before receiving the item. Use Lightning for instant, irreversible payments."},{emoji:"💰",title:"No Money Laundering or Wash Trading",desc:"No using the marketplace to launder money, create fake transactions, artificially inflate sales, or manipulate pricing. All listings must represent genuine offers."},{emoji:"📋",title:"Accurate Listings",desc:"Titles must clearly describe the item. Include condition, shipping options, and price in sats. One listing per item — no duplicate spam listings."},{emoji:"🤝",title:"Be Professional & Respectful",desc:"Communicate clearly with buyers/sellers. Respond to messages promptly. No harassment, threats, discrimination, or abusive language in any marketplace interaction."},{emoji:"🚫",title:"No Financial Products or Securities",desc:'No selling of financial instruments, investment schemes, MLM/pyramid schemes, "guaranteed returns," or unregistered securities. This is a marketplace for goods and services, not investments.'},{emoji:"⚖️",title:"Disputes & Moderation",desc:"LightningMart does not mediate disputes. All sales are final between buyer and seller. Report fraudulent listings using the 🚩 button. Moderators may remove listings and ban users without notice."}];function t(t){for(var o='

    LightningMart Rules

    Read before buying or selling
    ',n=0;n'+i.emoji+'
    '+i.title+'
    '+i.desc+"
    "}o+='',o+="
    ";var a=document.createElement("div");a.id="marketRulesOverlay",a.innerHTML=o,document.body.appendChild(a)}function o(){if(!auth||!auth.currentUser)return!1;var e=auth.currentUser.email||"";return"needcreations@gmail.com"===e||"info.603btc@gmail.com"===e}window.acceptMarketRules=function(){localStorage.setItem("btc_market_rules_accepted","true");var e=document.getElementById("marketRulesOverlay");e&&e.remove()},window.showMarketRulesBtn=function(){t()};var n=[{id:"educational",name:"Educational Products",emoji:"🎓",desc:"Learn Bitcoin with the best tools"},{id:"general",name:"Other Products",emoji:"🛒",desc:"Buy & sell everything else"},{id:"merchants",name:"More Bitcoin Merchants",emoji:"🏪",desc:"Browse more Bitcoin merchants"},{id:"noderunners",name:"Even More Merchants",emoji:"🌐",desc:"Bitcoin shops via Node Runners"}],i=[{id:"books",name:"Books",emoji:"📚",section:"educational"},{id:"courses",name:"Courses & Workshops",emoji:"🎓",section:"educational"},{id:"hardware_edu",name:"Hardware Wallets",emoji:"🔐",section:"educational"},{id:"nodes",name:"Node Kits & Guides",emoji:"💻",section:"educational"},{id:"kids",name:"Kids & Family",emoji:"👨‍👩‍👧‍👦",section:"educational"},{id:"tools",name:"Learning Tools",emoji:"🧰",section:"educational"},{id:"edu_other",name:"Other Educational",emoji:"📦",section:"educational"},{id:"mining",name:"Mining Equipment",emoji:"⛏️",section:"general"},{id:"merch",name:"Apparel & Merch",emoji:"👕",section:"general"},{id:"art",name:"Art & Collectibles",emoji:"🎨",section:"general"},{id:"stickers",name:"Stickers & Prints",emoji:"🖼️",section:"general"},{id:"services",name:"Services",emoji:"🛠️",section:"general"},{id:"electronics",name:"Electronics & Tech",emoji:"📱",section:"general"},{id:"other",name:"Other",emoji:"📦",section:"general"}],a=[{id:"new",label:"New",color:"#22c55e"},{id:"like_new",label:"Like New",color:"#84cc16"},{id:"good",label:"Good",color:"#eab308"},{id:"fair",label:"Fair",color:"#f97316"},{id:"for_parts",label:"For Parts",color:"#ef4444"}],r=[{id:"newest",label:"Newest First"},{id:"price_low",label:"Price: Low → High"},{id:"price_high",label:"Price: High → Low"},{id:"popular",label:"Most Saved"}];function s(e,t){"listing"===e?history.pushState({channel:"marketplace",mktView:"listing",listingId:t},"","#marketplace/listing/"+t):"my"===e&&history.pushState({channel:"marketplace",mktView:"my"},"","#marketplace/my")}window.handleMarketplacePopState=function(e,t){if(e&&"listing"===e.mktView&&e.listingId)return renderMarketplace({listingId:e.listingId,_noHistory:!0}),!0;if(e&&"my"===e.mktView)return showMyListings(!0),!0;if(t&&0===t.indexOf("marketplace/listing/")){var o=t.replace("marketplace/listing/","");return renderMarketplace({listingId:o,_noHistory:!0}),!0}return"marketplace/my"===t?(showMyListings(!0),!0):(renderMarketplace({_noHistory:!0}),!0)};var c=!1,l=!1;function d(e,t){var o=document.getElementById(e),n=document.getElementById(t);if(o&&n){var i=n.getBoundingClientRect();o.style.cssText="position:fixed;left:"+i.left+"px;top:"+i.top+"px;width:"+i.width+"px;height:"+i.height+"px;z-index:100;border-radius:12px;overflow:hidden;border:1px solid var(--border);background:var(--card-bg);pointer-events:auto;",o._reposition=function(){var e=n.getBoundingClientRect();o.style.left=e.left+"px",o.style.top=e.top+"px",o.style.width=e.width+"px",o.style.height=e.height+"px"},window.addEventListener("scroll",o._reposition,!0),window.addEventListener("resize",o._reposition)}}function u(e){var t=document.getElementById(e);t&&(t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t._reposition&&(window.removeEventListener("scroll",t._reposition,!0),window.removeEventListener("resize",t._reposition),t._reposition=null))}function p(e){var t=document.getElementById("forumContainer");if(t){t.style.display="block",t.innerHTML="";var c=e.category||"all",l=e.search||"",p=e.sort||"newest",m=e.listingId||null;if(m)return e._noHistory||s("listing",m),void function(e,t){e.innerHTML='
    Loading...
    ',db.collection("marketplace").doc(t).get().then(function(n){if(n.exists){var r={id:n.id,...n.data()},s=a.find(function(e){return e.id===r.condition}),c=s?s.label:"",l=s?s.color:"var(--text-faint)",d=i.find(function(e){return e.id===r.category}),u=d?d.emoji+" "+d.name:"📦 Other",p=-1!==safeJSON("btc_market_saved",[]).indexOf(r.id),m=void 0!==auth&&auth.currentUser&&auth.currentUser.uid===r.sellerUid,h=o(),f=r.priceSats>=1e6?(r.priceSats/1e6).toFixed(2)+"M sats":r.priceSats>=1e3?Math.floor(r.priceSats/1e3)+"K sats":r.priceSats.toLocaleString()+" sats",y="";try{var v=parseFloat(localStorage.getItem("btc_last_price")||"0");v>0&&(y=' (~$'+(r.priceSats/1e8*v).toFixed(2)+")")}catch(e){}var b=g(r.createdAt?r.createdAt.toDate():new Date),w='
    ';w+='',r.imageUrl?w+="
    ]/g,""):"")+"') center/contain no-repeat;background-color:var(--bg-side);border-radius:14px;border:1px solid var(--border);margin-bottom:16px;\">
    ":w+='
    '+(d?d.emoji:"📦")+"
    ",w+='
    '+escapeHtml(r.title)+'
    ⚡ '+f+y+"
    ",w+='
    '+c+''+u+'🕐 '+b+""+(r.shipping?'📦 Ships':"")+(r.localPickup?'📍 Local pickup':"")+"
    ",w+='
    Description
    '+escapeHtml(r.description||"No description provided.")+"
    ",w+='
    Seller
    '+(r.sellerName?r.sellerName.charAt(0).toUpperCase():"?")+'
    '+escapeHtml(r.sellerName||"Anonymous")+"
    "+(r.sellerRank?'
    '+escapeHtml(r.sellerRank)+"
    ":"")+'
    👤
    ',m?w+='
    ':(w+='
    '+(h?"':"")+"
    ",w+='
    🛡️ Safety Tips: Use escrow when possible. Never send payment before receiving the item. Meet in public if trading locally. Report suspicious listings.
    ',r.lightningAddress&&(w+='
    ⚡ This seller accepts Lightning payments
    ')),w+="
    ",e.innerHTML=w,db.collection("marketplace").doc(t).update({views:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})}else e.innerHTML='
    😕
    Listing not found
    '}).catch(function(){e.innerHTML='
    Error loading listing.
    '})}(t,m);var h='
    ';h+='
    Home
    ',h+='
    Lightning Mart
    Buy & sell with Bitcoin ⚡
    ',h+='
    ';var f=e.section||"merchants";if("all"!==c&&"all"===f){var y=i.find(function(e){return e.id===c});y&&(f=y.section)}h+='
    ';for(var v=[{id:"all",name:"All",emoji:"🛒"}].concat(n),b=0;b'+w.emoji+" "+w.name+""}if(h+="
    ",u("gmIframeWrap"),u("nrIframeWrap"),"merchants"===f)return h+='
    ',h+="
    ",t.innerHTML=h,void d("gmIframeWrap","gmIframePlaceholder");if("noderunners"===f)return h+='
    ',h+="",t.innerHTML=h,void d("nrIframeWrap","nrIframePlaceholder");var k="all"===f?i:i.filter(function(e){return e.section===f});h+='
    ',h+="';for(var T=0;T'+S.emoji+" "+S.name+""}h+="
    ","educational"!==f&&"all"!==f||(h+='
    🛒
    603BTC Pleb Shop
    Bitcoin educational products, merch & gear
    '),h+='
    Loading...
    ",h+='
    ',h+="",t.innerHTML=h,function(e,t,o,n){var r=document.getElementById("marketListings"),s=document.getElementById("marketResultCount");if(r&&void 0!==db){for(var c='
    ',l=0;l<6;l++)c+='
    ';c+="
    ",r.innerHTML=c;var d=db.collection("marketplace").where("status","==","active");e&&"all"!==e&&(d=d.where("category","==",e)),(d="price_low"===o?d.orderBy("priceSats","asc"):"price_high"===o?d.orderBy("priceSats","desc"):"popular"===o?d.orderBy("saves","desc"):d.orderBy("createdAt","desc")).limit(50).get().then(function(e){var o=[];if(e.forEach(function(e){o.push({id:e.id,...e.data()})}),n&&"all"!==n){var c=i.filter(function(e){return e.section===n}).map(function(e){return e.id});o=o.filter(function(e){return-1!==c.indexOf(e.category)})}if(t){var l=t.toLowerCase();o=o.filter(function(e){return(e.title||"").toLowerCase().includes(l)||(e.description||"").toLowerCase().includes(l)})}if(s&&(s.textContent=o.length+" listing"+(1!==o.length?"s":"")),0!==o.length){var d=safeJSON("btc_market_saved",[]);r.innerHTML=o.map(function(e){var t,o=-1!==d.indexOf(e.id),n=a.find(function(t){return t.id===e.condition}),r=n?n.color:"var(--text-faint)",s=n?n.label:"",c=i.find(function(t){return t.id===e.category}),l=c?c.emoji:"📦";return t=e.priceSats>=1e6?(e.priceSats/1e6).toFixed(2)+"M sats":e.priceSats>=1e3?Math.floor(e.priceSats/1e3)+"K sats":e.priceSats.toLocaleString()+" sats","
    '+(e.imageUrl?"
    ]/g,""):"")+"') center/cover;border-bottom:1px solid var(--border);\">
    ":'
    '+l+"
    ")+'
    '+escapeHtml(e.title)+'
    ⚡ '+t+"
    "+(satsToUSD(e.priceSats)?'
    '+satsToUSD(e.priceSats)+"
    ":'
    ')+'
    '+s+"'+(o?"❤️":"🤍")+"
    "}).join("")}else r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){console.error("Marketplace load error:",e),r&&("failed-precondition"===e.code?(console.log("Trying fallback marketplace query..."),db.collection("marketplace").orderBy("createdAt","desc").limit(50).get().then(function(e){var t=[];e.forEach(function(e){var o=e.data();o.id=e.id,"active"===o.status&&t.push(o)}),t.length>0?(r.innerHTML=t.map(function(e){return"
    '+escapeHtml(e.title||"Untitled")+'
    ⚡ '+(e.priceSats||0).toLocaleString()+" sats
    "}).join(""),s&&(s.textContent=t.length+" listing"+(1!==t.length?"s":""))):r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){r.innerHTML='
    ⚙️ Marketplace needs a database index.
    This is a one-time setup.

    Click here to create the index manually if requested →
    '})):r.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+". Try refreshing.
    ")})}}(c,l,p,f)}}window._hideMarketIframes=function(){u("gmIframeWrap"),u("nrIframeWrap")},window.renderMarketplace=function(e){if(e=e||{},document.getElementById("forumContainer")){if(c||(c=!0,"true"!==localStorage.getItem("btc_market_rules_accepted")&&t()),function(){if(!l){if(l=!0,!document.getElementById("gmIframeWrap")){var e=document.createElement("div");e.id="gmIframeWrap",e.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",e.innerHTML='',document.body.appendChild(e)}if(!document.getElementById("nrIframeWrap")){var t=document.createElement("div");t.id="nrIframeWrap",t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t.innerHTML='',document.body.appendChild(t)}}}(),"function"==typeof showSkeletonLoader&&!e.listingId&&!e.search)return showSkeletonLoader("forumContainer"),void setTimeout(()=>p(e),300);p(e)}},window.showCreateListing=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to create a listing!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e='
    📝 Create Listing
    — or paste an image URL —
    ',t=document.createElement("div");t.innerHTML=e,document.body.appendChild(t.firstChild)};var m=0;function g(e){var t=Math.floor((new Date-e)/1e3);if(t<60)return"just now";var o=Math.floor(t/60);if(o<60)return o+"m ago";var n=Math.floor(o/60);if(n<24)return n+"h ago";var i=Math.floor(n/24);return i<30?i+"d ago":Math.floor(i/30)+"mo ago"}window.submitListing=function(){if(!window._mktSubmitting){var e=Date.now();if(e-m<6e4)"function"==typeof showToast&&showToast("⏳ Wait 60 seconds between listings");else{m=e;var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim();"function"==typeof sanitizeInput&&(t=sanitizeInput(t),a=sanitizeInput(a));var r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),c=document.getElementById("mktShipping").checked,l=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1||o>1e11)showToast("Price must be between 1 and 100B sats");else{var d=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anonymous",u="";if(void 0!==currentUser&¤tUser&&"function"==typeof getLevel){var p=getLevel(currentUser.points||0);u=p.emoji+" "+p.name}var g={title:t,description:a,priceSats:o,category:n,condition:i,imageUrl:r||null,lightningAddress:s||null,shipping:c,localPickup:l,sellerUid:auth.currentUser.uid,sellerName:d,sellerRank:u,status:"active",views:0,saves:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()};db.collection("marketplace").add(g).then(function(){window._mktUploadedImage=null;var e=document.getElementById("createListingOverlay");e&&e.remove(),"function"==typeof showToast&&showToast("🛒 Listing posted!"),"function"==typeof awardPoints&&awardPoints(15,"🛒 Marketplace listing!"),auth&&auth.currentUser&&(db.collection("users").doc(auth.currentUser.uid).update({marketListings:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketListings=(currentUser.marketListings||0)+1)),renderMarketplace()}).catch(function(e){console.error("Marketplace post error:",e),showToast("Error posting: "+(e.code||e.message||"Unknown error"))})}}}},window.toggleMarketSave=function(e){var t=safeJSON("btc_market_saved",[]),o=t.indexOf(e);-1!==o?(t.splice(o,1),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(-1)}).catch(function(e){console.error("[marketplace] Error:",e)})):(t.push(e),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})),localStorage.setItem("btc_market_saved",JSON.stringify(t)),void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({marketSaved:t}).catch(function(e){console.error("[marketplace] Error:",e)});var n=document.getElementById("forumContainer");n&&n.innerHTML.includes("marketListings")&&renderMarketplace()},window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return showToast("🔒 Sign in to contact sellers"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var o='
    💬 Message '+escapeHtml(t)+'
    ',n=document.createElement("div");n.innerHTML=o,document.body.appendChild(n.firstChild)},window.sendMarketMessage=function(e){var t=(document.getElementById("mktMessage").value||"").trim();if(t){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Buyer";db.collection("marketplace").doc(e).get().then(function(n){if(n.exists){var i=n.data().sellerUid||"";return db.collection("marketplace_messages").add({listingId:e,buyerUid:auth.currentUser.uid,sellerUid:i,buyerName:o,message:t,createdAt:firebase.firestore.FieldValue.serverTimestamp(),read:!1})}showToast("Listing not found")}).then(function(){var t=document.getElementById("contactSellerOverlay");t&&t.remove(),showToast("💬 Message sent to seller!"),"function"==typeof sendNotification&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists&&t.data().sellerUid){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(t.data().sellerUid,"dm","🛒 "+o+" is interested in your listing!","marketplace",e)}}).catch(function(){}),db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1)}).catch(function(){showToast("Error sending message. Try again.")})}else showToast("Please write a message")},window.showMyListings=function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){e||s("my");var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading your listings...
    ',db.collection("marketplace").where("sellerUid","==",auth.currentUser.uid).orderBy("createdAt","desc").get().then(function(e){var o,n='
    ';n+='',n+='
    📋 My Listings
    ',e.empty?n+='
    No listings yet. Create one!
    ':e.forEach(function(e){var t=e.data(),o="active"===t.status?"#22c55e":"sold"===t.status?"#ef4444":"var(--text-faint)";n+='
    '+escapeHtml(t.title)+'
    ⚡ '+(t.priceSats||0).toLocaleString()+' sats
    👁️ '+(t.views||0)+" views · ❤️ "+(t.saves||0)+' saves
    '+(t.status||"active")+""+("active"===t.status?"':"")+"
    "}),n+='
    💬 Messages
    ',n+='
    Loading messages...
    ',n+="
    ",t.innerHTML=n,(o=document.getElementById("myMarketMessages"))&&db.collection("marketplace_messages").orderBy("createdAt","desc").limit(20).get().then(function(e){var t=auth.currentUser.uid,n=[];e.forEach(function(e){var o=e.data();o.buyerUid===t&&n.push({id:e.id,...o,role:"buyer"})}),db.collection("marketplace").where("sellerUid","==",t).get().then(function(i){var a=[];i.forEach(function(e){a.push(e.id)}),e.forEach(function(e){var o=e.data();-1!==a.indexOf(o.listingId)&&o.buyerUid!==t&&n.push({id:e.id,...o,role:"seller"})}),0!==n.length?o.innerHTML=n.map(function(e){var t=e.createdAt?g(e.createdAt.toDate()):"";return'
    '+("seller"===e.role?"📩 From ":"📤 To seller · ")+escapeHtml(e.buyerName||"Buyer")+''+t+'
    '+escapeHtml(e.message)+"
    "}).join(""):o.innerHTML='
    No messages yet.
    '})})}).catch(function(e){console.error("My listings error:",e),"failed-precondition"===e.code?t.innerHTML='
    ⚙️ Setting up marketplace database (index)...
    Please refresh in 1 minute.
    ':t.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+"
    "}))}else showToast("🔒 Sign in to see your listings")},window.markSold=function(e){db.collection("marketplace").doc(e).update({status:"sold"}).then(function(){showToast("✅ Marked as sold!"),showMyListings()})},window.editListing=function(e){auth&&auth.currentUser&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists){var n=t.data();n.sellerUid===auth.currentUser.uid||o()?(showCreateListing(),setTimeout(function(){var t=document.getElementById("mktTitle"),o=document.getElementById("mktPrice"),i=document.getElementById("mktCategory"),a=document.getElementById("mktCondition"),r=document.getElementById("mktDesc"),s=document.getElementById("mktImage"),c=document.getElementById("mktLightning"),l=document.getElementById("mktShipping"),d=document.getElementById("mktLocal");t&&(t.value=n.title||""),o&&(o.value=n.priceSats||"",updateMktPriceUSD()),i&&(i.value=n.category||""),a&&(a.value=n.condition||""),r&&(r.value=n.description||""),s&&n.imageUrl&&!n.imageUrl.startsWith("data:")&&(s.value=n.imageUrl||""),c&&(c.value=n.lightningAddress||""),l&&(l.checked=!!n.shipping),d&&(d.checked=!!n.local);var u=document.getElementById("createListingOverlay");if(u){var p=u.querySelector('div[style*="font-size:1.2rem"]');p&&(p.textContent="✏️ Edit Listing")}var m=u?u.querySelector('button[onclick*="submitListing"]'):null;m&&(m.textContent="✏️ Update Listing",m.onclick=function(){updateExistingListing(e)})},100)):showToast("You can only edit your own listings")}else showToast("Listing not found")}).catch(function(e){showToast("Error loading listing: "+(e.message||"Unknown"))})},window.updateExistingListing=function(e){var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim(),r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),c=document.getElementById("mktShipping").checked,l=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1)showToast("Please enter a price in sats");else{var d={title:t.substring(0,80),priceSats:o,category:n,condition:i,description:a.substring(0,1e3),lightningAddress:s,shipping:c,local:l,updatedAt:firebase.firestore.FieldValue.serverTimestamp()};r&&(d.imageUrl=r),db.collection("marketplace").doc(e).update(d).then(function(){var t=document.getElementById("createListingOverlay");t&&t.remove(),showToast("✅ Listing updated!"),window._mktUploadedImage=null,renderMarketplace({listingId:e})}).catch(function(e){showToast("Error updating: "+(e.message||"Unknown"))})}},window.deleteListing=function(e){if(auth&&auth.currentUser){var t=o();confirm(t?"Admin: Delete this listing?":"Delete this listing?")&&db.collection("marketplace").doc(e).update({status:"deleted",deletedBy:t?"admin":"owner",deletedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){showToast("🗑️ Listing deleted"),renderMarketplace()})}},window.updateMktPriceUSD=function(){var e=parseInt(document.getElementById("mktPrice").value)||0,t=document.getElementById("mktPriceUSD");if(t)if(e<=0)t.textContent="";else{var o=parseFloat(localStorage.getItem("btc_last_price")||"0");if(o<=0)return fetch("https://mempool.space/api/v1/prices").then(function(e){return e.json()}).then(function(e){e&&e.USD&&(localStorage.setItem("btc_last_price",e.USD),updateMktPriceUSD())}).catch(function(e){console.error("[marketplace] Error:",e)}),void(t.textContent="Loading USD price...");var n=e/1e8*o;t.textContent="≈ $"+n.toFixed(2)+" USD"}},window.satsToUSD=function(e){var t=parseFloat(localStorage.getItem("btc_last_price")||"0");return t<=0||!e?"":"~$"+(e/1e8*t).toFixed(2)},window.handleMktImageUpload=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var o=new FileReader;o.onload=function(e){var t=new Image;t.onload=function(){var e=t.width,o=t.height;e>800&&(o=Math.round(800*o/e),e=800);var n=document.createElement("canvas");n.width=e,n.height=o,n.getContext("2d").drawImage(t,0,0,e,o);var i=n.toDataURL("image/jpeg",.8),a=document.getElementById("mktImagePreview"),r=document.getElementById("mktImagePreviewImg");a&&r&&(r.src=i,a.style.display="block"),window._mktUploadedImage=i;var s=document.getElementById("mktImage");s&&(s.value="")},t.src=e.target.result},o.readAsDataURL(t)}},window._plebShopOpen=!1,window._togglePlebShop=function(){var e=document.getElementById("plebShopEmbed"),t=document.getElementById("plebShopToggle");e&&(window._plebShopOpen=!window._plebShopOpen,window._plebShopOpen?(e.style.display="block",e.style.height="calc(100vh - 280px)",e.style.minHeight="500px",e.querySelector("iframe")||(e.innerHTML=''),t&&(t.textContent="Close Shop",t.style.background="var(--border)")):(e.style.height="0",e.style.minHeight="0",setTimeout(function(){e.style.display="none"},300),t&&(t.textContent="Open Shop",t.style.background="var(--accent)")))},window.clearMktImage=function(){window._mktUploadedImage=null;var e=document.getElementById("mktImagePreview");e&&(e.style.display="none");var t=document.getElementById("mktImageFile");t&&(t.value="")}}();var MSG_CONFIG={onlineThreshold:3e5,awayThreshold:9e5,presenceInterval:6e4,maxMsgLength:500,maxMsgsPerHour:30,maxConvoHistory:100,unreadPollInterval:3e4,maxNewConvosPerDay:5,newAccountCooldownMs:864e5,minPointsToDM:50,duplicateWindowMs:5e3},SUSPICIOUS_PATTERNS=[/send\s*(?:me|ur|your)\s*(?:btc|bitcoin|sats|seed|key|phrase)/i,/(?:double|triple|multiply)\s*(?:your|ur)\s*(?:btc|bitcoin|sats|crypto)/i,/(?:free|win|won|claim|airdrop)\s*(?:btc|bitcoin|sats|crypto|nft)/i,/(?:invest|deposit)\s*(?:now|today|here)\b/i,/(?:guaranteed|100%)\s*(?:return|profit|roi)/i,/send\s*\d+\s*(?:btc|sats)\s*(?:to|and)\s*(?:get|receive|earn)/i,/(?:seed|private)\s*(?:phrase|key)\s*(?:here|now|please|share)/i,/(?:validate|verify|sync)\s*(?:your|ur)\s*(?:wallet|account)/i,/(?:connect|link)\s*(?:your|ur)\s*(?:wallet|metamask|phantom)/i,/(?:nigerian|prince|inheritance|lottery)\s*(?:fund|money|payment)/i],SUSPICIOUS_URLS=[/bit\.ly|tinyurl|t\.co|goo\.gl|is\.gd|buff\.ly|ow\.ly|rebrand\.ly/i,/(?:discord\.gift|discordapp\.gift|nitro.*free)/i,/(?:steamcommunity|steampowered).*(?:gift|trade|login)/i,/(?:wallet|connect|validate|sync|claim|airdrop).*(?:\.com|\.io|\.xyz|\.site|\.app)/i,/(?:dapp|defi|swap|bridge|mint).*(?:\.com|\.io|\.xyz|\.site)/i],BLOCKED_CONTENT=[/(?:child|minor|underage).*(?:porn|nude|nsfw)/i,/(?:kill|murder|attack|bomb|shoot).*(?:yourself|someone|them|people|school)/i,/\b(?:doxx|doxing|swat)\b/i,/\b(?:nigger|nigga|faggot|kike|spic|wetback|chink|gook|towelhead|raghead|beaner|coon|darkie|zipperhead)\b/i,/\b(?:white\s*power|white\s*supremacy|sieg\s*heil|race\s*war|ethnic\s*cleansing|final\s*solution)\b/i,/\b(?:gas\s*the|death\s*to)\s+\w+/i,/\b(?:heil\s*hitler|genocide)\b/i,/\b(?:i\s*(?:will|wanna|gonna|want\s*to)\s*(?:kill|hurt|stab|shoot|beat|attack|find)\s*(?:you|u|him|her|them))\b/i,/\b(?:i\s*know\s*where\s*(?:you|u)\s*live)\b/i,/\b(?:watch\s*your\s*back|you(?:'re|\s*are)\s*dead)\b/i,/\b(?:track\s*(?:you|u)\s*down|come\s*find\s*(?:you|u))\b/i,/\b(?:kill\s*myself|cut(?:ting)?\s*myself|slit\s*my\s*wrist|hang\s*myself|end\s*my\s*life)\b/i,/\b(?:want(?:a)?\s*(?:to\s*)?die|kys|kill\s*yourself)\b/i,/\b(?:self[\s-]*harm|overdose\s*on|jump\s*off\s*a)\b/i,/\b(?:blowjob|handjob|gangbang|threesome|deepthroat|rimjob|creampie)\b/i,/\b(?:send\s*(?:me\s*)?nudes|dick\s*pic|show\s*(?:me\s*)?(?:your|ur)\s*(?:body|tits|boobs|ass|pussy|dick))\b/i,/\b(?:wanna|want\s*to|lets)\s*(?:fuck|bang|screw|bone|smash)\b/i,/\b(?:suck\s*my|sit\s*on\s*my|bend\s*over|get\s*on\s*your\s*knees)\b/i,/\b(?:masturbat|fingering|bondage|bdsm|fetish|dominatrix)\b/i,/\b(?:escort|prostitut|hooker|camgirl|sexting)\b/i],PII_PATTERNS=[/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:phone|number|address|email|ssn|social|zip|location|real name|full name|home|where.*live)/i,/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:id|passport|driver.?s?\s*license|bank|routing|account\s*number|credit\s*card|debit\s*card)/i,/(?:dm|message|text|call|contact)\s*(?:me\s+)?(?:on|at|@)\s*(?:whatsapp|telegram|signal|insta|instagram|snap|snapchat|facebook|messenger|wechat|line)\b/i,/(?:my|here(?:'s| is))\s*(?:phone|number|cell|whatsapp|telegram|signal)\s*(?:is|:|\s)\s*[\+\d\(\)\-\s]{7,}/i,/(?:my|here(?:'s| is))\s*(?:email|e-mail)\s*(?:is|:|\s)\s*\S+@\S+\.\S+/i,/(?:my|here(?:'s| is))\s*(?:address|location)\s*(?:is|:)/i];function containsSuspiciousLink(e){for(var t=e.match(/https?:\/\/[^\s<>"{}|\\^`\[\]]+/gi)||[],o=0;o]*>/g,"")).trim()).length>MSG_CONFIG.maxMsgLength&&(e=e.substring(0,MSG_CONFIG.maxMsgLength)),e):""}function containsPII(e){for(var t=0;t"']+)/gi,function(e){return''+e+""})}function _getDailyConvoLog(){try{var e=localStorage.getItem("btc_dm_daily_log");if(!e)return{date:"",recipients:[]};var t=JSON.parse(e),o=(new Date).toISOString().slice(0,10);return t.date!==o?{date:o,recipients:[]}:t}catch(e){return{date:(new Date).toISOString().slice(0,10),recipients:[]}}}function _logNewConvo(e){var t=_getDailyConvoLog();t.date=(new Date).toISOString().slice(0,10),-1===t.recipients.indexOf(e)&&t.recipients.push(e),localStorage.setItem("btc_dm_daily_log",JSON.stringify(t))}function _canStartNewConvo(e){var t=_getDailyConvoLog();return-1!==t.recipients.indexOf(e)||t.recipients.length
    🚨
    "Friends in Distress" Scam
    Scammers will impersonate people you know and trust — your friends, family, even coworkers. They can:
    • Clone their profile picture, name, and bio
    • Copy their writing style and messages
    • Use AI-generated voice clones that sound exactly like them
    • Create fake emergencies — "I\'m stuck," "I need help," "send me Bitcoin and I\'ll pay you back"
    The scammer will pressure you to act fast so you don\'t have time to think or verify. They prey on your emotions and trust.
    🛡️ How to protect yourself:
    NEVER send Bitcoin to anyone claiming to be in distress over a message
    Verify their identity through a separate channel — call them, video chat, or meet in person
    Real friends will understand if you take time to verify
    Bitcoin transactions are irreversible — once sent, it\'s gone forever
    • If it feels urgent and emotional, that\'s exactly what the scammer wants
    ',document.body.appendChild(e.firstChild)};var _lastSentMsg={text:"",time:0};function _isDuplicateMessage(e){var t=Date.now();return e===_lastSentMsg.text&&t-_lastSentMsg.time
    Why are you reporting this user?
    ',i=document.createElement("div");return i.innerHTML=n,void document.body.appendChild(i.firstChild)}},window.submitReport=function(e,t,o){var n=document.getElementById("reportModal");if(n&&n.remove(),db&&auth&&auth.currentUser){var i=void 0!==currentUser&¤tUser?currentUser.username:"Anonymous";db.collection("reports").add({reportedUid:e,reportedName:t,reporterUid:auth.currentUser.uid,reporterName:i,reason:o,createdAt:firebase.firestore.FieldValue.serverTimestamp(),status:"pending"}).then(function(){"function"==typeof showToast&&showToast("🚩 Report submitted. Thank you for keeping the community safe."),blockUser(e,t)}).catch(function(){"function"==typeof showToast&&showToast("Failed to submit report")})}};var _presenceTimer=null;function updatePresence(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e="false"!==localStorage.getItem("btc_online_status");try{e?db.collection("users").doc(auth.currentUser.uid).update({lastSeen:firebase.firestore.FieldValue.serverTimestamp(),isOnline:!0}).catch(function(){}):db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:null}).catch(function(){})}catch(e){}}}function startPresenceTracking(){updatePresence(),_presenceTimer&&clearInterval(_presenceTimer),_presenceTimer=setInterval(updatePresence,MSG_CONFIG.presenceInterval),window.addEventListener("beforeunload",function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db)try{db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){}}),document.addEventListener("visibilitychange",function(){"visible"===document.visibilityState&&updatePresence()})}function profileStat(e,t,o){return'
    '+e+'
    '+t+'
    '+o+"
    "}window.toggleOnlineStatus=function(){updatePresence()},window.getOnlineStatus=function(e){if(!e)return{status:"offline",color:"#6b7280",label:"Offline",dot:"⚫"};var t=e.toDate?e.toDate().getTime():"number"==typeof e?e:new Date(e).getTime(),o=Date.now()-t;return o'},window.showUserProfile=function(e){if(e&&db){var t=document.createElement("div");t.innerHTML='
    Loading profile...
    ',document.body.appendChild(t.firstChild),db.collection("users").doc(e).get().then(function(t){if(!t.exists)return(m=document.getElementById("userProfileModal"))&&m.remove(),void("function"==typeof showToast&&showToast("User not found"));var o=t.data(),n=getOnlineStatus(o.lastSeen),i="function"==typeof getLevel?getLevel(o.points||0):{name:"Newbie",emoji:"🌱"},a=o.createdAt&&o.createdAt.toDate?o.createdAt.toDate().toLocaleDateString():"Unknown",r="function"==typeof escapeHtml?escapeHtml(o.displayBadge||o.equippedBadge||""):(o.displayBadge||o.equippedBadge||"").replace(//g,">").replace(/"/g,"""),s=0;o.visibleBadges&&(s+=o.visibleBadges.length),o.hiddenBadges&&(s+=o.hiddenBadges.length);var c="";if(r){var l=r;if(void 0!==HIDDEN_BADGES&&r.length>5){var d=HIDDEN_BADGES.find(e=>e.id===r);d&&(l=d.emoji)}c='
    '+l+' '+i.emoji+"
    "}else c='
    '+i.emoji+"
    ";var u,p,m,g=auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&auth.currentUser.uid!==e,h=g?_canAccountDM():{ok:!1},f='
    '+c+'
    '+escapeHtml(o.username||"Bitcoiner")+'
    '+i.name+" · "+(o.points||0).toLocaleString()+' XP
    '+n.label+"
    "+(o.bio?'
    About
    '+escapeHtml(o.bio)+"
    ":"")+(o.twitter||o.nostr||o.website?'
    '+(o.twitter?'𝕏 '+escapeHtml(o.twitter)+"":"")+(o.nostr?'🟣 Nostr':"")+(o.website&&!/^(javascript|data|vbscript|blob):/i.test(o.website.trim())?'🌐 Website':"")+"
    ":"")+'
    '+profileStat("🏅",s,"Badges")+profileStat("📖",Array.isArray(o.visitedChannelsList)?o.visitedChannelsList.length:Array.isArray(o.readChannels)?o.readChannels.length:0,"Channels")+profileStat("🎟️",o.orangeTickets||0,"Tickets")+'
    '+profileStat("🗣️",o.forumPosts||0,"Posts")+profileStat("🔥",(o.streak||0)+"("+(o.bestStreak||o.streak||0)+")","Streak")+profileStat("📅",a,"Joined")+"
    "+(o.pvpWins||o.pvpLosses?'
    '+profileStat("⚔️",(o.pvpWins||0)+"W","PVP Wins")+profileStat("💀",(o.pvpLosses||0)+"L","PVP Losses")+profileStat("📊",((o.pvpWins||0)+(o.pvpLosses||0)>0?Math.round((o.pvpWins||0)/((o.pvpWins||0)+(o.pvpLosses||0))*100):0)+"%","Win Rate")+"
    ":"")+(o.predictions&&o.predictions.total?(p=(u=o.predictions).total>0?Math.round(u.correct/u.total*100):0,'
    '+profileStat("📈",u.total,"Predictions")+profileStat("🎯",p+"%","Accuracy")+profileStat("🔥",u.bestStreak||u.streak||0,"Best Streak")+"
    "):"")+(o.lightningAddress||o.lightning?(window._profileTipData={recipientName:o.username||"Bitcoiner",recipientUid:e,lightningAddress:o.lightningAddress||o.lightning||"",label:"Tip "+(o.username||"Bitcoiner"),context:"profile"},'
    '+escapeHtml(o.lightningAddress||o.lightning)+'
    "):"")+(g&&h.ok?"":g&&!h.ok?'
    '+escapeHtml(h.reason)+"
    ":auth&&auth.currentUser&&!auth.currentUser.isAnonymous?"":"")+(g?'
    '+(isUserBlocked(e)?"":"")+"
    ':"")+"
    ";(m=document.getElementById("userProfileModal"))&&m.remove();var y=document.createElement("div");y.innerHTML=f,document.body.appendChild(y.firstChild)}).catch(function(t){console.error("Profile load error:",t);var o=document.getElementById("userProfileModal");o&&o.remove(),"function"==typeof showToast&&showToast("Could not load profile ["+e+"]: "+(t.message||"permission error"))})}},window._tipFromProfile=function(){var e=window._profileTipData;if(e){var t=document.getElementById("userProfileModal");t&&t.remove(),"function"==typeof showTipOverlay?showTipOverlay(e):"function"==typeof showToast&&showToast("⚡ Lightning tips still loading, try again in a moment")}};var _msgSentTimestamps=[];function checkRateLimit(){var e=Date.now();return(_msgSentTimestamps=_msgSentTimestamps.filter(function(t){return e-t<36e5})).length
    💬 '+escapeHtml(o)+'
    ⚠️ Never share your seed phrase, private keys, or send Bitcoin to strangers or "friends in distress."
    ',s=document.createElement("div");s.innerHTML=r,document.body.appendChild(s.firstChild),setTimeout(function(){var e=document.getElementById("dmInput");e&&e.focus()},300),loadDMMessages(e,n,t,o),db.collection("dm_conversations").doc(e).get().then(function(e){if(e.exists&&e.data().isBuddyMatch){var t=document.getElementById("dmWindow");if(!t)return;var o=t.querySelector('div[style*="rgba(234,179,8,0.1)"]');o&&(o.style.background="rgba(34,197,94,0.08)",o.style.borderColor="rgba(34,197,94,0.2)",o.style.color="#22c55e",o.innerHTML="🦌 Nacho is in this chat! Ask any Bitcoin question and Nacho will jump in. Teachers can add context to help learners.")}}).catch(function(){}),db.collection("users").doc(t).get().then(function(e){if(e.exists){var t=getOnlineStatus(e.data().lastSeen),o=document.getElementById("dmStatusDot");o&&(o.innerHTML='')}}).catch(function(){})}function loadDMMessages(e,t,o,n){var i=document.getElementById("dmMessages");i&&(i.innerHTML='
    Loading messages...
    ',window._dmUnsubscribe=db.collection("dm_conversations").doc(e).collection("messages").orderBy("createdAt","asc").limit(MSG_CONFIG.maxConvoHistory).onSnapshot(function(o){if(i.innerHTML="",o.empty)i.innerHTML='
    💬
    Start a conversation with '+escapeHtml(n)+'!
    Messages are private between you two.
    ';else{var a="";o.forEach(function(e){var o=e.data(),n=o.senderUid===t;if(n||o.isNachoAuto||"function"!=typeof isUserBlocked||!isUserBlocked(o.senderUid)){var r=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):new Date,s=r.toLocaleDateString();s!==a&&(i.innerHTML+='
    '+s+"
    ",a=s);var c=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),l="nacho-bot"===o.senderUid||!0===o.isNachoAuto,d=n||l||!containsScamPattern(o.text)&&!containsSuspiciousLink(o.text)?"":'
    ⚠️ This message may contain a scam. Never send money to strangers.
    ',u=n||l||!containsPII(o.text)?"":'
    ⚠️ This person is asking for personal info. Only share details for Lightning Mart transactions.
    ',p=l?"rgba(34,197,94,0.08)":n?"var(--accent)":"var(--card-bg)",m=l?"1px solid rgba(34,197,94,0.25)":"none",g=l?"var(--text)":n?"#fff":"var(--text)",h=l?'
    🦌 Nacho
    ':"",f=linkifyText(escapeHtml(o.text)).replace(/\n/g,"
    "),y="";o.imageUrl&&(y=''),i.innerHTML+='
    '+h+(f||"")+y+d+u+'
    '+c+"
    "}}),i.scrollTop=i.scrollHeight,markDMRead(e,t)}},function(e){i.innerHTML='
    💬
    Start a conversation!
    Send your first message below.
    '}))}window.openDM=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to send messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var o=_canAccountDM();if(o.ok)if(isUserBlocked(e))"function"==typeof showToast&&showToast("🚫 This user is blocked. Unblock them to message.");else if(_canStartNewConvo(e)){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";showDMWindow(getConversationId(n,e),e,t,n,i)}else"function"==typeof showToast&&showToast("⏳ You can only message "+MSG_CONFIG.maxNewConvosPerDay+" new people per day. This helps keep the community safe.");else"function"==typeof showToast&&showToast(o.reason)},window.closeDM=function(){window._dmUnsubscribe&&(window._dmUnsubscribe(),window._dmUnsubscribe=null);var e=document.getElementById("dmWindow");e&&e.remove()},window.handleDMImage=function(e,t,o,n){if(e&&e.files&&e.files[0]){var i=e.files[0];if(e.value="",i.type.startsWith("image/"))if(i.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var a=null;try{a=firebase.storage()}catch(e){}if(a){"function"==typeof showToast&&showToast("📷 Uploading image…");var r=auth.currentUser.uid,s=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",c=i.type.indexOf("png")>-1?"png":i.type.indexOf("gif")>-1?"gif":i.type.indexOf("webp")>-1?"webp":"jpg",l=Date.now()+"_"+Math.random().toString(36).substr(2,6)+"."+c,d=a.ref("dm-images/"+r+"/"+l),u=document.getElementById("dmMessages");u&&(u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML=""),(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),u.innerHTML+='
    📷
    Uploading…
    ',u.scrollTop=u.scrollHeight),d.put(i,{contentType:i.type}).then(function(e){return e.ref.getDownloadURL()}).then(function(e){var i=u&&u.querySelector("[data-dm-img-uploading]");i&&i.remove();var a=db.collection("dm_conversations").doc(t),c={senderUid:r,senderName:s,text:"",imageUrl:e,createdAt:firebase.firestore.FieldValue.serverTimestamp()},l={lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r};return l["unread_"+o]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(o,"dm","📷 Image from @"+s,"dm",t),a.update(l).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[r,o],lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r,participantNames:{}};return t.participantNames[r]=s,t.participantNames[o]=n,t["unread_"+o]=firebase.firestore.FieldValue.increment(1),a.set(t)}throw e}).then(function(){return a.collection("messages").add(c)}).then(function(){"function"==typeof showToast&&showToast("📷 Image sent!"),u&&document.getElementById("dmMessages")&&loadDMMessages(t,r,o,n)})}).catch(function(e){console.error("[DM Image] Upload failed:",e),"function"==typeof showToast&&showToast("Failed to send image: "+(e.message||"upload error"));var t=u&&u.querySelector("[data-dm-img-uploading]");t&&t.remove()})}else"function"==typeof showToast&&showToast("Image upload unavailable")}else"function"==typeof showToast&&showToast("Sign in to send images");else"function"==typeof showToast&&showToast("Only images are allowed")}},window.showDMGifPicker=function(e,t,o){var n=document.getElementById("dmGifPicker");if(n)n.remove();else{var i=document.createElement("div");i.id="dmGifPicker",i.style.cssText="position:fixed;bottom:80px;left:50%;transform:translateX(-50%);z-index:600000;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:16px;padding:12px;width:90%;max-width:360px;max-height:350px;display:flex;flex-direction:column;box-shadow:0 8px 32px rgba(0,0,0,0.5);",window._dmGifConvo={convoId:e,recipientUid:t,recipientName:o},i.innerHTML='
    Type to search or tap a category
    ',document.body.appendChild(i),document.getElementById("dmGifSearchInput").focus()}};var _dmGifSearchTimer=null;function markDMRead(e,t){db.collection("dm_conversations").doc(e).update({["unread_"+t]:0}).catch(function(){})}window.searchDMGifs=function(e){_dmGifSearchTimer&&clearTimeout(_dmGifSearchTimer);var t=document.getElementById("dmGifResults");if(t)if(!e||e.length<2)t.innerHTML='
    Type to search
    ';else{var o=document.getElementById("dmGifSearchInput");o&&o.value!==e&&(o.value=e),t.innerHTML='
    Searching...
    ',_dmGifSearchTimer=setTimeout(function(){fetch("https://g.tenor.com/v1/search?q="+encodeURIComponent(e)+"&key=LIVDSRZULELA&limit=20&media_filter=minimal").then(function(e){return e.json()}).then(function(e){if(e.results&&0!==e.results.length){for(var o="",n=0;n')}t.innerHTML=o||'
    No GIFs found
    '}else t.innerHTML='
    No GIFs found
    '}).catch(function(){t.innerHTML='
    Search failed
    '})},400)}},window.sendDMGifUrl=function(){var e=document.getElementById("dmGifUrlInput");e&&e.value.trim()&&sendDMGif(e.value.trim())},window.sendDMGif=function(e){if(e){var t=window._dmGifConvo;if(t){var o=document.getElementById("dmGifPicker");if(o&&o.remove(),auth&&auth.currentUser){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",a=t.convoId,r=t.recipientUid,s=t.recipientName,c=document.getElementById("dmMessages");if(c){var l=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});c.innerHTML+='
    '+l+"
    ",c.scrollTop=c.scrollHeight}var d=db.collection("dm_conversations").doc(a),u={senderUid:n,senderName:i,text:"",imageUrl:e,isGif:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp()},p={lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n};p["unread_"+r]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(r,"dm","GIF from @"+i,"dm",a),d.update(p).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[n,r],lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n,participantNames:{}};return t.participantNames[n]=i,t.participantNames[r]=s,t["unread_"+r]=firebase.firestore.FieldValue.increment(1),d.set(t)}throw e}).then(function(){return d.collection("messages").add(u)}).then(function(){c&&document.getElementById("dmMessages")&&loadDMMessages(a,n,r,s)}).catch(function(e){console.error("[DM GIF] Send failed:",e),"function"==typeof showToast&&showToast("Failed to send GIF")})}else"function"==typeof showToast&&showToast("Sign in to send GIFs")}else"function"==typeof showToast&&showToast("Error: no conversation context")}},window.sendDM=function(e,t,o){var n=document.getElementById("dmInput");if(n){var i=sanitizeMessage(n.value);if(i)if(i.length>MSG_CONFIG.maxMsgLength)"function"==typeof showToast&&showToast("Message too long (max "+MSG_CONFIG.maxMsgLength+" chars)");else if(_isDuplicateMessage(i))"function"==typeof showToast&&showToast("⏳ Message already sent");else if(isUserBlocked(t))"function"==typeof showToast&&showToast("🚫 You have blocked this user");else if(containsBlockedContent(i))"function"==typeof showToast&&showToast("⛔ Message contains prohibited content");else{if(containsPII(i)&&!confirm("⚠️ This message appears to contain or request personal information (phone numbers, addresses, emails, etc.).\n\nSharing personal info with strangers is risky. Only share contact details for Lightning Mart transactions.\n\nSend anyway?"))return;if(!containsScamPattern(i)||confirm("⚠️ This message contains patterns commonly used in scams. Are you sure you want to send it?"))if(containsSuspiciousLink(i)&&"function"==typeof showToast&&showToast("⚠️ Warning: Suspicious link detected. Be cautious with URLs."),checkRateLimit()){var a=auth.currentUser.uid,r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";n.value="",_msgSentTimestamps.push(Date.now()),_logNewConvo(t);var s=db.collection("dm_conversations").doc(e),c={senderUid:a,senderName:r,text:i,createdAt:firebase.firestore.FieldValue.serverTimestamp()},l={lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a};l["unread_"+t]=firebase.firestore.FieldValue.increment(1);var d={participants:[a,t],lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a,participantNames:{}};d.participantNames[a]=r,d.participantNames[t]=o,d["unread_"+t]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(t,"dm","💬 New message from @"+r,"dm",e);var u=document.getElementById("dmMessages");if(u){u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML="");var p=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),m=(new Date).toLocaleDateString(),g=u.querySelector("div[data-dm-date]:last-of-type");m!==(g?g.getAttribute("data-dm-date"):"")&&(u.innerHTML+='
    '+m+"
    "),u.innerHTML+='
    '+linkifyText(escapeHtml(i))+'
    '+p+"
    ",u.scrollTop=u.scrollHeight}s.update(l).catch(function(e){if("not-found"===e.code||"permission-denied"===e.code||-1!==e.message.indexOf("NOT_FOUND")||-1!==e.message.indexOf("No document to update")||-1!==e.message.indexOf("PERMISSION_DENIED"))return s.set(d,{merge:!0});throw e}).then(function(){return s.collection("messages").add(c)}).then(function(){u&&document.getElementById("dmMessages")&&loadDMMessages(e,a,t,o);var n=parseInt(localStorage.getItem("btc_dms_sent")||"0");localStorage.setItem("btc_dms_sent",String(n+1)),"function"==typeof checkBadges&&setTimeout(checkBadges,500)}).catch(function(e){console.error("DM send error:",e),"function"==typeof showToast&&showToast("Failed to send: "+(e.code||e.message||"Unknown error"));var t=u&&u.querySelector("[data-optimistic]");t&&t.remove()})}else"function"==typeof showToast&&showToast("⏳ Slow down! Max "+MSG_CONFIG.maxMsgsPerHour+" messages per hour.")}}},window.showInbox=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to see messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e=auth.currentUser.uid,t=document.getElementById("dmInbox");t&&t.remove();var o=document.createElement("div");o.innerHTML='
    📬 Messages
    Loading...
    ',document.body.appendChild(o.firstChild),db.collection("dm_conversations").where("participants","array-contains",e).orderBy("lastMessageTime","desc").limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");o&&(console.log("Inbox snap size:",t.size),t.empty?o.innerHTML='
    📬
    No messages yet
    Tap a user on the leaderboard to start chatting!
    ':(o.innerHTML="",t.forEach(function(t){var n=t.data(),i=n.participants.find(function(t){return t!==e}),a=n.participantNames&&n.participantNames[i]||"User",r=n["unread_"+e]||0,s=n.lastMessage||"";s.length>50&&(s=s.substring(0,50)+"...");var c=n.lastMessageTime?timeAgo(n.lastMessageTime):"",l=n.lastSenderUid===e,d=!0===n.isBuddyMatch,u=d?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+';" onmouseover="this.style.background=\'var(--card-bg)\'" onmouseout="this.style.background=\''+(r>0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+'\'">
    '+(d?"🦌":a.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(a)+u+'
    '+c+'
    0?"600":"400")+';white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">'+(l?"You: ":"")+escapeHtml(s)+"
    "+(r>0?'
    '+r+"
    ":"")+"
    "})))}).catch(function(t){console.error("Inbox load error:",t);var o=document.getElementById("dmInboxList");o&&("failed-precondition"!==t.code?o.innerHTML='
    💬
    No messages yet
    Tap a user on the leaderboard or in PlebTalk to start chatting!
    ':db.collection("dm_conversations").where("participants","array-contains",e).limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");if(o)if(t.empty)o.innerHTML='
    📬
    No messages yet
    ';else{o.innerHTML="";var n=[];t.forEach(function(e){n.push({id:e.id,...e.data()})}),n.sort(function(e,t){return(t.lastMessageTime||0)-(e.lastMessageTime||0)}),n.forEach(function(t){var n=t.participants.find(function(t){return t!==e}),i=t.participantNames&&t.participantNames[n]||"User",a=t["unread_"+e]||0,r=t.lastMessage||"";r.length>50&&(r=r.substring(0,50)+"...");var s=t.lastSenderUid===e,c=!0===t.isBuddyMatch,l=c?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":c?"rgba(34,197,94,0.03)":"none")+';">
    '+(c?"🦌":i.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(i)+l+'
    '+(s?"You: ":"")+escapeHtml(r)+"
    "+(a>0?'
    '+a+"
    ":"")+"
    "})}}).catch(function(e){var t=document.getElementById("dmInboxList");t&&(t.innerHTML='
    💬
    No messages yet
    ')}))})};var _unreadCount=0,_unreadTimer=null;function checkUnreadCount(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e=auth.currentUser.uid;db.collection("dm_conversations").where("participants","array-contains",e).get().then(function(t){var o=0;t.forEach(function(t){var n=t.data();o+=n["unread_"+e]||0}),_unreadCount=o,updateUnreadBadge()}).catch(function(){})}}function updateUnreadBadge(){document.querySelectorAll(".dm-unread-badge").forEach(function(e){_unreadCount>0?(e.textContent=_unreadCount>99?"99+":_unreadCount,e.style.display="inline-flex"):e.style.display="none"});var e=document.getElementById("bnavMsgBadge");e&&(_unreadCount>0?(e.textContent=_unreadCount,e.style.display="block"):e.style.display="none")}function startUnreadPolling(){checkUnreadCount(),_unreadTimer&&clearInterval(_unreadTimer),_unreadTimer=setInterval(checkUnreadCount,MSG_CONFIG.unreadPollInterval)}window.initMessaging=function(){startPresenceTracking(),restoreBlockedList(),setTimeout(startUnreadPolling,5e3)},void 0!==auth&&auth&&auth.currentUser&&initMessaging();const HIDDEN_BADGES=[{id:"nacho_friend",name:"Nacho's Friend",emoji:"🦌",pts:25,desc:"Interact with Nacho",hint:"Click on Nacho!",hidden:!1,check:function(){return"true"===localStorage.getItem("btc_nacho_clicked")}},{id:"genesis",name:"Genesis Reader",emoji:"📜",pts:75,desc:"Read the whitepaper channel",hint:"Open the Whitepaper channel",hidden:!1,check:function(){return"undefined"!=typeof currentChannelId&&"whitepaper"===currentChannelId}},{id:"nacho_curious",name:"Curious Deer",emoji:"❓",pts:50,desc:"Ask Nacho your first question",hint:"Ask Nacho anything!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=1}},{id:"ticket_bronze",name:"Ticket Fish",emoji:"🐟",pts:200,desc:"Earn 25 Orange Tickets",hint:"Spin daily + referrals!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=25},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,25)+"/25":"0/25"}},{id:"ticket_silver",name:"Ticket Shark",emoji:"🦈",pts:500,desc:"Earn 50 Orange Tickets",hint:"Keep spinning & referring!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=50},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,50)+"/50":"0/50"}},{id:"ticket_gold",name:"Ticket Whale",emoji:"🐋",pts:1e3,desc:"Earn 100 Orange Tickets",hint:"The ultimate ticket badge!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=100},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,100)+"/100":"0/100"}},{id:"nacho_10q",name:"Inquisitive Buck",emoji:"🔍",pts:200,desc:"Ask Nacho 10 questions",hint:"Keep asking Nacho!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=10},progress:function(){return Math.min(parseInt(localStorage.getItem("btc_nacho_questions")||"0"),10)+"/10"}},{id:"collector",name:"Collector",emoji:"💎",pts:150,desc:"Save 10+ topics to favorites",hint:"Star your favorite topics",hidden:!1,check:function(){return safeJSON("btc_favs",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_favs",[]).length,10)+"/10"}},{id:"first_post",name:"Town Crier",emoji:"📣",pts:100,desc:"Make your first Pleb Talk post",hint:"Post in PlebTalk!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=1||void 0!==currentUser&¤tUser&¤tUser.forumPosts>=1}},{id:"first_reply",name:"Conversationalist",emoji:"💬",pts:75,desc:"Reply to a forum post",hint:"Join a discussion!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.forumReplies>=1}},{id:"market_seller",name:"Merchant",emoji:"🏪",pts:150,desc:"List an item on Lightning Mart",hint:"Sell something for sats on Lightning Mart!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketListings>=1}},{id:"market_buyer",name:"Shopper",emoji:"🛍️",pts:150,desc:"Contact a seller on the marketplace",hint:"Find something to buy!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketMessages>=1}},{id:"donor_100",name:"Giving Pleb",emoji:"🫷",pts:50,desc:"Donate 100 XP for charity",hint:"Donate 100 XP in the Charity tab!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=100},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,100)+"/100"}},{id:"donor_500",name:"Stack Sharer",emoji:"💛",pts:150,desc:"Donate 500 XP for charity",hint:"Keep donating!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=500},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,500)+"/500"}},{id:"donor_1000",name:"Community Builder",emoji:"🧡",pts:300,desc:"Donate 1,000 XP for charity",hint:"A true community builder!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e3)+"/1,000"}},{id:"donor_5000",name:"Archive Patron",emoji:"❤️",pts:1e3,desc:"Donate 5,000 XP for charity",hint:"An archive patron — legendary!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e3)+"/5,000"}},{id:"donor_10000",name:"Sats Saint",emoji:"🔥",pts:2e3,desc:"Donate 10,000 XP for charity",hint:"A sats saint among us!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e4)+"/10,000"}},{id:"donor_25000",name:"Lightning Philanthropist",emoji:"⚡",pts:4e3,desc:"Donate 25,000 XP for charity",hint:"A lightning philanthropist!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=25e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,25e3)+"/25,000"}},{id:"donor_50000",name:"Satoshi's Steward",emoji:"🏆",pts:7500,desc:"Donate 50,000 XP for charity",hint:"Satoshi's Steward — incredible!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e4)+"/50,000"}},{id:"donor_100000",name:"Legend of the Archive",emoji:"👑",pts:15e3,desc:"Donate 100,000 XP for charity",hint:"A true legend of the archive!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e5},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e5)+"/100,000"}},{id:"night_owl",name:"Night Owl",emoji:"🦉",pts:50,desc:"Visit the archive after midnight",hidden:!0,check:function(){return(new Date).getHours()>=0&&(new Date).getHours()<5}},{id:"speed_runner",name:"Speed Runner",emoji:"⚡",pts:100,desc:"Visit 15+ channels in one session",hidden:!0,check:function(){return void 0!==sessionChannels&&sessionChannels.size>=15}},{id:"scholar",name:"Bitcoin Scholar",emoji:"🎓",pts:300,desc:"Pass the Scholar Certification",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_scholar_passed")}},{id:"nacho_20q",name:"20 Questions",emoji:"🏅",pts:500,desc:"Ask Nacho 20 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=20}},{id:"explorer_10",name:"Curious Pleb",emoji:"🗺️",pts:100,desc:"Explore 10 topics",hint:"Keep exploring!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,10)+"/10"}},{id:"explorer_25",name:"Rabbit Holer",emoji:"🐇",pts:250,desc:"Explore 25 topics",hint:"Dive deeper!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=25},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,25)+"/25"}},{id:"explorer_50",name:"Half Stack",emoji:"📚",pts:500,desc:"Explore 50 topics",hint:"Halfway there!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=50},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,50)+"/50"}},{id:"explorer_100",name:"Century Club",emoji:"💯",pts:1e3,desc:"Explore 100 topics",hint:"Almost all of them!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=100},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,100)+"/100"}},{id:"explorer_all",name:"Archive Master",emoji:"👑",pts:2e3,desc:"Explore every single topic",hint:"Visit them all!",hidden:!0,check:function(){return void 0!==CHANNELS&&safeJSON("btc_visited_channels",[]).length>=Object.keys(CHANNELS).length}},{id:"marathon",name:"Marathon Reader",emoji:"🏃",pts:150,desc:"Spent 30+ minutes reading in one session",hidden:!0,check:function(){return Date.now()-(window._sessionStart||Date.now())>18e5}},{id:"early_adopter",name:"Early Adopter",emoji:"🌅",pts:200,desc:"Browsing between 5am and 7am",hidden:!0,check:function(){var e=(new Date).getHours();return e>=5&&e<7}},{id:"weekend_warrior",name:"Weekend Warrior",emoji:"🎉",pts:75,desc:"Learning Bitcoin on a weekend",hidden:!0,check:function(){var e=(new Date).getDay();return 0===e||6===e}},{id:"triple_threat",name:"Triple Threat",emoji:"🎯",pts:300,desc:"Completed a quest, sent a chat message, and read a channel in one session",hidden:!0,check:function(){return"true"===sessionStorage.getItem("btc_quest_done")&&"true"===sessionStorage.getItem("btc_chat_sent")&&void 0!==sessionChannels&&sessionChannels.size>=1}},{id:"nacho_50q",name:"Nacho Sage",emoji:"🧙",pts:500,desc:"Ask Nacho 50 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=50}},{id:"bookmark_collector",name:"Bookmark Hoarder",emoji:"📚",pts:100,desc:"Bookmarked 20+ messages",hidden:!0,check:function(){return safeJSON("btc_bookmarks",[]).length>=20}},{id:"pvp_streak",name:"Undefeated",emoji:"🔱",pts:250,desc:"Won 5 PVP battles in a row",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_pvp_win_streak")||"0")>=5}},{id:"sats_maxed",name:"Faucet King",emoji:"👑",pts:1e3,desc:"Claimed all 10,000 sats from the faucet",hidden:!0,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e4}},{id:"streak_freeze",name:"Ice Shield",emoji:"🧊",pts:50,desc:"Used a streak freeze to save your streak",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_freeze_used")}},{id:"nacho_closet_full",name:"Fashionista",emoji:"👗",pts:200,desc:"Unlocked all Nacho closet items from the spin wheel",hidden:!0,check:function(){return safeJSON("btc_spin_closet_items",[]).length>=10}}];function _syncPredictionToFirestore(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db)return;var t=auth.currentUser.uid;db.collection("users").doc(t).set({predictions:{lastPrediction:{direction:e.direction,price:e.price,time:e.time}}},{merge:!0}).catch(function(){}),db.collection("active_predictions").doc(t).set({uid:t,direction:e.direction,price:e.price,time:e.time,resolved:!1}).catch(function(){})}catch(e){}}function _updatePredictionStats(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db||"undefined"==typeof firebase)return;var t=auth.currentUser.uid,o=firebase.firestore.FieldValue.increment,n=parseInt(localStorage.getItem("btc_predict_streak")||"0"),i=parseInt(localStorage.getItem("btc_predict_best_streak")||"0"),a={"predictions.total":o(1),"predictions.lastResolved":Date.now()};if(e){a["predictions.correct"]=o(1);var r=n+1;a["predictions.streak"]=r,r>i&&(a["predictions.bestStreak"]=r,localStorage.setItem("btc_predict_best_streak",r.toString()))}else a["predictions.streak"]=0;db.collection("users").doc(t).set(a,{merge:!0}).catch(function(){});var s={total:o(1)};e&&(s.correct=o(1)),db.collection("stats").doc("predictions").set(s,{merge:!0}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.predictions||(currentUser.predictions={total:0,correct:0,streak:0,bestStreak:0}),currentUser.predictions.total=(currentUser.predictions.total||0)+1,e?(currentUser.predictions.correct=(currentUser.predictions.correct||0)+1,currentUser.predictions.streak=(currentUser.predictions.streak||0)+1,currentUser.predictions.streak>(currentUser.predictions.bestStreak||0)&&(currentUser.predictions.bestStreak=currentUser.predictions.streak)):currentUser.predictions.streak=0)}catch(e){}}!function(){const e=["🎓 Someone just passed the Bitcoin Basics Certification! Can you?","⚡ A pleb just completed a Lightning Network quest — 50 XP earned!","🗺️ Someone just finished all 10 steps of the Bitcoin Journey!","🎮 A Bitcoiner just aced a quiz in Nacho Mode — 10/10!","📚 A new user just explored their first 3 topics — features unlocking!","🧠 Someone just asked Nacho 100 questions — Bitcoin Scholar status!","🎯 A pleb just scored 5/5 on a Conversation Quest!","📖 Someone just read through the entire Timechain channel!","🔥 A Bitcoiner just hit a 30-day streak! Legendary dedication!","🔥 Someone just started a 7-day streak — can you beat them?","🏆 A pleb just crossed 5,000 XP! Climbing the leaderboard!","⭐ Someone just earned 200 XP in a single session!","🔥 A user just protected their streak with a Freeze Ticket! Smart move.","📈 Someone just jumped 10 spots on the Leaderboard!","🧡 A Bitcoiner just leveled up to Bitcoin Believer!","🏔 Someone just reached Maxi status — top of the mountain!","👑 A pleb just entered the Top 25 on the Leaderboard!","🌱 A brand new user just earned their first 50 XP! Welcome!","🎡 Someone just spun the daily wheel and won 5 Orange Tickets!","🎟️ A pleb just earned bonus tickets from a referral!","🧊 Someone won a Streak Freeze on the daily spin — lucky!","🎡 A Bitcoiner just won a closet item from the spin wheel!","💬 New discussion in PlebTalk: 'Best cold storage for beginners?'","💬 Someone just posted in PlebTalk — join the conversation!","🛒 New listing on LightningMart — check it out!","🤝 A meetup was just created in IRL Sync — find one near you!","💬 A PlebTalk post just got 5 upvotes!","⚡ Someone just tipped a forum post with Lightning!","🦌 Someone just entered Nacho Mode for a 30-minute deep dive!","🎽 A pleb just equipped Diamond Hooves in Nacho's Closet! 💎","🕶️ Someone just unlocked Cool Shades from the spin wheel!","👑 A Bitcoiner just equipped the Royal Crown — looking regal!","🦌 Nacho just helped someone understand seed phrases!","🗺️ Someone just explored their 50th channel — almost full coverage!","🦉 A Night Owl badge was just earned at 2 AM!","🎲 Someone just used Random Channel and discovered 'cypherpunks'!","🎨 A user just browsed the Art Gallery — 200+ Bitcoin artworks!","📡 A Bitcoiner just opted in to The Signal newsletter!","🎉 Over 100 users are learning Bitcoin here right now!","📊 The archive has been visited over 10,000 times this month!","🧡 146 channels of pure Bitcoin education — and growing!","⚡ Over 500 Nacho conversations happened this week!","🏆 The Leaderboard top 10 just shuffled — who's climbing?"];async function t(){const t=safeJSON("btc_visited_channels",[]).length,o=firebase.auth().currentUser&&!firebase.auth().currentUser.isAnonymous;if(t<3&&!o)return;const n=document.getElementById("activity-ticker"),i=document.getElementById("ticker-content");if(n&&i){var a=e.slice();try{var r=firebase.firestore();(await r.collection("forum_posts").orderBy("createdAt","desc").limit(3).get()).forEach(function(e){var t=e.data(),o=t.authorName||"A pleb";a.push("💬 "+o+' just posted in PlebTalk: "'+(t.title||"").substring(0,40)+'..."')});try{(await r.collection("marketplace").where("status","==","active").orderBy("createdAt","desc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🛒 New on LightningMart: "'+(t.title||"Item").substring(0,35)+'" for '+(t.priceSats||t.price||"???")+" sats!")})}catch(e){}try{var s=await r.collection("users").orderBy("points","desc").limit(10).get(),c=[];if(s.forEach(function(e){var t=e.data();t.username&&c.push(t.username)}),c.length>=3){a.push("👑 "+c[0]+" is holding #1 on the Leaderboard! Can you catch them?");var l=c[Math.floor(Math.random()*Math.min(5,c.length))];a.push("📈 "+l+" just climbed the Leaderboard — competition is heating up!")}}catch(e){}try{(await r.collection("irl_events").where("date",">=",(new Date).toISOString()).orderBy("date","asc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🤝 Upcoming meetup: "'+(t.title||"Bitcoin Meetup").substring(0,35)+'" — RSVP in IRL Sync!')})}catch(e){}}catch(e){console.log("Ticker live data skipped:",e)}for(var d=a.length-1;d>0;d--){var u=Math.floor(Math.random()*(d+1)),p=a[d];a[d]=a[u],a[u]=p}n.style.display="flex";var m=0;g(),setInterval(g,12e3)}function g(){i.style.animation="none",i.offsetHeight,i.textContent=a[m],i.style.animation="tickerScroll 12s linear infinite",m=(m+1)%a.length}}const o=document.createElement("style");o.textContent="\n #ticker-content { \n white-space: nowrap !important;\n overflow: visible !important;\n text-overflow: clip !important;\n display: inline-block !important;\n width: auto !important;\n padding-right: 50px;\n }\n @keyframes tickerScroll {\n 0% { transform: translateX(100%); }\n 100% { transform: translateX(-100%); }\n }\n ",document.head.appendChild(o),window.rateChannel=async function(e,t){const o=document.getElementById("sentiment-"+e);if(o){o.innerHTML='
    Thank you! 🦌
    Nacho will use this to organize better content.
    ';try{const o=firebase.firestore();await o.collection("channel_feedback").add({channelId:e,rating:t,uid:firebase.auth().currentUser?firebase.auth().currentUser.uid:"anon",createdAt:firebase.firestore.FieldValue.serverTimestamp()}),"function"==typeof awardPoints&&awardPoints(5,"Feedback bonus")}catch(e){console.log("Feedback save skipped:",e)}}},window.checkNewsletterPrompt=function(){localStorage.getItem("btc_newsletter_prompt_shown")||safeJSON("btc_visited_channels",[]).length>=10&&(function(){const e=document.createElement("div");e.id="newsletterModal",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);z-index:10000;display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(5px);",e.innerHTML='
    📡

    Stay Orange-Pilled

    You\'ve explored 10+ channels! Stay connected with Bitcoin updates and community news.

    📱 Join Telegram Updates📧 Subscribe on Substack
    ',document.body.appendChild(e)}(),localStorage.setItem("btc_newsletter_prompt_shown","true"))},window.optInNewsletter=async function(){const e=document.getElementById("newsletterModal"),t=firebase.auth().currentUser;if(!t||t.isAnonymous)return showToast("Please sign in with email to join the newsletter!"),"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void(e&&e.remove());try{const e=firebase.firestore();await e.collection("users").doc(t.uid).update({newsletterOptIn:!0,newsletterOptInDate:firebase.firestore.FieldValue.serverTimestamp()}),showToast("🎉 Welcome to the Orange Pill newsletter!")}catch(e){console.log("Newsletter opt-in failed:",e)}e&&e.remove()},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){t(),checkNewsletterPrompt()}):(t(),checkNewsletterPrompt())}(),window.showNachoStory=function(e){var t=[{title:"Chapter 1: The Genesis Block",text:"In the beginning, there was nothing but fiat. Nacho was just a young buck growing up in the White Mountains of New Hampshire — the Live Free or Die state. He spent his fawn days splashing in the Pemigewasset River, racing chipmunks through birch groves, and nibbling on leaves of debt from the forest of traditional finance. His mama always said the acorns were getting smaller every year, but nobody could explain why. One cold January day in 2009, a mysterious message appeared carved into a sugar maple: 'Chancellor on brink of second bailout for banks.' Nacho didn't understand it yet, but something had changed forever. A new kind of money had been born — one that no government could print, no bank could freeze, and no deer could counterfeit. It was called Bitcoin."},{title:"Chapter 2: The Pizza That Changed Everything",text:"Nacho heard a rumor from a blue jay passing through Franconia Notch: someone had traded 10,000 bitcoins for two pizzas. 'That's crazy!' he thought, nearly choking on a wild blueberry. But was it? Those pizzas proved Bitcoin had real value — people would actually exchange goods for it. Nacho realized this wasn't just internet magic beans. It was the beginning of price discovery. He thought about all the acorns he'd traded with the squirrels over the years — weren't those his first 'transactions' too? Every great journey starts with a single trade, and Bitcoin's started with pepperoni and cheese."},{title:"Chapter 3: Down the Rabbit Hole",text:"Nacho found a weathered copy of the whitepaper pinned to a bulletin board at a general store in Lincoln, New Hampshire. Only 9 pages, but each one hit different. Peer-to-peer. No trusted third party. Proof of work. 21 million cap. He read it by the light of a campfire near the Kancamagus Highway, the stars of the Granite State blazing overhead. The deeper he went, the more he understood: Bitcoin wasn't just new money. It was a paradigm shift. Sound money that couldn't be debased. A monetary network with no CEO, no headquarters, no off switch. Nacho's antlers tingled — literally. His first set was coming in. He was growing up, and he was becoming a Bitcoiner."},{title:"Chapter 4: HODL Through the Storm",text:"A nor'easter hit New Hampshire that winter, and the price of Bitcoin crashed right along with the temperature. Then crashed again. Nacho watched his sats lose 80% of their dollar value from a snow-covered ridge overlooking the Presidential Range. His forest friends laughed. 'Told you it was a scam!' chirped a skeptical chickadee. But Nacho had done his homework. He understood the halving cycles. He knew that every 210,000 blocks, the new supply gets cut in half. Scarcity + time = value. So Nacho did what legends do: he stood firm in the blizzard and held. Not because he was reckless, but because he understood what he held. The storms always pass. The mountains remain."},{title:"Chapter 5: Not Your Keys, Not Your Cheese",text:"One crisp autumn morning, as the New Hampshire maples blazed orange and gold, Nacho woke up to terrible news. An exchange had been hacked. Billions gone. Friends who kept their bitcoin on the exchange lost everything. A young doe from Vermont had her entire savings wiped out. Nacho felt sick — but also relieved. He'd moved his sats to a hardware wallet weeks ago, buried it in a waterproof case near his favorite granite boulder in the White Mountains. Cold storage. Air-gapped. His keys, his bitcoin. From that day forward, Nacho's motto was clear: 'Not your keys, not your cheese.' 🧀🔑 He even carved it into a birch tree so no deer would forget."},{title:"Chapter 6: The Halving",text:"Every four years, something magical happens — and Nacho had the perfect view from Mount Washington's summit. The block reward — the number of new bitcoins created with each block — gets cut in half. He watched the countdown with a group of bitcoiners who'd hiked up for the occasion, huddled together at 6,288 feet with thermoses of coffee and Lightning-powered phones. From 6.25 BTC to 3.125 BTC per block. Less new supply entering the market. Same or growing demand. The wind howled, but nobody cared. It's not magic; it's math. And it's the most predictable monetary policy in the history of money. Nacho shed a single tear — which immediately froze to his fur."},{title:"Chapter 7: Nacho's Mission",text:"Nacho looked out from his favorite overlook in the White Mountains — the same spot where he'd first read the whitepaper by campfire light. He'd grown from a gangly fawn into a strong buck with a magnificent rack of antlers (seven points, if you're counting). But so many deer — so many people — still didn't understand Bitcoin. They heard 'crypto' and thought of scams, memecoins, and celebrity tokens. But Bitcoin is different. It's the signal in the noise. So Nacho decided to dedicate his life to education, right here from the Live Free or Die state. Not shilling. Not pumping. Teaching. Because the best way to orange-pill someone isn't to tell them to buy — it's to help them understand WHY. And that's why you're here. Welcome to the Archive. 🦌🟠"}],o=(new Date).toISOString().split("T")[0],n=safeJSON("btc_nacho_story_days",[]);(0===n.length||-1===n.indexOf(o))&&(n.push(o),localStorage.setItem("btc_nacho_story_days",JSON.stringify(n)));var i,a=Math.min(n.length,t.length);if(void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryProgress:a,nachoStoryDate:o,nachoStoryDays:n}).catch(function(){})}catch(e){}localStorage.setItem("btc_nacho_story_highest",a.toString()),localStorage.setItem("btc_nacho_story_date",o),"number"==typeof e?(i=Math.min(e,a-1))<0&&(i=0):(i=a-1)<0&&(i=0);var r=t[i],s=document.createElement("div");s.id="nachoStoryOverlay",s.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",s.onclick=function(e){e.target===s&&s.remove()};for(var c='
    ',l=0;l'+(l+1)+"":''}c+="
    ";var u,p=i>0?"':"";u=i+1Next →':i>=t.length-1?'✅ Story Complete!':'🔒 Come back tomorrow!';var m=document.createElement("div");m.style.cssText="background:#1a1a2e;border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:500px;width:100%;margin:40px auto;color:#e2e8f0;font-family:inherit;",m.innerHTML='
    🦌📖
    '+c+'

    '+r.title+'

    '+r.text+'

    📖 Chapter '+(i+1)+" of "+t.length+" · "+a+" unlocked ("+(t.length-a)+' remaining)
    '+p+u+'
    ',s.appendChild(m),document.body.appendChild(s);var g=safeJSON("btc_nacho_story_awarded",[]);if("function"==typeof awardPoints&&-1===g.indexOf(i)){g.push(i),localStorage.setItem("btc_nacho_story_awarded",JSON.stringify(g));var h=i===t.length-1?50:15;awardPoints(h,"📖 Completed Chapter "+(i+1)),"function"==typeof showToast&&showToast("📖 +"+h+" XP — Chapter "+(i+1)+" complete!"),g.length===t.length&&setTimeout(function(){if(awardPoints(100,"📖🎉 Completed Nacho's Story!"),"function"==typeof awardOrangeTickets)awardOrangeTickets(25,"📖 Nacho's Story Complete!");else{var e=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(e+25).toString())}"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound();var t=document.createElement("div");if(t.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",t.onclick=function(){t.style.opacity="0",t.style.transition="opacity 0.4s",setTimeout(function(){t.remove()},400)},t.innerHTML='
    🦌📖🎉
    STORY COMPLETE!
    You\'ve followed Nacho\'s entire Bitcoin journey from the Genesis Block to his mission of education. You\'re officially a Story Master! 🏆
    +100
    BONUS PTS
    +25
    🎟️ TICKETS
    ',document.body.appendChild(t),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryComplete:!0,nachoStoryCompletedAt:(new Date).toISOString()}).catch(function(){})}catch(e){}},800)}},window.showPricePrediction=function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0;if(!e&&"undefined"!=typeof _lastWsPrice&&_lastWsPrice&&(e=_lastWsPrice,localStorage.setItem("btc_last_price",e.toString())),!e&&"undefined"!=typeof _dashData&&_dashData&&_dashData.price&&(e=_dashData.price,localStorage.setItem("btc_last_price",e.toString())),!e)return"function"==typeof showToast&&showToast("⏳ Fetching price..."),void fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd?(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),showPricePrediction()):"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")}).catch(function(){"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")});var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&t.remove()};var o=safeJSON("btc_price_prediction",null),n=document.createElement("div");if(n.style.cssText="background:var(--card-bg,#1a1a2e);border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:420px;width:100%;color:var(--text,#e2e8f0);font-family:inherit;text-align:center;",o&&Date.now()-o.time<864e5){var i=Date.now()-o.time;if(!(i>=864e5)){var a=Math.ceil((864e5-i)/36e5);return n.innerHTML='

    Prediction Locked In!

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+'

    ⏳ Results in ~'+a+" hour"+(1!==a?"s":"")+'
    Come back after 24 hours to see if you were right!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},500),t.appendChild(n),void document.body.appendChild(t)}var r=e-o.price,s=(r/o.price*100).toFixed(2),c="up"===o.direction&&r>0||"down"===o.direction&&r<0;o._notified||("function"==typeof notifyPredictionResult&¬ifyPredictionResult(c,o.direction),o._notified=!0,localStorage.setItem("btc_price_prediction",JSON.stringify(o)));var l=parseInt(localStorage.getItem("btc_predict_streak")||"0");n.innerHTML=''+(c?"🎉":"😅")+'

    Your Prediction

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+" ("+(r>=0?"+":"")+s+'%)

    '+(c?"✅ You were RIGHT! +25 XP":"❌ Not this time!")+"

    "+(c&&l>=2?'

    🔥 '+l+" correct in a row!

    ":"")+'
    Come back tomorrow for a new prediction!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},100)}else n.innerHTML='📈📉

    Predict Bitcoin\'s Price

    Current BTC Price:

    $'+Math.round(e).toLocaleString()+'

    Will Bitcoin go UP or DOWN in the next 24 hours?

    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStats");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 Be the first to predict!"})},100);t.appendChild(n),document.body.appendChild(t)},window._savePrediction=function(e){var t={direction:e,price:parseFloat(localStorage.getItem("btc_last_price"))||0,time:Date.now(),resolved:!1};localStorage.setItem("btc_price_prediction",JSON.stringify(t)),"function"==typeof showToast&&showToast("🎯 Prediction saved! Check back tomorrow to see if you were right."),"function"==typeof awardPoints&&awardPoints(5,"📈 Price prediction made"),_syncPredictionToFirestore(t)},window.checkPredictionResult=function(){var e=safeJSON("btc_price_prediction",null);if(e&&!e.resolved&&!(Date.now()-e.time<864e5)){var t=parseFloat(localStorage.getItem("btc_last_price"))||0;if(t&&e.price){var o=t-e.price,n=(o/e.price*100).toFixed(2),i="up"===e.direction&&o>0||"down"===e.direction&&o<0;e.resolved=!0,e.result=i?"correct":"wrong",e.finalPrice=t,localStorage.setItem("btc_price_prediction",JSON.stringify(e)),_updatePredictionStats(i);try{void 0!==auth&&auth.currentUser&&void 0!==db&&db.collection("active_predictions").doc(auth.currentUser.uid).delete().catch(function(){})}catch(e){}if(i){"function"==typeof awardPoints&&awardPoints(25,"🎯 Correct price prediction!");var a=parseInt(localStorage.getItem("btc_predict_streak")||"0")+1;localStorage.setItem("btc_predict_streak",a.toString()),setTimeout(function(){"function"==typeof showToast&&showToast("🎉 Your prediction was RIGHT! Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"% — +25 XP!"+(a>=3?" 🔥 "+a+" correct in a row!":""))},2e3)}else localStorage.setItem("btc_predict_streak","0"),setTimeout(function(){"function"==typeof showToast&&showToast("📉 Your prediction was wrong — Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"%. Try again tomorrow!")},2e3)}}};var _globalPredCache=null,_globalPredCacheTs=0;window.getGlobalPredictionStats=function(e){if(_globalPredCache&&Date.now()-_globalPredCacheTs<12e4)e(_globalPredCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{db.collection("stats").doc("predictions").get().then(function(t){t.exists?(_globalPredCache=t.data(),_globalPredCacheTs=Date.now(),e(_globalPredCache)):e(null)}).catch(function(){e(null)})}catch(t){e(null)}else e(null)},window.getPredictionStats=function(e){var t=e&&e.predictions?e.predictions:null;if(!t||!t.total)return null;var o=t.total>0?Math.round(t.correct/t.total*100):0;return{total:t.total||0,correct:t.correct||0,percentage:o,streak:t.streak||0,bestStreak:t.bestStreak||0}};var _communityStatsCache=null,_communityStatsCacheTs=0,_communityStatsUnsub=null;function _renderCommunityStats(e,t,o){var n=[];o.channelVisits&&n.push("📖 "+_fmtNum(o.channelVisits)+" channel reads"),o.questsCompleted&&n.push("⚡ "+_fmtNum(o.questsCompleted)+" quests completed"),o.chatMessages&&n.push("💬 "+_fmtNum(o.chatMessages)+" chat messages"),o.spins&&n.push("🎡 "+_fmtNum(o.spins)+" daily spins"),o.pvpMatches&&n.push("⚔️ "+_fmtNum(o.pvpMatches)+" PVP battles");var i=document.getElementById("visitCount");if(i&&"—"!==i.textContent&&n.push("👥 "+i.textContent+" total visits"),o.userCount&&n.push("🧑‍🤝‍🧑 "+_fmtNum(o.userCount)+" registered users"),o.watchTimeMinutes){var a=Math.floor(o.watchTimeMinutes/60);n.push("📺 "+(a>0?_fmtNum(a)+" hours":o.watchTimeMinutes+" min")+" Timechain TV watched")}if(0!==n.length){e.innerHTML=n.join("  ·  ");var r=function(e,t){var o=document.getElementById(e);o&&t&&(o.textContent=t.toLocaleString())};if(r("csChannelReads",o.channelVisits),r("csQuests",o.questsCompleted),r("csChatMsgs",o.chatMessages),r("csSpins",o.spins),r("csPvp",o.pvpMatches),r("csUsers",o.userCount),o.watchTimeMinutes){var s=Math.floor(o.watchTimeMinutes/60);r("csWatchTime",s>0?s:o.watchTimeMinutes)}}else e.innerHTML="No stats yet"}function _fmtNum(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function renderExplorationMap(){var e=document.getElementById("explorationMap");if(e&&void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]);void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>t.length&&(t=currentUser.readChannels);var o=Object.keys(CHANNELS),n=o.length,i=t.length,a=Math.round(i/n*100),r="";o.forEach(function(e){var o=-1!==t.indexOf(e),n=CHANNELS[e].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}|\u{2700}-\u{27BF}|\u{FE00}-\u{FEFF}|\u{1F900}-\u{1F9FF}|\u{1FA00}-\u{1FA6F}|\u{1FA70}-\u{1FAFF}|\u{200D}|\u{FE0F}]+)/u),i=n?n[1]:"📄";r+="
    '+(o?i:"?")+"
    "});var s="true"===localStorage.getItem("btc_explore_map_open");e.innerHTML="
    "+(s?"▾":"▸")+'🗺️ Exploration Map
    '+i+"/"+n+" ("+a+'%)
    '+r+"
    "}}window.loadCommunityStats=function(){var e=document.getElementById("communityStatsInner");if(e){var t=e.parentElement;if(_communityStatsUnsub&&_communityStatsCache)_renderCommunityStats(e,t,_communityStatsCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{_communityStatsUnsub=db.collection("stats").doc("global").onSnapshot(function(e){var t=e.exists?e.data():{};_communityStatsCache=t,_communityStatsCacheTs=Date.now();var o=document.getElementById("communityStatsInner");o&&_renderCommunityStats(o,o.parentElement,t)})}catch(e){}}},setTimeout(function(){"function"==typeof loadCommunityStats&&loadCommunityStats()},5e3),window.updatePredictionLabel=function(){var e=document.getElementById("predAccuracyLabel");return!!e&&void 0!==db&&"undefined"!=typeof firebase&&"function"==typeof getGlobalPredictionStats&&(getGlobalPredictionStats(function(t){var o=[];if(t&&t.total){var n=Math.round(t.correct/t.total*100);o.push("🌍 "+n+"% community accuracy")}if(void 0!==currentUser&¤tUser&¤tUser.predictions&¤tUser.predictions.total){var i=Math.round(currentUser.predictions.correct/currentUser.predictions.total*100);o.push("👤 "+i+"% you")}e.innerHTML=o.join("
    ")}),!0)},function(){var e=0,t=setInterval(function(){e++,(window.updatePredictionLabel&&window.updatePredictionLabel()||e>60)&&clearInterval(t)},1e3)}(),function e(){if("function"==typeof window.goHome){if(!window.goHome.__predHooked){var t=window.goHome;window.goHome=function(){var e=t.apply(this,arguments);return setTimeout(function(){window.updatePredictionLabel&&window.updatePredictionLabel()},400),e},window.goHome.__predHooked=!0}}else var o=setInterval(function(){"function"==typeof window.goHome&&(clearInterval(o),e())},500)}(),window.renderExplorationMap=renderExplorationMap;var BITCOIN_QUOTES=[{text:"If you don't believe it or don't get it, I don't have the time to try to convince you, sorry.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"The root problem with conventional currency is all the trust that's required to make it work.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"It might make sense just to get some in case it catches on.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"Running bitcoin.",author:"Hal Finney",channel:"history"},{text:"Bitcoin is a remarkable cryptographic achievement and the ability to create something that is not duplicable in the digital world has enormous value.",author:"Eric Schmidt",channel:"dominant"},{text:"Bitcoin is a technological tour de force.",author:"Bill Gates",channel:"one-stop-shop"},{text:"I think the internet is going to be one of the major forces for reducing the role of government. The one thing that's missing, but that will soon be developed, is a reliable e-cash.",author:"Milton Friedman (1999)",channel:"videos"},{text:"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.",author:"Bitcoin Genesis Block",channel:"history"},{text:"Not your keys, not your coins.",author:"Bitcoin Proverb",channel:"self-custody"},{text:"Stay humble, stack sats.",author:"Bitcoin Community",channel:"investment-strategy"},{text:"In the long run, hard money is superior to soft money.",author:"Gigi, 21 Lessons",channel:"articles-threads"},{text:"Bitcoin is the first truly digital solution to the problem of money.",author:"Saifedean Ammous",channel:"books"},{text:"Fix the money, fix the world.",author:"Bitcoin Mantra",channel:"problems-of-money"},{text:"The supply of Bitcoin is limited. Period. No central bank is going to come along and print more.",author:"Andreas Antonopoulos",channel:"scarce"},{text:"Everyone is a scammer until proven otherwise. Don't trust, verify.",author:"Bitcoin Culture",channel:"secure"},{text:"Bitcoin makes money great again. It lets you transact freely, save freely, and live freely.",author:"Michael Saylor",channel:"giga-chad"},{text:"There is no second best.",author:"Michael Saylor",channel:"maximalism"},{text:"I don't think there's anything more important in my lifetime to work on.",author:"Jack Dorsey",channel:"giga-chad"},{text:"Bitcoin is the most important invention in the history of the world since the internet.",author:"Roger Ver (before he fell off)",channel:"history"},{text:"The computer can be used as a tool to liberate and protect people, rather than to control them.",author:"Hal Finney",channel:"cryptography"},{text:"One of the greatest things that Satoshi did was disappear.",author:"Gigi, 21 Lessons",channel:"satoshi-nakamoto"},{text:"Bitcoin has no CEO, no marketing department, no headquarters. It has math.",author:"Bitcoin Education Archive",channel:"decentralized"},{text:"We are all Satoshi.",author:"Bitcoin Community",channel:"satoshi-nakamoto"},{text:"Cypherpunks write code.",author:"Eric Hughes",channel:"cryptography"},{text:"Privacy is necessary for an open society in the electronic age.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Money is a tool for trading human time.",author:"Robert Breedlove",channel:"articles-threads"},{text:"Bitcoin is Time.",author:"Gigi",channel:"time"},{text:"The root cause of the housing crisis, student debt crisis, and healthcare crisis is the money crisis.",author:"Saifedean Ammous",channel:"problems-of-money"},{text:"Tick tock, next block.",author:"Bitcoin Community",channel:"blockchain-timechain"},{text:"The difficulty adjustment is the most elegant feature of Bitcoin.",author:"Bitcoin Educators",channel:"difficulty-adjustment"},{text:"Every informed person needs to know about Bitcoin because it might be one of the world's most important developments.",author:"Leon Luow",channel:"one-stop-shop"},{text:"Bitcoin is the only commodity in the world that the more demand there is, the more supply does NOT increase.",author:"Parker Lewis",channel:"scarce"},{text:"Gradually, then suddenly.",author:"Parker Lewis / Ernest Hemingway",channel:"articles-threads"},{text:"You can't stop an idea whose time has come.",author:"Victor Hugo (on Bitcoin)",channel:"organic"},{text:"Bitcoin is a hedge against the entire system.",author:"Lyn Alden",channel:"investment-strategy"},{text:"The question isn't what Bitcoin's price will be. The question is what the dollar's price will be.",author:"Bitcoiners",channel:"problems-of-money"},{text:"I was once told that nobody ever lost money saving in Bitcoin for 4+ years. I checked. It's true.",author:"Anonymous Bitcoiner",channel:"investment-strategy"},{text:"Bitcoin is the exit.",author:"Bitcoin Maximalists",channel:"maximalism"},{text:"Don't trust, verify.",author:"Bitcoin Ethos",channel:"nodes"},{text:"Number go up technology.",author:"Bitcoin Twitter",channel:"fun-facts"},{text:"Energy is the universal currency. Bitcoin makes that literal.",author:"Bitcoin Mining Community",channel:"energy"},{text:"Bitcoin is not an investment — it is a savings technology.",author:"Bitcoin Educators",channel:"money"},{text:"Fiat currency always returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Give me control of a nation's money supply, and I care not who makes its laws.",author:"Mayer Amschel Rothschild",channel:"problems-of-money"},{text:"Inflation is taxation without legislation.",author:"Milton Friedman",channel:"problems-of-money"},{text:"Bitcoin is for enemies. That's the whole point.",author:"Bitcoin Community",channel:"game_theory"},{text:"When you understand Bitcoin, you understand everything else differently.",author:"Many Bitcoiners",channel:"philosophy"},{text:"Bitcoin doesn't care about your feelings.",author:"Bitcoin Proverb",channel:"fun-facts"},{text:"Stack sats and stay humble.",author:"Matt Odell",channel:"investment-strategy"},{text:"Number go up because money printer go brr.",author:"Bitcoin Memes",channel:"memes-funny"},{text:"Those who would give up essential liberty, to purchase a little temporary safety, deserve neither liberty nor safety.",author:"Benjamin Franklin",channel:"human_rights__social_justice_and_freedo"},{text:"Freedom is never more than one generation away from extinction.",author:"Ronald Reagan",channel:"human_rights__social_justice_and_freedo"},{text:"The only way to deal with an unfree world is to become so absolutely free that your very existence is an act of rebellion.",author:"Albert Camus",channel:"philosophy"},{text:"If the American people ever allow private banks to control the issue of their currency, first by inflation, then by deflation, the banks and corporations that will grow up around them will deprive the people of all property.",author:"Thomas Jefferson",channel:"problems-of-money"},{text:"It is well enough that people of the nation do not understand our banking and monetary system, for if they did, I believe there would be a revolution before tomorrow morning.",author:"Henry Ford",channel:"problems-of-money"},{text:"The most dangerous man to any government is the man who is able to think things out for himself.",author:"H.L. Mencken",channel:"philosophy"},{text:"In a time of deceit, telling the truth is a revolutionary act.",author:"George Orwell",channel:"philosophy"},{text:"The urge to save humanity is almost always a false front for the urge to rule it.",author:"H.L. Mencken",channel:"philosophy"},{text:"A society that puts equality before freedom will get neither. A society that puts freedom before equality will get a high degree of both.",author:"Milton Friedman",channel:"philosophy"},{text:"The state is that great fiction by which everyone tries to live at the expense of everyone else.",author:"Frédéric Bastiat",channel:"austrian_school_of_economics"},{text:"There is no means of avoiding the final collapse of a boom brought about by credit expansion.",author:"Ludwig von Mises",channel:"austrian_school_of_economics"},{text:"The first panacea for a mismanaged nation is inflation of the currency; the second is war. Both bring a temporary prosperity; both bring a permanent ruin.",author:"Ernest Hemingway",channel:"problems-of-money"},{text:"Gold is money. Everything else is credit.",author:"J.P. Morgan",channel:"money"},{text:"We don't have a trillion-dollar debt because we haven't taxed enough; we have a trillion-dollar debt because we spend too much.",author:"Ronald Reagan",channel:"problems-of-money"},{text:"Government is the only institution that can take a valuable commodity like paper, and make it worthless by applying ink.",author:"Ludwig von Mises",channel:"problems-of-money"},{text:"Whenever destroyers appear among men, they start by destroying money.",author:"Ayn Rand",channel:"problems-of-money"},{text:"The way to crush the bourgeoisie is to grind them between the millstones of taxation and inflation.",author:"Vladimir Lenin",channel:"problems-of-money"},{text:"Savings represent goods produced but not yet consumed. That's what real wealth is — not digits in a bank database.",author:"Saifedean Ammous",channel:"money"},{text:"Civilization is in a race between education and catastrophe. Let us learn the truth and spread it as far and wide as our circumstances allow.",author:"H.G. Wells",channel:"one-stop-shop"},{text:"Paper money eventually returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Bitcoin is the separation of money and state.",author:"Bitcoin Community",channel:"maximalism"},{text:"Bitcoin is the first money in the history of the world where the supply is entirely unaffected by an increase in demand.",author:"Jeff Booth",channel:"scarce"},{text:"In a world where everything is printed, scarcity is the ultimate feature.",author:"Bitcoin Educators",channel:"scarce"},{text:"Bitcoin is hope for humanity.",author:"Jack Mallers",channel:"one-stop-shop"},{text:"The cost of Bitcoin is measured in electricity. The cost of fiat is measured in human freedom.",author:"Bitcoin Community",channel:"energy"},{text:"Your savings should not be someone else's liability.",author:"Bitcoin Educators",channel:"self-custody"},{text:"Bitcoin is the peaceful protest that cannot be silenced.",author:"Alex Gladstein",channel:"human_rights__social_justice_and_freedo"},{text:"Bitcoin gives us the ability to opt out of a system that was designed to extract value from us.",author:"Many Bitcoiners",channel:"problems-of-money"},{text:"Proof of work means proof of energy. Energy is the one thing that cannot be faked.",author:"Bitcoin Mining Community",channel:"mining"},{text:"The Bitcoin network processes more value per year than Visa. Without a CEO.",author:"Bitcoin Stats",channel:"decentralized"},{text:"If Bitcoin is a bubble, it's the only bubble that reflated itself five times in a row.",author:"Bitcoin Community",channel:"fun-facts"},{text:"Bitcoin has died 474 times according to the media. It's still here.",author:"Bitcoin Obituaries",channel:"misconceptions-fud"},{text:"Your grandchildren will ask you why you didn't buy Bitcoin when it was under six figures.",author:"Bitcoin Twitter",channel:"predictions"},{text:"The next 4 years are going to be very exciting for Bitcoin.",author:"Every Bitcoiner, Every Year",channel:"fun-facts"},{text:"Bitcoin isn't getting more expensive. Your dollars are getting cheaper.",author:"Bitcoin Community",channel:"problems-of-money"},{text:"If you can't hold it, you don't own it. If you didn't earn it, you'll lose it.",author:"Bitcoin Wisdom",channel:"self-custody"},{text:"Think in sats, not dollars.",author:"Bitcoin Community",channel:"sats__or__bits"},{text:"The best time to buy Bitcoin was 10 years ago. The second best time is now.",author:"Bitcoin Proverb",channel:"investment-strategy"},{text:"Work is the transfer of energy over time. Money should measure exactly that.",author:"Jason Lowery",channel:"energy"},{text:"Bitcoin is not anti-government. Bitcoin is anti-fraud.",author:"Bitcoin Educators",channel:"regulation"},{text:"We must defend our own privacy if we expect to have any.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Cryptography is the ultimate form of non-violent direct action.",author:"Julian Assange",channel:"cryptography"},{text:"Strong cryptography can resist an unlimited application of violence.",author:"Jacob Appelbaum",channel:"cryptography"},{text:"The Net interprets censorship as damage and routes around it.",author:"John Gilmore",channel:"privacy-nonkyc"},{text:"Bitcoin is a weapon of peace.",author:"Jason Lowery, Softwar",channel:"geopolitics___macroeconomics"},{text:"Running a node means nobody can change the rules on you.",author:"Bitcoin Node Runners",channel:"nodes"},{text:"Hashrate is the heartbeat of Bitcoin. As long as miners mine, Bitcoin lives.",author:"Bitcoin Mining Community",channel:"mining"},{text:"Lightning is what makes Bitcoin usable for 8 billion people.",author:"Lightning Network Community",channel:"layer-2-lightning"},{text:"2,099,999,997,690,000 satoshis. That's all there will ever be.",author:"The Bitcoin Protocol",channel:"scarce"},{text:"Code is speech. Math is law. Cryptography is defense.",author:"Cypherpunks",channel:"cryptography"},{text:"I predict the Internet will go spectacularly supernova and in 1996 catastrophically collapse.",author:"Robert Metcalfe (1995) — They said this about Bitcoin too",channel:"misconceptions-fud"},{text:"Every generation needs a new revolution.",author:"Thomas Jefferson",channel:"philosophy"},{text:"First they ignore you, then they laugh at you, then they fight you, then you win.",author:"Often attributed to Gandhi",channel:"organic"},{text:"I do not think there is any other quality so essential to success of any kind as the quality of perseverance.",author:"John D. Rockefeller",channel:"philosophy"},{text:"The world is a dangerous place, not because of those who do evil, but because of those who look on and do nothing.",author:"Albert Einstein",channel:"philosophy"},{text:"Hard times create strong men. Strong men create good times. Good times create weak men. Weak men create hard times.",author:"G. Michael Hopf",channel:"time_preference"},{text:"An investment in knowledge pays the best interest.",author:"Benjamin Franklin",channel:"one-stop-shop"}];window.renderDailyQuote=function(){var e=document.getElementById("quoteOfDay");if(e){var t=new Date,o=Math.floor((t-new Date(t.getFullYear(),0,0))/864e5),n=BITCOIN_QUOTES[o%BITCOIN_QUOTES.length];n&&(e.innerHTML="
    💬 Quote of the Day
    "'+n.text+'"
    — '+n.author+"
    ")}},window.renderReadNext=function(e){if(void 0===CHANNELS)return"";var t=CHANNELS[e];if(!t)return"";var o=Object.entries(CHANNELS).filter(function(o){return o[1].cat===t.cat&&o[0]!==e});if(0===o.length)return"";var n=o.sort(function(){return Math.random()-.5}).slice(0,3),i='
    📖 Read Next
    ';return n.forEach(function(e){var t=e[1].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}]+)/u),o=t?t[1]:"📄";i+=""}),i+="
    "},window.getNachoStoryProgress=function(){return parseInt(localStorage.getItem("btc_nacho_story_highest")||"0")},window.checkHiddenBadges=function(){if(void 0!==HIDDEN_BADGES&&window._hiddenBadgesReady){var e=safeJSON("btc_hidden_badges",[]),t=!1;HIDDEN_BADGES.forEach(function(o){if(-1===e.indexOf(o.id))try{if(o.check&&o.check()&&(e.push(o.id),t=!0,"function"==typeof showToast&&showToast(o.emoji+" Secret Badge: "+(o.revealName||o.name)+"! +"+o.pts+" XP"),"function"==typeof awardPoints&&awardPoints(o.pts,"Hidden Badge: "+(o.revealName||o.name)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:e})}catch(e){}}catch(e){}}),t&&localStorage.setItem("btc_hidden_badges",JSON.stringify(e))}},setInterval(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},3e4),setTimeout(function(){window._hiddenBadgesReady||(window._hiddenBadgesReady=!0)},2e4),window.awardHiddenBadge=function(e,t){var o=safeJSON("btc_hidden_badges",[]);if(-1===o.indexOf(e)&&(o.push(e),localStorage.setItem("btc_hidden_badges",JSON.stringify(o)),t&&"function"==typeof showToast&&showToast("🏅 "+t),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:o})}catch(e){}},window.awardOrangeTickets=function(e,t){void 0!==currentUser&¤tUser&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,currentUser._isLocal||"function"!=typeof awardPoints||awardPoints(0,"🎟️ "+(t||"Orange Tickets"),null,e));var o=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(o+e).toString()),"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Ticket"+(e>1?"s":"")+(t?" — "+t:""))},window.setFloatingElementsVisible=function(e){["floatingRandomBtn","lbFloatBtn","mobileSearchBtn","backToTop","scrollToBottom","chatOverlayBtn","aiToolsBtn","dashboardFloatBtn"].forEach(function(t){var o=document.getElementById(t);o&&(o.style.display=e?"":"none")})},window.showCelebration=function(e){var t=e.emoji||"🎉",o=e.title||"Achievement Unlocked!",n=e.message||"",i=e.rewards||[],a=e.btnText||"Amazing! 🎉",r=document.createElement("div");r.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",r.onclick=function(e){e.target===r&&(r.style.opacity="0",r.style.transition="opacity 0.4s",setTimeout(function(){r.remove()},400))};var s="";i.length>0&&(s='
    ',i.forEach(function(e){s+='
    +'+e.label+'
    '+e.sub+"
    "}),s+="
    "),r.innerHTML='
    '+t+'
    '+o+'
    '+n+"
    "+s+'
    ",document.body.appendChild(r),"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound(),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200)},setInterval(function(){["prop","tech"].forEach(function(e){var t="btc_scholar_"+e+"_passed",o="btc_scholar_"+e+"_celebrated";if("true"===localStorage.getItem(t)&&"true"!==localStorage.getItem(o)){localStorage.setItem(o,"true");var n="tech"===e;setTimeout(function(){showCelebration({emoji:n?"🛠️🎓🏆":"📖🎓🎉",title:n?"PROTOCOL EXPERT!":"BITCOIN SCHOLAR!",message:n?"You passed the Technical Protocol Expert Certification! You understand Bitcoin at the deepest level. True cypherpunk material! 🔐":"You passed the Bitcoin Scholar Certification! You have a thorough understanding of Bitcoin's properties and economics! 🧡",rewards:[{label:"2,100",sub:"PTS",color:"#22c55e"},{label:n?"🛠️":"🎓",sub:"BADGE",color:"#f7931a"}],btnText:n?"Protocol Expert! 🛠️":"Scholar! 🎓"})},500)}})},3e3),function(){var e=[{pct:25,key:"explore_25",emoji:"🗺️🌱",title:"25% EXPLORED!",msg:"A quarter of the archive explored! You're building a solid Bitcoin foundation.",pts:50,tickets:10},{pct:50,key:"explore_50",emoji:"🗺️🔥",title:"50% EXPLORED!",msg:"Halfway through the entire archive! You know more about Bitcoin than most people on Earth.",pts:100,tickets:25},{pct:75,key:"explore_75",emoji:"🗺️⚡",title:"75% EXPLORED!",msg:"Three quarters done! You're in the top tier of Bitcoin knowledge seekers.",pts:200,tickets:50},{pct:100,key:"explore_100",emoji:"🗺️👑🏆",title:"ARCHIVE COMPLETE!",msg:"You've explored EVERY SINGLE channel in the archive. You are a true Bitcoin scholar. Satoshi would be proud! 🧡",pts:500,tickets:100}];window._checkExplorationMilestones=function(){if(void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]),o=Object.keys(CHANNELS).length,n=Math.round(t.length/o*100);e.forEach(function(e){if(n>=e.pct&&"true"!==localStorage.getItem("btc_"+e.key+"_celebrated")){if(localStorage.setItem("btc_"+e.key+"_celebrated","true"),"function"==typeof awardPoints&&awardPoints(e.pts,"🗺️ "+e.pct+"% Explored"),"function"==typeof awardOrangeTickets)awardOrangeTickets(e.tickets,"🗺️ "+e.pct+"% Explored");else{var t=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(t+e.tickets).toString())}if(setTimeout(function(){showCelebration({emoji:e.emoji,title:e.title,message:e.msg,rewards:[{label:e.pts.toString(),sub:"PTS",color:"#22c55e"},{label:e.tickets.toString(),sub:"🎟️ TICKETS",color:"#f7931a"}]})},800),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o={};o["explorationMilestone_"+e.pct]=!0;try{db.collection("users").doc(auth.currentUser.uid).update(o).catch(function(){})}catch(e){}}}})}};var t=window.renderExplorationMap;window.renderExplorationMap=function(){t(),window._checkExplorationMilestones()}}(),function(){var e=window.showQuestFinalResults;e&&(window.showQuestFinalResults=function(){e.apply(this,arguments);var t=window._questScore||0;5===t?("function"==typeof showToast&&showToast("🏆 PERFECT SCORE! You nailed every question!"),"function"==typeof launchConfetti&&setTimeout(launchConfetti,300)):t>=3&&"function"==typeof showToast&&showToast("⚡ Quest passed! +"+(window._questPts||0)+" XP earned!")});var t=window.nachoQuizAnswer;t&&(window.nachoQuizAnswer=function(e,o){t.apply(this,arguments),o&&"function"==typeof haptic&&haptic("success")});var o=window.convoQuizAnswer;o&&(window.convoQuizAnswer=function(e,t){o.apply(this,arguments),t&&"function"==typeof haptic&&haptic("light")})}(),function(){window._scrollPositions={};var e=window.go;e&&(window.go=async function(t,o,n){var i=document.getElementById("main"),a=location.hash.slice(1);a&&i&&(window._scrollPositions[a]=i.scrollTop),await e(t,o,n),window._scrollPositions[t]&&i&&setTimeout(function(){i.scrollTop=window._scrollPositions[t]},100)}),window.haptic=function(e){if("visible"===document.visibilityState&&"false"!==localStorage.getItem("btc_haptic")&&navigator.vibrate)switch(e){case"light":navigator.vibrate(10);break;case"medium":navigator.vibrate(25);break;case"heavy":navigator.vibrate([30,50,30]);break;case"success":navigator.vibrate([15,30,15,30,15]);break;case"error":navigator.vibrate([50,30,50]);break;default:navigator.vibrate(15)}};var t=window.awardPoints;t&&(window.awardPoints=function(){return haptic("success"),t.apply(this,arguments)});var o=window.showLevelUpCelebration;o&&(window.showLevelUpCelebration=function(){return haptic("heavy"),o.apply(this,arguments)}),function(){var e=document.createElement("style");e.textContent="@keyframes slideInRight{from{transform:translateX(30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInLeft{from{transform:translateX(-30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInUp{from{transform:translateY(20px);opacity:0}to{transform:translateY(0);opacity:1}}.page-transition-right{animation:slideInRight 0.25s ease-out;}.page-transition-left{animation:slideInLeft 0.25s ease-out;}.page-transition-up{animation:slideInUp 0.2s ease-out;}",document.head.appendChild(e);var t=document.getElementById("main");t&&new MutationObserver(function(){var e=document.getElementById("hero");e&&e.innerHTML&&(e.classList.remove("page-transition-right"),e.offsetWidth,e.classList.add("page-transition-right"))}).observe(document.getElementById("hero")||t,{childList:!0})}();var n=0;document.addEventListener("touchend",function(e){var t=Date.now();if(t-n<300){var o=e.target.closest&&e.target.closest('[onclick*="forumViewPost"]');if(o){var i=o.querySelector('[onclick*="forumVotePost"]');i&&(i.click(),haptic("medium")),e.preventDefault()}}n=t},{passive:!1});var i=(new Date).toISOString().split("T")[0];function a(e){return localStorage.getItem(e+"_"+i)||null}function r(e,t){localStorage.setItem(e+"_"+i,t)}function s(e){return parseInt(a(e)||"0",10)}function c(e){var t=s(e)+1;return r(e,String(t)),t}var l,d=[{id:"read",text:"📖 Read a new channel",check:function(){return"true"===a("btc_new_channel_read")}},{id:"nacho",text:"🦌 Ask Nacho a question",check:function(){return s("btc_nacho_asked")>0}},{id:"quiz",text:"🎮 Complete a quiz question",check:function(){return"true"===a("btc_quiz_done")}},{id:"explore",text:"🗺️ Visit 3 different channels",check:function(){return s("btc_channels_today")>=3}},{id:"forum",text:"🗣️ Visit the PlebTalk",check:function(){return"true"===a("btc_forum_visited")}},{id:"streak",text:"🔥 Log in to keep your streak",check:function(){return!0}},{id:"favorite",text:"⭐ Save a channel to favorites",check:function(){return"true"===a("btc_fav_added")}},{id:"tctv_10m",text:"📺 Watch 10 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=10}},{id:"tctv_visit",text:"📺 Tune in to Timechain TV",check:function(){return"true"===a("btc_tctv_visited")}},{id:"tctv_3ch",text:"📺 Watch 3 different TCTV stations",check:function(){try{var e=a("btc_tctv_stations_visited");return!!e&&JSON.parse(e).length>=3}catch(e){return!1}}},{id:"tctv_30m",text:"📺 Watch 30 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=30}},{id:"tip_send",text:"⚡ Send a Lightning tip to someone",check:function(){return"true"===a("btc_tip_sent")}},{id:"tip_3",text:"⚡ Send 3 Lightning tips today",check:function(){return s("btc_tips_sent_count")>=3}},{id:"ln_setup",text:"⚡ Set up your Lightning wallet",check:function(){return!!(localStorage.getItem("btc_nwc_url")||localStorage.getItem("btc_ln_address")||void 0!==currentUser&¤tUser&¤tUser.lightningAddress)}},{id:"chat_msg",text:"🌍 Send a message in Global Chat",check:function(){return"true"===a("btc_chat_sent")}},{id:"pvp_battle",text:"⚔️ Complete a PVP trivia battle",check:function(){return"true"===a("btc_pvp_done")}},{id:"beats_listen",text:"🎸 Listen to a track on Bitcoin Beats",check:function(){return"true"===a("btc_beats_played")}},{id:"explore_5",text:"🗺️ Explore 5 different channels today",check:function(){return s("btc_channels_today")>=5}},{id:"nacho_3",text:"🦌 Ask Nacho 3 questions",check:function(){return s("btc_nacho_asked")>=3}}];function u(){var e=(new Date).toISOString().split("T")[0],t=Math.floor(new Date(e).getTime()/864e5);return d[t%d.length]}function p(){var e=u(),t=(new Date).toISOString().split("T")[0],o=localStorage.getItem("btc_challenge_done")===t,n=document.getElementById("dailyChallengeCard");n&&(o?(n.style.borderColor="#22c55e",n.style.background="rgba(34,197,94,0.05)",n.innerHTML='
    Today\'s Challenge ✔️
    '+e.text+" — Done! +100 XP 🎉
    "):(n.style.borderColor="var(--border)",n.style.background="var(--card-bg)",n.innerHTML='
    🎯
    Today\'s Challenge
    '+e.text+"
    "))}if(window.checkDailyChallenge=function(){var e=(new Date).toISOString().split("T")[0];if(localStorage.getItem("btc_challenge_done")!==e&&u().check()){localStorage.setItem("btc_challenge_done",e),"function"==typeof awardPoints&&awardPoints(100,"🎯 Daily challenge!"),"function"==typeof awardOrangeTickets&&awardOrangeTickets(5,"🎯 Daily challenge!"),"function"==typeof showToast&&showToast("🎯 Daily challenge complete! +100 XP + 🎟️ 5 tickets!"),haptic("success"),p();var t=document.getElementById("dailyChallengeCard");t&&(t.style.transition="transform 0.3s, box-shadow 0.3s",t.style.transform="scale(1.03)",t.style.boxShadow="0 0 20px rgba(34,197,94,0.4)",setTimeout(function(){t.style.transform="",t.style.boxShadow=""},1500))}},setInterval(window.checkDailyChallenge,3e3),window._raidHomeUnsub=null,window._raidHomeTimer=null,window.renderRaidBossHome=function(){var e=document.getElementById("raidBossHomeCard");e&&("undefined"!=typeof firebase&&void 0!==db?(window._raidHomeUnsub&&(window._raidHomeUnsub(),window._raidHomeUnsub=null),window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),window._raidHomeUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.style.display="none";else{var o=Date.now(),n=null,i=null,a=null;t.forEach(function(e){var t=e.data();t.id=e.id;var r=t.startTime&&t.startTime.toDate?t.startTime.toDate().getTime():0,s=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime&&i.startTime.toDate?i.startTime.toDate().getTime():0))&&(i=t):t.defeated&&(a||(a=t))}),function(e,t,o,n){if(window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),t||o||n){e.style.display="";var i="if(typeof showQuestHub==='function'){showQuestHub();setTimeout(function(){if(typeof window._questHubTab!=='undefined'){window._questHubTab='raid';if(typeof _renderQuestHubTab==='function')_renderQuestHubTab();}},300)}",a="";if(t){var r=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0,s=t.target>0?Math.min(100,Math.round((t.current||0)/t.target*100)):0,c=Math.max(0,(t.target||0)-(t.current||0)),l=Math.max(0,100-s),d=l<=25?"#ef4444":l<=50?"#f59e0b":"#22c55e",u=t.image||"";if(!u){var p={"Channel-Crawler":"channel-crawler","Quiz-Crusader":"quiz-crusader","TV-Titan":"tv-titan","Beats-Baron":"beats-baron","Flash-Flash":"flash-flash","XP-Hoarder":"xp-hoarder","Poll-Patroller":"poll-patroller","Chat-Charger":"chat-charger","Badge-Builder":"badge-builder","Streak-Sage":"streak-sage","Topic-Explorer":"topic-explorer","Lightning-Lancer":"lightning-lancer","Forum-Forge":"forum-forge","Trivia-Tactician":"trivia-tactician","Content-Conqueror":"content-conqueror"};p[t.name]&&(u="images/raid-bosses/"+p[t.name]+".png")}a+='
    '+(u?'':'⚔️')+'
    ⚔️ CURRENT RAID BOSS
    '+(t.name||"Raid Boss")+'
    ❤️ '+c+"/"+t.target+' HP⏱ '+h(r)+'
    ',window._raidActiveEndMs=r}if(o){var m=o.startTime&&o.startTime.toDate?o.startTime.toDate().getTime():0,g=new Date(m).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"});a+='
    ⚔️
    NEXT BOSS
    '+(o.name||"TBD")+" — "+g+'
    Starts in '+h(m)+'
    ',window._raidUpcomingStartMs=m}n&&!t&&(a='
    💀
    🎉 BOSS DEFEATED!
    '+("function"==typeof escapeHtml?escapeHtml(n.name||"Raid Boss"):n.name||"Raid Boss")+' has fallen!
    🏆 Orange ticket drawing this Friday!
    '+a),e.innerHTML=a,window._raidHomeTimer=setInterval(function(){var e=document.getElementById("raidHomeCountdown");e&&window._raidActiveEndMs&&(e.textContent="⏱ "+h(window._raidActiveEndMs));var t=document.getElementById("raidHomeUpcomingCountdown");t&&window._raidUpcomingStartMs&&(t.textContent="Starts in "+h(window._raidUpcomingStartMs)),e||t||(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null)},1e3)}else e.style.display="none";function h(e){var t=Math.max(0,e-Date.now());if(t<=0)return"⏳ Any moment now...";var o=Math.floor(t/864e5),n=Math.floor(t%864e5/36e5),i=Math.floor(t%36e5/6e4),a=Math.floor(t%6e4/1e3);return o>0?o+"d "+n+"h "+i+"m":n>0?n+"h "+i+"m "+a+"s":i+"m "+a+"s"}}(e,n,i,a)}},function(){e.style.display="none"})):e.style.display="none")},l="",window._trackChallengeNav=function(e){e&&e!==l&&(l=e,"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e||r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},500))},window.go){var m=window.go;window.go=async function(e){var t=!1;e&&"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e&&(t=-1===safeJSON("btc_visited_channels",[]).indexOf(e));var o=await m.apply(this,arguments);return"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e),e&&"forum"!==e&&(c("btc_channels_today"),t&&r("btc_new_channel_read","true")),"forum"===e&&r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},300),o}}var g=window.nachoUnifiedAnswer;g&&(window.nachoUnifiedAnswer=function(e,t){return c("btc_nacho_asked"),g.apply(this,arguments)}),window.addEventListener("hashchange",function(){var e=location.hash.slice(1);e&&"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e)}),window.renderProgressRings=function(){var e=document.getElementById("progressRings");if(e){var t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=0;void 0!==currentUser&¤tUser&&(currentUser.readChannels&¤tUser.readChannels.length?o=currentUser.readChannels.length:currentUser.channelsVisited&&(o=currentUser.channelsVisited)),0===o&&(o=safeJSON("btc_visited_channels",[]).length);var n=void 0!==currentUser&¤tUser&¤tUser.streak||0,i=void 0!==currentUser&¤tUser&¤tUser.points||0,a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.innerHTML='
    '+r(Math.min(100,o/t*100),"#f7931a","Channels",o+"/"+t)+r(Math.min(100,5*n),"#22c55e","Streak","🔥"+n)+r(Math.min(100,i/21e3*100),"#8B5CF6","XP",i>999?Math.floor(i/1e3)+"k":i)+r(Math.min(100,2*a),"#3B82F6","Nacho",a)+"
    "}function r(e,t,o,n){var i=2*Math.PI*32;return'
    '+n+'
    '+o+"
    "}};var h=null;function f(){console.log("[MobileUX] Initializing..."),function(){var e=document.createElement("div");e.id="bottomNav",e.className="mobile-nav",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:200000;background:rgba(10,10,10,0.95);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border-top:1px solid rgba(255,255,255,0.1);padding:10px 0 env(safe-area-inset-bottom,10px) 0;padding-bottom:max(env(safe-area-inset-bottom,10px),10px);display:none;transition:transform 0.25s ease;-webkit-transform:translateZ(0);transform:translateZ(0);",e.innerHTML='
    ';var t=document.createElement("style");t.textContent=".bnav-btn{background:none;border:none;color:var(--text-dim,#666);font-size:0.6rem;cursor:pointer;font-family:inherit;padding:6px 0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;touch-action:manipulation;-webkit-tap-highlight-color:transparent;transition:0.2s;flex:1;min-width:0;}.bnav-icon{font-size:1.3rem;line-height:1;display:block;transition:transform 0.2s;}.bnav-label{font-size:0.55rem;line-height:1;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;}.bnav-btn:active .bnav-icon{transform:scale(1.2);}.bnav-btn.active{color:var(--accent);}@media(min-width:901px){#bottomNav{display:none!important;}}@media(max-width:900px){#bottomNav{display:block!important;visibility:visible!important;opacity:1!important;}.messages{padding-bottom:140px!important;}.home-page{padding-bottom:100px!important;}}",document.head.appendChild(t),document.body.appendChild(e)}(),function(){var e=document.getElementById("main");if(e){var t=0,o=document.getElementById("bottomNav");o&&e.addEventListener("scroll",function(){if(!(window.innerWidth>900)){var n=e.scrollTop,i=n-t;i>10&&n>200?o.classList.add("nav-hidden"):(i<-5||n<=10)&&o.classList.remove("nav-hidden"),t=n}},{passive:!0})}}(),setTimeout(function(){!function(){var e=0;if(void 0!==currentUser&¤tUser&&(e=currentUser.streak||0),!(e<2||document.getElementById("streakBanner"))){var t=document.createElement("div");t.id="streakBanner",t.style.cssText="position:fixed;top:32px;left:0;right:0;z-index:300;background:linear-gradient(135deg,#f7931a,#ea580c);color:#fff;padding:10px 16px;text-align:center;font-size:0.85rem;font-weight:700;cursor:pointer;animation:slideInUp 0.3s;",t.innerHTML="🔥 Day "+e+' streak! Keep it alive! tap to dismiss',t.onclick=function(){t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.remove()},300)},document.body.appendChild(t),setTimeout(function(){t.parentNode&&(t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.parentNode&&t.remove()},300))},5e3)}}(),function(){if("function"==typeof forceShowBubble&&!sessionStorage.getItem("btc_welcomed_back")){sessionStorage.setItem("btc_welcomed_back","true");var e="";void 0!==currentUser&¤tUser&¤tUser.username&&(e=currentUser.username);var t,o=void 0!==currentUser&¤tUser&¤tUser.streak||0,n=(new Date).getHours(),i=n<12?"Morning":n<17?"Afternoon":"Evening",a=u();t=e&&o>=2?"Good "+i.toLowerCase()+", "+e+"! ☀️ Day "+o+" streak — you're on fire! 🔥 Today's challenge: "+a.text:e?"Hey "+e+"! 🦌 Welcome back! Today's challenge: "+a.text:"Welcome back! 🦌 Today's challenge: "+a.text,setTimeout(function(){forceShowBubble(t)},3e3)}}(),p(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof renderProgressRings&&renderProgressRings()},2500)}window.addEventListener("beforeinstallprompt",function(e){if(e.preventDefault(),h=e,!window.matchMedia("(display-mode: standalone)").matches){var t=localStorage.getItem("btc_pwa_dismissed");if(t&&Date.now()-parseInt(t)<6048e5)return;window._pwaLoadTime=Date.now(),window._pwaCheckInterval=setInterval(function(){if(!(Date.now()-(window._pwaLoadTime||Date.now())<9e4)){var e=[];try{e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}e.length>=3&&(clearInterval(window._pwaCheckInterval),function(){if(!document.getElementById("pwaInstallBanner")){var e=document.createElement("div");if(e.id="pwaInstallBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Install Bitcoin Education
    Add to home screen for the best experience — works offline!
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}}())}},1e4)}}),window.installPWA=function(){h&&(h.prompt(),h.userChoice.then(function(e){"accepted"===e.outcome&&"function"==typeof showToast&&showToast("🦌 Welcome aboard! App installed!"),h=null})),dismissPWABanner()},window.dismissPWABanner=function(){var e=document.getElementById("pwaInstallBanner");e&&e.remove(),localStorage.setItem("btc_pwa_dismissed",Date.now().toString())},function(){var e=/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,t=/Safari/.test(navigator.userAgent)&&!/CriOS|FxiOS|Chrome/.test(navigator.userAgent),o=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(e&&t&&!o){var n=localStorage.getItem("btc_ios_a2hs_dismissed");n&&Date.now()-parseInt(n)<2592e6||setTimeout(function(){if(!document.getElementById("iosA2HSBanner")){var e=document.createElement("div");if(e.id="iosA2HSBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Add to Home Screen
    For the best experience, add this app to your home screen:
    1. Tap the Share button ⬆️ at the bottom
    2. Scroll down and tap Add to Home Screen
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}},12e4)}}(),window.dismissIOSA2HS=function(){var e=document.getElementById("iosA2HSBanner");e&&e.remove(),localStorage.setItem("btc_ios_a2hs_dismissed",Date.now().toString())},window.toggleMobileLearnMenu=function(){var e=document.getElementById("mobileLearnMenu");if(e)e.remove();else{var t=document.getElementById("appsMenu");t&&t.remove();var o=document.createElement("div");o.id="mobileLearnMenu",o.style.cssText="position:fixed;bottom:70px;left:8px;right:8px;z-index:250;max-width:400px;margin:0 auto;background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:18px;box-shadow:0 -8px 40px rgba(0,0,0,0.6);animation:fadeSlideIn 0.25s ease-out;",o.innerHTML='

    🎓 Learn

    ',document.body.appendChild(o),setTimeout(function(){document.addEventListener("click",function e(t){var o=document.getElementById("mobileLearnMenu");!o||o.contains(t.target)||t.target.closest("#bnavLearn")||(o.remove(),document.removeEventListener("click",e))})},100)}},window.toggleMobileFlashcards=function(){var e=document.getElementById("mLearnFlashGrid"),t=document.getElementById("mLearnFlashBtn");e&&("none"===e.style.display?(e.style.display="flex",t&&(t.textContent="📚 Flashcards ▼")):(e.style.display="none",t&&(t.textContent="📚 Flashcards ▶")))},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",f):f()}(),function(){"use strict";var e=null,t=null,o=null,n=null;function i(){if(!(e&&e.readyState<=1))try{(e=new WebSocket("wss://ws.coincap.io/prices?assets=bitcoin")).onopen=function(){console.log("[Dashboard] Price WebSocket connected (CoinCap)"),window._wsDataTimer=setTimeout(function(){t||(console.warn("[Dashboard] WS connected but no data — falling back"),r())},1e4)},e.onmessage=function(e){try{window._wsDataTimer&&(clearTimeout(window._wsDataTimer),window._wsDataTimer=null);var i=JSON.parse(e.data);if(!i.bitcoin)return;var a=parseFloat(i.bitcoin);!n&&t&&(n=t),t=a,n&&(o=(t-n)/n*100),n=parseFloat(i.o);var r=document.getElementById("dashLivePrice");r&&(r.textContent="$"+p(t,2));var s=document.getElementById("dashLiveChange");if(s){var c=o>=0?"#22c55e":"#ef4444",l=o>=0?"▲":"▼";s.innerHTML=''+l+" "+Math.abs(o).toFixed(2)+"% (24h)"}var d=document.getElementById("dashBtnPrice");if(d){var u=o>=0?"#22c55e":"#ef4444",m=o>=0?"▲":"▼";d.innerHTML="$"+p(t,0)+' '+m+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}catch(e){}},e.onclose=function(){console.log("[Dashboard] WS closed, reconnecting..."),e=null,setTimeout(i,5e3)},e.onerror=function(t){console.warn("[Dashboard] WS error, falling back to polling");try{e.close()}catch(e){}e=null,r()}}catch(e){r()}}var a=null;function r(){function e(){fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true").then(function(e){return e.json()}).then(function(e){if(e&&e.bitcoin){t=e.bitcoin.usd,o=e.bitcoin.usd_24h_change||0;var n=document.getElementById("dashLivePrice");n&&(n.textContent="$"+p(t,2));var i=document.getElementById("dashLiveChange");if(i){var a=o>=0?"#22c55e":"#ef4444",r=o>=0?"▲":"▼";i.innerHTML=''+r+" "+Math.abs(o).toFixed(2)+"% (24h)"}var s=document.getElementById("dashBtnPrice");if(s){var c=o>=0?"#22c55e":"#ef4444",l=o>=0?"▲":"▼";s.innerHTML="$"+p(t,0)+' '+l+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}}).catch(function(){})}a||(console.log("[Dashboard] Starting price polling fallback (CoinGecko)"),e(),a=setInterval(e,3e4))}var s="btc_dashboard_cache",c=12e4,l=null,d=!1,u=null;function p(e,t){return null==e?"—":"number"==typeof t?Number(e).toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t}):Number(e).toLocaleString()}function m(e){return null==e?"—":e>=1e12?"$"+(e/1e12).toFixed(1)+"T":e>=1e9?"$"+(e/1e9).toFixed(1)+"B":e>=1e6?"$"+(e/1e6).toFixed(1)+"M":e>=1e3?"$"+(e/1e3).toFixed(0)+"K":"$"+Math.round(e)}function g(e){return null==e?"—":e>=1e12?(e/1e12).toFixed(2)+" T":e>=1e9?(e/1e9).toFixed(2)+" B":p(e)}async function h(){if(d)return await new Promise(function(e){var t=setInterval(function(){d||(clearInterval(t),e())},200);setTimeout(function(){clearInterval(t),d=!1,e()},1e4)}),l||{};d=!0;var e=null;try{var i=JSON.parse(localStorage.getItem(s));if(i&&i.data&&(e=i.data,Date.now()-i.tse.text()).then(e=>{a.blockHeight=parseInt(e);try{localStorage.setItem("btc_last_height",a.blockHeight.toString())}catch(e){}var t=document.getElementById("btcDashCard");t&&!a.price&&a.blockHeight&&(t.innerHTML=f(a))}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/fees/recommended").then(e=>e.json()).then(e=>{a.feeFast=e.fastestFee,a.feeHalf=e.halfHourFee,a.feeHour=e.hourFee,a.feeEcon=e.economyFee,a.feeMin=e.minimumFee}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/mining/hashrate/1m").then(e=>e.json()).then(e=>{if(e.currentHashrate&&(a.hashrate=e.currentHashrate),e.currentDifficulty&&(a.difficulty=e.currentDifficulty),e.hashrates&&e.hashrates.length>=6){var t=e.hashrates.length,o=(e.hashrates[t-1].avgHashrate+e.hashrates[t-2].avgHashrate+e.hashrates[t-3].avgHashrate)/3,n=(e.hashrates[t-4].avgHashrate+e.hashrates[t-5].avgHashrate+e.hashrates[t-6].avgHashrate)/3;n>0&&(a.hashrateChange24h=(o-n)/n*100)}}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/difficulty-adjustment").then(e=>e.json()).then(e=>{a.diffChange=e.difficultyChange,a.diffEstDate=e.estimatedRetargetDate,a.diffRemaining=e.remainingBlocks,a.diffProgress=e.progressPercent}).catch(()=>{})),r.push(fetch("https://mempool.space/api/mempool").then(e=>e.json()).then(e=>{a.mempoolTxs=e.count,a.mempoolSize=e.vsize}).catch(()=>{})),r.push(fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true&include_24hr_vol=true&include_market_cap=true").then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{if(e.bitcoin){a.price=e.bitcoin.usd;try{localStorage.setItem("btc_last_price",e.bitcoin.usd.toString())}catch(e){}a.change24h=e.bitcoin.usd_24h_change,a.volume24h=e.bitcoin.usd_24h_vol,a.marketCap=e.bitcoin.usd_market_cap,!n&&a.price&&a.change24h&&(n=a.price/(1+a.change24h/100),o=a.change24h)}var t=document.getElementById("btcDashCard");return t&&a.price&&(t.innerHTML=f(a)),new Promise(function(e){setTimeout(e,1500)})}).then(function(){return fetch("https://api.coingecko.com/api/v3/coins/bitcoin?localization=false&tickers=false&community_data=false&developer_data=false")}).then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{e.market_data&&(a.supply=e.market_data.circulating_supply,a.ath=e.market_data.ath?e.market_data.ath.usd:null,a.athDate=e.market_data.ath_date?e.market_data.ath_date.usd:null,a.athChange=e.market_data.ath_change_percentage?e.market_data.ath_change_percentage.usd:null,a.high24h=e.market_data.high_24h?e.market_data.high_24h.usd:null,a.low24h=e.market_data.low_24h?e.market_data.low_24h.usd:null,a.mktCapChange24h=e.market_data.market_cap_change_percentage_24h||null)}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/lightning/statistics/latest").then(e=>e.json()).then(e=>{e&&(a.lnCapacity=e.latest?e.latest.total_capacity:e.total_capacity,a.lnNodes=e.latest?e.latest.node_count:e.node_count,a.lnChannels=e.latest?e.latest.channel_count:e.channel_count)}).catch(()=>{})),r.push(fetch("https://api.alternative.me/fng/?limit=1").then(e=>e.json()).then(e=>{e.data&&e.data[0]&&(a.fearGreed=parseInt(e.data[0].value),a.fearGreedLabel=e.data[0].value_classification)}).catch(()=>{})),await Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,12e3))]),!a.price&&t&&(a.price=t);for(var u=[s,"btc_dash_backup"],p=0;p'+(r<=2?"Live metrics · Updates every 2 min":"📦 Data from "+(r<60?r+"m":Math.round(r/60)+"h")+" ago · Refreshing...")+"",a+='',a+="";var s=t||n.price,c=null!==o?o:n.change24h||0,l=c>=0?"#22c55e":"#ef4444",d=c>=0?"▲":"▼";if(a+='
    ',a+='
    $'+p(s,2)+"
    ",a+='
    '+d+" "+Math.abs(c).toFixed(2)+"%
    ",a+='
    🔴 Live — updates automatically · All % changes are 24h
    ',a+='
    ',a+='24h High: $'+p(n.high24h,0)+"",a+='24h Low: $'+p(n.low24h,0)+"",a+="
    ",a+="
    ",void 0!==n.halvingDays){var u=n.halving?((21e4-n.halving)/21e4*100).toFixed(1):0,m=n.halvingEta?n.halvingEta.toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"}):"—";a+='
    ',a+='
    ⏳ Next Halving — Block #'+p(n.halvingBlock)+'
    ',window._halvingTargetMs=Date.now()+10*n.halving*60*1e3,a+='
    ',a+='
    '+(n.halvingDays||0)+'
    Days
    ',a+='
    :
    ',a+='
    '+(n.halvingHours||0)+'
    Hours
    ',a+='
    :
    ',a+='
    '+(n.halvingMins||0)+'
    Mins
    ',a+='
    :
    ',a+='
    00
    Secs
    ',a+="
    ",a+='
    Est. '+m+" · "+p(n.halving)+" blocks remaining
    ",a+='
    ',a+='
    ',a+="
    ",a+='
    '+u+"% through epoch · Subsidy drops "+n.subsidy+" → "+(n.nextSubsidy||"?")+" BTC
    ",a+="
    "}a+='
    ',a+=y("⚡","Sats per Dollar",p(n.satsPerDollar),"Moscow Time","How many satoshis (sats) you get for $1 USD. A satoshi is the smallest unit of Bitcoin (0.00000001 BTC). Also called Moscow Time — the number on the clock is how many sats per dollar."),a+=y("⛓️","Block Height",p(n.blockHeight),"","The total number of blocks mined since Bitcoin's Genesis Block on Jan 3, 2009. A new block is added roughly every 10 minutes. This number only goes up — never down."),a+=y("🪙","Block Subsidy",n.subsidy+" BTC",p(n.halving)+" blocks to halving","The reward miners receive for finding each new block. Started at 50 BTC in 2009 and halves every 210,000 blocks (~4 years). Currently 3.125 BTC per block.");var h,f="";if(null!=n.hashrateChange24h){var v=n.hashrateChange24h;f=''+(v>=0?"▲":"▼")+" "+Math.abs(v).toFixed(1)+"%"}a+=y("⛏️","Hashrate",null==(h=n.hashrate)?"—":h>=1e18?(h/1e18).toFixed(2)+" EH/s":h>=1e15?(h/1e15).toFixed(2)+" PH/s":h>=1e12?(h/1e12).toFixed(2)+" TH/s":h>=1e9?(h/1e9).toFixed(2)+" GH/s":h>=1e6?(h/1e6).toFixed(2)+" M":h>=1e3?(h/1e3).toFixed(1)+"K":p(h),f,"The total computing power securing the Bitcoin network, measured in hashes per second. Higher hashrate = more secure network. EH/s = quintillion hashes per second."),a+=y("🎯","Difficulty",g(n.difficulty),"","How hard it is to mine a new block. Adjusts every 2,016 blocks (~2 weeks) to keep block times at ~10 minutes. If miners join, difficulty goes up. If miners leave, it goes down."),a+=y("🔄","Next Adjustment",(n.diffChange>=0?"+":"")+(n.diffChange||0).toFixed(2)+"%",i+" · "+p(n.diffRemaining)+" blocks","The estimated change in mining difficulty at the next adjustment. Positive means blocks are being found faster than 10 min (more miners joined). Negative means slower (miners left)."),a+=y("💸","Fast Fee",(n.feeFast||"—")+" sat/vB","Half-hour: "+(n.feeHalf||"—")+" · Economy: "+(n.feeEcon||"—"),"The recommended transaction fee in satoshis per virtual byte (sat/vB). Fast = next block (~10 min). Half-hour = 1-3 blocks. Economy = lowest priority. Higher fees = faster confirmation."),a+=y("📋","Mempool",p(n.mempoolTxs)+" txs",n.mempoolSize?(n.mempoolSize/1e6).toFixed(1)+" MvB":"","The waiting room for unconfirmed Bitcoin transactions. Shows how many transactions are waiting to be included in a block and their total size. A full mempool means higher fees."),a+=y("💰","Circulating Supply",function(e){return e?(e/1e6).toFixed(2)+"M / 21M":"—"}(n.supply),function(e){return e?(e/21e6*100).toFixed(2)+"%":"—"}(n.supply)+" mined","How many of the 21 million total Bitcoin have been mined so far. No more than 21 million will ever exist — this is enforced by code and consensus. The last Bitcoin will be mined around the year 2140.");var b="";if(null!=n.mktCapChange24h){var w=n.mktCapChange24h;b=''+(w>=0?"▲":"▼")+" "+Math.abs(w).toFixed(1)+"%"}a+=y("📊","Market Cap","$"+g(n.marketCap),b,"Total value of all Bitcoin in circulation (price × circulating supply). Puts Bitcoin's size in perspective compared to gold (~$16T), the S&P 500, or global real estate.");var x="";n.volume24h&&n.marketCap&&(x="Vol/MCap: "+(n.volume24h/n.marketCap*100).toFixed(2)+"%"),a+=y("📈","24h Volume","$"+g(n.volume24h),x,"Total USD value of Bitcoin traded across all exchanges in the last 24 hours. High volume often signals strong market interest or significant price moves.");var k=n.lnCapacity?(n.lnCapacity/1e8).toFixed(0):"—",_=n.lnCapacity&&n.price?"$"+g(n.lnCapacity/1e8*n.price):"",E=(n.lnNodes?p(n.lnNodes)+" nodes · ":"")+(n.lnChannels?p(n.lnChannels)+" channels":"")+(_?"
    "+_:"");a+=y("⚡","Lightning Capacity",p(k)+" BTC",E,"Total Bitcoin locked in Lightning Network payment channels. Lightning enables instant, near-free Bitcoin payments. More capacity = more liquidity for fast payments. Nodes route payments; channels connect them."),n.ath&&(a+='
    ',a+='🏔️',a+='
    All-Time High
    ',a+='
    $'+p(n.ath,0)+"
    ",a+='
    '+(n.athChange||0).toFixed(1)+"%
    ",n.athDate&&(a+='
    '+new Date(n.athDate).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})+"
    "),a+="
    "),a+="
    ";var A=n.marketCap?n.marketCap/1e12:0;return a+='
    ',a+='
    ⚖️ Bitcoin vs Gold
    ',a+='
    ',a+='
    ₿ Bitcoin$'+A.toFixed(2)+"T
    ",a+='
    ',a+='
    🥇 GoldLoading...
    ',a+='
    Fetching live gold price...
    ',a+="
    ",setTimeout(function(){!function(e,t){if(!T)try{var o=JSON.parse(localStorage.getItem("btc_gold_cache"));o&&o.p&&(T=o.p,S=o.t||0)}catch(e){}T&&Date.now()-S<18e5?B(T,e,t):(T&&B(T,e,t),fetch("https://api.coingecko.com/api/v3/simple/price?ids=tether-gold&vs_currencies=usd").then(function(e){return e.json()}).then(function(o){var n=o["tether-gold"]?o["tether-gold"].usd:null;if(n){T=n,S=Date.now();try{localStorage.setItem("btc_gold_cache",JSON.stringify({p:n,t:Date.now()}))}catch(e){}B(n,e,t)}}).catch(function(){T||B(3200,e,t)}))}(A,n.supply||0)},150),a+='
    ',a+='
    🏛️ Bitcoin Treasuries ⓘ tap for top holders
    ',a+='
    Loading live treasury data...
    ',a+="
    ",setTimeout(function(){!function(e){var t=document.getElementById("treasuryData");if(t){if(!I)try{var o=JSON.parse(localStorage.getItem("btc_treasury_cache"));o&&o.d&&(I=o.d,C=o.t||0)}catch(e){}I&&Date.now()-C<18e5?M(t,I,e):(I&&M(t,I,e),fetch("https://api.coingecko.com/api/v3/companies/public_treasury/bitcoin").then(function(e){return e.json()}).then(function(o){I=o,C=Date.now();try{localStorage.setItem("btc_treasury_cache",JSON.stringify({d:o,t:Date.now()}))}catch(e){}M(t,o,e)}).catch(function(){I||(t.innerHTML='
    Could not load treasury data
    ')}))}}(n.price||0)},200),a+='
    ',a+='
    🏦 Bitcoin ETFs top 5 by BTC in custody
    ',a+='
    Loading ETF holdings...
    ',a+="
    ",setTimeout(function(){!function(e,t){var o=document.getElementById("etfHoldingsData");if(o){var n=e||parseFloat(localStorage.getItem("btc_last_price"))||83e3,i=t||1984e4,a=null;try{a=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"))}catch(e){}a&&a.holdings&&P(o,a.holdings,a.totalBtc,n,i,a.updated),fetch("data/etf-holdings.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.holdings&&e.holdings.length){try{localStorage.setItem("btc_etf_holdings_cache",JSON.stringify(e))}catch(e){}P(o,e.holdings,e.totalBtc,n,i,e.updated)}}).catch(function(){a||P(o,z,L,n,i,null)})}}(n.price||0,n.supply||0)},250),a+='
    ',a+='',a+='
    ",a+='
    ',a+="Data Sources: ",a+='mempool.space (blocks, fees, hashrate, difficulty, mempool) · ',a+='CoinGecko (price, market cap, supply, volume) · ',a+='Alternative.me (Fear & Greed Index) · ',a+='BitcoinTreasuries.net (company & government holdings)',a+='
    Last updated: '+new Date(n.ts||Date.now()).toLocaleTimeString()+"
    ",a+="
    ",setTimeout(function(){window._halvingTargetMs&&document.getElementById("halvSecs")&&"function"==typeof window._startHalvingTicker&&window._startHalvingTicker(),"function"==typeof window._attachTipListeners&&window._attachTipListeners()},100),a}function y(e,t,o,n,i){return"
    '+e+" "+t+(i?' ':"")+'
    '+(o||"—")+"
    "+(n?'
    '+n+"
    ":"")+""}setInterval(function(){d&&(console.warn("[Dashboard] Force-clearing stuck loading flag"),d=!1)},15e3);var v="ontouchstart"in window||navigator.maxTouchPoints>0;function b(){injectDashboardButton(),injectHomeDashboardButton(),i()}window.showDashTip=function(e,t){var o=document.getElementById("dashTipPopup");o&&o.remove();var n=document.createElement("div");n.id="dashTipPopup",n.style.cssText="position:absolute;left:50%;transform:translateX(-50%);bottom:calc(100% + 8px);z-index:10;background:var(--bg-side,#1a1a2e);border:1px solid var(--accent);border-radius:10px;padding:10px 14px;max-width:320px;width:max-content;box-shadow:0 8px 24px rgba(0,0,0,0.5);animation:fadeSlideIn 0.2s ease-out;pointer-events:auto;",n.innerHTML='
    '+t.replace(/\\n/g,"
    ").replace(/\n/g,"
    ")+'
    ',e.style.position="relative",e.appendChild(n),setTimeout(function(){document.addEventListener("click",function e(t){n.parentNode&&n.remove(),document.removeEventListener("click",e)},{once:!0})},50)},window.hideDashTip=function(e){var t=e?e.querySelector("#dashTipPopup"):document.getElementById("dashTipPopup");t&&t.remove()},window._attachTipListeners=function(){document.querySelectorAll("[data-dash-tip]:not([data-tip-bound])").forEach(function(e){e.setAttribute("data-tip-bound","1");var t=e.getAttribute("data-dash-tip");t&&(v?e.addEventListener("click",function(o){o.stopPropagation();var n=e.querySelector("#dashTipPopup");n?n.remove():showDashTip(e,t)}):(e.addEventListener("mouseenter",function(){showDashTip(e,t)}),e.addEventListener("mouseleave",function(){hideDashTip(e)})))})},window.injectDashboardButton=function(){},window.injectHomeDashboardButton=function(){},window.toggleDashboard=async function(){var e=document.getElementById("btcDashOverlay");if(e)return e.remove(),clearInterval(u),void(u=null);var t=document.createElement("div");t.id="btcDashOverlay",t.style.cssText="position:fixed;inset:0;z-index:10002;background:rgba(0,0,0,0.88);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&closeDashboard()};var o=document.createElement("div");o.id="btcDashCard",o.style.cssText="background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:24px;max-width:500px;width:100%;margin:40px auto;box-shadow:0 20px 60px rgba(0,0,0,0.5);animation:fadeSlideIn 0.3s ease-out;",t.appendChild(o),document.body.appendChild(t),i();var n=!1;try{var a=JSON.parse(localStorage.getItem(s));a&&a.data&&(a.data.price||a.data.blockHeight)&&(o.innerHTML=f(a.data),n=!0)}catch(e){}if(!n){var r={};if("undefined"!=typeof nachoLiveData&&(nachoLiveData.price&&(r.price=nachoLiveData.price),nachoLiveData.blockHeight&&(r.blockHeight=nachoLiveData.blockHeight)),!r.price)try{r.price=parseFloat(localStorage.getItem("btc_last_price"))||0}catch(e){}if(!r.blockHeight)try{r.blockHeight=parseInt(localStorage.getItem("btc_last_height"))||0}catch(e){}r.price||r.blockHeight?(o.innerHTML=f(r),n=!0):o.innerHTML='
    Loading Bitcoin metrics...
    '}h().then(function(e){var t=document.getElementById("btcDashCard");if(t){var o=document.getElementById("topIndicatorsPanel"),i=o&&"none"!==o.style.display;if(e&&(e.price||e.blockHeight)?t.innerHTML=f(e):n||(t.innerHTML='
    📊
    Unable to load fresh metrics.
    Showing last known data. Try again later.
    '),i){var a=document.getElementById("topIndicatorsPanel"),r=document.getElementById("topIndArrow");a&&(a.style.display="block",w=!1,k()),r&&(r.textContent="▲")}}}),u=setInterval(async function(){if(document.getElementById("btcDashOverlay")){var e=document.getElementById("topIndicatorsPanel"),t=e&&"none"!==e.style.display;localStorage.removeItem(s);var o=await h(),n=document.getElementById("btcDashCard");if(n&&(n.innerHTML=f(o),t)){var i=document.getElementById("topIndicatorsPanel"),a=document.getElementById("topIndArrow");i&&(i.style.display="block",w=!1,k()),a&&(a.textContent="▲")}}else clearInterval(u)},c)},window.closeDashboard=function(){var e=document.getElementById("btcDashOverlay");e&&e.remove(),u&&(clearInterval(u),u=null)},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(b,2e3)}):setTimeout(b,2e3),window.toggleTopIndicators=function(){var e=document.getElementById("topIndicatorsPanel"),t=document.getElementById("topIndArrow");e&&("none"===e.style.display?(e.style.display="block",t.textContent="▲",k()):(e.style.display="none",t.textContent="▼"))};var w=!1,x="btc_top_indicators_cache";function k(){if(!w){w=!0;var e=document.getElementById("topIndContent");if(e){try{var t=JSON.parse(localStorage.getItem(x));if(t&&t.html){var o=Math.round((Date.now()-t.ts)/6e4),n=o>5?'
    📦 Cached '+(o<60?o+"m":Math.round(o/60)+"h")+" ago · refreshing...
    ":"";e.innerHTML=n+t.html}}catch(e){}var i=l||{},a=i.price||0,r=i.blockHeight||0,s=i.supply||0,c=i.fearGreed||0,d=i.fearGreedLabel||"—",u=[];if(r){var m=Math.floor(r/21e4),g=50/Math.pow(2,m)*6*24*365,h=g>0?(s||198e5)/g:0,f=Math.pow(10,3.31954*Math.log10(h)-1.32093),y=a>0?(a/f).toFixed(2):"—";u.push({emoji:"📈",name:"Stock-to-Flow",value:h.toFixed(1),sub:"Model: $"+p(Math.round(f))+" · Ratio: "+y+"x",tip:"Stock-to-Flow measures scarcity. Higher S2F = scarcer asset. Bitcoin's S2F increases with each halving. Gold is ~62, Silver ~22. A ratio below 1x suggests undervalued vs the model."})}if(c){var v=c<=25?"#ef4444":c<=45?"#f97316":c<=55?"#eab308":c<=75?"#84cc16":"#22c55e";u.push({emoji:"😱",name:"Fear & Greed",value:c,color:v,sub:d,tip:"Crypto Fear & Greed Index. 0 = Extreme Fear (potential buy), 100 = Extreme Greed (potential sell). Aggregates volatility, momentum, social media, and surveys."})}if(u.push({emoji:"📐",name:"Mayer Multiple",value:"...",sub:"Loading...",tip:"Price divided by 200-day moving average. Below 1.0 = historically cheap. Above 2.4 = overheated. Named after Trace Mayer.",id:"mayerMultiple"}),r){var b=r%21e4,k=(b/21e4*100).toFixed(1),T=Math.round(10*b/1440),S=T>=365&&T<=730;u.push({emoji:"🔄",name:"Halving Cycle",value:k+"%",sub:"Day "+T+"/~1460"+(S?" · 🔥 Peak Window":""),color:S?"#f97316":null,tip:"Position in the current 4-year halving cycle (210,000 blocks). Historically, price peaks occur 12-24 months after a halving (Day 365-730). We are at day "+T+"."})}if(i.ath&&i.athDate){var _=new Date(i.athDate),B=Math.floor((Date.now()-_.getTime())/864e5),I=i.athChange?Math.abs(i.athChange).toFixed(1):"—";u.push({emoji:"🏔️",name:"ATH Drawdown",value:"-"+I+"%",sub:B+" days since ATH ($"+p(Math.round(i.ath))+")",tip:"Current drawdown from the all-time high. In previous cycles, bear markets saw -70% to -85% drawdowns. Recovery to new ATH has always followed."})}if(a&&s&&r){m=Math.floor(r/21e4);for(var C=0,E=r,A=0;A<=m&&E>0;A++){var M=Math.min(E,21e4);C+=M*(50/Math.pow(2,A)),E-=M}var z=3e4*C,P=z>0?(a*s/z).toFixed(1):"—";u.push({emoji:"🌡️",name:"Thermo Multiple",value:P+"x",sub:"Market Cap / Thermocap",tip:'Thermocap Multiple compares market cap to total miner revenue (a proxy for "energy spent"). Values >5x historically signal overheating (cycle tops hit 4-8x). <10x = accumulation zone.'})}if(a&&s&&i.volume24h){var U=a*s,N=i.volume24h>0?(U/i.volume24h).toFixed(1):"—",H=N<30?"#22c55e":N>150?"#ef4444":"var(--heading)";u.push({emoji:"📡",name:"NVT Ratio",value:N,color:H,sub:N<30?"Undervalued zone":N>150?"Overvalued zone":"Normal range",tip:"Network Value to Transactions ratio. Compares market cap to annualized transaction volume. Below 30 = undervalued relative to usage. Above 150 = potentially overvalued. Think of it like P/E ratio for Bitcoin."})}if(i.marketCap){var q=i.marketCap/.62;(i.marketCap/q*100).toFixed(1),u.push({emoji:"👑",name:"BTC Dominance",value:"~62%",sub:"Market cap share vs all crypto",tip:"Bitcoin's share of the total cryptocurrency market cap. Higher dominance = Bitcoin is outperforming alts. During alt seasons, dominance drops below 40%. During Bitcoin seasons (now), it rises above 55-65%. Historically, increasing dominance signals strength.",id:"btcDominance"})}if(u.push({emoji:"💎",name:"MVRV Z-Score",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Market Value to Realized Value ratio. Compares market cap to realized cap (sum of each coin valued at its last move price). Above 3.0 historically marks cycle tops. Below 1.0 marks bottoms. Data from CBBI open-source API. Top threshold: normalized ≥ 0.7 (≈ MVRV 3+).",id:"mvrvScore"}),a){var D=new Date("2009-01-03T00:00:00Z"),O=Math.floor((Date.now()-D.getTime())/864e5),j=5.82*Math.log10(O)-17.01,R=Math.pow(10,j),F=((a-R)/R*100).toFixed(0),W=parseFloat(F),V=W>200?"#ef4444":W>100?"#f97316":W<-30?"#22c55e":"var(--heading)",G=W>200,Q=W>200?"Far above — extreme ⚠️":W>100?"Above trend — elevated":W>0?"Above fair value":W>-30?"Near fair value":"Below trend — deep value 🟢";u.push({emoji:"📏",name:"Power Law",value:(W>=0?"+":"")+F+"%",color:V,sub:"Fair value: ~$"+p(Math.round(R))+" · "+Q,tip:"Bitcoin Power Law model tracks the long-term price trend using a log-log regression since genesis (Jan 3, 2009). Parameters: P = 10^(5.82 × log₁₀(days) - 17.01). Above +200% = historically extreme (cycle top zone). Below -30% = deep value accumulation. Current: "+O+" days since genesis.",flashing:G})}if(u.push({emoji:"🔵",name:"Pi Cycle Top",value:"...",sub:"Loading...",tip:"When the 111-day MA crosses above the 350-day MA × 2, it has historically signaled the exact top of every Bitcoin cycle. Flashes when the gap narrows to <5%.",id:"piCycleTop",flashing:!1}),r&&a){var Y=(144*(i.subsidy?parseFloat(i.subsidy):3.125)*a/27e6).toFixed(2),J=parseFloat(Y);u.push({emoji:"⛏️",name:"Puell Multiple",value:Y,color:J>2.2?"#ef4444":J<.5?"#22c55e":"var(--heading)",sub:J>2.2?"Miners overleveraged ⚠️":J<.5?"Miner capitulation zone 🟢":"Normal range",tip:"Ratio of daily miner revenue to its 365-day moving average. Above 2.2 = miners are earning far more than usual (historically a sell signal). Below 0.5 = miner capitulation (buy signal). Top threshold: ≥ 2.2.",flashing:J>=2.2})}if(a){for(var X=new Date("2010-07-18"),K=Math.floor((Date.now()-X.getTime())/864e5),$=Math.log(K+1400),Z=[2.775,2.788,2.801,2.815,2.8295,2.8445,2.859,2.872,2.886,2.9],ee=10,te=0;te=9})}if(a){for(var ae=new Date("2009-01-03T00:00:00Z"),re=Math.floor((Date.now()-ae.getTime())/864e5),se=0,ce=0;ce<1460;ce++){var le=re-ce;le>365&&(se+=Math.pow(10,5.82*Math.log10(le)-17.01))}var de=se/1460,ue=de>0?(a/de).toFixed(2):"—",pe=parseFloat(ue);u.push({emoji:"📊",name:"4-Year MA Multiple",value:ue+"x",color:pe>=3.5?"#ef4444":pe<1?"#22c55e":"var(--heading)",sub:"Est. 4Y MA: ~$"+p(Math.round(de))+(pe>=3.5?" · Top zone ⚠️":""),tip:"Price divided by the 4-year (1460-day) moving average. Historically, when price exceeds 3.5× the 4-year MA, it signals a cycle top. Below 1× = accumulation zone. Top threshold: ≥ 3.5.",flashing:pe>=3.5})}if(u.push({emoji:"💰",name:"NUPL",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Net Unrealized Profit/Loss. Shows aggregate profit/loss of all Bitcoin holders. Above 75% = euphoria (top zone). Below 0% = capitulation (bottom zone). Data from CBBI open-source API. Top threshold: normalized ≥ 0.75.",id:"nuplScore"}),a&&r){var me=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),ge=Math.pow(10,5.82*Math.log10(me)-17.01),he=ge>0?(a/ge).toFixed(2):"—",fe=parseFloat(he);u.push({emoji:"🔢",name:"AHR999",value:he,color:fe>1.2?"#ef4444":fe<.45?"#22c55e":"var(--heading)",sub:fe>1.2?"Overvalued — stop DCA ⚠️":fe<.45?"Deep value — DCA zone 🟢":fe<1?"Below model — DCA":"Near model",tip:"AHR999 compares current price to its long-term model value. Below 0.45 = extreme buy (accumulate aggressively). Above 1.2 = stop DCA, consider selling. Used by cost-averaging investors to time entries. Top threshold: ≥ 1.2.",flashing:fe>=1.2})}if(a){for(var ye=new Date("2009-01-03T00:00:00Z"),ve=Math.floor((Date.now()-ye.getTime())/864e5),be=0,we=0;we<730;we++){var xe=ve-we;xe>365&&(be+=Math.pow(10,5.82*Math.log10(xe)-17.01))}var ke=be/730,Te=5*ke,Se=a>Te;u.push({emoji:"📉",name:"2-Year MA ×5",value:(a/ke).toFixed(2)+"x",color:Se?"#ef4444":a365&&(Ie+=Math.pow(10,5.82*Math.log10(Ee)-17.01))}var Ae=Ie/350,Me=Ae>0?(a/Ae).toFixed(2):"—",ze=parseFloat(Me),Le=ze>=8?"Above ×8 — max top ⚠️":ze>=5?"Above ×5 — overheated":ze>=3?"Above ×3 — elevated":ze>=1.6?"Above ×1.6 — bullish":"Below ×1.6";u.push({emoji:"🔱",name:"Golden Ratio",value:Me+"x",color:ze>=5?"#ef4444":ze>=3?"#f97316":"var(--heading)",sub:"350d MA: $"+p(Math.round(Ae))+" · "+Le,tip:"Price relative to the 350-day MA using Fibonacci golden ratio multiples (1.6, 2, 3, 5, 8, 13, 21). Each cycle top has touched a lower multiple. Top threshold: ≥ 5×.",flashing:ze>=5})}if(r&&s&&a){for(var Pe=0,Ue=r,Ne=0;Ne<=Math.floor(r/21e4)&&Ue>0;Ne++){var He=Math.min(Ue,21e4);Pe+=He*(50/Math.pow(2,Ne)),Ue-=He}var qe=21*(s>0?3e4*Pe/s:0),De=qe>0?(a/qe*100).toFixed(0):"—";u.push({emoji:"🎯",name:"Terminal Price",value:"$"+p(Math.round(qe)),color:a>=qe?"#ef4444":"var(--heading)",sub:"Current: "+De+"% of terminal · "+(a>=qe?"ABOVE — extreme ⚠️":"Below terminal"),tip:"Terminal Price = Transferred Price × 21. Represents a theoretical maximum based on cumulative miner revenue and coin movement. Every cycle top has approached or exceeded this level. Top threshold: price ≥ Terminal Price.",flashing:a>=qe})}if(a){var Oe=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),je=Math.pow(10,5.82*Math.log10(Oe)-17.01),Re=(je>0?(Math.log10(a)-Math.log10(je))/.3:0).toFixed(1),Fe=parseFloat(Re);u.push({emoji:"🫧",name:"Bubble Index",value:Re+"σ",color:Fe>=2?"#ef4444":Fe>=1?"#f97316":Fe<-1?"#22c55e":"var(--heading)",sub:Fe>=2?"Extreme bubble ⚠️":Fe>=1?"Elevated":Fe<-1?"Deep discount 🟢":"Normal",tip:"How many standard deviations Bitcoin's price is above its long-term log trend. Above +2σ = extreme bubble territory (historical tops). Below -1σ = deep value. Top threshold: ≥ 2σ.",flashing:Fe>=2})}if(a){var We=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),Ve=Math.pow(10,5.82*Math.log10(We-90)-17.01),Ge=(Ve>0?100*(Math.pow(a/Ve,4)-1):0).toFixed(0),Qe=parseFloat(Ge);u.push({emoji:"🚀",name:"3M Annualized",value:(Qe>=0?"+":"")+Ge+"%",color:Qe>200?"#ef4444":Qe>100?"#f97316":"var(--heading)",sub:Qe>200?"Unsustainable — top risk ⚠️":Qe>100?"Very high":"Normal",tip:"3-month return annualized. When Bitcoin is gaining over 200% annualized, it historically signals the late stages of a bull run. Top threshold: > 200%.",flashing:Qe>200,id:"ann3m"})}if(a){var Ye=75694,Je=762099,Xe=((a-Ye)/Ye*100).toFixed(1);u.push({emoji:"🏢",name:"MSTR Avg Cost",value:"$"+p(Ye),sub:p(Je)+" BTC · P&L: "+(Xe>=0?"+":"")+Xe+"%",tip:"MicroStrategy (MSTR) average Bitcoin acquisition cost. When price is far above MSTR's cost basis, it indicates broader market euphoria. MSTR holds "+p(Je)+" BTC. Informational — no top threshold.",flashing:!1,noFlashLogic:!0})}if(u.push({emoji:"🎯",name:"CBBI Index",value:"...",color:"var(--heading)",sub:"Loading CBBI data...",tip:"Colin Talks Crypto Bitcoin Bull Run Index. Combines 9 on-chain metrics into a single 0-100 confidence score. Above 80 = approaching cycle top. Below 20 = approaching bottom. Open source. Top threshold: ≥ 80.",id:"cbbiScore"}),u.push({emoji:"💎",name:"RHODL Ratio",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Realized HODL Ratio. Compares 1-week realized value to 1-2 year realized value, adjusted by market age. High values = speculative activity dominating (top signal). Low values = long-term holders dominating. Top threshold: normalized ≥ 0.85.",id:"rhodlRatio"}),u.push({emoji:"📊",name:"Macro Oscillator",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Bitcoin Macro Oscillator (Woobull). Composite z-score of MVRV, VWAP, CVDD, and Sharpe ratios. Above 0.7 = euphoria zone. Below 0.2 = accumulation zone. Top threshold: normalized ≥ 0.7.",id:"macroOsc"}),a){var Ke=23e4,$e=(a/Ke*100).toFixed(1);u.push({emoji:"🔮",name:"Smithson's Forecast",value:$e+"%",color:parseFloat($e)>=90?"#ef4444":"var(--heading)",sub:"Target: $"+p(175e3)+"-$"+p(Ke)+" · Current: $"+p(Math.round(a)),tip:"Sminston With quantile regression model (99th percentile). Forecasts cycle top at $175K-$230K. Progress shows how close current price is to the upper target. Top threshold: ≥ 90% of target.",flashing:parseFloat($e)>=90})}u.push({emoji:"⏳",name:"LTH/STH Ratio",value:"...",color:"var(--heading)",sub:"Estimated from CBBI data...",tip:"Long-Term Holder to Short-Term Holder supply ratio (estimated). When LTH supply drops sharply (distributing to STH), it signals late-cycle selling. When LTH supply grows, holders are accumulating. Derived from CBBI on-chain metrics. Top threshold: CBBI MVRV + Puell both > 0.7.",id:"lthSthRatio"}),u.push({emoji:"📉",name:"RSI-22 Day",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Relative Strength Index over 22 days. Above 80 = overbought (potential top signal). Below 30 = oversold (potential bottom). 22-day RSI smooths out short-term noise. Top threshold: ≥ 80.",id:"rsi22d"}),u.push({emoji:"🚨",name:"AHR999x",value:"...",color:"var(--heading)",sub:"Loading 200d MA...",tip:"AHR999x Escape Top indicator. Calculated as (price / 200-day MA)². When above 8, signals extreme overvaluation. Above 3.5 = elevated. A complement to the AHR999 DCA indicator. Top threshold: ≥ 8.",id:"ahr999x"}),u.push({emoji:"🏦",name:"ETF/BTC Ratio",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Bitcoin spot ETF total AUM divided by BTC market cap. Shows how much of Bitcoin's value is held in ETFs. High ratios (>8%) could indicate institutional overexposure. Low ratios = room to grow. Top threshold: ≥ 8%.",id:"etfBtcRatio"}),u.push({emoji:"📊",name:"ETF Net Flow",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Daily Bitcoin spot ETF net inflows/outflows. Sustained outflows (7+ days) can signal institutional selling. Sustained inflows signal demand. Data from Bitbo/BitcoinTreasuries. Top threshold: 7+ consecutive outflow days.",flashing:!1,id:"etfNetFlow"}),u.push({emoji:"📈",name:"ETF 5-Day Flow",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Sum of last 5 trading days of ETF flows. Large negative = sustained selling pressure. Large positive = accumulation. Top threshold: 5-day sum below -$500M.",flashing:!1,id:"etf5dFlow"}),u.forEach(function(e){if(!e.noFlashLogic&&void 0===e.flashing){var t=e.name;e.flashing="Stock-to-Flow"===t?a>0&&f>0&&a>1.5*f:"Fear & Greed"===t?c>=75:"Mayer Multiple"!==t&&("Halving Cycle"===t?e.sub&&-1!==e.sub.indexOf("Peak Window"):"ATH Drawdown"===t?parseFloat(e.value)>-5:"Thermo Multiple"===t?parseFloat(e.value)>5:"NVT Ratio"===t&&parseFloat(e.value)>150)}});var Ze=u.filter(function(e){return e.flashing}).length,et=u.filter(function(e){return!e.noFlashLogic}).length,tt="",ot=et>0?Math.round(Ze/et*100):0,nt=0===Ze?"#22c55e":ot<15?"#eab308":ot<40?"#f97316":"#ef4444";tt+='
    ',tt+='
    '+Ze+" / "+et+"
    ",tt+='
    '+(0===Ze?"No top signals — Accumulate 🟢":ot<15?"Few signals — Monitor 🟡":ot<40?"Multiple signals — Caution 🟠":"Many signals — Extreme caution 🔴")+"
    ",tt+='
    Top indicators flashing 🔴 = potential cycle top signal
    ',tt+="
    ",u.forEach(function(e){var t=e.flashing?"rgba(239,68,68,0.5)":"var(--border)",o=e.flashing?"background:rgba(239,68,68,0.04);":"";tt+="",e.noFlashLogic||(e.flashing?tt+='
    🔴 TOP
    ':tt+='
    🟢 OK
    '),tt+='
    '+e.emoji+" "+e.name+(e.tip?' ':"")+"
    ",tt+='
    '+(e.value||"—")+"
    ",e.sub&&(tt+='
    '+e.sub+"
    "),tt+=""}),tt+='',e.innerHTML=tt,setTimeout(function(){"function"==typeof window._attachTipListeners&&window._attachTipListeners()},50);try{localStorage.setItem(x,JSON.stringify({html:tt,ts:Date.now()}))}catch(e){}fetch("https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=365&interval=daily").then(function(e){return e.json()}).then(function(e){if(e&&e.prices&&e.prices.length>=200){for(var t=e.prices,o=t.length,n=0,i=Math.max(0,o-200);i2.4?"#ef4444":"var(--heading)";c.style.color=l,c.textContent=s+"x";var d=c.nextElementSibling;d&&(d.textContent="200d MA: $"+p(Math.round(a))+(s<1?" · Below MA ✅":s>2.4?" · Overheated ⚠️":""));var u=c.closest('div[style*="border-radius:12px"]');if(u&&s>2.4){u.style.borderColor="rgba(239,68,68,0.5)",u.style.background="rgba(239,68,68,0.04)";var m=u.querySelector('div[style*="OK"]');m&&(m.innerHTML="🔴 TOP",m.style.color="#ef4444",m.style.background="rgba(239,68,68,0.15)",m.style.borderColor="rgba(239,68,68,0.4)")}}if(o>=111){for(var g=0,h=o-111;h0?((f-w)/w*100).toFixed(1):0,k=parseFloat(x),T=document.getElementById("piCycleTop");if(T){var S=k>=0;T.textContent=(k>=0?"+":"")+x+"%",T.style.color=S?"#ef4444":k>-5?"#f97316":"var(--heading)";var _=T.nextElementSibling;_&&(_.textContent="111d: $"+p(Math.round(f))+" vs 350d×2: $"+p(Math.round(w))+(S?" · CROSSED ⚠️":k>-5?" · Narrowing!":""));var B=T.closest('div[style*="border-radius:12px"]');if(B&&S){B.style.borderColor="rgba(239,68,68,0.5)",B.style.background="rgba(239,68,68,0.04)";var I=B.querySelector('div[style*="OK"]');I&&(I.innerHTML="🔴 TOP",I.style.color="#ef4444",I.style.background="rgba(239,68,68,0.15)",I.style.borderColor="rgba(239,68,68,0.4)")}}}if(o>=23){for(var C=0,E=0,A=o-22;A0?C+=M:E-=M}var z=E/22,L=0===z?100:100-100/(1+C/22/z),P=L.toFixed(1),U=document.getElementById("rsi22d");if(U){var N=L>=80;U.textContent=P,U.style.color=L>=80?"#ef4444":L<=30?"#22c55e":"var(--heading)";var H=U.nextElementSibling;if(H&&(H.textContent=L>=80?"Overbought ⚠️":L<=30?"Oversold ✅":L>=60?"Bullish":L<=40?"Bearish":"Neutral"),N){var q=U.closest('div[style*="border-radius:12px"]');if(q){q.style.borderColor="rgba(239,68,68,0.5)",q.style.background="rgba(239,68,68,0.04)";var D=q.querySelector('div[style*="OK"]');D&&(D.innerHTML="🔴 TOP",D.style.color="#ef4444",D.style.background="rgba(239,68,68,0.15)",D.style.borderColor="rgba(239,68,68,0.4)")}}}}var O=Math.pow(r/a,2).toFixed(2),j=document.getElementById("ahr999x");if(j){var R=parseFloat(O),F=R>=8;j.textContent=O,j.style.color=R>=8?"#ef4444":R>=3.5?"#f97316":"var(--heading)";var W=j.nextElementSibling;if(W&&(W.textContent="200d MA: $"+p(Math.round(a))+(R>=8?" · Extreme top ⚠️":R>=3.5?" · Elevated":R<1?" · Below MA":" · Normal")),F){var V=j.closest('div[style*="border-radius:12px"]');if(V){V.style.borderColor="rgba(239,68,68,0.5)",V.style.background="rgba(239,68,68,0.04)";var G=V.querySelector('div[style*="OK"]');G&&(G.innerHTML="🔴 TOP",G.style.color="#ef4444",G.style.background="rgba(239,68,68,0.15)",G.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("mayerMultiple");e&&(e.textContent="N/A")}),fetch("https://api.coingecko.com/api/v3/global").then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.market_cap_percentage&&e.data.market_cap_percentage.btc){var t=e.data.market_cap_percentage.btc.toFixed(1),o=document.getElementById("btcDominance");if(o){o.textContent=t+"%";var n=t>55?"#22c55e":t<40?"#ef4444":"var(--heading)";o.style.color=n;var i=o.nextElementSibling;i&&(i.textContent=t>55?"Bitcoin season 👑":t<40?"Alt season ⚠️":"Neutral")}}}).catch(function(){}),fetch("https://colintalkscrypto.com/cbbi/data/latest.json").then(function(e){return e.json()}).then(function(e){if(e&&e.Confidence){var t=Object.keys(e.Confidence).sort(),o=t[t.length-1],n=(100*e.Confidence[o]).toFixed(0),i=parseInt(n),a=document.getElementById("cbbiScore");if(a){a.textContent=n+"%",a.style.color=i>=80?"#ef4444":i<=20?"#22c55e":"var(--heading)";var r=a.nextElementSibling;if(r&&(r.textContent=i>=80?"Approaching top ⚠️":i<=20?"Approaching bottom 🟢":i>=50?"Mid-cycle bullish":"Early cycle"),i>=80){var s=a.closest('div[style*="border-radius:12px"]');if(s){s.style.borderColor="rgba(239,68,68,0.5)",s.style.background="rgba(239,68,68,0.04)";var c=s.querySelector('div[style*="OK"]');c&&(c.innerHTML="🔴 TOP",c.style.color="#ef4444",c.style.background="rgba(239,68,68,0.15)",c.style.borderColor="rgba(239,68,68,0.4)")}}}var l=Object.keys(e.RHODL).sort(),d=e.RHODL[l[l.length-1]],u=document.getElementById("rhodlRatio");if(u){u.textContent=(100*d).toFixed(0)+"%",u.style.color=d>=.85?"#ef4444":d<=.2?"#22c55e":"var(--heading)";var p=u.nextElementSibling;if(p&&(p.textContent=d>=.85?"Speculative frenzy ⚠️":d<=.2?"Accumulation zone 🟢":"Normalized: "+(100*d).toFixed(0)+"%"),d>=.85){var m=u.closest('div[style*="border-radius:12px"]');if(m){m.style.borderColor="rgba(239,68,68,0.5)",m.style.background="rgba(239,68,68,0.04)";var g=m.querySelector('div[style*="OK"]');g&&(g.innerHTML="🔴 TOP",g.style.color="#ef4444",g.style.background="rgba(239,68,68,0.15)",g.style.borderColor="rgba(239,68,68,0.4)")}}}var h=Object.keys(e.Woobull).sort(),f=e.Woobull[h[h.length-1]],y=document.getElementById("macroOsc");if(y){y.textContent=(100*f).toFixed(0)+"%",y.style.color=f>=.7?"#ef4444":f<=.2?"#22c55e":"var(--heading)";var v=y.nextElementSibling;if(v&&(v.textContent=f>=.7?"Euphoria zone ⚠️":f<=.2?"Accumulation 🟢":"Normalized: "+(100*f).toFixed(0)+"%"),f>=.7){var b=y.closest('div[style*="border-radius:12px"]');if(b){b.style.borderColor="rgba(239,68,68,0.5)",b.style.background="rgba(239,68,68,0.04)";var w=b.querySelector('div[style*="OK"]');w&&(w.innerHTML="🔴 TOP",w.style.color="#ef4444",w.style.background="rgba(239,68,68,0.15)",w.style.borderColor="rgba(239,68,68,0.4)")}}}var x=Object.keys(e.MVRV).sort(),k=Object.keys(e.Puell).sort(),T=e.MVRV[x[x.length-1]],S=e.Puell[k[k.length-1]],_=document.getElementById("lthSthRatio");if(_){var B=((T+S)/2*100).toFixed(0),I=parseInt(B);_.textContent=I+"%",_.style.color=I>=70?"#ef4444":I<=25?"#22c55e":"var(--heading)";var C=_.nextElementSibling;if(C&&(C.textContent=I>=70?"LTH distributing ⚠️":I<=25?"LTH accumulating 🟢":"Distribution score: "+I+"%"),I>=70){var E=_.closest('div[style*="border-radius:12px"]');if(E){E.style.borderColor="rgba(239,68,68,0.5)",E.style.background="rgba(239,68,68,0.04)";var A=E.querySelector('div[style*="OK"]');A&&(A.innerHTML="🔴 TOP",A.style.color="#ef4444",A.style.background="rgba(239,68,68,0.15)",A.style.borderColor="rgba(239,68,68,0.4)")}}}var M=document.getElementById("mvrvScore");if(M){var z=(100*T).toFixed(0);M.textContent=z+"%",M.style.color=T>=.7?"#ef4444":T<=.2?"#22c55e":"var(--heading)";var L=M.nextElementSibling;if(L&&(L.textContent=T>=.7?"Overvalued — top zone ⚠️":T<=.2?"Undervalued — accumulate 🟢":"Normalized: "+z+"%"),T>=.7){var P=M.closest('div[style*="border-radius:12px"]');if(P){P.style.borderColor="rgba(239,68,68,0.5)",P.style.background="rgba(239,68,68,0.04)";var U=P.querySelector('div[style*="OK"]');U&&(U.innerHTML="🔴 TOP",U.style.color="#ef4444",U.style.background="rgba(239,68,68,0.15)",U.style.borderColor="rgba(239,68,68,0.4)")}}}var N=Object.keys(e.RUPL).sort(),H=e.RUPL[N[N.length-1]],q=document.getElementById("nuplScore");if(q){var D=(100*H).toFixed(0);q.textContent=D+"%",q.style.color=H>=.75?"#ef4444":H<=.2?"#22c55e":"var(--heading)";var O=q.nextElementSibling;if(O&&(O.textContent=H>=.75?"Euphoria ⚠️":H<=.2?"Capitulation zone 🟢":"Normalized: "+D+"%"),H>=.75){var j=q.closest('div[style*="border-radius:12px"]');if(j){j.style.borderColor="rgba(239,68,68,0.5)",j.style.background="rgba(239,68,68,0.04)";var R=j.querySelector('div[style*="OK"]');R&&(R.innerHTML="🔴 TOP",R.style.color="#ef4444",R.style.background="rgba(239,68,68,0.15)",R.style.borderColor="rgba(239,68,68,0.4)")}}}var F=Object.keys(e.ReserveRisk).sort();e.ReserveRisk[F[F.length-1]];try{localStorage.setItem("cbbi_cache",JSON.stringify({ts:Date.now(),confidence:n,rhodl:d,woobull:f,mvrv:T,puell:S}))}catch(e){}}}).catch(function(){try{var e=JSON.parse(localStorage.getItem("cbbi_cache"));if(e&&Date.now()-e.ts<864e5){var t=document.getElementById("cbbiScore");t&&(t.textContent=e.confidence+"%")}}catch(e){}}),fetch("data/etf-flows.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.latestFlow){var t=document.getElementById("etfNetFlow");if(t){var o=e.latestFlow,n=(o>=0?"+":"")+o.toFixed(1)+"M";t.textContent=n,t.style.color=o>0?"#22c55e":o<-100?"#ef4444":o<0?"#f97316":"var(--heading)";var i=t.nextElementSibling;if(i&&(i.textContent=e.latestDate+" · "+e.outflowDays+"/"+e.totalDays+" outflow days"+(e.outflowDays>=7?" ⚠️":"")),e.outflowDays>=7){var a=t.closest('div[style*="border-radius:12px"]');if(a){a.style.borderColor="rgba(239,68,68,0.5)",a.style.background="rgba(239,68,68,0.04)";var r=a.querySelector('div[style*="OK"]');r&&(r.innerHTML="🔴 TOP",r.style.color="#ef4444",r.style.background="rgba(239,68,68,0.15)",r.style.borderColor="rgba(239,68,68,0.4)")}}}var s=document.getElementById("etf5dFlow");if(s){var c=e.sum5d;s.textContent=(c>=0?"+":"")+c.toFixed(1)+"M",s.style.color=c>100?"#22c55e":c<-500?"#ef4444":c<0?"#f97316":"var(--heading)";var l=s.nextElementSibling;if(l&&(l.textContent="5-day total"+(c<-500?" · Heavy selling ⚠️":c>500?" · Strong inflows 🟢":"")),c<-500){var d=s.closest('div[style*="border-radius:12px"]');if(d){d.style.borderColor="rgba(239,68,68,0.5)",d.style.background="rgba(239,68,68,0.04)";var u=d.querySelector('div[style*="OK"]');u&&(u.innerHTML="🔴 TOP",u.style.color="#ef4444",u.style.background="rgba(239,68,68,0.15)",u.style.borderColor="rgba(239,68,68,0.4)")}}}var p=L;try{var m=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"));m&&m.totalBtc&&(p=m.totalBtc)}catch(e){}var g=parseFloat(localStorage.getItem("btc_last_price"))||83e3,h=p*g,f=1984e4*g,y=f>0?(h/f*100).toFixed(1):"—",v=document.getElementById("etfBtcRatio");if(v){var b=parseFloat(y);v.textContent=y+"%",v.style.color=b>=8?"#ef4444":"var(--heading)";var w=v.nextElementSibling;if(w&&(w.textContent="ETF AUM: ~$"+(h/1e9).toFixed(0)+"B / Mkt Cap: ~$"+(f/1e12).toFixed(2)+"T"+(b>=8?" · High exposure ⚠️":"")),b>=8){var x=v.closest('div[style*="border-radius:12px"]');if(x){x.style.borderColor="rgba(239,68,68,0.5)",x.style.background="rgba(239,68,68,0.04)";var k=x.querySelector('div[style*="OK"]');k&&(k.innerHTML="🔴 TOP",k.style.color="#ef4444",k.style.background="rgba(239,68,68,0.15)",k.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("etfNetFlow");e&&(e.textContent="N/A")})}}}var T=null,S=0,_=212582*32150.7;function B(e,t,o){var n=e*_/1e12,i=t>0?(t/n*100).toFixed(1):"—",a=o>0?Math.round(1e12*n/o):"—",r=document.getElementById("goldMktCapLabel");r&&(r.textContent="$"+n.toFixed(1)+"T");var s=document.getElementById("goldBar");s&&(s.style.width=Math.min(parseFloat(i)||0,100)+"%");var c=document.getElementById("goldPctArea");c&&(c.innerHTML='
    '+i+'% of Gold Market Cap
    BTC needs ~$'+("number"==typeof a?p(a):a)+'/coin to match Gold
    Gold: $'+p(Math.round(e))+"/oz · Live via CoinGecko
    ");var l=document.getElementById("goldCompareCard");if(l){var d="Gold has been humanitys store of value for 5,000+ years. Bitcoin is digital gold — scarce, durable, portable, divisible, and verifiable. Gold price: $"+p(Math.round(e))+"/oz. Total above-ground gold: ~212,582 tonnes (~6.83B troy oz). Gold market cap: ~$"+n.toFixed(1)+"T. The flippening = Bitcoin absorbs golds entire monetary premium.";l.setAttribute("data-dash-tip",d),"function"==typeof window._attachTipListeners&&window._attachTipListeners()}}var I=null,C=0,E=[{name:"🇺🇸 United States",btc:325293},{name:"🇨🇳 China",btc:19e4},{name:"🇬🇧 United Kingdom",btc:61245},{name:"🇧🇹 Bhutan",btc:10635},{name:"🇸🇻 El Salvador",btc:6135}],A=649864;function M(e,t,o){var n=(t.companies||[]).slice(0,5),i=Math.round(t.total_holdings||0),a=t.total_value_usd||0,r=o||(i>0?a/i:0),s=n.map(function(e){return'
    '+(e.name||"?")+''+p(e.total_holdings)+" BTC
    "}).join(""),c=E.map(function(e){return'
    '+e.name+''+p(e.btc)+" BTC
    "}).join(""),l=i+A;e.innerHTML='
    🏢 Public Companies
    '+p(i)+'
    BTC · ~'+m(a||i*r)+'
    🏛️ Governments
    '+p(A)+'
    BTC · ~'+m(A*r)+'
    Total: '+p(l)+" BTC ("+(l/21e6*100).toFixed(1)+'% of supply)
    TOP 5 COMPANIES
    '+s+'
    TOP 5 GOVERNMENTS
    '+c+'
    Companies: live via CoinGecko · Governments: bitcointreasuries.net
    ';var d=document.getElementById("treasuryCard");d&&d.removeAttribute("onclick")}var z=[{ticker:"IBIT",name:"BlackRock",btc:787044,color:"#6366f1"},{ticker:"FBTC",name:"Fidelity",btc:213399,color:"#22c55e"},{ticker:"GBTC",name:"Grayscale",btc:180584,color:"#eab308"},{ticker:"ARKB",name:"ARK 21Shares",btc:63920,color:"#f97316"},{ticker:"BITB",name:"Bitwise",btc:53930,color:"#06b6d4"}],L=1367239;function P(e,t,o,n,i,a){var r=o*n,s=(o/i*100).toFixed(1),c=t[0].btc,l=t.map(function(e){var t=Math.max(4,e.btc/c*100).toFixed(0),o=m(e.btc*n);return'
    '+e.ticker+' '+e.name+''+p(e.btc)+' BTC
    '+o+"
    "}).join(""),d="";if(a){var u=Math.round((Date.now()-new Date(a).getTime())/36e5);d=u<1?"Updated just now":u<24?"Updated "+u+"h ago":"Updated "+Math.round(u/24)+"d ago"}e.innerHTML='
    '+p(o)+' BTC
    ~'+m(r)+" AUM · "+s+'% of supply held in ETFs
    '+l+'
    Data: SEC filings + CoinGlass'+(d?" · "+d:"")+"
    "}var U=null;window._startHalvingTicker=function(){U&&clearInterval(U),U=setInterval(function(){if(window._halvingTargetMs){var e=document.getElementById("halvSecs");if(!e)return clearInterval(U),void(U=null);var t=Math.max(0,window._halvingTargetMs-Date.now()),o=Math.floor(t/1e3),n=Math.floor(o/86400),i=Math.floor(o%86400/3600),a=Math.floor(o%3600/60),r=o%60,s=document.getElementById("halvDays"),c=document.getElementById("halvHours"),l=document.getElementById("halvMins");s&&(s.textContent=n),c&&(c.textContent=i),l&&(l.textContent=a),e.textContent=r<10?"0"+r:r}},1e3)}}(),function(){if(window._sessionStart=window._sessionStart||Date.now(),window._cleanUrl=function(e){if(!e)return"/";var t=window.location.pathname;return t==="/"+e||t==="/app/"+e?t:"#"+e},window._parseCleanUrl=function(){var e,t=window.location.pathname;return(e=t.match(/^\/channels\/(.+)$/))||(e=t.match(/^\/app\/(.+)$/))?e[1]:"/timechain-tv"===t||"/tv"===t?"timechain-tv":"/meetup-builder"===t?"meetup-builder":"/irl-sync"===t||"/meet"===t?"irl-sync":"/forum"===t?"forum":"/marketplace"===t?"marketplace":"/bitcoin-beats"===t||"/beats"===t?"bitcoin-beats":"/chat"===t?"chat":"/pvp"===t?"pvp":window.location.hash.replace("#","")||null},!document.getElementById("lb")){var e=document.createElement("div");e.id="lb",e.onclick=function(){document.getElementById("lb").classList.remove("open")},e.innerHTML='',document.body.appendChild(e)}function t(e){document.getElementById("lb-img").src=e,document.getElementById("lb").classList.add("open")}function o(){return window.innerWidth<=900}function n(){const e="light"!==document.body.getAttribute("data-theme");document.body.setAttribute("data-theme",e?"light":"dark"),localStorage.setItem("theme",e?"light":"dark");const t=document.getElementById("themeBtn");t&&(t.textContent=e?"☀️":"🌙");const o=document.getElementById("mobileThemeBtn");o&&(o.textContent=e?"☀️":"🌙")}function i(){var e=document.getElementById("sidebar");e&&(e.classList.toggle("open"),"function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!e.classList.contains("open")))}function a(){var e=document.getElementById("sidebar");if(e){var t=e.classList.toggle("sidebar-collapsed");try{localStorage.setItem("sidebar-collapsed",t?"1":"0")}catch(e){}}}function r(e){var t=e.nextElementSibling;if(t){var o=e.querySelector(".cat-arrow");"true"===e.getAttribute("data-expanded")?(t.style.display="none",e.setAttribute("data-expanded","false"),o&&(o.textContent="▶")):(t.style.display="",e.setAttribute("data-expanded","true"),o&&(o.textContent="▼"))}}function s(e){if(e){var t=e.closest(".cat-group");if(t&&"none"===t.style.display){var o=t.previousElementSibling;if(o&&o.classList.contains("cat-toggle")){t.style.display="",o.setAttribute("data-expanded","true");var n=o.querySelector(".cat-arrow");n&&(n.textContent="▼")}}}}function c(){return safeJSON("btc_favs",[])}function l(){var e=document.getElementById("favsList"),t=document.getElementById("favsSection");if(e){var o=c(),n=safeJSON("btc_bookmarks",[]);if(!(o.length>0||n.length>0))return e.innerHTML="",(i=document.getElementById("bookmarksList"))&&(i.innerHTML=""),void(t&&(t.style.display="none"));t&&(t.style.display="block");var i,a="";if(o.forEach(function(e){var t=void 0!==CHANNELS?CHANNELS[e]:null,o=t?(t.emoji||"")+" "+(t.name||e):e;a+="
    "+o+"
    "}),e.innerHTML=a,i=document.getElementById("bookmarksList"))if(0===n.length)i.innerHTML="";else{var r='
    🔖 Bookmarked Messages
    ';n.slice(0,15).forEach(function(e){var t=void 0!==CHANNELS&&CHANNELS[e.channel]?CHANNELS[e.channel]:null,o=t?(t.emoji||"")+" "+(t.name||e.channel):e.channel;r+="
    🔖 "+o+"
    "}),i.innerHTML=r}}}function d(e,t){let o=c();if(o.includes(e))o=o.filter(t=>t!==e),t&&(t.innerHTML="☆ Save");else{o.push(e),t&&(t.innerHTML="⭐ Saved");try{var n=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_fav_added_"+n,"true")}catch(e){}}var i;i=o,localStorage.setItem("btc_favs",JSON.stringify(i)),l(),"function"==typeof syncFavsToFirebase&&syncFavsToFirebase()}!function(){try{if(window.innerWidth>900&&"1"===localStorage.getItem("sidebar-collapsed")){var e=document.getElementById("sidebar");e&&e.classList.add("sidebar-collapsed")}}catch(e){}}();let u=!1,p=null,m=null;function g(e){u=!u;const t=document.getElementById("galleryBtn");t&&(t.classList.toggle("active",u),t.textContent=u?"📄 List View":"🖼️ Gallery View"),h(e)}function h(e){const t=p;if(!t)return;const n=document.getElementById("msgs");if(u){let e=[];t.msgs.forEach(t=>{t.imgs&&t.imgs.forEach(t=>e.push(t))});let i='",e.length>a&&(window._galleryImgs=e,window._galleryOffset=a,i+='"),n.innerHTML=i}else{const i=o()?20:50,a=t.msgs;let r=function(){const t=a.slice(0,0+i);let n="";{const t=void 0!==CHANNELS?CHANNELS[e]:null;t&&t.desc&&(n+='
    🦌
    Nacho\'s Summary
    '+t.desc+"
    ")}return t.forEach((t,i)=>{if(n+='
    ',t.text){let e=t.text,i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"});let a=[];e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){const t=e.startsWith("http")?e:"https://"+e;return a.push(t),"%%TW"+(a.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){const n=a[parseInt(t)],i="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),c=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+c+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),n+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?n+='':n+=''});var a=0+i,r=safeJSON("btc_bookmarks",[]).some(function(t){return t.channel===e&&t.idx===a});n+="',n+="
    "}),n}();a.length>i&&(r+='"),n.innerHTML=r,window._currentMsgs=a,window._currentOffset=i}window._sidebarOrder||(window._sidebarOrder=[...document.querySelectorAll(".ch-btn")].map(e=>{const t=e.getAttribute("onclick").match(/go\('([^']+)'/);return t?t[1]:null}).filter(Boolean));const i=window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),a=i.indexOf(e),r=a0?i[a-1]:i[i.length-1]);CHANNELS[s]&&CHANNELS[s].title;let c='
    ';c+="',c+='',c+='',c+='',c+='',c+="',c+="
    ",c+='
    ',c+='',c+="
    ","function"==typeof renderReadNext&&(c+=renderReadNext(e)),c+='
    Disclaimer
    This Bitcoin education is presented authentically and from a first-principles standpoint that maximizes truth. However, this is not financial, investment, legal, or tax advice and anyone reading this material should still verify its validity by doing their own research. Bitcoin is volatile and you can lose money. Bitcoin Education Archive, its operators, and contributors make no warranty regarding the accuracy, completeness, or timeliness of any educational content and accept no liability for decisions made based on it. Always consult a licensed professional before making financial decisions. Terms · Privacy
    ',n.innerHTML+=c,n.classList.add("fade-in")}let f=!1;function y(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML='
    Loading tweet...
    ',f)v(e,t);else{const o=document.createElement("script");o.src="https://platform.twitter.com/widgets.js",o.async=!0,o.onload=function(){f=!0,v(e,t)},document.head.appendChild(o)}}function v(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML="",window.twttr&&window.twttr.widgets){const e=t.match(/status\/(\d+)/);if(e){const n=document.createElement("div");o.appendChild(n),twttr.widgets.createTweet(e[1],n,{theme:"light"===document.body.getAttribute("data-theme")?"light":"dark",align:"center",conversation:"none",width:500}).then(function(e){e||(o.innerHTML='')})}}else o.innerHTML=''}async function b(){window._keepFloatingBtn=!0;const e=Object.keys(CHANNELS);window._randomChannelHistory||(window._randomChannelHistory=[]);var t=e.filter(function(e){return-1===window._randomChannelHistory.indexOf(e)});0===t.length&&(window._randomChannelHistory.length=0,t=e);const o=t[Math.floor(Math.random()*t.length)];window._randomChannelHistory.push(o),window._randomChannelHistory.length>Math.floor(.3*e.length)&&window._randomChannelHistory.shift(),await go(o),window._keepFloatingBtn=!1,S("__random__","🎲","Next Random Channel")}async function w(e,t,o){window._keepFloatingBtn=!0;const n=CHANNELS[e];if(!n)return void(window._keepFloatingBtn=!1);let i;if(G[e])i=G[e];else try{const t=await fetch(n.file);i=await t.json(),G[e]=i}catch(e){return}const a=i.msgs.length>1?i.msgs.slice(1):i.msgs,r=[];if(a.forEach((e,t)=>{e.imgs&&e.imgs.length>0&&r.push(t)}),0!==r.length){window._randomHistory||(window._randomHistory={}),window._randomHistory[e]||(window._randomHistory[e]=[]);var s=window._randomHistory[e],c=Math.min(Math.floor(.2*r.length),50),l=r.filter(function(e){return-1===s.indexOf(e)});0===l.length&&(s.length=0,l=r);var d=l[Math.floor(Math.random()*l.length)];s.push(d),s.length>c&&s.shift();var u=a[d];if(u&&u.imgs&&u.imgs.forEach(function(e){(new Image).src=e}),await go(e),d>=50){const e=document.getElementById("loadMoreBtn");for(var p=0;window._currentOffset<=d&&e&&document.contains(e)&&p<50;)window.loadMoreMsgs(),p++}setTimeout(function(){const n=document.getElementById("msg-"+d);n&&(n.querySelectorAll('img[loading="lazy"]').forEach(function(e){e.loading="eager"}),n.scrollIntoView({behavior:"smooth",block:"center"}),n.style.transition="box-shadow 0.3s, border-color 0.3s",n.style.boxShadow="0 0 20px rgba(247,147,26,0.4)",n.style.borderColor="#f7931a",setTimeout(function(){n.style.boxShadow="",n.style.borderColor=""},2e3),window._keepFloatingBtn=!1,S(e,t,o))},300)}}function x(){return w("memes-funny","😂","Next Random Meme")}function k(){return w("art-inspiration","🎨","Next Random Art")}function T(){return w("graphics","📊","Next Random Graphic")}function S(e,t,o){var n=document.getElementById("floatingRandomBtn");n||((n=document.createElement("button")).id="floatingRandomBtn",n.style.cssText="position:fixed;bottom:140px;right:180px;z-index:150;padding:12px 20px;background:var(--accent);color:#fff;border:none;border-radius:12px;font-size:0.9rem;font-weight:700;cursor:pointer;font-family:inherit;box-shadow:0 4px 20px rgba(0,0,0,0.3);transition:0.2s;display:flex;align-items:center;gap:6px;",document.body.appendChild(n)),n.innerHTML=t+" "+o,n.onclick="__random__"===e?function(){b()}:function(){w(e,t,o)},n.style.display="flex",window.addEventListener("popstate",function e(){n.style.display="none",window.removeEventListener("popstate",e)},{once:!0})}function _(e,t){const o=e+"\n\n"+t;navigator.clipboard.writeText(o).then(()=>{showToast("📋 Note copied! Paste it in Primal to post.")}).catch(()=>{}),window.open("https://primal.net/home","_blank")}window.goRandomMeme=x,window.goRandomArt=k,window.goRandomGraphic=T,window.toggleBookmark=function(e,t,o){var n=safeJSON("btc_bookmarks",[]),i=n.findIndex(function(o){return o.channel===e&&o.idx===t});-1!==i?(n.splice(i,1),o&&(o.style.opacity="0.3",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Bookmark removed")):(n.push({channel:e,idx:t,ts:Date.now()}),o&&(o.style.opacity="1",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Saved to sidebar")),localStorage.setItem("btc_bookmarks",JSON.stringify(n)),l(),"function"==typeof syncBookmarksToFirebase&&syncBookmarksToFirebase()},window.loadMoreGallery=function(){const e=window._galleryImgs,o=window._galleryOffset,n=document.querySelector(".gallery-grid"),i=document.getElementById("loadMoreGallery");e.slice(o,o+100).forEach(e=>{const o=document.createElement("img");o.src=e,o.loading="lazy",o.onclick=function(){t(this.src)},n.appendChild(o)}),window._galleryOffset=o+100,window._galleryOffset>=e.length?i.remove():i.textContent="Load more ("+(e.length-window._galleryOffset)+" remaining)"},window.showSpinWheel=function(){var e=localStorage.getItem("btc_last_spin_date"),t=(new Date).toDateString();if(e!==t){var o=document.getElementById("spinModal");o&&o.remove();var n=document.createElement("div");n.id="spinModal",n.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.85);-webkit-overflow-scrolling:touch;overflow-y:auto;padding:20px;";var i=[{label:"🎟️ 1 Ticket",value:"ticket_1",weight:25,color:"#f7931a"},{label:"🎟️ 2 Tickets",value:"ticket_2",weight:22,color:"#ea580c"},{label:"⭐ 25 XP",value:"points_25",weight:18,color:"#22c55e"},{label:"🎟️ 3 Tickets",value:"ticket_3",weight:12,color:"#fbbf24"},{label:"⭐ 50 XP",value:"points_50",weight:8,color:"#3b82f6"},{label:"👔 Closet!",value:"closet_item",weight:5,color:"#ec4899"},{label:"🧊 Freeze!",value:"freeze",weight:4,color:"#06b6d4"},{label:"⭐ 100 XP",value:"points_100",weight:3,color:"#8b5cf6"},{label:"🎟️ 5 Tickets",value:"ticket_5",weight:1.5,color:"#a855f7"},{label:"💎 RARE!",value:"rare_drop",weight:1.5,color:"#ef4444"}],a=[{label:"🎟️ 10 Tickets",value:"ticket_10",weight:1e3},{label:"🎟️ 25 Tickets",value:"ticket_25",weight:500},{label:"🎟️ 50 Tickets",value:"ticket_50",weight:100},{label:"🎟️ 100 Tickets!",value:"ticket_100",weight:50},{label:"🎟️ 500 Tickets!!",value:"ticket_500",weight:10},{label:"🎟️💎 1,000 Tickets!!!",value:"ticket_1000",weight:3},{label:"🎟️👑 10,000 TICKETS!!!!",value:"ticket_10000",weight:1}];n.innerHTML='
    🎡
    Daily Spin

    Spin for Orange Tickets, XP, Nacho Closet items, and rare Freeze Tickets!

    ',document.body.appendChild(n);var r=document.getElementById("spinCanvas").getContext("2d"),s=125,c=125,l=2*Math.PI/i.length;i.forEach(function(e,t){r.beginPath(),r.moveTo(s,c),r.arc(s,c,120,t*l,(t+1)*l),r.fillStyle=e.color,r.fill(),r.strokeStyle="#fff",r.lineWidth=2,r.stroke(),r.save(),r.translate(s,c),r.rotate(t*l+l/2),r.textAlign="right",r.fillStyle="#fff",r.font="bold 12px sans-serif",r.fillText(e.label,105,4),r.restore()});var d=!1,u=document.getElementById("spinBtn"),p=document.getElementById("spinResult");u.addEventListener("click",function(){if(!d){d=!0,u.disabled=!0,u.style.opacity="0.5";for(var e=i.reduce(function(e,t){return e+t.weight},0),o=Math.random()*e,n=0,m=0,g=0;gMath.floor(30*(d-.01))&&"function"==typeof playSpinTick&&playSpinTick(),requestAnimationFrame(e);else{"function"==typeof playSpinWin&&playSpinWin();var g="",f=h.value.split("_")[0],y=parseInt(h.value.split("_")[1])||1;if("rare_drop"===h.value){for(var v=a.reduce(function(e,t){return e+t.weight},0),w=Math.random()*v,x=a[0],T=0,S=0;S.01&&(_=100,x={label:"🎟️ 100 Tickets!",value:"ticket_100"}),g="💎 RARE DROP! "+x.label,"function"==typeof awardOrangeTickets)awardOrangeTickets(_,"Rare Spin Drop");else{var B=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",B+_)}_>=100&&("function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound())}else if("closet"===f){var I=safeJSON("btc_spin_closet_items",[]),C=["orange_scarf","sunglasses","bowtie","mining_helmet","lightning_chain","party_hat","hodl_hoodie","crown","steak","diamond_hooves"].filter(function(e){return-1===I.indexOf(e)});if(C.length>0){var E=C[Math.floor(Math.random()*C.length)];if(I.push(E),localStorage.setItem("btc_spin_closet_items",JSON.stringify(I)),void 0!==currentUser&¤tUser&&!currentUser._isLocal)try{db.collection("users").doc(auth.currentUser.uid).update({spinClosetItems:firebase.firestore.FieldValue.arrayUnion(E)}).catch(function(){})}catch(e){}g="👔 CLOSET ITEM! You unlocked: "+({orange_scarf:"Bitcoin Scarf 🧣",sunglasses:"Cool Shades 🕶️",bowtie:"Fancy Bowtie 🎀",mining_helmet:"Mining Helmet ⛑️",lightning_chain:"Lightning Chain ⚡",party_hat:"Party Hat 🎉",hodl_hoodie:"HODL Hoodie 🧥",crown:"Royal Crown 👑",steak:"Proof of Steak 🥩",diamond_hooves:"Diamond Hooves 💎"}[E]||E)+"! Equip it in Nacho's Closet!"}else g="👔 You already own all spin closet items! +25 bonus XP instead!","function"==typeof awardPoints&&awardPoints(25,"Closet bonus")}else if("freeze"===f){g="🧊 STREAK FREEZE TICKET! Your streak is protected for 1 missed day!";var A=parseInt(localStorage.getItem("btc_streak_freezes")||"0");localStorage.setItem("btc_streak_freezes",A+1),"function"==typeof awardPoints&&awardPoints(0,"🧊 Streak Freeze",null,0,1),void 0!==currentUser&¤tUser&&(currentUser.streakFreezes=(currentUser.streakFreezes||0)+1)}else if("ticket"===f)if(g="🎟️ You won "+y+" Orange Ticket"+(y>1?"s":"")+"!","function"==typeof awardOrangeTickets)awardOrangeTickets(y,"Daily Spin");else{var M=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",M+y)}else if("points"===f)if(g="⭐ You won "+y+" XP!","function"==typeof awardPoints)awardPoints(y,"Daily Spin");else{var z=parseInt(localStorage.getItem("btc_points")||"0");localStorage.setItem("btc_points",z+y)}p.innerHTML='
    '+h.label.split(" ")[0]+'
    '+g+'
    ',"function"==typeof notifySelfSpin&¬ifySelfSpin(g);var L=parseInt(localStorage.getItem("btc_spin_count")||"0");localStorage.setItem("btc_spin_count",String(L+1));var P=localStorage.getItem("btc_spin_last_day")||"";if(P===new Date(Date.now()-864e5).toISOString().slice(0,10)){var U=parseInt(localStorage.getItem("btc_spin_streak")||"0");localStorage.setItem("btc_spin_streak",String(U+1))}else P!==t&&localStorage.setItem("btc_spin_streak","1");localStorage.setItem("btc_spin_last_day",t),"rare_drop"===h.value&&localStorage.setItem("btc_spin_hit_rare","true"),localStorage.setItem("btc_last_spin_date",t),"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("dailySpin")({}).catch(function(e){console.log("[SPIN] Server validation:",e.message||"ok")}),void 0!==currentUser&¤tUser&¤tUser._isLocal}})}}),n.addEventListener("click",function(e){e.target===n&&n.remove()})}else showToast("🎡 You already spun today! Come back tomorrow!")};var B=null;function I(e,t,o,n,i){var a="dc_"+Math.random().toString(36).substr(2,6),r=n?'Open ↗':"";return'
    '+e+"
    "+(i?'
    '+e+' QR
    ':"")+(t?'
    "+o+'
    "+r+"
    ":"")+"
    "}function C(e,t){navigator.clipboard.writeText(e).then(()=>{t.classList.add("copied"),t.textContent="✅ Copied!",setTimeout(()=>{t.classList.remove("copied"),t.innerHTML="🔗 Copy Link"},2e3)})}setTimeout(function(){var e=new Image;e.crossOrigin="anonymous",e.src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:spontaneousleopard54@zeuspay.com",e.onload=function(){try{var t=document.createElement("canvas");t.width=e.width,t.height=e.height,t.getContext("2d").drawImage(e,0,0),B=t.toDataURL("image/png")}catch(t){B=e.src}}},3e3),window.showDonateModal=function(){var e=document.getElementById("donateModal");e&&e.remove();var t=document.createElement("div");t.id="donateModal",t.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:flex-start;justify-content:center;background:rgba(2,6,23,0.9);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;";var o="spontaneousleopard54@zeuspay.com",n=B||"https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:"+o;t.innerHTML='
    🧡
    Support the Archive

    Your sats help keep this archive free and open for the next billion Bitcoiners! 🦌⚡

    Lightning QR Code
    '+o+"

    ⚠️ Donations are non-refundable

    "+I("💵 Cash App","$NEEDcreations","$NEEDcreations","https://cash.app/$NEEDcreations","images/donate/cashapp-qr.jpg")+I("💜 Venmo","@Phil2140","@Phil2140","https://venmo.com/code?user_id=1358236213051392692&created=1773155307","images/donate/venmo-qr.jpg")+I("💙 PayPal","paypal.me/PhilipFazioli","paypal.me/PhilipFazioli","https://paypal.me/PhilipFazioli","images/donate/paypal-qr.jpg")+I("💚 Zelle",null,null,null,"images/donate/zelle-qr.jpg")+I("₿ On-Chain Bitcoin","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf",null,"images/donate/onchain-qr.jpg")+I("🔒 BIP47 Payment Code","PM8TJWpq8HqPeBEuz3dAoB3uyZADVxQjWekQJCJYddpWPce9nDaeK6XjYnifBUnjjKcWF8Y98EkfPZYaftC7uDJkiFqBTBYrd8TJhRg5qQwXtfnTTg89","PM8TJWpq8Hq...Tg89",null,"images/donate/bip47-qr.jpg")+"
    ",document.body.appendChild(t);var i=document.getElementById("donateCopyBtn");i&&i.addEventListener("click",function(e){e.stopPropagation();var t=this;if(navigator.clipboard)navigator.clipboard.writeText(o).then(function(){t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)});else{var n=document.createElement("textarea");n.value=o,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)}}),t.addEventListener("click",function(e){e.target===t&&t.remove()})};let E=!1;function A(){const e=document.getElementById("supportBtn");E?(navigator.clipboard.writeText("info.603btc@gmail.com").then(function(){e.innerHTML="✅ Copied!",e.style.color="#22c55e",setTimeout(function(){e.innerHTML='info.603btc@gmail.com tap to copy',e.style.color="var(--text)"},1500)}).catch(function(){}),window.location.href="mailto:info.603btc@gmail.com?subject=Support%20-%20Bitcoin%20Education%20Archive"):(E=!0,e.style.transition="0.3s",e.style.background="var(--accent)",e.style.color="#fff",e.style.borderColor="var(--accent)",e.innerHTML='info.603btc@gmail.com tap to copy',setTimeout(function(){e.style.background="var(--card-bg)",e.style.color="var(--text)",e.style.borderColor="var(--border)"},400))}function M(e){if(!e)return"";var t=new Date(e),o=t.getHours(),n=t.getMinutes(),i=o>=12?"PM":"AM";return 0==(o%=12)&&(o=12),o+":"+(n<10?"0":"")+n+" "+i}window._nachoMode=!1,window._nachoModeEarnings={points:0,badges:[],interactions:0},window.enterNachoMode=function(e){if(window._nachoMode=!0,window._nachoBusy=!0,window._nachoModeEarnings={points:0,badges:[],interactions:0},window._nachoModeStartTime=Date.now(),window._nachoModeTopics=[],window._nachoConvoQuizOffered=!1,!window._nachoPointsHooked){window._nachoPointsHooked=!0;var t=window.awardPoints;t&&(window.awardPoints=function(e,o){return window._nachoMode&&window._nachoModeEarnings&&(window._nachoModeEarnings.points+=e),t.apply(this,arguments)});var o=window.showToast;o&&(window.showToast=function(e){return window._nachoMode&&window._nachoModeEarnings&&"string"==typeof e&&(-1!==e.indexOf("badge")||-1!==e.indexOf("Badge")||-1!==e.indexOf("🏅"))&&window._nachoModeEarnings.badges.push(e),o.apply(this,arguments)})}e||history.pushState({nachoMode:!0},"","/app/nacho"),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="none")});var n=document.querySelector(".mobile-bar");n&&(n.style.display="none");var i=document.getElementById("main");i.scrollTop=0,"undefined"!=typeof NACHO_SVG&&NACHO_SVG,void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var a=!(!window.SpeechRecognition&&!window.webkitSpeechRecognition),r=a?'':"";window._nachoChatHistory=safeJSON("btc_nacho_chat",[]),window._nachoSentHistory=safeJSON("btc_nacho_sent",[]),window._nachoSentIdx=-1;var s=document.createElement("div");s.id="nachoModeScreen",s.style.cssText="display:flex;flex-direction:column;height:calc(100vh - 32px);margin-top:32px;animation:fadeSlideIn 0.4s ease-out;position:relative;z-index:9999;",s.innerHTML='
    Nacho
    '+("function"==typeof nachoNickname?nachoNickname():"Nacho").toUpperCase()+' MODE
    Home
    '+r+'
    ',i.appendChild(s),N(),setTimeout(function(){var e=document.getElementById("nachoModeChat");e&&(e.scrollTop=e.scrollHeight)},100),j();var c=document.getElementById("nachoEli5Btn");c&&(c.style.opacity=window._nachoEli5?"1":"0.5"),function(){var e=document.getElementById("nachoModeOverlay");if(e&&(e.innerHTML="","function"==typeof getEquippedItem)){var t=getEquippedItem();if(t){var o=t.hidden?t.revealEmoji:t.emoji,n=document.createElement("span");n.textContent=t.overlay&&t.overlay.custom?t.overlay.custom:o,n.style.cssText="position:absolute;font-size:2.5rem;pointer-events:none;",t.overlay&&(t.overlay.top&&(n.style.top=t.overlay.top),t.overlay.left&&(n.style.left=t.overlay.left),t.overlay.right&&(n.style.right=t.overlay.right),t.overlay.bottom&&(n.style.bottom=t.overlay.bottom),t.overlay.transform&&(n.style.transform=t.overlay.transform)),e.appendChild(n)}}}(),setTimeout(function(){var e=document.getElementById("nachoModeInput");e&&e.focus()},300)},window.nachoModeKeydown=function(e){if("Enter"!==e.key){var t=document.getElementById("nachoModeInput");if(t){var o=window._nachoSentHistory||[];if("ArrowUp"===e.key){if(0===o.length)return;-1===window._nachoSentIdx&&(window._nachoSentDraft=t.value),window._nachoSentIdx=Math.min(window._nachoSentIdx+1,o.length-1),t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault(),setTimeout(function(){t.setSelectionRange(t.value.length,t.value.length)},0)}else if("ArrowDown"===e.key){if(window._nachoSentIdx<=0)return window._nachoSentIdx=-1,void(t.value=window._nachoSentDraft||"");window._nachoSentIdx--,t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault()}}}else nachoModeSend()};var z=["There will only ever be 21 million Bitcoin. No government, company, or person can change this. 🔒","The Bitcoin network has been running non-stop since January 3, 2009 — over 99.98% uptime. No bank can say that! 🏦","The first Bitcoin transaction was 10,000 BTC for two pizzas. Today that's worth hundreds of millions! 🍕","Bitcoin processes over $10 billion in transactions daily — more than most countries' payment systems. 💸","Bitcoin mining now uses more renewable energy than almost any other industry — over 50%! ⚡","Satoshi Nakamoto's true identity remains unknown. They hold about 1 million BTC and have never spent any. 🕵️","A 'satoshi' (sat) is the smallest unit of Bitcoin: 0.00000001 BTC. You don't need to buy a whole coin! 🪙","The Bitcoin Lightning Network can process millions of transactions per second — faster than Visa! ⚡","El Salvador became the first country to adopt Bitcoin as legal tender in September 2021. 🇸🇻","Bitcoin's code is completely open source — anyone can read, verify, and contribute to it. 📖","Every 4 years, Bitcoin's new supply gets cut in half. This is called the 'halving.' The next one is in 2028! 📉","There are more Bitcoin wallets than bank accounts in most countries. Over 100 million and growing! 📈","Bitcoin can be sent anywhere in the world in minutes, 24/7, with no middleman. Try that on a Sunday with a bank! 🌍","The Genesis Block contains a hidden message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰","About 20% of all Bitcoin is estimated to be permanently lost — mostly from early users who lost their keys. 🔑","Bitcoin's difficulty adjustment is like a thermostat — it automatically adapts every 2 weeks to keep blocks at ~10 minutes. ⚙️","Running a Bitcoin node means YOU verify every transaction yourself. No trust required. Don't trust, verify! ✅","The Lightning Network lets you send payments as small as 1 sat (~$0.0003). Try doing that with a credit card! 💳","Bitcoin has survived 400+ declared 'deaths' by media. It keeps coming back stronger every time. 💪","Over 50 publicly traded companies now hold Bitcoin on their balance sheets, led by MicroStrategy. 🏢","Bitcoin transactions are pseudonymous, not anonymous. Every transaction is recorded on the public blockchain forever. 🔍","The Bitcoin network is protected by more computing power than all the world's supercomputers combined. 🖥️","You can run a full Bitcoin node on a Raspberry Pi — a $50 computer can verify the entire monetary system. 🥧","Bitcoin's inflation rate is currently lower than gold's. After the 2028 halving, it'll be even lower. 🥇","Multisig wallets require multiple keys to spend Bitcoin — like a safety deposit box that needs 2 of 3 keys. 🗝️","Bitcoin doesn't care about borders, politics, or holidays. It works the same everywhere, always. 🌐","The last Bitcoin won't be mined until approximately the year 2140. We're still very early! ⏰","Jack Dorsey, Elon Musk, and many tech leaders have publicly supported Bitcoin's vision. 🚀","A Bitcoin block is mined roughly every 10 minutes. That's about 144 blocks per day, every day, forever. ⛏️","Nostr is a decentralized social protocol that many Bitcoiners are building on — social media you can't be censored from. 📡"];window.nachoModeChip=function(e){var t=document.getElementById("nachoModeInput");t&&(t.value=e,nachoModeSend())},window._nachoEli5="true"===localStorage.getItem("btc_nacho_eli5"),window.toggleNachoEli5=function(){window._nachoEli5=!window._nachoEli5,localStorage.setItem("btc_nacho_eli5",window._nachoEli5?"true":"false");var e=document.getElementById("nachoEli5Btn");e&&(e.style.opacity=window._nachoEli5?"1":"0.5",e.title=window._nachoEli5?"ELI5 Mode ON — Simple language":"Explain Like I'm 5"),"function"==typeof showToast&&showToast(window._nachoEli5?"🧒 ELI5 Mode ON — Nacho will use simple language!":"🧒 ELI5 Mode OFF — Back to normal")},window.showEli5Prompt=function(){var e=window._nachoEli5,t='
    🧒
    ELI5 Mode
    Explain Like I\'m 5

    When turned on, Nacho will answer your questions using super simple language — like explaining Bitcoin to a 5-year-old! 🦌

    Perfect for beginners or anyone who wants the basics without the jargon.
    Currently: '+(e?"ON ✅":"OFF")+'
    ',o=document.createElement("div");o.innerHTML=t,document.body.appendChild(o.firstChild)},window.nachoShareAnswer=function(e){var t="🦌 I learned this from Nacho at bitcoineducation.quest:\n\n"+e.replace(/<[^>]+>/g,"").replace(/🦌\s*/g,"").substring(0,280);if(navigator.share)navigator.share({title:"Bitcoin Fact from Nacho 🦌",text:t,url:"https://bitcoineducation.quest"}).catch(function(){});else{var o=document.createElement("textarea");o.value=t,document.body.appendChild(o),o.select();try{document.execCommand("copy")}catch(e){}document.body.removeChild(o),"function"==typeof showToast&&showToast("📋 Copied to clipboard!")}};var L=!1,P=[{step:1,emoji:"📘",title:"What is Bitcoin?",q:"What is Bitcoin and how does it work?"},{step:2,emoji:"💡",title:"Why Bitcoin Matters",q:"Why is Bitcoin important? Why should I care?"},{step:3,emoji:"📈",title:"Bitcoin vs Money",q:"How is Bitcoin different from regular money and gold?"},{step:4,emoji:"🛒",title:"Buying Your First Bitcoin",q:"How do I buy my first Bitcoin? Where do I start?"},{step:5,emoji:"💼",title:"Wallets & Storage",q:"What Bitcoin wallet should I use? What are the types?"},{step:6,emoji:"🔑",title:"Seed Phrases & Security",q:"What is a seed phrase and how do I keep my Bitcoin safe?"},{step:7,emoji:"⚡",title:"Lightning Network",q:"What is the Lightning Network and why does it matter?"},{step:8,emoji:"⛏️",title:"Mining & Proof of Work",q:"How does Bitcoin mining work? What is proof of work?"},{step:9,emoji:"🏃",title:"Running a Node",q:"What is a Bitcoin node and should I run one?"},{step:10,emoji:"🔒",title:"Privacy & KYC",q:"How private is Bitcoin? What is KYC and why does it matter?"}];window.nachoLearningPath=function(){var e=parseInt(localStorage.getItem("btc_nacho_path_step")||"0");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth&&auth?auth.currentUser:null;if(document.getElementById("nachoModeChat")){var o='
    🗺️ Your Bitcoin Journey
    '+Math.round(e/P.length*100)+"% concepts mastered
    ";o+='
    ✅ All Features Unlocked

    Every app and feature is available to you. Explore freely! 🦌

    🗣️ Pleb Talk
    🤝 IRL Sync
    ⚡ Lightning Mart
    🔹 Sign Up: 🏁 Profile & Persistence
    ',o+='
    ';for(var n=0;n'+(a?"✅":i.emoji)+'
    Level '+i.step+": "+i.title+"
    "+(r?'NEXT →':"")+""}e>=P.length&&(o+='
    🎓🦌🎉
    Journey Complete!
    You\'ve covered all the Bitcoin basics. You\'re officially not a normie anymore!
    '),q("nacho","",o)}},window.nachoPathStep=function(e){var t=P[e];t&&(e>=parseInt(localStorage.getItem("btc_nacho_path_step")||"0")&&localStorage.setItem("btc_nacho_path_step",(e+1).toString()),nachoModeChip(t.q))};const U=[{q:"What is the primary benefit of running a Bitcoin full node?",a:"You can independently verify the consensus rules and your own transactions.",w:["It earns you a small percentage of every transaction fee on the network.","It automatically mines new Bitcoins using your computer's idle CPU.","It hides your IP address from everyone else using the network.","It increases the speed of your internet connection by 21%."]},{q:"What does 'Satoshi' represent in the context of Bitcoin?",a:"The smallest unit of Bitcoin, equal to 0.00000001 BTC.",w:["A type of advanced encryption used for private messages.","The official name for a Bitcoin wallet's public address.","A digital certificate of ownership for a single Bitcoin.","The name of the first computer used to mine block zero."]},{q:"Why is Bitcoin's difficulty adjustment important?",a:"It ensures blocks are produced roughly every 10 minutes regardless of total hash rate.",w:["It prevents the price of Bitcoin from dropping below its mining cost.","It automatically updates the Bitcoin Core software for all users.","It calculates the total number of users active on the network daily.","It decides which transactions are most important for the miners."]},{q:"What happens if you lose your 12 or 24-word seed phrase?",a:"You lose access to your funds forever, as there is no central 'reset' authority.",w:["You can call Bitcoin's customer support to verify your identity and reset it.","The government can recover your coins using your social security number.","Your hardware wallet will automatically generate a new phrase after 24 hours.","Your Bitcoin is donated to a pool for new developers to use for testing."]},{q:"What is the primary function of the Lightning Network?",a:"To enable instant, near-free Bitcoin payments by moving them off-chain.",w:["To increase the total number of Bitcoins that will ever exist to 42 million.","To allow Bitcoin to be mined using only mobile phones and tablets.","To encrypt the entire blockchain so it cannot be read by anyone.","To create a secondary blockchain that is faster but less secure than Bitcoin."]}];function N(){var e=document.getElementById("nachoModeChat");if(e){var t=window._nachoChatHistory||[];if(0!==t.length){for(var o,n="",i="",a=0;a'+s+"",i=s),"user"===r.role?n+='
    '+escapeHtml(r.text)+'
    '+M(r.ts)+"
    ":n+='
    🦌 '+escapeHtml("function"==typeof nachoNickname?nachoNickname():"Nacho")+": "+r.html+'
    '+M(r.ts)+"
    "}e.innerHTML=n,e.scrollTop=e.scrollHeight}else{var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"";e.innerHTML='
    Nacho
    🦌 NACHO MODE
    '+(c?"Hey "+escapeHtml(c)+"! Let's talk Bitcoin.":"Hey! Let's talk Bitcoin.")+'
    💡 DID YOU KNOW?
    '+(o=Math.floor((Date.now()-new Date((new Date).getFullYear(),0,0))/864e5),z[o%z.length]+'
    Tap a topic or ask me anything:
    ')+function(){for(var e=[{emoji:"📘",label:"What is Bitcoin?",q:"What is Bitcoin and what problem does it solve?"},{emoji:"💰",label:"Why Bitcoin?",q:"Why is Bitcoin better than regular money and why should I care?"},{emoji:"🔒",label:"21 Million",q:"Why is the 21 million cap important and why can't it be changed?"},{emoji:"🛒",label:"How to Buy",q:"How do I buy my first Bitcoin and start stacking sats?"},{emoji:"🔑",label:"Self-Custody",q:"What is self-custody and why is it the most important thing in Bitcoin?"},{emoji:"⚡",label:"Lightning",q:"What is the Lightning Network and how does it make Bitcoin faster?"},{emoji:"🪙",label:"Why Not Altcoins?",q:"Why do Bitcoiners only focus on Bitcoin and not other cryptocurrencies?"},{emoji:"🌍",label:"Fix the World",q:"How is Bitcoin actually changing the world for the better?"}],t='
    ',o=0;o"+e[o].emoji+" "+e[o].label+"";return t+"
    "}()+'
    '}}}function H(e,t,o){var n={role:e,text:t||"",html:o||escapeHtml(t||""),ts:Date.now()};return window._nachoChatHistory.push(n),nachoChatSave(),n}function q(e,t,o){var n=document.getElementById("nachoModeChat");if(n){window._nachoChatHistory.length<=1&&n.querySelector("#nachoModeAvatar")&&(n.innerHTML="");var i=M(Date.now()),a=document.createElement("div");if(a.className="nm-msg "+("user"===e?"nm-user":"nm-nacho"),"user"===e)a.innerHTML=""+escapeHtml(t)+'
    '+i+"
    ";else{var r="function"==typeof nachoNickname?nachoNickname():"Nacho";a.innerHTML='🦌 '+escapeHtml(r)+": "+o+'
    '+i+"
    "}n.appendChild(a),"user"===e?n.scrollTop=n.scrollHeight:a.scrollIntoView({behavior:"smooth",block:"start"})}}function D(){if(window._nachoMode){var e=document.getElementById("nachoModeInput");if(e&&e===document.activeElement)setTimeout(D,3e4);else if(document.querySelector(".nm-nacho .thinking, .nm-thinking"))setTimeout(D,1e4);else{var t=window._nachoModeTopics||[];if(!(t.length<3)){var o=[],n=[],i=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;if(i&&"object"==typeof i&&Object.keys(i).forEach(function(e){var t=i[e];Array.isArray(t)&&t.forEach(function(t){n.push({question:t.q,options:[t.a].concat(t.wrong||[]),answer:t.a,category:e})})}),n.length>0){for(var a=0;a3&&-1!==l.indexOf(r[d])){o.push(c);break}}for(;o.length<3&&n.length>0;){var u=n[Math.floor(Math.random()*n.length)];-1===o.indexOf(u)&&o.push(u)}}0!==o.length&&(q("nacho","",'
    🎯
    Conversation Quest!
    You\'ve been learning a lot! Let\'s see how much you remember from our chat.
    '),window._convoQuizQuestions=o)}}}}function O(){var e,t,o,n,i=window._convoQuizQuestions||[],a=window._convoQuizIdx||0;if(a>=window._convoQuizTotal||a>=i.length)e=window._convoQuizScore||0,t=window._convoQuizTotal||3,q("nacho","",'
    '+(o>=80?"🏆":o>=60?"⭐":o>=40?"💪":"📚")+'
    Conversation Quest Complete!
    '+e+"/"+t+' correct
    '+(o>=80?"Outstanding! You really paid attention!":o>=60?"Great job! You learned a lot from our chat!":o>=40?"Not bad! Keep learning and you'll get there!":"Keep going! Every question is a learning opportunity!")+"
    "+((n=5*e)>0?'
    +'+n+" XP earned! 🎉
    ":"")+"
    "),n>0&&("function"==typeof awardPoints&&awardPoints(n,"🎯 Conversation Quest!"),"function"==typeof showToast&&showToast("🎯 +"+n+" XP — Conversation Quest!"));else{for(var r=i[a],s='
    Question '+(a+1)+" of "+window._convoQuizTotal+'
    '+escapeHtml(r.question)+"
    ",c=r.options||[],l=0;l'+escapeHtml(c[l])+""}q("nacho","",s+="
    ")}}function j(){var e=document.getElementById("nachoModeFriendship");if(e){var t="function"==typeof getNachoFriendship?getNachoFriendship():{emoji:"🦌",name:"Unknown",level:0},o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.textContent=t.emoji+" Friendship: "+t.name+" · "+o+" interactions"}}function R(){const e=document.getElementById("continueReading");if(!e)return;const t=localStorage.getItem("btc_last_channel");if(t&&CHANNELS[t]){const o=CHANNELS[t];e.style.display="block",e.innerHTML='
    📖 Continue Reading
    "+o.title+'
    '+o.cat+"
    "}else e.style.display="none"}window.nachoQuizMe=function(e){if(!window._nachoMode)return void("function"==typeof enterNachoMode&&(enterNachoMode(),setTimeout(function(){nachoQuizMe(e)},500)));let t=[];var o=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;o&&"object"==typeof o&&Object.keys(o).length>0&&Object.keys(o).forEach(e=>{var n=o[e];Array.isArray(n)&&n.forEach(o=>{t.push({question:o.q,options:fisherYates([o.a,...o.wrong||o.w||[]]),answer:o.a,category:e})})}),U.forEach(e=>{t.push({question:e.q,options:fisherYates([e.a,...e.w]),answer:e.a,category:"generic"})});var n=e?t.filter(function(t){return t.category&&-1!==t.category.toLowerCase().indexOf(e.toLowerCase())}):t;0===n.length&&(n=t);for(var i=n[Math.floor(Math.random()*n.length)],a='
    🎮 Quiz Time!
    '+(e?"Topic: "+e:"Nacho Challenge")+'
    '+escapeHtml(i.question)+"
    ",r=i.options||[],s=0;s'+escapeHtml(r[s])+""}a+="
    ",e||(a+='
    🦌 Pro Tip: Chat with me first! Future quizzes will be based on the questions you ask me.
    '),q("nacho","",a+="')},window.nachoQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n,i=e.parentElement.querySelectorAll("button");i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.7"}),t?(e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1","function"==typeof awardPoints&&awardPoints(10,"🎮 Quiz correct!"),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(34,197,94,0.1);border:1px solid #22c55e;border-radius:8px;color:#22c55e;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="✅ Correct! +10 XP",e.parentElement.appendChild(n)):(e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.borderColor="#22c55e",t.style.color="#22c55e",t.style.opacity="1")}),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(239,68,68,0.1);border:1px solid #ef4444;border-radius:8px;color:#ef4444;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="❌ Incorrect. Try another!",e.parentElement.appendChild(n))},window.nachoChatSave=function(){var e=window._nachoChatHistory||[];e.length>100&&(e=e.slice(e.length-100)),window._nachoChatHistory=e;try{localStorage.setItem("btc_nacho_chat",JSON.stringify(e))}catch(e){}},window.startConversationQuiz=function(){var e=window._convoQuizQuestions||[];0!==e.length&&(window._convoQuizIdx=0,window._convoQuizScore=0,window._convoQuizTotal=Math.min(e.length,5),O())},window.convoQuizAnswer=function(e,t){var o=e.parentElement,n=o.querySelectorAll("button");if(n.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1",window._convoQuizScore=(window._convoQuizScore||0)+1;var i=document.createElement("div");i.style.cssText="margin-top:6px;color:#22c55e;font-size:0.8rem;font-weight:700;",i.textContent="✅ Correct!",o.appendChild(i)}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",n.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var a=document.createElement("div");a.style.cssText="margin-top:6px;color:#ef4444;font-size:0.8rem;font-weight:700;",a.textContent="❌ Not quite!",o.appendChild(a)}window._convoQuizIdx=(window._convoQuizIdx||0)+1,setTimeout(O,1500)},window.nachoChatExport=function(){var e=window._nachoChatHistory||[];if(0!==e.length){for(var t=["=== Nacho Mode Chat Export ===","Exported: "+(new Date).toLocaleString(),""],o=0;o]+>/g,"");t.push("["+i+"] "+a+": "+r)}t.push("","--- bitcoineducation.quest ---");var s=new Blob([t.join("\n")],{type:"text/plain"}),c=document.createElement("a");c.href=URL.createObjectURL(s),c.download="nacho-chat-"+(new Date).toISOString().slice(0,10)+".txt",c.click(),URL.revokeObjectURL(c.href),"function"==typeof showToast&&showToast("💾 Chat saved!")}else"function"==typeof showToast&&showToast("No chat to save!")},window.nachoChatClear=function(){confirm("Clear all chat history with Nacho?")&&(window._nachoChatHistory=[],localStorage.removeItem("btc_nacho_chat"),N(),"function"==typeof showToast&&showToast("🗑️ Chat cleared"))},window.nachoModeSend=function(){var e=document.getElementById("nachoModeInput");if(e){var t=e.value.trim();if(t){e.value="",window._nachoSentIdx=-1,window._nachoSentDraft="",window._nachoAskedQuestions||(window._nachoAskedQuestions=[]),window._nachoAskedQuestions.push(t.toLowerCase()),window._nachoAskedQuestions.length>30&&(window._nachoAskedQuestions=window._nachoAskedQuestions.slice(-20)),window._nachoSentHistory.push(t),window._nachoSentHistory.length>50&&window._nachoSentHistory.shift();try{localStorage.setItem("btc_nacho_sent",JSON.stringify(window._nachoSentHistory))}catch(e){}var o;(o=document.getElementById("nachoHeroAvatar"))&&o.classList.add("talking"),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,window._nachoModeTopics&&t.length>10&&window._nachoModeTopics.push(t),!window._nachoConvoQuizOffered&&window._nachoModeStartTime&&window._nachoModeTopics&&(Date.now()-window._nachoModeStartTime)/6e4>=15&&window._nachoModeTopics.length>=5&&(window._nachoConvoQuizOffered=!0,setTimeout(function(){D()},8e3)),H("user",t),q("user",t),function(){var e=document.getElementById("nachoModeChat");if(e){e.querySelector("#nachoModeAvatar")&&(e.innerHTML="");var t=document.createElement("div");t.id="nmThinking",t.className="nm-msg nm-nacho",t.innerHTML='🦌 Thinking',e.appendChild(t),e.scrollTop=e.scrollHeight;var o=t.querySelector(".nacho-dots"),n=0;window._nmDotsTimer=setInterval(function(){n=(n+1)%4,o&&(o.textContent=".".repeat(n))},400)}}();var n="nm_"+Date.now()+"_"+Math.random().toString(36).substr(2,4),i=!1,a=setTimeout(function(){i||(i=!0,console.warn("[Nacho] Master timer fired — pipeline took >15s for:",t),s("That's a great question! I'm having a little trouble with my brain right now 🦌 Try asking me again in a moment, or explore the channels on the left to learn about Bitcoin!","fallback"))},15e3);if("function"!=typeof nachoUnifiedAnswer){if(!document.querySelector("script[data-nacho-retry]")){var r=document.createElement("script");r.src="nacho-qa.js?v="+Date.now(),r.setAttribute("data-nacho-retry","1"),document.head.appendChild(r)}setTimeout(function(){if("function"==typeof nachoUnifiedAnswer)try{nachoUnifiedAnswer(t,c)}catch(e){console.warn("Nacho pipeline retry error:",e),c({type:"fallback",answer:"I'm still loading up my Bitcoin knowledge! Try again in a moment 🦌"})}else!function(e,t){if("function"==typeof checkOffTopic){var o=checkOffTopic(e);if(o)return void t("function"==typeof personalize?personalize(o):o,"offtopic")}var n=e.toLowerCase().trim();if(/^(hey|hi|hello|yo|sup|howdy|hola|what'?s up|how are you|how'?s it going|good morning|good evening|good afternoon|gm|greetings)$/i.test(n)||/^(hey|hi|hello|yo) (nacho|there|buddy|friend|deer)/i.test(n)){var i=["Hey there! 🦌 Doing great — just hanging out waiting for someone to ask me about Bitcoin! What's on your mind?","Hey hey! 🧡 Welcome! I'm Nacho, your Bitcoin buddy. What would you like to learn about today?","Well hello! 🦌 Nice to see you. Ask me anything about Bitcoin — I've got 146 channels of knowledge in these antlers!","Hey! 👋 I'm good, thanks for asking! Ready to talk Bitcoin whenever you are. What's on your mind?"];t(i[Math.floor(Math.random()*i.length)],"offtopic")}else"function"==typeof nachoTrackMiss&&nachoTrackMiss(e),t("Give me just a moment — I'm loading up my Bitcoin knowledge! Try again in a few seconds. 🦌","fallback")}(t,s)},2e3)}else try{console.log("[Nacho] Calling nachoUnifiedAnswer for:",t),nachoUnifiedAnswer(t,function(e){console.log("[Nacho] Pipeline returned:",e?e.type:"null"),c(e)})}catch(e){console.error("[Nacho] Pipeline CRASH:",e),c({type:"fallback",answer:"Oops, my brain hit a bump! 🦌 Try asking again — I know a LOT about Bitcoin!"})}}}function s(e,o){!function(){window._nmDotsTimer&&(clearInterval(window._nmDotsTimer),window._nmDotsTimer=null);var e=document.getElementById("nmThinking");e&&e.remove()}(),function(){var e=document.getElementById("nachoHeroAvatar");e&&e.classList.remove("talking")}();var i="";if(o&&"safety"!==o){window._nachoAnswerData||(window._nachoAnswerData={}),window._nachoAnswerData[n]=e;var a="background:none;border:1px solid var(--border);border-radius:16px;cursor:pointer;font-size:0.75rem;padding:4px 10px;transition:0.2s;color:var(--text-muted);display:inline-flex;align-items:center;gap:3px;touch-action:manipulation;",r='
    ';"function"==typeof nachoRatingHtml&&(r+='",r+='"),r+="',i+=r+="
    ",i+=function(e){if(!e||0===e.length)return"";for(var t='
    ',o=0;o💬 "+e[o]+"";return t+"
    "}("function"==typeof nachoFollowUps?nachoFollowUps((t||"")+" "+(e||"")):[])}H("nacho","",e+i),q("nacho","",e+i),j(),"function"==typeof nachoTrackTopic&&nachoTrackTopic(t,o||"unknown");var s=function(){if(L)return null;for(var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[10,25,50,100,200,500],o=safeJSON("btc_nacho_q_milestones",[]),n=null,i=0;i=a&&-1===o.indexOf(r)&&-1===o.indexOf(a)&&(o.push(r),n=a)}return null===n?null:(localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(o)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({nachoMilestones:o}).catch(function(){}),L=!0,{10:"🎉 10 questions! You're officially a Bitcoin Beginner! Keep going — there's so much to learn! 🦌",25:"🎉 25 questions! You've leveled up to Bitcoin Explorer! You're asking the right questions! 💪",50:"🎉 50 questions! Bitcoin Apprentice unlocked! You know more than most people already! 🧠",100:"🏆 100 questions! You're a Bitcoin Scholar now! Satoshi would be proud! 🎓",200:"🔥 200 questions! Bitcoin Expert status! You could probably teach ME a thing or two! 🦌💡",500:"👑 500 QUESTIONS! You are a Bitcoin LEGEND! There's nothing Nacho can't discuss with you now! 🦌🏆🔥"}[n]||null)}();s&&setTimeout(function(){H("nacho","",s),q("nacho","",s)},1500)}function c(e){if(!i){i=!0,clearTimeout(a);var t="";e&&e.siteAction?t='

    ":e&&e.channel&&(t='

    📖 Read more: '+(e.channelName||e.channel)+" →"),s((e&&e.answer?e.answer:"Hmm, let me think about that... Try asking another way! 🦌")+t,e&&e.type||"fallback")}}},window.nachoModeAvatarTap=function(){var e=document.getElementById("nachoModeAvatar");e&&(e.style.transform="scale(1.1) rotate("+(Math.random()>.5?"5":"-5")+"deg)",setTimeout(function(){e.style.transform=""},300),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,j())},window._nachoModeRecognition=null,window._nachoModeListening=!1,window.nachoModeVoice=function(){var e=window.SpeechRecognition||window.webkitSpeechRecognition;if(e){var t=document.getElementById("nachoModeInput"),o=document.getElementById("nachoModeMic");if(t&&o)if(window._nachoModeListening&&window._nachoModeRecognition)window._nachoModeRecognition.stop();else{var n=new e;window._nachoModeRecognition=n,n.lang="en-US",n.interimResults=!0,n.maxAlternatives=1,n.continuous=!0,o.style.opacity="1",o.innerHTML="🛑",t.placeholder="Nacho is listening... (Tap 🛑 to finish)",t.style.borderColor="#f7931a",window._nachoModeListening=!0;var i="";n.onresult=function(e){for(var o="",n=e.resultIndex;n0&&nachoModeSend()},n.onerror=function(){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6",t.style.borderColor="var(--border,#333)",t.placeholder="Voice error — try typing"};try{n.start()}catch(e){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6"}}}},window.exitNachoMode=function(e){window._nachoMode=!1,window._nachoBusy=!1,window._btcPriceTimer&&(clearInterval(window._btcPriceTimer),window._btcPriceTimer=null);var t=document.getElementById("nachoModeScreen");t&&t.remove(),document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="")});var o=document.querySelector(".mobile-bar");if(o&&window.innerWidth<=900&&(o.style.display="flex"),!e){var n=window._nachoModeEarnings,i=window._nachoModeStartTime||Date.now(),a=Math.round((Date.now()-i)/6e4);if("function"==typeof showToast){var r=[];a>0&&r.push("⏱️ "+a+" min"),n&&n.interactions>0&&r.push("🦌 "+n.interactions+" interactions"),n&&n.points>0&&r.push("+"+n.points+" XP");var s=n?Array.isArray(n.badges)?n.badges.length:n.badges||0:0;s>0&&r.push("🏅 "+s+" badge"+(s>1?"s":"")),r.length>0?showToast(r.join(" · ")):showToast("🦌 Thanks for hanging out with "+("function"==typeof nachoNickname?nachoNickname():"Nacho")+"!")}goHome()}},window.goHome=function(e){if(document.activeElement&&document.activeElement.blur&&document.activeElement.blur(),"function"==typeof hideUsernamePrompt){var t=document.getElementById("usernameModal");t&&t.classList.contains("open")&&hideUsernamePrompt()}"function"==typeof _tctvStopTracker&&_tctvStopTracker();var n=document.getElementById("bottomNav");n&&n.classList.remove("nav-hidden"),"function"==typeof _updateSEO&&_updateSEO("home","Learn Bitcoin","A curated Bitcoin education archive with 146 topics, 8800+ messages, and community tools.");var i=document.getElementById("floatingRandomBtn");i&&(i.style.display="none");var a=document.getElementById("lbFloatBtn");a&&a.classList.remove("chat-shifted"),(l=document.getElementById("forumContainer"))&&(l.style.display="none"),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes();var r=document.getElementById("msgs");r&&(r.style.display="none");var s=document.getElementById("hero");s&&(s.style.display="none");var c=void 0!==auth&&auth?auth.currentUser:null;c&&c.email,void 0!==currentUser&¤tUser&¤tUser.totalVisits;try{safeJSON("btc_visited_channels",[]).length}catch(e){}var l,d=document.querySelector('[onclick*="showSpinWheel"]'),u=(document.querySelector('[onclick*="showPricePrediction"]'),document.querySelector('[onclick*="showNachoStory"]'),document.getElementById("dailyChallengeCard")),p=document.querySelector("[onclick*=\"go('bitcoin-beats'\"]"),m=document.querySelector("[onclick*=\"go('forum'\"]"),g=document.querySelector("[onclick*=\"go('marketplace'\"]"),h=document.querySelector('[onclick*="enterNachoMode"]');d&&(d.parentElement.style.display="grid"),u&&(u.style.display=""),m&&(m.style.display=""),p&&(p.style.display=""),g&&(g.style.display=""),h&&(h.style.display=""),(l=document.getElementById("forumContainer"))&&(l.style.display="none",l.innerHTML="");var f=document.getElementById("hero");f&&(f.style.display="none",f.innerHTML="");var y=document.getElementById("msgs");if(y&&(y.style.display="none",y.innerHTML=""),document.getElementById("home").classList.remove("hidden"),document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),document.getElementById("main").scrollTop=0,e||history.pushState({channel:null},"","/"),"function"==typeof window._renderSatoshiFavorHome&&window._renderSatoshiFavorHome(),o()){document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0);var v=document.querySelector(".mobile-bar");v&&(v.style.display="flex"),"function"==typeof updateRankUI&&updateRankUI()}R(),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof loadCommunityStats&&loadCommunityStats(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof window._renderCharityHome&&window._renderCharityHome(),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn()},document.addEventListener("keydown",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.isContentEditable){var t=e.key.toLowerCase();if(!e.ctrlKey&&!e.metaKey)if("h"!==t)if("/"!==t)if("c"!==t)if("r"!==t)if("m"!==t)if("a"!==t)if("t"!==t)if("s"!==t)if("l"!==t)if("q"!==t)if("f"!==t)if("n"!==t)if("d"!==t)if("v"!==t)if("g"!==t)if("p"!==t)if("x"!==t)if("j"!==t)if("k"!==t){if(" "===t)return e.preventDefault(),void document.getElementById("main").scrollBy({top:.8*window.innerHeight,behavior:"smooth"});if("?"===t||e.shiftKey&&"/"===t)!function(){var e=document.getElementById("kbHelpModal");if(e)e.remove();else{var t=document.createElement("div");t.id="kbHelpModal",t.style.cssText="position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.7);",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

    ⌨️ Keyboard Shortcuts

    Press ? to toggle this menu
    Navigation
    '+V("H","Go home")+V("/","Search")+V("C","Random topic")+V("M","Random Meme")+V("R","Random Art")+V("G","Random Graphic")+V("B","Back to last channel")+V("T","PlebTalk (Forum)")+V("S","Lightning Mart")+'
    Actions
    '+V("F","Favorite channel")+V("A","Ask Nacho")+V("N","Nacho Mode")+V("D","Dark / Light mode")+V("L","Leaderboard")+V("Q","Start quest")+V("V","Gallery view")+V("X","PVP Battle")+V("P","Donate")+V("I","Settings")+'
    Scrolling
    '+V("J","Scroll down")+V("K","Scroll up")+V("Space","Page down")+V("Esc","Close modals")+'
    Mobile Gestures
    '+V("2-finger","Nacho Mode")+V("3-finger","Settings")+V("Long-press","Explore Apps (on logo)")+"
    ",document.body.appendChild(t)}}();else if("i"!==t)if("b"!==t)if("2"!==t)if("3"!==t)if("1"!==t){if("0"===t)return W("Don't trust. Verify."),void("function"==typeof earnSticker&&earnSticker("cool"));if("9"===t)return W("Number go up!"),void("function"==typeof nachoFly&&nachoFly());if("2"!==window._eggBuffer||"1"!==t)if("w"!==t){if(window._eggBuffer=(window._eggBuffer||"")+t,window._eggBuffer.length>10&&(window._eggBuffer=window._eggBuffer.slice(-10)),-1!==window._eggBuffer.indexOf("btc")&&(window._eggBuffer="",localStorage.setItem("btc_bitcoin_eyes_unlocked","true"),"function"==typeof showToast&&showToast("₿₿ Secret unlocked: Bitcoin Eyes! Check Nacho's Closet!"),"function"==typeof haptic&&haptic("success")),"escape"===t){e.preventDefault();var i=document.getElementById("lb");if(i&&i.classList.contains("open"))return void i.classList.remove("open");var a=document.getElementById("usernameModal");if(a&&a.classList.contains("open"))return void("function"==typeof hideUsernamePrompt&&hideUsernamePrompt());var r=document.getElementById("questModal");if(r&&r.classList.contains("open"))return void r.classList.remove("open");var s=document.getElementById("searchOverlay");if(s&&"none"!==s.style.display)return void(s.style.display="none");var c=document.getElementById("nachoStoryOverlay");if(c)return void c.remove();var l=document.getElementById("spinModal");if(l)return void l.remove();var d=document.getElementById("donateModal");if(d)return void d.remove();var u=document.getElementById("kbHelpModal");if(u)return void u.remove();if(document.getElementById("pvpOverlay"))return void("function"==typeof exitPVPMode&&exitPVPMode());var p=document.getElementById("appsMenu");if(p&&"block"===p.style.display)return void(p.style.display="none");if(o()){var m=document.getElementById("sidebar");if(m&&m.classList.contains("open"))return m.classList.remove("open"),void("function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!0))}if(window._nachoMode&&"function"==typeof exitNachoMode)return void exitNachoMode()}}else W("Stay humble. Stack sats.");else W("Twenty-one million. Final and absolute.")}else W("One more block.");else W("Three point one two five. The current block reward.");else W("There is no second best.");else{var g=localStorage.getItem("btc_last_channel");g&&go(g)}else"function"==typeof showSettingsPage&&showSettingsPage("account")}else document.getElementById("main").scrollBy({top:-300,behavior:"smooth"});else document.getElementById("main").scrollBy({top:300,behavior:"smooth"});else"function"==typeof enterPVPMode&&enterPVPMode();else showDonateModal();else T();else{var h=document.getElementById("galleryBtn");h&&h.click()}else n();else"function"==typeof enterNachoMode&&enterNachoMode();else{var f=document.getElementById("favBtn");f&&f.click()}else{var y=document.getElementById("questBtn");y&&y.click()}else"function"==typeof toggleLeaderboard&&toggleLeaderboard();else go("marketplace");else go("forum");else"function"==typeof showNachoInput&&showNachoInput();else x();else k();else b();else{e.preventDefault();var v=document.getElementById("searchInput");v&&(v.focus(),o()&&document.getElementById("sidebar").classList.add("open"))}else goHome()}});var F=0;function W(e){var t=Date.now();if(!(t-F<3e3)){F=t,"function"==typeof showToast&&showToast("🟠 "+e);try{var o=new SpeechSynthesisUtterance(e);o.rate=.9,o.pitch=.85,o.volume=.8;var n=speechSynthesis.getVoices().find(function(e){return-1!==e.name.indexOf("Daniel")||-1!==e.name.indexOf("Google UK English Male")||-1!==e.name.indexOf("Male")});n&&(o.voice=n),speechSynthesis.cancel(),speechSynthesis.speak(o)}catch(e){}}}function V(e,t){return'
    '+e+'
    '+t+"
    "}"undefined"!=typeof speechSynthesis&&speechSynthesis.getVoices(),function(){if("ontouchstart"in window){var e=0,t=0;window.addEventListener("devicemotion",function(o){var n=o.acceleration&&null!==o.acceleration.x?o.acceleration:null;if(n&&Math.abs(n.x)+Math.abs(n.y)+Math.abs(n.z)>25){if(e++,clearTimeout(window._shakeResetTimer),window._shakeResetTimer=setTimeout(function(){e=0},1e3),e<3)return;e=0;var i=Date.now();if(i-t<1e4)return;t=i;var a=["There is no second best.","One more block.","Don't trust. Verify.","Number go up!","Stay humble. Stack sats.","Not your keys, not your coins.","Bitcoin fixes this.","Tick tock, next block."];W(a[Math.floor(Math.random()*a.length)]),Math.random()<.3&&"function"==typeof nachoFly&&nachoFly()}});var o=0,n=0,i=0,a=document.getElementById("main");a.addEventListener("touchstart",function(e){"INPUT"===e.target.tagName||"TEXTAREA"===e.target.tagName||e.target.closest(".no-swipe")||(o=e.touches[0].clientX,n=e.touches[0].clientY,i=Date.now())},{passive:!0}),a.addEventListener("touchend",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.closest(".no-swipe")){var t=e.changedTouches[0].clientX-o,a=e.changedTouches[0].clientY-n,r=Date.now()-i,s=Math.abs(t),c=Math.abs(a);r>600||s>150&&s>2.5*c&&(t>0?(goPrev(),"function"==typeof haptic&&haptic("light")):(goNext(),"function"==typeof haptic&&haptic("light")))}},{passive:!0});var r=0,s=0;document.getElementById("main").addEventListener("touchstart",function(e){2===e.touches.length&&(s=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(s&&0===e.touches.length&&e.changedTouches.length>=1){var t=Date.now()-s;if(s=0,t>400)return;var o=Date.now();if(o-r<3e3)return;r=o,"function"==typeof enterNachoMode&&enterNachoMode()}},{passive:!0}),document.querySelectorAll(".home-logos img, .channel-logos .channel-logo-img").forEach(d),new MutationObserver(function(){document.querySelectorAll(".channel-logos .channel-logo-img").forEach(d)}).observe(document.getElementById("main"),{childList:!0,subtree:!0});var c=0,l=0;document.getElementById("main").addEventListener("touchstart",function(e){3===e.touches.length&&(l=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(l&&0===e.touches.length){var t=Date.now()-l;if(l=0,t>400)return;var o=Date.now();if(o-c<3e3)return;c=o,"function"==typeof showSettings&&showSettings()}},{passive:!0})}function d(e){var t;e._logoLongPress||(e._logoLongPress=!0,e.addEventListener("touchstart",function(e){t=setTimeout(function(){"function"==typeof toggleAppsMenu&&toggleAppsMenu(),"function"==typeof haptic&&haptic("medium")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t)}),e.addEventListener("touchmove",function(){clearTimeout(t)}))}}();const G={};function Q(){const e=safeJSON("btc_visited_channels",[]).length;void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth?auth:null,o=t&&t.currentUser;o&&o.email;var n="function"==typeof getOnboardingProfile?getOnboardingProfile():null;n&&("advanced"===n.level||n.level);const i=document.querySelectorAll(".cat-label.cat-toggle"),a=document.querySelectorAll(".quest-start-btn, .home-cta, #beatsBtnHome, [onclick*=\"go('forum'\"], [onclick*=\"go('marketplace'\"]");function r(e){return function(){var t=e.match(/^go\(['"]([^'"]+)['"]/);if(t)go(t[1]);else{var o=e.match(/^(?:if\(typeof\s+(\w+)==='function'\))?\s*(\w+)\(\)/);if(o){var n=o[2]||o[1];if("function"==typeof window[n])return void window[n]()}var i=e.match(/renderChatHub\(['"](\w+)['"]\)/);if(i&&"function"==typeof window.renderChatHub)window.renderChatHub(i[1]);else{var a=e.match(/showSettingsPage\(['"](\w+)['"]\)/);a&&"function"==typeof window.showSettingsPage?window.showSettingsPage(a[1]):console.warn("[SECURITY] Unrecognized action pattern:",e)}}}}i.forEach(function(e){var t=e.nextElementSibling;t&&t.classList.contains("cat-group")&&(e.style.display="",t.style.display="true"===e.getAttribute("data-expanded")?"":"none")}),a.forEach(e=>{if(e.closest("#appsMenu")||e.closest("#guideOverlay")||e.closest("#questHubOverlay"))return;const t=e.getAttribute("data-name")||e.textContent.replace("🔒 ","").trim();e.getAttribute("data-name")||e.setAttribute("data-name",t);const o=e.getAttribute("data-onclick")||e.getAttribute("onclick");e.getAttribute("data-onclick")||e.setAttribute("data-onclick",o),e.innerHTML=t,e.style.opacity="1",e.style.filter="none",e.style.cursor="pointer",e.title="";var n=e.getAttribute("data-onclick");n&&(e.onclick=r(n))}),document.querySelectorAll("[data-tier]").forEach(t=>{const o=t.getAttribute("data-tier"),n=t.getAttribute("data-unlock-name")||t.textContent.trim(),i=t.getAttribute("data-onclick")||t.getAttribute("onclick");!t.getAttribute("data-onclick")&&i&&t.setAttribute("data-onclick","string"==typeof i?i:i.toString()),!t.getAttribute("data-orig-tooltip")&&t.getAttribute("data-tooltip")&&t.setAttribute("data-orig-tooltip",t.getAttribute("data-tooltip"));let a=!1,s="";if("explorer"===o?(a=true,s="🔒 Visit "+Math.max(0,3-e)+" more channel"+(3-e==1?"":"s")+" to unlock "+n+"!"):"community"===o?(a=true,s="🔒 Explore "+Math.max(0,5-e)+" more channel"+(5-e==1?"":"s")+" to unlock "+n+"!"):"full"===o&&(a=true,s="🔒 Explore "+Math.max(0,10-e)+" more channel"+(10-e==1?"":"s")+" or sign in to unlock "+n+"!"),a){t.innerHTML=n,t.style.opacity="1",t.style.filter="none";var c=t.getAttribute("data-orig-tooltip")||t.getAttribute("data-tooltip");c?(t.title=c,t.setAttribute("data-tooltip",c)):t.title=n,t.style.cursor="pointer",t.title="";var l=t.getAttribute("data-onclick");l&&(t.onclick=r(l))}else t.innerHTML="🔒 "+n,t.style.opacity="0.45",t.style.filter="grayscale(0.8)",t.style.cursor="help",t.title=s,t.setAttribute("data-tooltip",s),t.onclick=function(e){e.preventDefault(),e.stopPropagation(),"function"==typeof showToast&&showToast(s)}});var s=localStorage.getItem("btc_unlocked_tier")||"none",c=["none","explorer","community","full"],l="full",d=c.indexOf(s);if(c.indexOf(l)>d){localStorage.setItem("btc_unlocked_tier",l);var u=document.getElementById("appsMenu");u&&u.remove(),"function"==typeof showToast&&showToast("🚀 ⚡ Lightning Mart unlocked! You have full access!")}var p=document.getElementById("sidebarMilestone");p&&p.remove()}function Y(){window.audioEnabled=!window.audioEnabled,localStorage.setItem("btc_audio",window.audioEnabled.toString()),X(),"function"==typeof showToast&&showToast(window.audioEnabled?"🔊 Sound on":"🔇 Sound off")}function J(e){window.audioVolume=parseFloat(e),localStorage.setItem("btc_volume",window.audioVolume.toString()),window.audioVolume<=0?(window.audioEnabled=!1,localStorage.setItem("btc_audio","false")):window.audioEnabled||(window.audioEnabled=!0,localStorage.setItem("btc_audio","true")),window._beatsAudio&&(window._beatsAudio.volume=window.audioVolume),window._djAudio&&(window._djAudio.volume=window.audioVolume);var t=document.getElementById("beatsVolume");t&&(t.value=Math.round(100*window.audioVolume));var o=document.getElementById("djVolume");o&&(o.value=Math.round(100*window.audioVolume)),X()}function X(){const e=document.getElementById("audioBtn");e&&(e.textContent=window.audioEnabled&&window.audioVolume>0?window.audioVolume>.5?"🔊":"🔉":"🔇");const t=document.getElementById("volumeSlider");t&&(t.value=window.audioEnabled?window.audioVolume:0),document.querySelectorAll('button[onclick*="toggleAudio"]').forEach(function(e){"ON"!==e.textContent&&"OFF"!==e.textContent||(e.textContent=window.audioEnabled?"ON":"OFF",e.style.background=window.audioEnabled?"#22c55e":"var(--bg-side)",e.style.color=window.audioEnabled?"#fff":"var(--text-muted)")})}Q(),window._sidebarTierInterval=setInterval(Q,5e3),window.audioEnabled="false"!==localStorage.getItem("btc_audio"),window.audioVolume=parseFloat(localStorage.getItem("btc_volume")||"0.5"),window.canPlaySound=function(){return window.audioEnabled&&window.audioVolume>0&&"visible"===document.visibilityState},window.goNext=function(){if(void 0===CHANNELS)return;const e=window._sidebarOrder&&window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(m);if(-1===t)return void go(e[0]);const o=t0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(m);if(-1===t)return void go(e[e.length-1]);const o=t>0?e[t-1]:e[e.length-1];go(o)},window.go=async function(e,t,n){"function"==typeof _tctvStopTracker&&_tctvStopTracker();var i=document.getElementById("bottomNav");i&&i.classList.remove("nav-hidden"),window._nachoMode&&!n&&("function"==typeof nachoChatSave&&nachoChatSave(),window._nachoReturnPending=!0);var a=document.getElementById("msgs"),r=document.getElementById("hero");const l=CHANNELS[e];let d="";l&&(d='"),a.innerHTML=d+'
    \x3c!-- Nacho Summary skeleton --\x3e
    \x3c!-- Message skeletons --\x3e
    \x3c!-- Image skeleton --\x3e
    ',a.style.display="",document.getElementById("home").classList.add("hidden"),r.style.display="none",o()&&document.getElementById("sidebar").classList.remove("open");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var g,f=void 0!==auth&&auth?auth.currentUser:null;if(f&&f.email,"forum"===e||"marketplace"===e||"bitcoin-beats"===e||"irl-sync"===e||"dms"===e||"lightning"===e||"chat"===e||"first-purchase"===e||"timechain-tv"===e||"trails"===e)return window._nachoMode&&exitNachoMode(!0),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.getElementById("msgs").style.display="none",document.getElementById("hero").style.display="none",(g=document.getElementById("forumContainer"))&&(g.style.display="block"),n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&document.getElementById("sidebar").classList.remove("open"),function e(t,o){if(o=o||0,"first-purchase"===t&&"function"==typeof renderFirstPurchase)renderFirstPurchase(),document.getElementById("main").scrollTop=0;else if("timechain-tv"===t&&"function"==typeof renderTimechainTV)renderTimechainTV(),document.getElementById("main").scrollTop=0,"function"==typeof _tctvStartTracker&&_tctvStartTracker();else if("marketplace"===t&&"function"==typeof renderMarketplace)renderMarketplace();else if("bitcoin-beats"===t&&"function"==typeof renderBitcoinBeats)renderBitcoinBeats();else if("irl-sync"===t&&"function"==typeof renderIRLSync)renderIRLSync();else if("dms"===t&&"function"==typeof showInbox)showInbox();else if("lightning"===t&&"function"==typeof renderLightning)renderLightning();else if("chat"===t&&"function"==typeof renderChatHub)renderChatHub("global");else if("trails"===t&&"function"==typeof renderModules)renderModules();else if("forum"===t&&"function"==typeof renderForum)renderForum();else if(o<20){if(setTimeout(function(){e(t,o+1)},250),0===o){var n=document.getElementById("forumContainer");n&&(n.innerHTML='
    Loading...
    ')}}else if("forum"===t&&"function"==typeof renderForum)renderForum();else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
    ⚠️
    Still loading...
    This feature is taking longer than expected.
    ')}}(e),document.getElementById("main").scrollTop=0,g&&(g.scrollTop=0),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0,setTimeout(function(){document.getElementById("main").scrollTop=0,document.getElementById("forumContainer")&&(document.getElementById("forumContainer").scrollTop=0),window.scrollTo(0,0)},50),setFloatingElementsVisible(!0),void("function"==typeof nachoOnPage&&nachoOnPage(e));if(!l)return;if(window._nachoMode&&exitNachoMode(!0),(g=document.getElementById("forumContainer"))&&(g.style.display="none",g.innerHTML=""),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes(),document.getElementById("hero").style.display="",document.getElementById("msgs").style.display="",!window._keepFloatingBtn){var y=document.getElementById("floatingRandomBtn");y&&"none"!==y.style.display&&"memes-funny"!==e&&"art-inspiration"!==e&&"graphics"!==e&&(y.style.display="none")}localStorage.setItem("btc_last_channel",e),function(){if(window.canPlaySound())try{const e=new(window.AudioContext||window.webkitAudioContext),t=window.audioVolume,o=e.createOscillator(),n=e.createGain();o.connect(n),n.connect(e.destination),o.frequency.value=880,o.type="sine",n.gain.setValueAtTime(.08*t,e.currentTime),n.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15),o.start(e.currentTime),o.stop(e.currentTime+.15);const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=1318.5,i.type="sine",a.gain.setValueAtTime(.05*t,e.currentTime+.05),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.25),i.start(e.currentTime+.05),i.stop(e.currentTime+.25)}catch(e){}}(),document.getElementById("home").classList.add("hidden"),(a=document.getElementById("msgs")).innerHTML=d+'
    ',document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),t?(t.classList.add("active"),s(t)):document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("'"+e+"'")&&(t.classList.add("active"),s(t))});const v=["graphics","memes-funny","art-inspiration","charts","swag-merch","fun-facts"].includes(e),b="https://bitcoineducation.quest/#"+e,w=l.title+" — Bitcoin Education Archive";let x;if(document.getElementById("hero").innerHTML='
    Home
    '+l.cat+"

    "+l.title+'

    "+(v?'":""),document.getElementById("hero").classList.remove("fade-in"),document.getElementById("msgs").innerHTML='
    Loading channel...
    ',document.getElementById("main").scrollTop=0,n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&(document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0)),G[e])x=G[e];else try{const t=await fetch(l.file);x=await t.json(),G[e]=x}catch(e){return void(document.getElementById("msgs").innerHTML='
    Error loading channel data
    ')}if(p=x,m=e,window.currentChannelId=e,u=!1,"function"==typeof window._raidOnChannelVisit&&window._raidOnChannelVisit(e),"function"==typeof _updateSEO&&void 0!==CHANNELS&&CHANNELS[e]){var k=CHANNELS[e];_updateSEO(e,k.title||k.name,k.desc||"")}if(h(e),window._searchScrollTarget&&window._searchScrollTarget.channel===e){var T=0;setTimeout(function e(){T++,window._searchScrollTarget&&(document.getElementById("msg-"+window._searchScrollTarget.msgIdx)||T>=3?"function"==typeof window._tryScrollToSearchResult&&window._tryScrollToSearchResult():setTimeout(e,400*T))},200)}document.getElementById("hero").classList.add("fade-in"),document.getElementById("msgs").classList.add("fade-in"),window._currentMsgs=x.msgs,window._currentOffset=o()?20:50,window._currentLoadChannel=e,window.loadMoreMsgs=function(){if(window._currentLoadChannel!==m)return;const e=window._currentOffset,t=window._currentMsgs,n=document.getElementById("loadMoreBtn");if(!n)return;const i=t.slice(e,e+50);let a="";i.forEach((t,n)=>{if(a+='
    ',t.text){let e=t.text,n=[],i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){var t=e.startsWith("http")?e:"https://"+e;return i.push(t),"%%TW"+(i.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){var n=i[parseInt(t)],a="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),c=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+c+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),a+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?a+='':a+=''}),a+="
    "}),n.insertAdjacentHTML("beforebegin",a),window._currentOffset=e+50,window._currentOffset>=t.length?(n.remove(),window._scrollObserver&&window._scrollObserver.disconnect()):n.textContent="Load more ("+(t.length-window._currentOffset)+" remaining)"},function(){if(window._scrollObserver&&(window._scrollObserver.disconnect(),window._scrollObserver=null),document.getElementById("loadMoreBtn")){window._scrollObserver=new IntersectionObserver(function(e){e[0].isIntersecting&&"function"==typeof window.loadMoreMsgs&&window.loadMoreMsgs()},{root:null,rootMargin:"300px",threshold:0});var e=document.getElementById("loadMoreBtn");e&&window._scrollObserver.observe(e)}}(),document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")});let S=safeJSON("btc_visited_channels",[]);S.includes(e)||(S.push(e),localStorage.setItem("btc_visited_channels",JSON.stringify(S)),Q());try{void 0!==db&&"undefined"!=typeof firebase&&db.collection("stats").doc("global").set({channelVisits:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}if("function"==typeof window._raidContribute&&window._raidContribute("channelVisit",1,e),x.msgs&&x.msgs.length>0){const t='
    Did this help you learn something?
    Your feedback helps Nacho improve the archive!
    ';a.insertAdjacentHTML("beforeend",t)}window._lastChannelOpenTime=Date.now(),"function"==typeof onChannelOpen&&onChannelOpen(e)};let K=!1,$={},Z=null;const ee=[{id:"_irl",title:"🤝 IRL Sync",desc:"Find and create local Bitcoin meetups and events",keywords:"irl meetup events sync meeting community local map gather conference meetup event rsvp",action:"go('irl-sync')"},{id:"_beats",title:"🎸 Bitcoin Beats",desc:"Community music — discover, upload, and listen to Bitcoin tracks. Upload entire albums and EPs.",keywords:"beats music livestream live video radio stream audio upload song track listen discover artist genre community album ep discography bulk batch dj broadcast",action:"go('bitcoin-beats')"},{id:"_nacho",title:"🦌 Nacho Mode",desc:"Interactive AI-powered Bitcoin tutor",keywords:"nacho mode ai chat ask question tutor learn mascot deer",action:"enterNachoMode()"},{id:"_forum",title:"🗣️ PlebTalk",desc:"Discuss Bitcoin with the community",keywords:"forum community chat discuss talk conversation post plebtalk reply thread threaded replies nested conversation",action:"go('forum')"},{id:"_articles",title:"📝 Articles",desc:"Read and write long-form Bitcoin articles",keywords:"article write publish essay blog read long form content author",action:"forumTab='articles';go('forum')"},{id:"_market",title:"⚡ LightningMart",desc:"Buy and sell with Bitcoin",keywords:"marketplace market buy sell trade shop store bitcoin sats lightning wallet hardware merch",action:"go('marketplace')"},{id:"_settings",title:"⚙️ Settings",desc:"Profile, rank, tickets, referral link, theme",keywords:"settings profile account rank level points tickets referral theme dark light audio sound notifications push",action:"showSettings()"},{id:"_spin",title:"🎡 Daily Spin",desc:"Spin the wheel for free Orange Tickets",keywords:"spin wheel daily reward ticket prize free",action:"showSpinWheel()"},{id:"_quest",title:"⚔️ Quest Hub",desc:"Quiz, Trivia, and Poll quests — earn XP!",keywords:"quest mission journey learn guided start challenge quiz trivia poll hub",action:"showQuestHub()"},{id:"_scholar",title:"🎓 Scholar Certification",desc:"Bitcoin Scholar & Protocol Expert Certifications",keywords:"scholar certification exam test certificate diploma bitcoin technical protocol",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_signal",title:"📡 The Signal",desc:"Weekly curated Bitcoin insights newsletter",keywords:"signal newsletter weekly email updates curated insights",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_flashcards",title:"📚 Flashcards",desc:"Study Bitcoin topics with interactive flashcards",keywords:"flashcard study cards learn review quiz prep memorize practice drill test",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_leaderboard",title:"🏆 Leaderboard",desc:"See top ranked Bitcoiners",keywords:"leaderboard ranking top leaders scoreboard competition",action:"toggleLeaderboard()"},{id:"_tickets",title:"🎟️ Orange Tickets",desc:"Earn tickets for giveaways and rewards",keywords:"tickets orange giveaway raffle prize sats reward earn",action:"showSettings()"},{id:"_referral",title:"🔗 Referral Program",desc:"Invite friends and earn 50 tickets each",keywords:"referral invite share link friend earn bonus",action:"showSettings()"},{id:"_closet",title:"🎽 Nacho's Closet",desc:"Dress up Nacho with items you unlock",keywords:"closet outfit clothes dress costume item equip nacho customize color hat scarf sunglasses crown hoodie accessories wardrobe",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_badges",title:"🏅 Badges",desc:"View your earned badges and goals — chat, DJ, discovery, knowledge",keywords:"badges achievement trophy unlock goal progress medal chat dj streak listener",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_story",title:"📖 Nacho's Story",desc:"Read Nacho's Bitcoin adventure — one chapter per day",keywords:"story chapter read book adventure nacho tale",action:"showNachoStory()"},{id:"_predict",title:"📈 Price Prediction",desc:"Predict if Bitcoin goes up or down in 24 hours",keywords:"predict prediction price bitcoin up down forecast",action:"showPricePrediction()"},{id:"_random",title:"🎲 Random Channel",desc:"Jump to a random Bitcoin channel",keywords:"random channel surprise discover explore dice",action:"goRandom()"},{id:"_meme",title:"😂 Random Meme",desc:"See a random Bitcoin meme",keywords:"meme funny joke random humor laugh memes",action:"goRandomMeme()"},{id:"_art",title:"🎨 Random Art",desc:"See random Bitcoin art and inspiration",keywords:"art random artwork creative inspiration gallery",action:"goRandomArt()"},{id:"_graphic",title:"📊 Random Graphic",desc:"See a random Bitcoin graphic or chart",keywords:"graphic chart data visual infographic random graphics",action:"goRandomGraphic()"},{id:"_quiz",title:"🎮 Quiz Me",desc:"Test your Bitcoin knowledge with Nacho",keywords:"quiz question test knowledge trivia game answer",action:"nachoQuizMe()"},{id:"_pvp",title:"⚔️ PVP Battle",desc:"Real-time Bitcoin trivia battles against other players",keywords:"pvp battle fight 1v1 versus trivia quiz compete multiplayer arena duel challenge opponent leaderboard wins losses",action:"enterPVPMode()"},{id:"_donate",title:"💛 Donate",desc:"Support Bitcoin Education Archive with sats",keywords:"donate support tip sats lightning contribute funding",action:"showDonateModal()"},{id:"_theme",title:"🌙 Toggle Theme",desc:"Switch between dark and light mode",keywords:"theme dark light mode toggle switch appearance color night day",action:'document.getElementById("themeToggle").click()'},{id:"_audio",title:"🔊 Toggle Audio",desc:"Turn sound effects on or off",keywords:"audio sound music mute volume effects toggle",action:"toggleAudio()"},{id:"_keyboard",title:"⌨️ Keyboard Shortcuts",desc:"View all keyboard shortcuts",keywords:"keyboard shortcut hotkey key binding keys shortcuts help",action:"showKeyboardHelp()"},{id:"_explore",title:"🗺️ Exploration Map",desc:"See which topics you have visited",keywords:"exploration map progress visited topics grid complete coverage",action:"goHome()"},{id:"_globalchat",title:"🌍 Global Chat",desc:"Live global chat room — talk with the community in real time",keywords:"global chat room live talk community message send public chatroom online users presence dm reaction gif emoji sticker emoji picker smiley face emoticon",action:"if(typeof renderChatHub==='function')renderChatHub('global');else if(typeof toggleChatOverlay==='function')toggleChatOverlay()"},{id:"_timechaintv",title:"📺 Timechain TV",desc:"Live Bitcoin television — 8 channels of curated Bitcoin videos playing 24/7",keywords:"tv television video watch live stream channel timechain tube youtube documentary tutorial mining sync broadcast cinema epg guide schedule remote couch nacho",action:"go('timechain-tv')"},{id:"_djmode",title:"🎧 DJ Mode",desc:"Go live as a DJ — broadcast music, use sound effects, crossfade, and play Bitcoin quotes",keywords:"dj mode broadcast live music stream turntable crossfade sound effects horn airhorn scratch mixer controls",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('livestream')},300)"},{id:"_upload_album",title:"📀 Upload Album/EP",desc:"Upload up to 20 songs at once — group as Album or EP with cover art",keywords:"upload album ep discography batch bulk multiple songs tracks artist release collection",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('upload')},300)"},{id:"_messages",title:"💬 Messages / DMs",desc:"Direct messages — chat privately with other users",keywords:"messages dm direct message inbox chat private conversation contact send receive talk",action:"showInbox()"},{id:"_signin",title:"🔐 Sign In",desc:"Sign in or create an account",keywords:"sign in login register create account google twitter github facebook email",action:"showUsernamePrompt()"},{id:"_home",title:"🏠 Home",desc:"Return to the homepage",keywords:"home main start beginning",action:"goHome()"},{id:"_firstpurchase",title:"🛒 Your First Bitcoin Purchase",desc:"Step-by-step guide to buying your first Bitcoin — apps for 11 regions",keywords:"buy purchase first bitcoin exchange app strike river cash coinbase amber wallet region country how to start beginner dca",action:"go('first-purchase')"},{id:"_trails",title:"🦌 Nacho's Trails",desc:"Guided learning paths through Bitcoin education — Meadow, Mountain & Summit",keywords:"trails nacho guided path learning course module meadow mountain summit exam test progress curriculum education beginner intermediate advanced",action:"go('trails')"},{id:"_dashboard",title:"📊 Top Indicators",desc:"Live Bitcoin cycle top indicators — Pi Cycle, NUPL, Puell, Power Law & more",keywords:"dashboard indicators top cycle signal pi cycle nupl puell mayer multiple rsi ahr999 mstr etf power law rainbow reserve risk bitcoin metrics data analytics chart",action:"if(typeof toggleDashboard==='function')toggleDashboard()"},{id:"_meetupbox",title:"📦 Meetup-in-a-Box",desc:"Ready-made meetup templates with agendas and host tips",keywords:"meetup box template agenda host tips lightning workshop self custody mining event organize plan download",action:"go('irl-sync')"},{id:"_buddy",title:"🤝 Bitcoin Buddy",desc:"Find a learning partner — teachers matched with learners",keywords:"buddy partner match learn teach mentor mentee pair connect chat find friend study accountability group",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_certs",title:"📜 Shareable Certificates",desc:"Share your Scholar Certification with a verifiable public link",keywords:"certificate share verify link public proof scholar achievement social media url",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_satsvbits",title:"⚡ Sats vs Bits",desc:"Live community vote — sats or bits for the Bitcoin denomination?",keywords:"sats bits vote poll denomination unit satoshi community debate live",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_newbie",title:"🟢 Brand New to Bitcoin?",desc:"Quick introduction for absolute beginners",keywords:"new beginner brand new start zero nothing know nothing introduction first time newbie noob",action:"go('one-stop-shop')"},{id:"_meetupbuilder",title:"🔨 Meetup Builder",desc:"Plan, share, and discover Bitcoin meetups — resources, venues & guides",keywords:"meetup builder create plan share venue platform resource guide community",action:"go('meetup-builder')"},{id:"_sats",title:"⚡ Claim Sats",desc:"Convert your earned points into real Bitcoin sats via Lightning",keywords:"sats claim withdraw cashout bitcoin lightning faucet earn XP convert redeem payout real btc satoshi",action:"showSettings();setTimeout(function(){showSettingsPage('sats')},100)"},{id:"_tips",title:"⚡ Lightning Tips",desc:"Tip other users with Lightning sats",keywords:"tip tips lightning send sats zap reward give appreciation",action:"if(typeof showTipOverlay==='function')showTipOverlay()"},{id:"_network",title:"📡 Bitcoin Network",desc:"Live mempool, hashrate, difficulty, fees, and block explorer",keywords:"network mempool hashrate difficulty fees block explorer transaction confirmations bitcoin network stats",action:"go('bitcoin-dashboard')"},{id:"_notifications",title:"🔔 Notifications",desc:"Enable push notifications for updates and alerts",keywords:"notifications push alerts notify bell updates permission enable disable",action:"if(typeof requestNotificationPermission==='function')requestNotificationPermission();else showSettings()"},{id:"_streakfreeze",title:"🧊 Streak Freeze",desc:"Protect your visit streak with freeze tickets",keywords:"streak freeze ticket protect miss save guard insurance ice",action:"showSettings();setTimeout(function(){showSettingsPage('data')},100)"},{id:"_cotd",title:"📅 Channel of the Day",desc:"Today's featured Bitcoin education channel",keywords:"channel of the day daily featured recommendation today pick spotlight",action:"goHome()"},{id:"_nostr",title:"🟣 Nostr Login",desc:"Sign in with Nostr — extension, nsec, or npub",keywords:"nostr login sign in nip npub nsec extension relay decentralized identity",action:"showUsernamePrompt()"},{id:"_buddyfind",title:"🤝 Find a Bitcoin Buddy",desc:"Get matched with a learning partner — teachers meet learners",keywords:"buddy partner match learn teach mentor mentee pair connect study group accountability partner friend",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_favor",title:"✨⛏️ Satoshi's Favor",desc:"Community mining game — earn points, activate mining, hash for 21,000 sats",keywords:"satoshi favor mining hash mine community points activate 21 sats game block nonce difficulty target hashing brute force proof of work",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='favor';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_raid",title:"⚔️ Raid Boss",desc:"Monthly community challenge — deal damage by earning badges and completing activities",keywords:"raid boss challenge monthly community damage badge activity quest defeat winner prize leaderboard attack",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='raid';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_charity",title:"❤️ Donate XP for Charity",desc:"Donate your XP points for charity — 1,000 XP = 1,000 sats pledged. 10× more impact than redeeming for yourself.",keywords:"charity donate donation xp points sats bitcoin giving community philanthropy pledge faction badger hornet",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='charity';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_pow",title:"🚶 Proof of Walk",desc:"Connect Strava and earn XP for walking — proof of work with your feet",keywords:"proof of walk strava walking steps exercise fitness health outdoor move earn xp activity sync connect",action:"go('explore');setTimeout(function(){if(typeof renderProofOfWalk==='function')renderProofOfWalk()},300)"},{id:"_pop",title:"🕹️ Proof of Play",desc:"Bitcoin gaming hub — Timechain Arcade games + PVP trivia battles",keywords:"proof of play arcade games pvp battle timechain bitcoin gaming 1v1 trivia lightning to the moon node runner nakamoto knights block hunt",action:'if(typeof enterProofOfPlay==="function")enterProofOfPlay()'}];function te(e){const t=document.getElementById("searchResults"),o=document.getElementById("channelList");if(["searchInput","searchOverlayInput"].forEach(t=>{const o=document.getElementById(t);o&&o.value!==e&&(o.value=e)}),e&&"satoshi"===e.toLowerCase()&&("function"==typeof awardHiddenBadge&&awardHiddenBadge("discovery_satoshi","Found Satoshi! 🦢"),W("I am Satoshi. We are all Satoshi.")),e&&"deer"===e.toLowerCase()&&("function"==typeof setPose&&setPose("celebrate"),W("Fawntastic! You found the secret buck."),"function"==typeof nachoFly&&setTimeout(nachoFly,1e3)),!e||e.length<2){var n=safeJSON("btc_recent_searches",[]);if(n.length>0&&t){var i='
    🕐 Recent Searches
    ';n.forEach(function(e){i+=""}),i+="
    ",t.innerHTML=i,t.classList.add("active")}else t.classList.remove("active"),t.innerHTML="";return void(o&&(o.style.display=""))}e=e.toLowerCase(),o.style.display="none",t.classList.add("active");let a=[];for(const t of ee)(t.title.toLowerCase().includes(e)||t.keywords.includes(e)||t.desc.toLowerCase().includes(e))&&a.push({key:t.id,title:t.title,cat:"⚡ App",match:t.desc,action:t.action});let r=[];for(const[t,o]of Object.entries(CHANNELS))(o.title.toLowerCase().includes(e)||o.desc.toLowerCase().includes(e))&&r.push({key:t,title:o.title,cat:o.cat,match:"Channel match"});ie([...a,...r],t),clearTimeout(Z),Z=setTimeout(async()=>{await async function(){if(K)return;const e=Object.entries(CHANNELS).map(async([e,t])=>{if(G[e])$[e]=G[e];else try{const o=await fetch(t.file),n=await o.json();G[e]=n,$[e]=n}catch(e){}});await Promise.all(e),K=!0}();let o=[];for(const[t,n]of Object.entries($)){const i=CHANNELS[t];if(!i)continue;if(r.some(e=>e.key===t))continue;const a=n.msgs||[];for(let n=0;n0?"...":"")+r.text.substring(s,a+e.length+30).replace(/<[^>]+>/g,"")+"...";o.push({key:t,title:i.title,cat:i.cat,match:c,msgIdx:n});break}}}ie([...a,...r,...o],t)},500)}const oe=[{q:"What is Bitcoin?",icon:"💰",reason:"Most asked"},{q:"Lightning Network",icon:"⚡",reason:"Trending"},{q:"How to buy Bitcoin",icon:"🛒",reason:"Popular"},{q:"Self-custody wallets",icon:"🔐",reason:"Essential"},{q:"Bitcoin vs Ethereum",icon:"🆚",reason:"Hot topic"},{q:"Why 21 million?",icon:"🔢",reason:"Fundamental"},{q:"Mining explained",icon:"⛏️",reason:"Technical"},{q:"Bitcoin security",icon:"🛡️",reason:"Important"}];function ne(){var e=document.getElementById("searchResults");if(e){var t='
    🔥 Trending Topics
    ';oe.forEach(function(e){t+=""}),t+="
    ",e.innerHTML=t,e.classList.add("active")}}function ie(e,t){0!==e.length?t.innerHTML=e.slice(0,30).map(e=>{const t=e.key&&e.key.startsWith("_");return'
    "+e.cat+"
    "+e.title+'
    '+e.match+"
    "}).join(""):t.innerHTML='
    No results found
    Try: "Lightning Network" or "What is Bitcoin?"
    '}function ae(e,t){var o=document.getElementById("searchOverlayInput"),n=document.getElementById("searchInput"),i=o&&o.value||n&&n.value||"";!function(e){if(e&&!(e.length<2)){var t=safeJSON("btc_recent_searches",[]);(t=t.filter(function(t){return t.toLowerCase()!==e.toLowerCase()})).unshift(e.length>40?e.substring(0,40):e),t.length>10&&(t=t.slice(0,10)),localStorage.setItem("btc_recent_searches",JSON.stringify(t))}}(i),n&&(n.value=""),o&&(o.value=""),document.getElementById("searchOverlay").style.display="none",te(""),"number"==typeof t&&t>=0&&(window._searchScrollTarget={channel:e,msgIdx:t,query:i}),go(e)}window._tryScrollToSearchResult=function(){var e=window._searchScrollTarget;if(e){var t=e.msgIdx;if(e.query,window._searchScrollTarget=null,t>=(o()?20:50)&&"function"==typeof window.loadMoreMsgs)for(var n=0;!document.getElementById("msg-"+t)&&document.getElementById("loadMoreBtn")&&n<50;)window.loadMoreMsgs(),n++;var i=document.getElementById("msg-"+t);i&&setTimeout(function(){i.scrollIntoView({behavior:"smooth",block:"center"}),i.style.transition="background 0.3s, box-shadow 0.3s",i.style.background="rgba(249,115,22,0.12)",i.style.boxShadow="inset 3px 0 0 #f97316",i.style.borderRadius="8px",setTimeout(function(){i.style.background="",i.style.boxShadow="",i.style.borderRadius=""},3e3)},300)}},function(){const e=document.getElementById("visitCount");setTimeout(function(){if("undefined"==typeof firebase||!firebase.firestore)return;const t=firebase.firestore(),o=(new Date).toISOString().split("T")[0];for(var n=[screen.width,screen.height,screen.colorDepth,Intl.DateTimeFormat().resolvedOptions().timeZone,navigator.language,navigator.hardwareConcurrency||0,navigator.platform].join("|"),i=0,a=0;a{a.textContent="Submit Suggestion",a.disabled=!1},3e3)}catch(e){i.innerHTML='Error submitting. Please try again.',a.textContent="Submit Suggestion",a.disabled=!1}}else i.innerHTML='Please enter a suggestion!'},function(){const e=Object.keys(CHANNELS),t=new Date,o=e[Math.floor((t-new Date(t.getFullYear(),0,0))/864e5)%e.length],n=CHANNELS[o];if(n){const e=document.getElementById("dailyChannel");e.innerHTML='
    📅 Channel of the Day
    '+n.title+'
    '+n.desc+"
    ",e.onclick=()=>go(o)}}(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof renderExplorationMap&&renderExplorationMap(),window.innerWidth>900&&document.getElementById("main").addEventListener("scroll",function(){const e=this;document.getElementById("backToTop").classList.toggle("visible",e.scrollTop>400);var t=e.scrollTop+e.clientHeight>=e.scrollHeight-200;document.getElementById("scrollToBottom").classList.toggle("visible",!t)}),window._launchPVP=function(){if("function"==typeof enterPVPMode)enterPVPMode();else{"function"==typeof window._loadDeferred&&window._loadDeferred(),"function"==typeof showToast&&showToast("⚔️ Loading PVP arena...");var e=0,t=setInterval(function(){e++,"function"==typeof enterPVPMode?(clearInterval(t),enterPVPMode()):e>15&&(clearInterval(t),"function"==typeof showToast&&showToast("⚠️ PVP failed to load — try refreshing the page"))},200)}},window.toggleAppsMenu=function(e){e&&e.stopPropagation();var t=document.getElementById("appsMenu");if(t&&"block"===t.style.display)t.style.display="none";else{t&&t.remove();var o=safeJSON("btc_visited_channels",[]).length,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i=void 0!==auth?auth:null,a=i&&i.currentUser,r=a&&-1!==["needcreations@gmail.com","info.603btc@gmail.com"].indexOf(a.email||""),s="function"==typeof getOnboardingProfile?getOnboardingProfile():null,c=s&&("advanced"===s.level||"full"===s.level)||r||a&&!a.isAnonymous||n>=10||o>=10,l=c||n>=5||o>=5,d="padding:15px;background:var(--card-bg);border:1px solid var(--border);border-radius:16px;color:var(--text);font-size:0.85rem;font-weight:700;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:8px;transition:0.2s;",u=d+"opacity:0.45;filter:grayscale(0.8);cursor:help;",p={"Nacho Mode":"Chat with our AI Bitcoin tutor","Proof of Play":"Bitcoin gaming hub — Arcade + PVP","Pleb Talk":"Community discussion board for Bitcoin topics","Lightning Mart":"Buy and sell with Lightning sats","IRL Sync":"Find or host local Bitcoin meetups","Bitcoin Beats":"Community music player","Timechain TV":"21 channels of Bitcoin video content","Proof of Walk":"Earn XP by walking — connect Strava","Proof of Play":"Bitcoin gaming hub — Arcade + PVP"},m=!(l||n>=3||o>=3),g=!l,h=!c,f="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Bitcoin Beats!",y="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Pleb Talk!",v="🔒 Explore "+Math.max(0,5-o)+" more topics to unlock IRL Sync!",b="🔒 Explore "+Math.max(0,10-o)+" more topics or sign in to unlock Lightning Mart!",w='";document.body.insertAdjacentHTML("beforeend",w);var x=document.getElementById("appsMenu");document.addEventListener("click",function(e){"block"!==x.style.display||x.contains(e.target)||(x.style.display="none")}),x.style.display="block","function"==typeof playSound&&playSound("pop")}function k(e,t,o,n,i){var a=p[t]||t;return n?"":""}},window.showProofOfWalk=function(){var e=document.getElementById("appsMenu");e&&(e.style.display="none");var t=document.getElementById("main");t&&(t.innerHTML='
    ',window.renderProofOfWalk&&window.renderProofOfWalk())},window.toggleSidebarMenu=function(e){var t=document.getElementById(e);t&&("flex"===t.style.display||"grid"===t.style.display||"block"===t.style.display?t.style.display="none":(e.includes("Flash")?t.style.display="flex":e.includes("homeAppsMenu")?t.style.display="grid":(t.style.display="flex",t.style.flexDirection="column"),"function"==typeof playSound&&playSound("pop")))},window.onload=()=>{"true"!==localStorage.getItem("btc_nacho_mode_default")||window.location.hash||setTimeout(function(){"function"==typeof enterNachoMode&&enterNachoMode()},1500),safeJSON("btc_visited_channels",[]).forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})}),l(),R(),"function"==typeof checkPredictionResult&&setTimeout(checkPredictionResult,4e3);var e=window.location.hash||"";history.state||(history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname+e)),window.addEventListener("popstate",function(e){var t=e.state||{},o=location.hash.slice(1);if(o||"function"!=typeof _parseCleanUrl||(o=_parseCleanUrl()||""),!e.state||t.guard)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);if(!e.state&&!o)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);var n=document.getElementById("notifPanel");if(n&&"translateY(0px)"===n.style.transform)"function"==typeof toggleNotifOverlay&&toggleNotifOverlay();else if(window._chatOverlayOpen)"function"==typeof toggleChatOverlay&&toggleChatOverlay();else{var i=document.getElementById("usernameModal");if(i&&i.classList.contains("open"))return i.classList.remove("open"),void("function"==typeof window._restoreSignUpForm&&window._restoreSignUpForm());var a=document.getElementById("mobileLearnMenu");if(a)a.remove();else{var r=document.getElementById("appsMenu");if(r&&"block"===r.style.display)r.style.display="none";else{var s=document.getElementById("questModal");if(s&&s.classList.contains("open"))s.classList.remove("open");else if(t.returnToGuide)"function"==typeof showGuide&&(showGuide(),setTimeout(function(){var e=document.getElementById("guideOverlay");if(e&&window._guideScrollTop){var t=e.querySelector('div[style*="border-radius:24px"]');t&&(t.scrollTop=window._guideScrollTop)}},500));else{for(var c=["guideOverlay","onboardingOverlay","pvpNameOverlay","pvpOverlay","tipOverlay","donateModal","lnAuthModal","nostrAuthOverlay","spinModal","hostEventModal","eventDetailOverlay","editEventOverlay","nachoColorPicker","articleLinkDialog","articleImageDialog","eli5Prompt","kbHelpModal","forumRulesOverlay","chatRulesOverlay","marketRulesOverlay","irlRulesOverlay"],l=0;l30&&clearInterval(o)},300)},1500)},function(){function e(){var e=window.location.hash.replace("#","");if(e||"function"!=typeof _parseCleanUrl||(e=_parseCleanUrl()||""),e){console.log("[ROUTE] Routing to:",e);var t=0;setTimeout(function o(){if(t>8e3)console.warn("[HASH] Gave up routing to:",e);else{if(!document.getElementById("msgs")||!document.getElementById("home"))return t+=200,void setTimeout(o,200);switch(e){case"nacho":if("function"==typeof enterNachoMode)return void enterNachoMode();break;case"pvp":if("function"==typeof enterPVPMode)return void enterPVPMode();break;case"forum":if("function"==typeof go)return void go("forum");break;case"marketplace":if("function"==typeof go)return void go("marketplace");break;case"first-purchase":case"buy":if("function"==typeof go)return void go("first-purchase");break;case"trails":case"learn":case"modules":if("function"==typeof go)return void go("trails");break;case"meetup-builder":if(window._mbRouted)return;if("function"==typeof go){window._mbRouted=!0,window._skipIRLRules=!0,localStorage.setItem("btc_irl_rules_accepted","true"),go("irl-sync"),setTimeout(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove()},100),history.replaceState({channel:"meetup-builder"},"","#meetup-builder");var n=0,i=setInterval(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove();var t=document.getElementById("meetupBuilderSection");t&&(clearInterval(i),t.scrollIntoView({behavior:"smooth",block:"start"})),++n>30&&clearInterval(i)},300);return}break;case"irl-sync":case"meet":if("function"==typeof go)return void go("irl-sync");break;case"bitcoin-beats":if("function"==typeof go)return void go("bitcoin-beats");break;case"chat":if("function"==typeof renderChatHub)return void renderChatHub("global");break;case"dms":if("function"==typeof renderChatHub)return void renderChatHub("dms");if("function"==typeof openDMInbox)return void openDMInbox();if("function"==typeof showInbox)return void showInbox();break;case"lightning":if("function"==typeof go)return void go("lightning");break;case"timechain-tv":case"tv":if("function"==typeof go)return void go("timechain-tv");break;case"pow-support":if("function"==typeof renderPOWSupport)return void renderPOWSupport();break;case"quests":if("function"==typeof showQuestHub)return void showQuestHub();break;case"dashboard":case"bitcoin-dashboard":case"metrics":case"network":if("function"==typeof toggleDashboard)return history.replaceState({home:!0},"",window.location.pathname),void toggleDashboard();break;default:if(0===e.indexOf("beats/")&&"function"==typeof go&&!window._beatsRouted){if(0===e.indexOf("beats/playlist/")){var a=e.replace("beats/playlist/","").split("/");2===a.length&&(window._beatsDeepLink={type:"playlist",ownerUid:a[0],playlistId:a[1]})}else{var r=e.replace("beats/","");r&&-1===r.indexOf("/")&&(window._beatsDeepLink={type:"track",trackId:r})}return window._beatsRouted=!0,void go("bitcoin-beats")}if(0===e.indexOf("beats/")&&window._beatsRouted)return;if(0===e.indexOf("cert/")&&"function"==typeof go)return void go(e);if("function"==typeof go&&void 0!==CHANNELS&&CHANNELS[e])return void go(e)}t+=200,setTimeout(o,200)}},500)}}e(),window.addEventListener("load",function(){setTimeout(function(){var t=window.location.hash.replace("#","");t&&document.getElementById("home")&&!document.getElementById("home").classList.contains("hidden")&&(console.log("[HASH] Post-load fallback routing to:",t),e())},800)}),window.addEventListener("hashchange",e)}(),void 0!==r&&(window.toggleCat=r),void 0!==n&&(window.toggleTheme=n),void 0!==Y&&(window.toggleAudio=Y),void 0!==J&&(window.setVolume=J),void 0!==A&&(window.handleSupportClick=A),"undefined"!=typeof showDonateModal&&(window.showDonateModal=showDonateModal),"undefined"!=typeof enterNachoMode&&(window.enterNachoMode=enterNachoMode),"undefined"!=typeof goHome&&(window.goHome=goHome),void 0!==b&&(window.goRandom=b),void 0!==k&&(window.goRandomArt=k),void 0!==x&&(window.goRandomMeme=x),void 0!==T&&(window.goRandomGraphic=T),void 0!==te&&(window.doSearch=te),void 0!==ne&&(window.showTrendingTopics=ne),void 0!==ae&&(window.selectResult=ae),void 0!==i&&(window.toggleMenu=i),void 0!==a&&(window.toggleSidebarCollapse=a),void 0!==t&&(window.openImg=t),void 0!==d&&(window.toggleFav=d),void 0!==_&&(window.shareNostr=_),void 0!==C&&(window.copyLink=C),void 0!==g&&(window.toggleGallery=g),void 0!==h&&(window.renderContent=h),"undefined"!=typeof showBeginnerGuide&&(window.showBeginnerGuide=showBeginnerGuide),void 0!==y&&(window.loadTweetEmbed=y)}(),window._spinSoundCtx=null,window.playSpinTick=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx,t=e.createOscillator(),o=e.createGain();t.connect(o),o.connect(e.destination),t.frequency.value=800+400*Math.random(),t.type="triangle",o.gain.value=.08,o.gain.exponentialRampToValueAtTime(.001,e.currentTime+.08),t.start(e.currentTime),t.stop(e.currentTime+.08)}catch(e){}},window._tctvTimer=null,window._tctvMinutesSession=0,window._tctvStartTracker=function(){if(!window._tctvTimer){window._tctvMinutesSession=0;try{var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_tctv_visited_"+e,"true")}catch(e){}console.log("[TCTV] Watch tracker started."),window._tctvTimer=setInterval(function(){if("timechain-tv"===(window.currentChannelId||"")){if(!document.hidden){var e=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")+1;localStorage.setItem("btc_tctv_watch_time",e.toString()),window._tctvMinutesSession++;try{var t=(new Date).toISOString().split("T")[0],o=parseInt(localStorage.getItem("btc_tctv_minutes_"+t)||"0")+1;localStorage.setItem("btc_tctv_minutes_"+t,String(o))}catch(e){}console.log("[TCTV] Watch time:",e,"min (Session:",window._tctvMinutesSession,"min)");try{void 0!==db&&"undefined"!=typeof firebase&&void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("stats").doc("global").set({watchTimeMinutes:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}e%10==0?("function"==typeof awardPoints&&awardPoints(10,"tctv_watch_10m"),"function"==typeof checkBadges&&checkBadges(),"function"==typeof showToast&&showToast("👁️ +10 Points — Thanks for watching Timechain TV!")):1===e&&"function"==typeof showToast&&showToast("📺 Watching Timechain TV — Points awarded every 10 min!")}}else window._tctvStopTracker()},6e4)}},window._tctvStopTracker=function(){window._tctvTimer&&(clearInterval(window._tctvTimer),window._tctvTimer=null,console.log("[TCTV] Watch tracker stopped. Total minutes watched:",window._tctvMinutesSession))},window._updateSEO=function(e,t,o){if(e){document.title=(t?t+" | ":"")+"Bitcoin Education Archive";var n=document.querySelector('link[rel="canonical"]');if(n){var i="home"===e||"/"===e?"":"/app/"+e;n.setAttribute("href","https://bitcoineducation.quest"+i)}var a=document.querySelector('meta[name="description"]');a&&o&&a.setAttribute("content",o.substring(0,160));var r=window._cleanUrl(e);window.location.href.includes(r)||history.replaceState({channel:e},"",r)}},window.playSpinWin=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx;[523,659,784,1047].forEach(function(t,o){var n=e.createOscillator(),i=e.createGain();n.connect(i),i.connect(e.destination),n.frequency.value=t,n.type="sine",i.gain.value=.1,i.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15*(o+1)+.3),n.start(e.currentTime+.15*o),n.stop(e.currentTime+.15*(o+1)+.3)})}catch(e){}},window._aiToolsOpen=!1,window.toggleAITools=function(){var e=document.getElementById("aiToolsPanel");if(!e){(e=document.createElement("div")).id="aiToolsPanel",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:250000;background:var(--bg,#0a0a0f);border-top:2px solid var(--accent,#f7931a);border-radius:16px 16px 0 0;transform:translateY(100%);transition:transform 0.3s ease;box-shadow:0 -10px 40px rgba(0,0,0,0.6);",e.innerHTML='
    🤖AI Toolspowered by PPQ
    ',document.body.appendChild(e);var t=document.createElement("style");t.id="aiToolsPanelCSS",t.textContent="@media(min-width:901px){#aiToolsPanel{max-width:480px;right:16px;left:auto;border-radius:16px 16px 0 0;}}@media(max-width:900px){#aiToolsPanel iframe{height:calc(70vh - 56px);}}",document.head.appendChild(t)}window._aiToolsOpen=!window._aiToolsOpen,e.style.transform=window._aiToolsOpen?"translateY(0)":"translateY(100%)";var o=document.getElementById("aiToolsBtn");if(o&&(o.style.background=window._aiToolsOpen?"var(--card-bg)":"linear-gradient(135deg,#6366f1,#8b5cf6)",o.style.borderColor=window._aiToolsOpen?"var(--accent)":"transparent"),window._aiToolsOpen&&void 0!==db&&db)try{var n=auth&&auth.currentUser?auth.currentUser.uid:"anon_"+(localStorage.getItem("visitorId")||"unknown");db.collection("ai_tools_opens").add({uid:n,openedAt:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){console.warn("[AI Tools] tracking error",e)}},function(){function e(){if(!document.getElementById("aiToolsBtn")){var e=document.createElement("button");e.id="aiToolsBtn",e.onclick=toggleAITools,e.title="AI Tools",e.setAttribute("aria-label","Open AI Tools"),e.style.cssText="position:fixed;bottom:10px;right:132px;z-index:200001;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;border:2px solid transparent;border-radius:50%;width:48px;height:48px;font-size:1.4rem;cursor:pointer;font-family:inherit;box-shadow:0 4px 20px rgba(99,102,241,0.4);display:flex;align-items:center;justify-content:center;transition:0.2s;-webkit-transform:translateZ(0);transform:translateZ(0);",e.innerHTML="🤖",document.body.appendChild(e);var t=document.getElementById("aiToolsBtnCSS");t||((t=document.createElement("style")).id="aiToolsBtnCSS",t.textContent="@media(max-width:900px){#aiToolsBtn{bottom:70px!important;right:128px!important;}}",document.head.appendChild(t))}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}(),function(){var e=window.renderBitcoinBeats;e&&(window.renderBitcoinBeats=function(){e(),setTimeout(function(){document.getElementById("beatsLoader");var e=document.getElementById("beatsEmbedArea");if(e){var t=e.querySelector("iframe"),o=e.querySelector(".twitter-tweet-rendered, twitter-widget");t||o||(e.innerHTML='
    🎸
    Stream Unavailable
    The live stream couldn\'t be loaded. Check out these great Bitcoin audio sources instead:
    ')}},8e3)})}(),void 0===window.contactSeller&&(window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to contact sellers!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==db&&db.collection("marketplace").doc(e).get().then(function(e){if(e.exists){var t=e.data(),o=t.sellerUid;o!==auth.currentUser.uid?("function"==typeof openDM?openDM(o,t.sellerName||"Seller"):"function"==typeof showInbox&&(showInbox(),setTimeout(function(){"function"==typeof startNewDM&&startNewDM(o,t.sellerName||"Seller")},500)),void 0!==db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1),"function"==typeof showToast&&showToast("💬 Opening chat with "+(t.sellerName||"seller")+"...")):"function"==typeof showToast&&showToast("That's your own listing!")}})}),window.handleMktImageUploadV2=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var o=document.getElementById("mktImagePreview"),n=document.getElementById("mktImagePreviewImg");if(o&&(o.style.display="block",n&&(n.src=""),o.innerHTML='
    📤 Uploading...
    '),"undefined"!=typeof firebase&&firebase.storage){var i=firebase.storage().ref(),a="marketplace/"+auth.currentUser.uid+"/"+Date.now()+"_"+t.name.replace(/[^a-zA-Z0-9.]/g,"_"),r=i.child(a).put(t,{contentType:t.type});r.on("state_changed",function(e){var t=Math.round(e.bytesTransferred/e.totalBytes*100);o&&(o.innerHTML='
    📤 Uploading... '+t+"%
    ")},function(t){"function"==typeof showToast&&showToast("Upload failed: "+t.message),o&&(o.style.display="none"),handleMktImageUpload(e)},function(){r.snapshot.ref.getDownloadURL().then(function(e){window._mktUploadedImage=e,o&&n&&(o.innerHTML=''),"function"==typeof showToast&&showToast("✅ Image uploaded!")})})}else"function"==typeof handleMktImageUpload&&handleMktImageUpload(e)}else"function"==typeof showToast&&showToast("Sign in to upload images")},function(){var e=[{type:"youtube",id:"UvSnC7P-m-U",title:"What is Bitcoin? — Andreas Antonopoulos",desc:"The best intro talk ever given"},{type:"youtube",id:"l1si5ZWLgy0",title:"Bitcoin for Beginners — BTC Sessions",desc:"Step-by-step Bitcoin guide"},{type:"youtube",id:"ZKwqNgG-Sv4",title:"The Bitcoin Standard — Saifedean Ammous",desc:"Author presentation on sound money"},{type:"youtube",id:"2pDlaOGA2ac",title:"How Bitcoin Works Under the Hood",desc:"Technical deep-dive"},{type:"youtube",id:"bBC-nXj3Ng4",title:"But How Does Bitcoin Actually Work?",desc:"3Blue1Brown explains"},{type:"youtube",id:"Gc2en3nHxA4",title:"Michael Saylor on Why Bitcoin",desc:"The macro case for Bitcoin"},{type:"youtube",id:"xLYhx1z7gC4",title:"This Machine Greens — Bitcoin & Energy",desc:"Bitcoin mining documentary"},{type:"youtube",id:"HCLWDGYnAzk",title:"Running a Bitcoin Node — Ministry of Nodes",desc:"How to verify for yourself"}];window.beatsPlaylistIndex=parseInt(localStorage.getItem("btc_beats_idx")||"0")%e.length,window.renderBeatsPlaylist=function(t){if(t){var o=e[window.beatsPlaylistIndex],n=e.length,i=window.beatsPlaylistIndex,a='
    ';a+='
    ',a+='
    '+o.title+'
    '+o.desc+" • "+(i+1)+"/"+n+'
    ',t.innerHTML=a}},window.beatsNav=function(t){window.beatsPlaylistIndex=(window.beatsPlaylistIndex+t+e.length)%e.length,localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var o=document.getElementById("beatsEmbedArea");o&&renderBeatsPlaylist(o)},window.beatsNavRandom=function(){window.beatsPlaylistIndex=Math.floor(Math.random()*e.length),localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var t=document.getElementById("beatsEmbedArea");t&&renderBeatsPlaylist(t)};var t=8e3,o=setInterval(function(){var e=document.getElementById("beatsEmbedArea");e&&(document.getElementById("beatsLoader")?(t-=500)<=0&&(clearInterval(o),renderBeatsPlaylist(e)):clearInterval(o))},500)}(),window.fuzzyMatch=function(e,t){if(!t||!e)return!0;var o=e.toLowerCase();return t.toLowerCase().split(/\s+/).every(function(e){return-1!==o.indexOf(e)})},function(){function e(){return!(!auth||!auth.currentUser)&&"needcreations@gmail.com"===(auth.currentUser.email||"")}window.forumEditPost=function(t){auth&&auth.currentUser&&void 0!==db&&db.collection("forum_posts").doc(t).get().then(function(o){if(o.exists){var n=o.data();if(n.authorId===auth.currentUser.uid||e()){var i=n.createdAt?n.createdAt.toDate():new Date;if(Date.now()-i.getTime()>9e5&&!e())"function"==typeof showToast&&showToast("Posts can only be edited within 15 minutes of creation");else{var a='
    ✏️ Edit Post
    Edited posts will show an "edited" indicator
    ',r=document.createElement("div");r.innerHTML=a,document.body.appendChild(r.firstChild)}}else"function"==typeof showToast&&showToast("You can only edit your own posts")}})},window.forumSaveEdit=function(e){var t=(document.getElementById("editPostTitle").value||"").trim(),o=(document.getElementById("editPostBody").value||"").trim();!t||t.length<5?"function"==typeof showToast&&showToast("Title must be at least 5 characters"):"function"!=typeof isCleanText||isCleanText(t+" "+o)?db.collection("forum_posts").doc(e).update({title:t.substring(0,120),body:o.substring(0,2e3),editedAt:firebase.firestore.FieldValue.serverTimestamp(),edited:!0}).then(function(){var t=document.getElementById("forumEditOverlay");t&&t.remove(),"function"==typeof showToast&&showToast("✅ Post updated!"),"function"==typeof forumViewPost&&forumViewPost(e,!0)}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))}):"function"==typeof showToast&&showToast("Post contains inappropriate language")}}(),function(){var e=[{level:1,name:"Just Met",emoji:"🦌",threshold:1},{level:2,name:"Getting Acquainted",emoji:"👋",threshold:10},{level:3,name:"Good Friends",emoji:"😊",threshold:100},{level:4,name:"Close Friends",emoji:"🧡",threshold:350},{level:5,name:"Best Buds",emoji:"💛",threshold:750}],t=window.trackNachoInteraction;t&&(window.trackNachoInteraction=function(){for(var o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),n=0,i=e.length-1;i>=0;i--)if(o>=e[i].threshold){n=e[i].level;break}t();for(var a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r=0,s=null,c=e.length-1;c>=0;c--)if(a>=e[c].threshold){r=e[c].level,s=e[c];break}if(r>n&&s){var l=JSON.parse(localStorage.getItem("btc_nacho_level_celebrated")||"[]");-1===l.indexOf(s.level)&&(l.push(s.level),localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(l)),"function"==typeof syncCelebratedState&&syncCelebratedState(),setTimeout(function(){var e="function"==typeof nachoUserName?nachoUserName():"",t=s.emoji+" "+(e?e+", w":"W")+"e just became "+s.name+"! "+(s.level>=3?"New closet items are now available! Check the Closet! 👔✨":"Keep chatting with me to unlock more! 🦌");"function"==typeof forceShowBubble?(forceShowBubble(t),s.level>=3&&setTimeout(function(){var e=document.getElementById("nacho-bubble");e&&(e.style.cursor="pointer",e.onclick=function(){e.classList.remove("show"),window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},300)})},100)):"function"==typeof showToast&&showToast("🦌 Friendship Level Up: "+s.emoji+" "+s.name+"!")},1e3))}})}(),function(){var e=[],t=!1,o=0;function n(){if(!t&&0!==e.length){var i=Date.now();if(i-o<3e4)setTimeout(n,3e4-(i-o)+100);else{t=!0;var a=e.shift();o=i;try{a.show()}catch(e){console.log("Notification error:",e)}setTimeout(function(){t=!1,n()},5e3)}}}window.queueNotification=function(t,o){e.push({type:t,show:o,queued:Date.now()}),n()};var i=window.showToast;i&&(window.showToastQueued=function(e){queueNotification("toast",function(){i(e)})})}(),window.initMiniPlayer=function(){if(!document.getElementById("miniPlayer")){var e=document.createElement("div");e.id="miniPlayer",e.style.cssText="position:fixed;bottom:60px;left:0;right:0;z-index:180;background:rgba(10,10,10,0.95);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-top:1px solid rgba(247,147,26,0.3);padding:8px 16px;display:none;align-items:center;gap:12px;",e.innerHTML='
    Not playing
    Bitcoin Beats
    ',document.body.appendChild(e)}},window._miniPlayerAudio=null,window.playInMiniPlayer=function(e,t,o){initMiniPlayer();var n=document.getElementById("miniPlayer");n&&(window._miniPlayerAudio&&window._miniPlayerAudio.pause(),window._miniPlayerAudio=new Audio(e),window._miniPlayerAudio.play().catch(function(){}),document.getElementById("mpTitle").textContent=t||"Playing...",document.getElementById("mpArtist").textContent=o||"Bitcoin Beats",document.getElementById("mpPlayPause").textContent="⏸",n.style.display="flex")},window.toggleMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.paused?(window._miniPlayerAudio.play(),document.getElementById("mpPlayPause").textContent="⏸"):(window._miniPlayerAudio.pause(),document.getElementById("mpPlayPause").textContent="▶"))},window.closeMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.pause(),window._miniPlayerAudio=null);var e=document.getElementById("miniPlayer");e&&(e.style.display="none")},function(){var e=2592e6;window.isListingExpired=function(t){if(!t||!t.createdAt)return!1;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt);return Date.now()-o.getTime()>e},window.renewListing=function(e){auth&&auth.currentUser&&void 0!==db&&db.collection("marketplace").doc(e).update({createdAt:firebase.firestore.FieldValue.serverTimestamp(),renewed:!0,renewedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){"function"==typeof showToast&&showToast("✅ Listing renewed for 30 more days!"),"function"==typeof renderMarketplace&&renderMarketplace({listingId:e})}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))})},window.getExpiryStatus=function(t){if(!t||!t.createdAt)return null;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt),n=Date.now()-o.getTime(),i=Math.max(0,Math.ceil((e-n)/864e5));return i<=0?{status:"expired",text:"This listing has expired",color:"#ef4444"}:i<=5?{status:"expiring",text:"Expires in "+i+" day"+(1!==i?"s":""),color:"#eab308"}:null}}(),window.renderSellerReputation=function(e,t){e&&t&&void 0!==db&&db.collection("users").doc(e).get().then(function(e){if(e.exists){var o=e.data(),n=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):null,i=n?n.toLocaleDateString("en-US",{month:"short",year:"numeric"}):"Unknown",a="function"==typeof getLevel?getLevel(o.points||0):{emoji:"🟢",name:"Normie"},r='
    '+a.emoji+" "+a.name+'📅 Member since '+i+""+(o.forumPosts?'💬 '+o.forumPosts+" posts":"")+(o.marketListings?'🛒 '+o.marketListings+" listings":"")+"
    ";t.innerHTML+=r}}).catch(function(){})},function(){var e="btc_forum_draft",t="btc_forum_reply_",o=null;window.saveForumDraft=function(){var t=document.getElementById("forumNewTitle"),o=document.getElementById("forumNewBody"),n=document.getElementById("forumNewCategory");if(t||o){var i={title:t?t.value:"",body:o?o.value:"",category:n?n.value:"general",savedAt:Date.now()};localStorage.setItem(e,JSON.stringify(i))}},window.restoreForumDraft=function(){try{var t=JSON.parse(localStorage.getItem(e));return!t||Date.now()-t.savedAt>864e5?null:t}catch(e){return null}},window.clearForumDraft=function(){localStorage.removeItem(e)},window.saveReplyDraft=function(e){var o=document.getElementById("forumReplyInput");o&&o.value.trim()?localStorage.setItem(t+e,o.value):localStorage.removeItem(t+e)},window.restoreReplyDraft=function(e){return localStorage.getItem(t+e)||""},window.clearReplyDraft=function(e){localStorage.removeItem(t+e)};var n=new MutationObserver(function(){var e=document.getElementById("forumNewTitle"),t=document.getElementById("forumNewBody");if(e&&!e._draftBound){e._draftBound=!0,e.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)});var n=restoreForumDraft();n&&(n.title||n.body)&&(e.value=n.title||"",t&&(t.value=n.body||""),"function"==typeof showToast&&showToast("📝 Draft restored"))}t&&!t._draftBound&&(t._draftBound=!0,t.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)}));var i=document.getElementById("forumReplyInput");if(i&&!i._draftBound&&"undefined"!=typeof forumCurrentPost&&forumCurrentPost){i._draftBound=!0;var a=forumCurrentPost.id,r=restoreReplyDraft(a);r&&(i.value=r),i.addEventListener("input",function(){clearTimeout(o),o=setTimeout(function(){saveReplyDraft(a)},3e3)})}});document.body?n.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",function(){n.observe(document.body,{childList:!0,subtree:!0})})}(),window.isCleanTextV2=function(e){if(!e)return!0;for(var t=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","faggot","retard","nazi","hitler","kkk","porn","hentai","rape","pedo","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","jap","paki","wop","slut","whore","cum","dildo","tits","nude","naked","milf","molest","suicide","terrorist","jihad","genocide","lynch","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","supremacy","acab","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","erection","ejaculat","deepthroat","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes"],o=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g,"").split(/\s+/),n=0;n=4&&-1!==o[n].indexOf(t[i]))return!1}return!0},void 0!==window.isCleanText&&(window._origIsCleanText=window.isCleanText,window.isCleanText=window.isCleanTextV2),function(){var e=document.createElement("style");e.id="ux-patch-styles",e.textContent="\n /* Modal overlay */\n .modal-overlay {\n position: fixed; inset: 0;\n background: rgba(0,0,0,0.7);\n backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);\n z-index: 9999;\n display: flex; align-items: center; justify-content: center;\n padding: 16px;\n }\n /* Modal card */\n .modal-card {\n background: var(--bg-side, #1a1a2e);\n border: 1px solid rgba(255,255,255,0.1);\n border-radius: 24px;\n padding: 24px;\n max-width: 480px; width: 100%;\n max-height: 85vh; overflow-y: auto;\n box-shadow: 0 20px 60px rgba(0,0,0,0.5);\n animation: fadeSlideIn 0.3s;\n -webkit-overflow-scrolling: touch;\n }\n /* Pill button */\n .pill-btn {\n padding: 6px 14px;\n border-radius: 20px;\n border: 1px solid var(--border);\n background: var(--card-bg);\n color: var(--text-muted);\n font-size: 0.75rem;\n cursor: pointer;\n font-family: inherit;\n white-space: nowrap;\n font-weight: 600;\n transition: 0.2s;\n }\n .pill-btn.active {\n border-color: var(--accent);\n background: var(--accent);\n color: #fff;\n }\n /* scroll-top-btn removed — using #backToTop in index.html */\n /* Badge progress bar */\n .badge-progress {\n width: 100%; height: 4px;\n background: rgba(255,255,255,0.1);\n border-radius: 2px;\n margin-top: 4px;\n overflow: hidden;\n }\n .badge-progress-fill {\n height: 100%;\n background: var(--accent);\n border-radius: 2px;\n transition: width 0.5s ease;\n }\n ",document.head.appendChild(e)}(),window.renderQuestDashboard=function(){if(void 0===QUESTION_BANK)return"";var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=parseInt(localStorage.getItem("btc_quests_completed")||"0"),o=Object.keys(QUESTION_BANK).filter(function(t){return-1!==e.indexOf(t)}),n=Object.keys(QUESTION_BANK).length;return'
    ⚔️
    Quest Progress
    '+t+' quests completed
    Channels with questions unlocked'+o.length+"/"+n+'
    Visit more topics to unlock new quests! Each topic you read adds its questions to your quest pool.
    '},window.renderBadgeWithProgress=function(e,t){var o="";if(!t&&e.progress&&"function"==typeof e.progress){var n=e.progress(),i=n.match(/(\d+)\/(\d+)/);if(i){var a=parseInt(i[1]),r=parseInt(i[2]);o='
    '+n+"
    "}}return'
    '+e.emoji+'
    '+e.name+'
    '+e.desc+"
    "+(t?'
    ✅ Earned!
    ':"")+o+"
    "},function(){function e(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;for(var o=[],n=0;n<=t.length;n++)o[n]=[n];for(var i=0;i<=e.length;i++)o[0][i]=i;for(n=1;n<=t.length;n++)for(i=1;i<=e.length;i++)t.charAt(n-1)===e.charAt(i-1)?o[n][i]=o[n-1][i-1]:o[n][i]=Math.min(o[n-1][i-1]+1,o[n][i-1]+1,o[n-1][i]+1);return o[t.length][e.length]}window.fuzzyChannelSearch=function(t,o){if(!t||!o)return[];var n=t.toLowerCase().trim().split(/\s+/),i=[];for(var a in o){var r=o[a],s=(r.name||r.title||a).toLowerCase(),c=(r.desc||"").toLowerCase(),l=s+" "+c+" "+a.replace(/-/g," "),d=0,u=0;n.forEach(function(t){if(-1!==s.indexOf(t))d+=10,u++;else if(-1!==l.indexOf(t))d+=5,u++;else if(t.length>3)for(var o=l.split(/\s+/),n=0;n0&&i.push({id:a,channel:r,score:d})}return i.sort(function(e,t){return t.score-e.score}),i}}(),console.log("✅ UX Patches loaded — 24 tasks from the UX Review Report"),new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e].concat(Array.from(e.querySelectorAll('.msg-text, .msg-body, [class*="msg"]'))):[e]).forEach(function(e){e.innerHTML&&-1!==e.innerHTML.indexOf("this Discord")&&(e.innerHTML=e.innerHTML.replace(/this Discord/g,"this App"))})})})}).observe(document.body,{childList:!0,subtree:!0}),function(){var e=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e,...e.querySelectorAll("img.msg-img")]:[e]).forEach(function(e){"IMG"===e.tagName&&e.classList.contains("msg-img")&&!e.dataset.blurUp&&(e.dataset.blurUp="1",e.style.filter="blur(8px)",e.style.transition="filter 0.4s ease",e.complete&&e.naturalWidth>0?e.style.filter="none":(e.addEventListener("load",function(){e.style.filter="none"},{once:!0}),e.addEventListener("error",function(){e.style.filter="none"},{once:!0})))})})})});document.getElementById("main")&&e.observe(document.getElementById("main"),{childList:!0,subtree:!0})}(),function(){var e="btc_nacho_convo_persist",t=window.nachoRemember;"function"==typeof t&&(window.nachoRemember=function(o,n){t(o,n);try{var i=JSON.parse(localStorage.getItem(e)||"[]");i.push({q:o,a:(n||"").substring(0,200),t:Date.now()}),i.length>20&&(i=i.slice(-20)),localStorage.setItem(e,JSON.stringify(i))}catch(e){}}),setTimeout(function(){if(void 0!==window._nachoConvoHistory&&0===window._nachoConvoHistory.length)try{var t=JSON.parse(localStorage.getItem(e)||"[]");if(t.length>0)for(var o=Math.max(0,t.length-5);ot.clientHeight?Math.round(t.scrollTop/(t.scrollHeight-t.clientHeight)*100):100;try{var n=JSON.parse(localStorage.getItem(e)||"{}");o>(n[window.currentChannelId]||0)&&(n[window.currentChannelId]=o,localStorage.setItem(e,JSON.stringify(n)))}catch(e){}},500))},{passive:!0}),window.getChannelProgress=function(t){try{return JSON.parse(localStorage.getItem(e)||"{}")[t]||0}catch(e){return 0}}}}(),function(){var e=0,t=!1;window.addEventListener("unhandledrejection",function(o){if(!(++e>10)){var n=o.reason&&o.reason.message?o.reason.message:"",i=o.reason&&o.reason.code?o.reason.code:"";console.error("[Error Boundary] Unhandled promise rejection:",n||o.reason),/permission.denied|Missing or insufficient|requires an index|PERMISSION_DENIED/i.test(n+i)||!t&&/network|fetch|Failed to fetch|UNAVAILABLE|unavailable/i.test(n+i)&&(t=!0,"function"==typeof showToast&&showToast("⚠️ Connection issue — some features may not work. Try refreshing."))}}),window.addEventListener("error",function(t){++e>5||console.error("[Error Boundary]",t.message,t.filename,t.lineno)})}(),function(){var e="btc_offline_channels";"function"!=typeof window.go||window._offlineCacheHooked||(window._offlineCacheHooked=!0,setInterval(function(){if(window.currentChannelId&&void 0!==CHANNELS){var t=CHANNELS[window.currentChannelId];if(t&&t.file)try{var o=JSON.parse(localStorage.getItem(e)||"{}");if(o[window.currentChannelId]&&Date.now()-o[window.currentChannelId].ts<864e5)return;"caches"in window&&caches.open("btc-offline-channels").then(function(e){e.add(t.file).catch(function(){})}),o[window.currentChannelId]={ts:Date.now()};var n=Object.keys(o);if(n.length>10){n.sort(function(e,t){return o[e].ts-o[t].ts});for(var i=0;iwindow.innerWidth-8&&(n=window.innerWidth-240-8),t.style.left=n+"px",t.style.width="240px",window.innerWidth>900?(t.style.top=o.top-8+"px",t.style.transform="translateY(-100%)"):(t.style.top=o.bottom+8+"px",t.style.transform="none")}}document.addEventListener("mouseover",function(t){var o=t.target.closest(".badge-item");o&&e(o)}),document.addEventListener("click",function(t){var o=t.target.closest(".badge-item");o&&e(o)})}(),function(){"use strict";function e(){var e=function(){if(void 0===window.NACHO_TRAILS)return null;var e=[];try{e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]")}catch(e){}var t={};try{t=JSON.parse(localStorage.getItem("btc_trail_progress")||"{}")}catch(e){}for(var o=0;o=0&&t!==i.correct&&r[t]&&(r[t].style.borderColor="#ef4444",r[t].style.background="rgba(239,68,68,0.15)")}a&&a.insertAdjacentHTML("afterend",'
    '+(t===i.correct?"✅ Correct! Waiting...":t<0?"⏰ Time's up!":"❌ Wrong! Waiting...")+"
    ")}"undefined"!=typeof firebase&&firebase.functions&&n.matchId&&firebase.functions().httpsCallable("pvpSubmitAnswer")({matchId:n.matchId,questionIndex:e,answerIndex:t}).then(function(e){e.data&&e.data.alreadyAnswered&&console.log("[PVP] Already answered, idempotent")}).catch(function(e){console.error("[PVP] Server answer submission failed:",e),"function"==typeof showToast&&showToast("⚠️ Answer submit failed — check connection")})}}))}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(e,3e3)}):setTimeout(e,3e3);var t=null,o=0;setTimeout(function n(){window._pvpEnterPatched||("function"==typeof window.enterPVPMode?(window._pvpEnterPatched=!0,t=window.enterPVPMode,window.enterPVPMode=function(){t.apply(this,arguments),setTimeout(e,500);var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null;o&&"function"==typeof window.nachoGlobalAnnounce&&window.nachoGlobalAnnounce("⚔️ @"+o+" just entered the PVP arena! Think you can beat them? ➡️ [Enter PVP Lobby](#pvp)")}):o<20&&(o++,setTimeout(n,2e3)))},3e3)}(),function(){function e(){try{var e=JSON.parse(localStorage.getItem("btc_channel_progress")||"{}");document.querySelectorAll(".ch-btn").forEach(function(t){var o=(t.getAttribute("onclick")||"").match(/go\('([^']+)'\)/);if(o){var n=o[1],i=e[n]||0,a=t.querySelector(".ch-progress");if(a&&a.remove(),i>0){var r=document.createElement("div");if(r.className="ch-progress",r.style.cssText="position:absolute;bottom:0;left:0;height:2px;background:"+(i>=100?"#22c55e":"var(--accent,#f7931a)")+";width:"+Math.min(i,100)+"%;border-radius:0 1px 0 0;transition:width 0.3s;opacity:0.7;",t.style.position="relative",t.style.overflow="hidden",t.appendChild(r),i>=100&&!t.querySelector(".ch-done")){var s=document.createElement("span");s.className="ch-done",s.style.cssText="position:absolute;right:6px;top:50%;transform:translateY(-50%);font-size:0.6rem;opacity:0.5;",s.textContent="✓",t.appendChild(s)}}}})}catch(e){}}setTimeout(e,2e3);var t=window.goHome;t&&(window.goHome=function(){var o=t.apply(this,arguments);return setTimeout(e,500),o});var o=window.go;o&&(window.go=function(){var t=o.apply(this,arguments);return setTimeout(e,1e3),t}),window.updateSidebarProgress=e}(); \ No newline at end of file +var CHANNELS={decentralized:{cat:"Properties Layer 1",title:"👪decentralized-censorship-resistant-ungovernable-incorruptible-trustless-unconfiscatable-updatable",desc:"Why no single person, company, or government controls Bitcoin — and why that's the most important feature.",file:"data/D_decentralized.json"},dominant:{cat:"Properties Layer 1",title:"🏆dominant-recognizable-brand-legitimate-limitless-infinite-exponential-transformative-revolutionary",desc:"Bitcoin's brand recognition, network effects, and why it has maintained the #1 position since 2009.",file:"data/D_dominant.json"},money:{cat:"Properties Layer 1",title:"💰money-deflationary-salable-durable-anti-fragile-divisible-portable-transmittable-verifiable-fair",desc:"What money actually is, how it works, and why Bitcoin satisfies every property of sound money better than anything before it.",file:"data/D_money.json"},organic:{cat:"Properties Layer 1",title:"🌳organic-empowering-elegant-freedom-centric-irrefutable-unseizable-irreversible-unbreakable",desc:"How Bitcoin grew from an idea worth nothing to a trillion-dollar network — without marketing, without a company, without a leader.",file:"data/D_organic.json"},peaceful:{cat:"Properties Layer 1",title:"☮peaceful-neutral-voluntary-open-universal-permissionless-borderless-global-inevitable-unstoppable",desc:"Bitcoin is voluntary, permissionless, borderless, and unstoppable. No one forces you to use it — and no one can stop you.",file:"data/D_peaceful.json"},programmable:{cat:"Properties Layer 1",title:"🤖programable-interoperable-deflationary-pseudonymous-opt-in-resilient-adiabatic-egalitarian",desc:"Bitcoin as programmable money — interoperable, pseudonymous, resilient, and thermodynamically sound.",file:"data/D_programmable.json"},scarce:{cat:"Properties Layer 1",title:"🍀scarce-unforgeable-hedge-scalable-p2p-instant-open-source-auditable-inaliable",desc:"Only 21 million will ever exist. Explore what makes Bitcoin the scarcest asset humanity has ever created.",file:"data/D_scarce.json"},secure:{cat:"Properties Layer 1",title:"™secure-fungible-immutable-incorruptible-immalleable-infallible-reliable-predictable-irreplicable",desc:"How Bitcoin's network security makes it virtually impossible to hack — protected by more computing power than anything on Earth.",file:"data/D_secure.json"},supranational:{cat:"Properties Layer 1",title:"🕊supranational-lindy-inviolate-dilution-proof-frictionless-freely-accessible-settlement-finality",desc:"Bitcoin transcends nations and governments. Explore the Lindy Effect, settlement finality, and dilution-proof money.",file:"data/D_supranational.json"},"use-cases":{cat:"Properties Layer 1",title:"✔use-cases",desc:"Real-world uses for Bitcoin: savings, payments, remittances, store of value, and more.",file:"data/D_use-cases.json"},whitepaper:{cat:"Properties Layer 1",title:"📄whitepaper",desc:"The 9-page document that started it all. Published October 31, 2008 by Satoshi Nakamoto — the foundation of Bitcoin.",file:"data/D_whitepaper.json"},bitvm:{cat:"Experienced Topics",title:"🖥bitvm",desc:"BitVM: computation on Bitcoin without changing the protocol. A new frontier for Bitcoin programmability.",file:"data/E_bitvm.json"},"blockchain-timechain":{cat:"Experienced Topics",title:"⛓blockchain-timechain-transactions-addresses",desc:"How the Bitcoin blockchain (timechain) works — blocks, transactions, timestamps, and the immutable ledger.",file:"data/E_blockchain-timechain.json"},"chaumian-mints":{cat:"Experienced Topics",title:"💸layer-2-chaumian-mints-ecash",desc:"Chaumian ecash, Cashu, and blinded signatures — the cutting edge of Bitcoin privacy technology.",file:"data/E_chaumian-mints.json"},consensus:{cat:"Additional Info",title:"🤝Consensus",desc:"How Bitcoin achieves consensus without a central authority — Nakamoto Consensus and beyond.",file:"data/H_consensus.json"},"core-source-code":{cat:"Experienced Topics",title:"💾core-source-code-forks-testnet-future-potential-upgrades",desc:"Bitcoin Core's source code, forks, testnet, and the open-source development process.",file:"data/E_core-source-code.json"},cryptography:{cat:"Experienced Topics",title:"🔒cryptography-cypherpunks",desc:"The cryptographic foundations of Bitcoin — SHA-256, elliptic curves, digital signatures, and the cypherpunk legacy.",file:"data/E_cryptography.json"},"ctv-covenants":{cat:"Experienced Topics",title:"📜ctv-bip119-covenants",desc:"BIP-119, CTV, and Bitcoin covenants — proposed upgrades and the debates around them.",file:"data/E_ctv-covenants.json"},developers:{cat:"Experienced Topics",title:"🖥developers",desc:"Building on Bitcoin — resources, guides, and paths for developers who want to contribute.",file:"data/E_developers.json"},"difficulty-adjustment":{cat:"Experienced Topics",title:"😤difficulty-adjustment",desc:"The most elegant part of Bitcoin's design — how the network self-adjusts every 2,016 blocks.",file:"data/E_difficulty-adjustment.json"},energy:{cat:"Experienced Topics",title:"💡energy",desc:"The truth about Bitcoin's energy use: 0.1% of global energy, renewable mining, methane capture, and grid stabilization.",file:"data/E_energy.json"},"evidence-against-alts":{cat:"Experienced Topics",title:"⚠evidence-against-ethereum-other-alt-coins-crypto-defi-nfts-web3-monero-bsv-bch-cbdcs-other-projects",desc:"Why every altcoin fails against Bitcoin — premines, centralization, broken promises, and the evidence.",file:"data/E_evidence-against-alts.json"},"extension-blocks":{cat:"Experienced Topics",title:"🚧extension-blocks-and-other-proposed-scaling-solutions",desc:"Extension blocks and other proposed scaling solutions for Bitcoin.",file:"data/E_extension-blocks.json"},"fedi-ark":{cat:"Experienced Topics",title:"🛡layer-2-fedi-ark",desc:"Fedimints, Ark, and Bitcoin's privacy/scaling layers — community custody with enhanced privacy.",file:"data/E_fedi-ark.json"},"investment-strategy":{cat:"Experienced Topics",title:"🤑investment-strategy-taxes-retirement-inheritance-loans-donate-gift-consulting-remittance",desc:"DCA, HODL, lump sum strategies, taxes, retirement planning, and thinking long-term with Bitcoin.",file:"data/E_investment-strategy.json"},"layer-2-lightning":{cat:"Experienced Topics",title:"⚡layer-2-lightning",desc:"The Lightning Network: instant, nearly-free Bitcoin payments. How Bitcoin scales without sacrificing decentralization.",file:"data/E_layer-2-lightning.json"},"layer-3-sidechains":{cat:"Experienced Topics",title:"📱layer-3-sidechain-applications",desc:"Sidechains, Liquid Network, and layer-3 applications built on top of Bitcoin.",file:"data/E_layer-3-sidechains.json"},maximalism:{cat:"Experienced Topics",title:"💯maximalism",desc:"Why people who study Bitcoin the most become maximalists. The case for Bitcoin-only.",file:"data/E_maximalism.json"},mining:{cat:"Experienced Topics",title:"🌋mining",desc:"How Bitcoin mining actually works — nonces, SHA-256 hashing, difficulty adjustment, and the brute-force lottery.",file:"data/E_mining.json"},nodes:{cat:"Experienced Topics",title:"💻nodes",desc:"Run your own Bitcoin node. Don't trust, verify. How 14,000+ nodes keep the network decentralized.",file:"data/E_nodes.json"},"op-codes":{cat:"Experienced Topics",title:"👨‍💻op-codes-simplicity",desc:"OP_CAT, Simplicity, and Bitcoin's scripting language — the building blocks of smart functionality.",file:"data/E_op-codes.json"},"pow-vs-pos":{cat:"Experienced Topics",title:"💪proof-of-work-vs-proof-of-stake",desc:"Why Proof of Work is fundamentally superior to Proof of Stake — energy, security, fairness, and decentralization.",file:"data/E_pow-vs-pos.json"},"privacy-nonkyc":{cat:"Experienced Topics",title:"🤫privacy-nonkyc-stacking-self-sovereignty",desc:"Financial privacy as a human right. KYC, non-KYC stacking, and protecting your sovereignty.",file:"data/E_privacy-nonkyc.json"},"problems-of-money":{cat:"Experienced Topics",title:"📉the-problems-of-todays-money-and-freedom",desc:"The broken fiat system: inflation, money printing, the Cantillon Effect, and why today's money is failing everyone.",file:"data/E_problems-of-money.json"},regulation:{cat:"Experienced Topics",title:"🏛regulation-policy-legal",desc:"Bitcoin and government: bans, adoption, legal tender, ETFs, and why regulation can't stop decentralization.",file:"data/E_regulation.json"},"self-custody":{cat:"Experienced Topics",title:"🔑personal-storage-self-custody-security",desc:"Not your keys, not your coins. Learn how to truly own your Bitcoin with wallets, seed phrases, and security.",file:"data/E_self-custody.json"},"smart-contracts":{cat:"Experienced Topics",title:"📱smart-contracts",desc:"Smart contracts on Bitcoin — what's possible, what's coming, and why Bitcoin's approach is different.",file:"data/E_smart-contracts.json"},stablecoins:{cat:"Additional Info",title:"🪙Stablecoins",desc:"The role of stablecoins in the Bitcoin economy — and why they're not a threat to Bitcoin.",file:"data/H_stablecoins.json"},"0_mining__hashing":{cat:"Additional Info",title:"0⃣Mining (Hashing)",desc:"Deep dive into Bitcoin mining and hashing — how SHA-256 works at the bit level.",file:"data/H_0_mining__hashing.json"},"100_sats":{cat:"Additional Info",title:"💯100 sats",desc:"What can you do with just 100 satoshis? More than you think.",file:"data/H_100_sats.json"},"1_first_principles":{cat:"Additional Info",title:"1⃣First Principles",desc:"First principles thinking applied to Bitcoin — reasoning from fundamentals, not analogies.",file:"data/H_1_first_principles.json"},"2__solved_technical_problems":{cat:"Additional Info",title:"2⃣ Solved Technical Problems",desc:"The technical problems Bitcoin solved — digital scarcity, double-spending, and Byzantine fault tolerance.",file:"data/H_2__solved_technical_problems.json"},analogies:{cat:"Additional Info",title:"🔋Analogies",desc:"The best analogies for explaining Bitcoin to anyone — from trees to brains to hearts.",file:"data/H_analogies.json"},austrian_school_of_economics:{cat:"Additional Info",title:"🇦🇹Austrian School of Economics",desc:"Austrian Economics and Bitcoin: Mises, Hayek, sound money theory, and the intellectual foundation.",file:"data/H_austrian_school_of_economics.json"},bip119:{cat:"Additional Info",title:"🚧BIP119",desc:"BIP-119 (CheckTemplateVerify) — what it is, why it's controversial, and the community debate.",file:"data/H_bip119.json"},bitcoin_exam:{cat:"Additional Info",title:"🎓Bitcoin Exam",desc:"Test questions for a Bitcoin exam — study material and self-assessment.",file:"data/H_bitcoin_exam.json"},bitcoin_vs_real_estate:{cat:"Additional Info",title:"Bitcoin vs Real Estate",desc:"Bitcoin vs. real estate as an investment — comparing the two hardest assets.",file:"data/H_bitcoin_vs_real_estate.json"},"block_time-block-size":{cat:"Additional Info",title:"⏰Block Time-Block-Size",desc:"Why Bitcoin uses 10-minute blocks and how block size affects the network.",file:"data/H_block_time-block-size.json"},burn_bitcoin:{cat:"Additional Info",title:"Burn bitcoin",desc:"How Bitcoin can be burned (made permanently unspendable) and why people do it.",file:"data/H_burn_bitcoin.json"},byzantine_generals__problem:{cat:"Additional Info",title:"⚔Byzantine Generals’ Problem",desc:"The Byzantine Generals' Problem — the computer science challenge Satoshi solved.",file:"data/H_byzantine_generals__problem.json"},"chaumian_e-cash_and_blind_signatures":{cat:"Additional Info",title:"💲Chaumian E-cash and Blind Signatures",desc:"David Chaum's ecash, blind signatures, and the cryptographic foundations of digital privacy.",file:"data/H_chaumian_e-cash_and_blind_signatures.json"},coin_mixing_coinjoin_coin_control_utxo:{cat:"Additional Info",title:"🌀Coin Mixing/Coinjoin/Coin Control/UTXO Management",desc:"CoinJoin, coin mixing, UTXO management — advanced Bitcoin privacy techniques.",file:"data/H_coin_mixing_coinjoin_coin_control_utxo.json"},cyles:{cat:"Additional Info",title:"🚲Cyles",desc:"Bitcoin's 4-year cycles, Gartner Hype Cycles, and whether the pattern continues.",file:"data/H_cyles.json"},derivation_path:{cat:"Additional Info",title:"↕Derivation Path",desc:"HD wallet derivation paths — how your seed phrase generates all your addresses.",file:"data/H_derivation_path.json"},discrete_log_contracts__dlcs:{cat:"Additional Info",title:"📝Discrete Log Contracts (DLCs)?",desc:"DLCs (Discrete Log Contracts) — smart contracts on Bitcoin using oracle signatures.",file:"data/H_discrete_log_contracts__dlcs.json"},"dollar-bitcoin_milkshake_theory":{cat:"Additional Info",title:"🥤Dollar-Bitcoin Milkshake Theory",desc:"The Dollar-Bitcoin Milkshake Theory — how global dollar demand and Bitcoin intersect.",file:"data/H_dollar-bitcoin_milkshake_theory.json"},dust:{cat:"Additional Info",title:"⏳Dust",desc:"Dust UTXOs: what they are, why they're a problem, and how to manage them.",file:"data/H_dust.json"},elevator_pitches:{cat:"Additional Info",title:"↕Elevator Pitches",desc:"Quick 20-30 second explanations of why Bitcoin matters — for every audience.",file:"data/H_elevator_pitches.json"},environment___energy:{cat:"Additional Info",title:"🌳Environment & Energy",desc:"Bitcoin and the environment: energy usage facts, renewable mining, and debunking the FUD.",file:"data/H_environment___energy.json"},faith___religion:{cat:"Additional Info",title:"🙏Faith & Religion",desc:"Bitcoin and faith — how sound money relates to religious and spiritual values.",file:"data/H_faith___religion.json"},fedimints:{cat:"Additional Info",title:"💚Fedimints",desc:"Fedimints: community custody with enhanced privacy using federated Chaumian mints.",file:"data/H_fedimints.json"},feedback_loops:{cat:"Additional Info",title:"➰Feedback Loops",desc:"Bitcoin's feedback loops — the self-reinforcing cycles that drive adoption and security.",file:"data/H_feedback_loops.json"},free_and_open_source_software__foss:{cat:"Additional Info",title:"💿Free and Open Source Software (FOSS)",desc:"Free and open source software (FOSS) projects connected to Bitcoin.",file:"data/H_free_and_open_source_software__foss.json"},game_theory:{cat:"Additional Info",title:"🏈Game Theory",desc:"Game theory and Bitcoin: Nash equilibrium, prisoner's dilemma, and strategic incentives.",file:"data/H_game_theory.json"},geopolitics___macroeconomics:{cat:"Additional Info",title:"💰Geopolitics & Macroeconomics",desc:"Bitcoin's role in geopolitics: nation-state adoption, reserve currencies, and macro trends.",file:"data/H_geopolitics___macroeconomics.json"},governance:{cat:"Additional Info",title:"🏛Governance",desc:"How Bitcoin is governed — consensus mechanisms, BIPs, and decentralized decision-making.",file:"data/H_governance.json"},ham_radio:{cat:"Additional Info",title:"Ham Radio",desc:"Using Bitcoin without internet — ham radio, mesh networks, and offline transactions.",file:"data/H_ham_radio.json"},human_rights__social_justice_and_freedo:{cat:"Additional Info",title:"🗽Human Rights, Social Justice and Freedom",desc:"Bitcoin as a tool for human rights, social justice, and financial freedom worldwide.",file:"data/H_human_rights__social_justice_and_freedo.json"},improved_incentive_structure:{cat:"Additional Info",title:"✅Improved Incentive Structure",desc:"How Bitcoin's incentive structure improves civilization — aligning individual and collective interests.",file:"data/H_improved_incentive_structure.json"},laws_of_thermodynamics:{cat:"Additional Info",title:"🔥Laws of Thermodynamics",desc:"How Bitcoin follows the laws of thermodynamics — energy, entropy, and proof of work.",file:"data/H_laws_of_thermodynamics.json"},lightning_node:{cat:"Additional Info",title:"⚡ Lightning Node",desc:"Running a Lightning Network node — setup guides, routing, and earning sats.",file:"data/H_lightning_node.json"},lindy_effect:{cat:"Additional Info",title:"👴Lindy Effect",desc:"The Lindy Effect: the longer Bitcoin survives, the longer it will survive.",file:"data/H_lindy_effect.json"},market_cap:{cat:"Additional Info",title:"🧢Market Cap",desc:"Bitcoin's market cap potential — can it reach millions per coin? The math says yes.",file:"data/H_market_cap.json"},math:{cat:"Additional Info",title:"➕Math",desc:"The mathematics of Bitcoin — from SHA-256 to elliptic curves to probability.",file:"data/H_math.json"},mathematics:{cat:"Additional Info",title:"➕Mathematics",desc:"Advanced mathematical concepts underlying Bitcoin's protocol and security.",file:"data/H_mathematics.json"},mev:{cat:"Additional Info",title:"⛏MEV",desc:"MEV (Miner Extractable Value) in Bitcoin — what it is and its implications.",file:"data/H_mev.json"},network_effects:{cat:"Additional Info",title:"🌐Network Effects",desc:"Bitcoin's network effects — why the most adopted network wins and keeps winning.",file:"data/H_network_effects.json"},open_source:{cat:"Additional Info",title:"⭕Open Source",desc:"What free and open source really means — and why it matters for Bitcoin.",file:"data/H_open_source.json"},oracle:{cat:"Additional Info",title:"🔮Oracle",desc:"Oracles in Bitcoin — how external data connects to the blockchain.",file:"data/H_oracle.json"},"orange-pilling":{cat:"Additional Info",title:"🟠Orange-Pilling",desc:"The art of orange-pilling — strategies for explaining Bitcoin to different audiences.",file:"data/H_orange-pilling.json"},ordinals:{cat:"Additional Info",title:"Ordinals",desc:"Bitcoin Ordinals and inscriptions — NFTs on the world's most secure blockchain.",file:"data/H_ordinals.json"},ordinals__nfts_on_bitcoin__and_block_spa:{cat:"Additional Info",title:"Ordinals, NFTs on Bitcoin, and Block Space",desc:"The Ordinals debate: NFTs on Bitcoin, block space economics, and community perspectives.",file:"data/H_ordinals__nfts_on_bitcoin__and_block_spa.json"},"peace_and_anti-war":{cat:"Additional Info",title:"☮Peace and Anti-War",desc:"Can a Bitcoin Standard end wars? The case for Bitcoin as a force for peace.",file:"data/H_peace_and_anti-war.json"},philosophy:{cat:"Additional Info",title:"🍎Philosophy",desc:"The philosophy of Bitcoin — from first principles to existential implications.",file:"data/H_philosophy.json"},politics:{cat:"Additional Info",title:"🏛Politics",desc:"Bitcoin and politics — how Bitcoin intersects with government policy and elections.",file:"data/H_politics.json"},predictions:{cat:"Additional Info",title:"🔮Predictions",desc:"Bitcoin predictions timestamped by the community — bold calls and their outcomes.",file:"data/H_predictions.json"},public_key_vs_private_key:{cat:"Additional Info",title:"🗝Public Key vs Private Key",desc:"Public keys vs. private keys — the cryptographic foundation of Bitcoin ownership.",file:"data/H_public_key_vs_private_key.json"},rbf:{cat:"Additional Info",title:"↔RBF",desc:"Replace-By-Fee (RBF) — how to speed up stuck Bitcoin transactions.",file:"data/H_rbf.json"},"referral-links":{cat:"Referral Links",title:"🔗free-btc-referral-links",desc:"Curated Bitcoin referral links — earn free sats with trusted platforms like River, Fold, and Strike.",file:"data/H_referral-links.json"},risks__threats__attack_vectors__weaknes:{cat:"Additional Info",title:"⚔Risks, Threats, Attack Vectors, Weaknesses, Issues",desc:"Bitcoin's risks, threats, and attack vectors — what could go wrong and why it probably won't.",file:"data/H_risks__threats__attack_vectors__weaknes.json"},rollups:{cat:"Additional Info",title:"🥐Rollups",desc:"Rollups on Bitcoin — scaling and privacy solutions using off-chain computation.",file:"data/H_rollups.json"},sats__or__bits:{cat:"Additional Info",title:'"Sats" or "Bits"?',desc:"The sats vs. bits debate — which denomination should Bitcoin use?",file:"data/H_sats__or__bits.json"},scalability:{cat:"Additional Info",title:"🌐Scalability",desc:"Can Bitcoin scale to serve the world? Layers, Lightning, and the path forward.",file:"data/H_scalability.json"},sidechains:{cat:"Additional Info",title:"♻Sidechains",desc:"Bitcoin sidechains like Liquid — benefits, tradeoffs, and use cases.",file:"data/H_sidechains.json"},simplified_payment_verification__spv:{cat:"Additional Info",title:"✔Simplified Payment Verification (SPV)",desc:"SPV (Simplified Payment Verification) — lightweight Bitcoin verification without a full node.",file:"data/H_simplified_payment_verification__spv.json"},soft_vs_hard_forks:{cat:"Additional Info",title:"🍴Soft vs Hard Forks",desc:"Soft forks vs. hard forks — how Bitcoin upgrades while maintaining consensus.",file:"data/H_soft_vs_hard_forks.json"},softwar:{cat:"Additional Info",title:"Softwar",desc:"Jason Lowery's Softwar thesis — Bitcoin as a non-lethal alternative to physical warfare.",file:"data/H_softwar.json"},stratum_v2:{cat:"Additional Info",title:"🟩Stratum V2",desc:"Stratum V2 — the next-generation mining protocol for better decentralization and efficiency.",file:"data/H_stratum_v2.json"},submarine_swap:{cat:"Additional Info",title:"⛵Submarine Swap",desc:"Submarine swaps — trustlessly moving Bitcoin between on-chain and Lightning.",file:"data/H_submarine_swap.json"},swaps:{cat:"Additional Info",title:"↔Swaps",desc:"How to swap between on-chain Bitcoin and Lightning — tools, techniques, and protocols.",file:"data/H_swaps.json"},ta_tips:{cat:"Additional Info",title:"📈TA Tips",desc:"Technical analysis tips for Bitcoin — chart patterns, indicators, and trading education.",file:"data/H_ta_tips.json"},tail_emission:{cat:"Additional Info",title:"🐈Tail Emission",desc:"The tail emission debate — should Bitcoin ever have perpetual block rewards?",file:"data/H_tail_emission.json"},taproot:{cat:"Additional Info",title:"🧰Taproot",desc:"Taproot: Bitcoin's latest major upgrade — Schnorr signatures, script improvements, and privacy.",file:"data/H_taproot.json"},taro:{cat:"Additional Info",title:"🥕Taro",desc:"Taro (now Taproot Assets) — issuing assets on the Bitcoin and Lightning networks.",file:"data/H_taro.json"},the_future:{cat:"Additional Info",title:"🔮The Future",desc:"How Bitcoin could change the future — hyperbitcoinization, global adoption, and beyond.",file:"data/H_the_future.json"},time:{cat:"Additional Info",title:"⏰Time",desc:"How Bitcoin keeps time — block time, timestamps, and the decentralized clock.",file:"data/H_time.json"},time_preference:{cat:"Additional Info",title:"🕑Time Preference",desc:"Time preference: how sound money encourages long-term thinking and civilization building.",file:"data/H_time_preference.json"},toxicity:{cat:"Additional Info",title:"☣ Toxicity",desc:"Is Bitcoin community toxicity real? Or is it integrity? The debate and its meaning.",file:"data/H_toxicity.json"},transaction_fees:{cat:"Additional Info",title:"💲Transaction Fees",desc:"Bitcoin transaction fees — how they work, fee markets, and long-term sustainability.",file:"data/H_transaction_fees.json"},unpopular_opinions:{cat:"Additional Info",title:"💀Unpopular Opinions",desc:"Unpopular opinions in the Bitcoin space — controversial takes and honest debates.",file:"data/H_unpopular_opinions.json"},utxos:{cat:"Additional Info",title:"🕳UTXOs",desc:"UTXOs (Unspent Transaction Outputs) — the fundamental building block of Bitcoin transactions.",file:"data/H_utxos.json"},vbyte:{cat:"Additional Info",title:"🏋vByte",desc:"Virtual bytes (vBytes) — how Bitcoin measures transaction weight for fee calculation.",file:"data/H_vbyte.json"},"apps-tools":{cat:"Resources",title:"🍎apps-tools-services-models",desc:"Bitcoin apps, tools, services, and platforms — everything you need to use Bitcoin daily.",file:"data/R_apps-tools.json"},"art-inspiration":{cat:"Resources",title:"🤩art-inspiration-motivation",desc:"Bitcoin art, inspiration, and motivational content from the community.",file:"data/R_art-inspiration.json"},"articles-threads":{cat:"Resources",title:"📃articles-threads",desc:"The best Bitcoin articles and Twitter threads — curated deep dives into every aspect of Bitcoin.",file:"data/R_articles-threads.json"},books:{cat:"Resources",title:"📚books",desc:"The essential Bitcoin reading list: The Bitcoin Standard, 21 Lessons, Mastering Bitcoin, and more.",file:"data/R_books.json"},charts:{cat:"Resources",title:"📊charts",desc:"Bitcoin price charts, on-chain analytics, stock-to-flow, and data visualizations.",file:"data/R_charts.json"},curriculum:{cat:"Resources",title:"🎓curriculum-presentations",desc:"Bitcoin education curriculum and presentations for teachers and students.",file:"data/R_curriculum.json"},"faq-glossary":{cat:"Resources",title:"❓faq-glossary-search-ai-calendar",desc:"Bitcoin FAQ, glossary of terms, and quick answers to common questions.",file:"data/R_faq-glossary.json"},"fun-facts":{cat:"Resources",title:"🎉fun-facts",desc:"Mind-blowing Bitcoin trivia: Pizza Day, Satoshi's birthday code, lost coins, and 200+ amazing facts.",file:"data/R_fun-facts.json"},games:{cat:"Resources",title:"🎮games",desc:"Bitcoin-themed games and gamified learning experiences.",file:"data/R_games.json"},"giga-chad":{cat:"Resources",title:"👑giga-chad",desc:"Michael Saylor, MicroStrategy, and the corporate Bitcoin movement.",file:"data/R_giga-chad.json"},graphics:{cat:"Resources",title:"🎨graphics",desc:"Bitcoin infographics, charts, diagrams, and visual explanations.",file:"data/R_graphics.json"},hardware:{cat:"Resources",title:"💻hardware",desc:"Bitcoin hardware: mining rigs, hardware wallets, nodes, and open-source projects like Bitaxe.",file:"data/R_hardware.json"},health:{cat:"Resources",title:"🥩health",desc:"Bitcoin and health: low time preference living, breaking free from the system.",file:"data/R_health.json"},history:{cat:"Resources",title:"📆history",desc:"The complete history of Bitcoin — from the cypherpunks to today.",file:"data/R_history.json"},"informational-sites":{cat:"Resources",title:"📃informational-sites-courses-workshops-newsletters-projects-communities-meetups-conferences",desc:"Bitcoin dashboards, tools, courses, newsletters, communities, and educational websites.",file:"data/R_informational-sites.json"},international:{cat:"Resources",title:"🌍international",desc:"Bitcoin resources in multiple languages and global adoption stories.",file:"data/R_international.json"},"jobs-earn":{cat:"Resources",title:"👷job-postings-employer-info-entrepreneurship-earn-bitcoin-stack-sats",desc:"Bitcoin job boards, entrepreneurship resources, and ways to earn sats.",file:"data/R_jobs-earn.json"},"memes-funny":{cat:"Resources",title:"😂memes-funny",desc:"The best Bitcoin memes, jokes, and humor from the community. Laugh while you learn.",file:"data/R_memes-funny.json"},"misconceptions-fud":{cat:"Resources",title:"🤡common-misconceptions-fud-debunked",desc:"Every Bitcoin myth debunked: too volatile, wastes energy, used by criminals, no intrinsic value — all wrong.",file:"data/R_misconceptions-fud.json"},"movies-tv":{cat:"Resources",title:"🎬movies-tv-documentaries",desc:"Bitcoin documentaries, films, and TV appearances. From The Big Short to Bitcoin-specific docs.",file:"data/R_movies-tv.json"},music:{cat:"Resources",title:"🎵music",desc:"Bitcoin-inspired music, songs, and audio content from the community.",file:"data/R_music.json"},"news-adoption":{cat:"Resources",title:"📰news-adoption",desc:"Latest Bitcoin news, adoption milestones, and real-world usage stories.",file:"data/R_news-adoption.json"},nostr:{cat:"Resources",title:"💜nostr",desc:"Nostr: the decentralized social protocol Bitcoiners are building on. Social media you can't be censored from.",file:"data/R_nostr.json"},"one-stop-shop":{cat:"Resources",title:"🛑one-stop-shop",desc:"The best resources to understand Bitcoin's value as fast as possible. Start here if you're new.",file:"data/R_one-stop-shop.json"},podcasts:{cat:"Resources",title:"🔊podcasts",desc:"Top Bitcoin podcasts: Bitcoin Audible, What Bitcoin Did, Stephan Livera, and more.",file:"data/R_podcasts.json"},"poems-stories":{cat:"Resources",title:"📒poems-stories-jokes",desc:"Bitcoin poetry, short stories, jokes, and creative writing from the community.",file:"data/R_poems-stories.json"},"projects-diy":{cat:"Resources",title:"🔧projects-diy",desc:"DIY Bitcoin projects: build your own node, Lightning ATM, and more.",file:"data/R_projects-diy.json"},"research-theses":{cat:"Resources",title:"✍research-theses",desc:"Academic research papers and theses on Bitcoin, monetary policy, and cryptographic systems.",file:"data/R_research-theses.json"},"satoshi-nakamoto":{cat:"Resources",title:"🦸satoshi-nakamoto",desc:"The mystery of Bitcoin's creator: who was Satoshi Nakamoto? The evidence, theories, and legacy.",file:"data/R_satoshi-nakamoto.json"},"social-media":{cat:"Resources",title:"👍social-media-proponents",desc:"Bitcoin Twitter/X accounts, influencers, and social media communities to follow.",file:"data/R_social-media.json"},"swag-merch":{cat:"Resources",title:"👕swag-merch-businesses-spend",desc:"Bitcoin merchandise, clothing, and businesses where you can spend your sats.",file:"data/R_swag-merch.json"},videos:{cat:"Resources",title:"📺videos",desc:"Must-watch Bitcoin lectures, talks, and presentations from Andreas Antonopoulos, Michael Saylor, and others.",file:"data/R_videos.json"},web5:{cat:"Resources",title:"5⃣web5",desc:"Web5 and decentralized web technologies built on Bitcoin.",file:"data/R_web5.json"}},_SAFE_COVER_PLACEHOLDER="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjMWUxYTJlIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZpbGw9IiNmNzkzMWEiIGZvbnQtc2l6ZT0iMjAiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj7wnY61PC90ZXh0Pjwvc3ZnPg==";function _safeCover(e){if(!e||"string"!=typeof e||""===e.trim())return _SAFE_COVER_PLACEHOLDER;var t=e.trim(),o=t.toLowerCase();return/^(javascript|data:text\/html|vbscript|blob):/i.test(o)?(console.warn("[XSS BLOCKED] Malicious image URL scheme rejected:",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER):/^(https:\/\/|data:image\/)/i.test(t)?t.replace(/["'<>\\]/g,""):(console.warn("[XSS BLOCKED] Invalid URL scheme (must be https:// or data:image/):",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER)}function safeJSON(e,t){try{var o=localStorage.getItem(e);return null===o?t:JSON.parse(o)}catch(o){console.warn('safeJSON: corrupted data for key "'+e+'", resetting.',o);try{localStorage.removeItem(e)}catch(e){}return t}}function escapeHtml(e){if(!e)return"";var t=document.createElement("div");return t.appendChild(document.createTextNode(e)),t.innerHTML}function sanitizeUrl(e){return e?(e=e.trim(),/^(javascript|data|vbscript|blob):/i.test(e)?"":e):""}function timeAgo(e){if(!e)return"";var t;t=e.toDate?e.toDate():e instanceof Date?e:new Date(e);var o=Math.floor((Date.now()-t.getTime())/1e3);return o<60?"just now":o<3600?Math.floor(o/60)+"m ago":o<86400?Math.floor(o/3600)+"h ago":o<604800?Math.floor(o/86400)+"d ago":t.toLocaleDateString()}function isPremium(){return void 0!==currentUser&¤tUser&¤tUser.premium&&!0===currentUser.premium.active}function getSatCap(){return isPremium()?21e3:1e4}!function(){var e=[],t=[];window.registerInterval=function(t,o,n){var i=setInterval(t,o);return e.push({id:i,fn:t,ms:o,name:n||"unnamed"}),i},document.addEventListener("visibilitychange",function(){document.hidden?(e.forEach(function(e){clearInterval(e.id)}),t=e.slice(),e=[]):(t.forEach(function(t){t.fn(),t.id=setInterval(t.fn,t.ms),e.push(t)}),t=[])})}(),window._factionNameStyle=function(e){return"cyber_hornets"===e?"color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;font-weight:700;":"honey_badgers"===e?"color:#1a1a1a;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff;font-weight:700;":""};var PREMIUM_CONFIG={FREE_SAT_CAP:1e4,PREMIUM_SAT_CAP:21e3,FREE_SPINS:1,PREMIUM_SPINS:3,MONTHLY_PRICE_USD:4.99,YEARLY_PRICE_USD:42,LIFETIME_SATS:21e4,TIER_NAME:"Bitcoin Maxi"};const FIREBASE_CONFIG={apiKey:"AIzaSyCkUGX2KWaVGmSQXpYJhWDxF_BSiHRX6SM",authDomain:"btc-archive-test.firebaseapp.com",projectId:"btc-archive-test",storageBucket:"btc-archive-test.firebasestorage.app",messagingSenderId:"60810625669",appId:"1:60810625669:web:ea4dacd55333e41429dfec",measurementId:"G-7C2FKDJ8E4"},LEVELS=[{name:"Normie",emoji:"🟢",min:0},{name:"Curious",emoji:"🔵",min:10},{name:"Pleb",emoji:"🟠",min:144},{name:"Pleb II",emoji:"🟠🟠",min:170},{name:"Pleb III",emoji:"🟠🟠🟠",min:256},{name:"Stacker",emoji:"📦",min:500},{name:"Stacker II",emoji:"📦📦",min:1913},{name:"Stacker III",emoji:"📦📦📦",min:2016},{name:"Maxi",emoji:"🔥",min:2140},{name:"Maxi II",emoji:"🔥🔥",min:6102},{name:"Maxi III",emoji:"🔥🔥🔥",min:8888},{name:"Papa John",emoji:"🍕",min:1e4},{name:"Full Node",emoji:"🖥️",min:18333},{name:"Whale",emoji:"🐋",min:5e4},{name:"Sovereign",emoji:"🏴",min:1e5},{name:"Cypherpunk",emoji:"🔒",min:133337},{name:"Satoshi",emoji:"👑",min:21e4}];function _renderQRCode(e,t,o){if(window.qrcode&&"function"==typeof window.qrcode)_drawQR(e,t,o);else{var n=document.createElement("script");n.src="https://cdnjs.cloudflare.com/ajax/libs/qrcode-generator/1.4.4/qrcode.min.js",n.integrity="sha384-mZT2gIty7ZDdOGkxfP6joZcYdMW1Jvj9dRlfpTmaJAKKXTqzygtB22k7FLe+KZC1",n.crossOrigin="anonymous",n.onload=function(){_drawQR(e,t,o)},n.onerror=function(){e.innerHTML='
    '+t+"
    "},document.head.appendChild(n)}}function _drawQR(e,t,o){try{var n=qrcode(0,"M");n.addData(t),n.make();var i=document.createElement("img");i.src=n.createDataURL(6,4),i.width=o,i.height=o,i.alt="QR Code",i.style.cssText="border-radius:8px;image-rendering:pixelated;",e.innerHTML="",e.appendChild(i)}catch(t){e.innerHTML='
    QR generation failed
    '}}const POINTS={visit:5,openChannel:10,readTime:15,explore10:50,streak:100};let db,auth,currentUser=null,signInAttempts=0,signInLockout=0,redirectResultResolved=!1,redirectResultPromise=Promise.resolve(null),sessionChannels=new Set,readTimer=null,readSeconds=0,lastReadAward=0,rankingReady=!1,allTimeChannels=new Set,lastLevelName="",lastLevelMin=0,levelUpReady=!1;function initRanking(){try{firebase.initializeApp(FIREBASE_CONFIG),db=firebase.firestore(),db.enablePersistence({synchronizeTabs:!0}).catch(function(e){"failed-precondition"!==e.code&&"unimplemented"!==e.code&&console.log("Persistence error:",e.code)}),auth=firebase.auth(),auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).catch(function(){}),auth.isSignInWithEmailLink(window.location.href)&&handleEmailSignIn(),redirectResultPromise=auth.getRedirectResult().then(async function(e){if(redirectResultResolved=!0,console.log("[Auth] getRedirectResult:",e?e.user?e.user.uid:"no user":"null"),!e||!e.user)return null;const t=e.user;sessionStorage.setItem("btc_redirect_auth","1");const o=await db.collection("users").doc(t.uid).get(),n=localStorage.getItem("btc_anon_uid");let i=null;try{i=JSON.parse(localStorage.getItem("btc_anon_data"))}catch(e){}if(localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),o.exists){if(i&&!o.data().mergedAnon){await o.ref.update({mergedAnon:!0});var a=Math.min(i.points||0,500);a>0&&"function"==typeof awardPoints&&await awardPoints(a,"🔗 Anonymous progress merged")}}else{i?(i.email=t.email||"",i.username||(i.username=t.displayName||"Bitcoiner"),await db.collection("users").doc(t.uid).set(i)):await db.collection("users").doc(t.uid).set({username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(t.uid)}if(n&&n!==t.uid)try{await db.collection("users").doc(n).delete()}catch(e){}return loadUser(t.uid),updateAuthButton(),"function"==typeof hideUsernamePrompt&&hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(t.displayName||t.email||"Bitcoiner")),t}).catch(function(e){return redirectResultResolved=!0,"auth/popup-closed-by-user"!==e.code&&console.log("Redirect result error:",e),null});let o=!0,n=auth.isSignInWithEmailLink(window.location.href);var e=localStorage.getItem("btc_pwa_auth_pending"),t=!!localStorage.getItem("btc_anon_uid")||"1"===sessionStorage.getItem("btc_redirect_pending")||!!e;e&&(localStorage.removeItem("btc_pwa_auth_pending"),console.log("[Auth] PWA auth pending detected")),t&&console.log("[Auth] Detected pending redirect return"),auth.onAuthStateChanged(e=>{if(console.log("[Auth] onAuthStateChanged:",e?e.isAnonymous?"anon:"+e.uid:"real:"+e.uid:"null","firstEvent:",o,"pendingRedirect:",t),e&&!e.isAnonymous){var i=localStorage.getItem("btc_last_auth_uid");i&&i!==e.uid&&(console.log("[Auth] Account switch detected:",i,"->",e.uid,"— clearing localStorage"),clearUserLocalStorage()),localStorage.setItem("btc_last_auth_uid",e.uid)}if(o){if(o=!1,n)return;if(e&&!e.isAnonymous)console.log("[Auth] Real user on first event:",e.uid),sessionStorage.removeItem("btc_redirect_auth"),loadUser(e.uid).then(function(){currentUser&¤tUser.username&&setTimeout(function(){"function"==typeof showToast&&showToast("👋 Welcome back, "+escapeHtml(currentUser.username||"")+"!")},2e3)}).catch(function(){});else if(e&&e.isAnonymous)if(t){console.log("[Auth] Anon user but pending redirect — waiting 8s for real auth...");var a=setTimeout(function(){auth.currentUser&&!auth.currentUser.isAnonymous?(console.log("[Auth] Real user appeared after wait:",auth.currentUser.uid),loadUser(auth.currentUser.uid)):(console.log("[Auth] No real user after 8s — loading anon"),loadUserLocal(e.uid)),localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),localStorage.removeItem("btc_pwa_auth_pending"),sessionStorage.removeItem("btc_redirect_pending")},8e3);redirectResultPromise.then(function(e){e&&clearTimeout(a)})}else loadUserLocal(e.uid);else if(redirectResultResolved&&!t)auth.signInAnonymously().then(()=>{});else{var r=setTimeout(function(){auth.currentUser||(console.log("[Auth] 10s timeout with no user — going anonymous"),localStorage.removeItem("btc_pwa_auth_pending"),auth.signInAnonymously().then(()=>{}))},1e4);redirectResultPromise.then(function(e){clearTimeout(r),e||auth.currentUser||auth.signInAnonymously().then(()=>{})})}}else if(e){if(currentUser&¤tUser.uid===e.uid)return void updateAuthButton();e.isAnonymous?loadUserLocal(e.uid):loadUser(e.uid)}else currentUser=null,redirectResultResolved?auth.signInAnonymously().then(()=>{}):redirectResultPromise.then(function(e){e||auth.currentUser||auth.signInAnonymously().then(()=>{})})})}catch(e){console.error("Ranking init error:",e),setTimeout(function(){"function"==typeof showToast&&showToast("⚠️ Init error: "+(e.message||e))},2e3)}}async function handleEmailSignIn(){var e=window.location.href;let t=null;var o=new URLSearchParams(window.location.search);return o.get("signin_email")&&(t=decodeURIComponent(o.get("signin_email"))),t||(t=localStorage.getItem("btc_signin_email")),t?finishEmailSignIn(t,e):new Promise(function(o){var n=document.createElement("div");n.id="emailConfirmOverlay",n.style.cssText="position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:20px;",n.innerHTML='
    📧
    Confirm Your Email
    It looks like you opened this link on a different device. Enter the email you used to sign up:
    Cancel
    ',document.body.appendChild(n);var i=document.getElementById("crossDeviceEmail");function a(){var a=i.value.trim().toLowerCase();a&&a.includes("@")?(n.remove(),t=a,o(finishEmailSignIn(t,e))):"function"==typeof showToast&&showToast("Please enter a valid email")}document.getElementById("crossDeviceSubmit").onclick=a,i.addEventListener("keydown",function(e){"Enter"===e.key&&a()}),setTimeout(function(){i.focus()},100)})}async function finishEmailSignIn(e,t){if(e)try{const i=auth.currentUser;let a=null,r=null;if(i&&i.isAnonymous){a=i.uid,console.log("[Email Sign-In] Anon user found:",a);try{const e=await db.collection("users").doc(a).get();e.exists&&(r=e.data()),console.log("[Email Sign-In] Anon data loaded:",!!r)}catch(e){console.log("[Email Sign-In] Anon data load failed (non-fatal):",e.code)}}console.log("[Email Sign-In] Starting signInWithEmailLink for:",e);const s=await auth.signInWithEmailLink(e,t);console.log("[Email Sign-In] Sign-in result:",s.user?s.user.uid:"no user"),localStorage.removeItem("btc_signin_email");const c=s.user.uid;console.log("[Email Sign-In] Waiting for auth token propagation...");for(var o=0;o<5;o++){await new Promise(e=>setTimeout(e,200));try{await db.collection("users").doc(c).get(),console.log("[Email Sign-In] Firestore auth ready after",200*(o+1),"ms");break}catch(e){if("permission-denied"===e.code){console.log("[Email Sign-In] Permission denied on retry "+(o+1)+", waiting for token propagation...");continue}throw e}}console.log("[Email Sign-In] Fetching existing user doc:",c);const l=await db.collection("users").doc(c).get();if(console.log("[Email Sign-In] Existing doc exists:",l.exists),!l.exists&&r)r.email=e,await db.collection("users").doc(c).set(r);else if(l.exists&&r){const e=l.data();var n=Math.min(r.points||0,500);!e.mergedAnon&&n>(e.points||0)&&await l.ref.update({points:Math.max(n,e.points||0),channelsVisited:Math.max(r.channelsVisited||0,e.channelsVisited||0),totalVisits:(e.totalVisits||0)+(r.totalVisits||0),mergedAnon:!0})}if(a&&a!==c)try{await db.collection("users").doc(a).delete()}catch(e){}window.history.replaceState(null,"",window.location.pathname+window.location.hash);const d=localStorage.getItem("btc_pending_username"),u=(localStorage.getItem("btc_pending_email"),localStorage.getItem("btc_pending_giveaway"));if(d&&!l.exists){const t={username:d,email:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};if(u){t.lightningAddress=u,t.giveaway={entered:!0,lightningAddress:u,enteredAt:(new Date).toISOString()};try{await db.collection("giveaway_entries").doc(c).set({username:d,lightningAddress:u,email:e,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:c})}catch(e){}}await db.collection("users").doc(c).set(t);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(c)}localStorage.removeItem("btc_pending_username"),localStorage.removeItem("btc_pending_email"),localStorage.removeItem("btc_pending_giveaway"),localStorage.removeItem("btc_wallet_enc"),localStorage.removeItem("btc_wallet_addrs"),loadUser(c),showToast("✅ Email verified! Signed in as "+escapeHtml(d||e)),u&&setTimeout(function(){showToast("🎉 You're entered for the 25,000 sats giveaway! Good luck!")},2e3)}catch(e){console.error("[Email Sign-In] Full error:",e.code,e.message,e.stack),"permission-denied"===e.code?(showToast("⚠️ Permission denied. Try refreshing the page or clearing cache."),console.error("[Email Sign-In] Firestore permission denied - auth state may not be ready")):"auth/invalid-action-code"===e.code||"auth/expired-action-code"===e.code?showToast("⚠️ This sign-in link has expired. Please request a new one."):"auth/invalid-email"===e.code?showToast("⚠️ Email mismatch. Make sure you enter the same email you signed up with."):showToast("Sign-in error ("+(e.code||"unknown")+"). Please try again."),window.history.replaceState(null,"",window.location.pathname+window.location.hash),auth.signInAnonymously()}else showToast("⚠️ Could not determine your email. Please sign in again from the app.")}var GOOGLE_CLIENT_ID="1055248200518-jcn5efjp7vhk0vm8cbmj4mfsgc0edkga.apps.googleusercontent.com";async function signInWithGIS(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){var n=e.anonUid,i=e.anonData;google.accounts.id.initialize({client_id:GOOGLE_CLIENT_ID,callback:async function(e){if(e&&e.credential)try{var a=firebase.auth.GoogleAuthProvider.credential(e.credential),r=await auth.signInWithCredential(a);try{google.accounts.id.cancel()}catch(e){}var s=document.getElementById("gsi-temp-btn");if(s){var c=s.closest('div[style*="position:fixed"]');c?c.remove():s.remove()}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()}),await _handleSignInResultGlobal(r.user,n,i),t(r.user)}catch(e){o(e)}else o(new Error("No credential received"))},auto_select:!1,cancel_on_tap_outside:!0,context:"signin",ux_mode:"popup"}),google.accounts.id.prompt(function(e){(e.isNotDisplayed()||e.isSkippedMoment())&&(console.log("[Auth] One Tap not shown, falling back to Firebase popup"),o(new Error("One Tap unavailable")))})})}function showPWAAuthFallback(e){var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='
    🔐
    '+e+' Sign-In
    '+e+' sign-in requires a browser window. Open the site in your browser to sign in.
    ',document.body.appendChild(t)}window.signInWithGoogle=async function(){if(!/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||"")&&"undefined"!=typeof google&&google.accounts&&google.accounts.id)try{return void await signInWithGIS()}catch(e){console.warn("[Auth] GIS failed, falling back to Firebase popup:",e);try{google.accounts.id.cancel()}catch(e){}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()})}await signInWithProvider(new firebase.auth.GoogleAuthProvider)},window.signInWithTwitter=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.TwitterAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("Twitter")}await signInWithProvider(new firebase.auth.TwitterAuthProvider)},window.signInWithGithub=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.GithubAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("GitHub")}await signInWithProvider(new firebase.auth.GithubAuthProvider)};var FB_APP_ID="1400842698021858";async function signInWithFBSDK(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){FB.login(function(n){if(n.authResponse){var i=firebase.auth.FacebookAuthProvider.credential(n.authResponse.accessToken);auth.signInWithCredential(i).then(async function(o){await _handleSignInResultGlobal(o.user,e.anonUid,e.anonData),t(o.user)}).catch(o)}else o(new Error("Facebook login cancelled"))},{scope:"email,public_profile"})})}function checkRateLimit(){const e=Date.now();return e5&&(signInLockout=e+6e4,signInAttempts=0,showToast("⏳ Too many attempts. Please wait 60 seconds."),1)))}function isInAppBrowser(){var e=navigator.userAgent||"";return/FBAN|FBAV|Instagram|Twitter|Line\/|Snapchat|BytedanceWebview|musical_ly|TikTok|Weibo|MicroMessenger|LinkedInApp|Telegram/i.test(e)}async function _saveAnonDataGlobal(){var e=auth.currentUser,t=null,o=null;if(e&&e.isAnonymous){t=e.uid;try{var n=await db.collection("users").doc(t).get();n.exists&&(o=n.data())}catch(e){}}return{anonUid:t,anonData:o}}async function _handleSignInResultGlobal(e,t,o){var n=await db.collection("users").doc(e.uid).get();if(n.exists){if(o){var i=n.data(),a=Math.min(o.points||0,500);!i.mergedAnon&&a>(i.points||0)&&await n.ref.update({points:Math.max(a,i.points||0),channelsVisited:Math.max(o.channelsVisited||0,i.channelsVisited||0),totalVisits:(i.totalVisits||0)+(o.totalVisits||0),mergedAnon:!0})}!n.data().email&&e.email&&await n.ref.update({email:e.email})}else o?(o.email=e.email||"",o.username||(o.username=e.displayName||"Bitcoiner"),await db.collection("users").doc(e.uid).set(o)):await db.collection("users").doc(e.uid).set({username:e.displayName||"Bitcoiner",email:e.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()});if(t&&t!==e.uid)try{await db.collection("users").doc(t).delete()}catch(e){}if(loadUser(e.uid),n.exists)hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(e.displayName||e.email||"Bitcoiner"));else{"function"==typeof attachReferral&&attachReferral(e.uid),showGiveawayPrompt(e.uid,e.displayName||e.email||"Bitcoiner");try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},1500)}catch(e){}}}async function signInWithProvider(e){if(checkRateLimit()){if(isInAppBrowser()){var t=navigator.userAgent||"",o=/iPhone|iPad/i.test(t)?'Tap the share icon (↑) → "Open in Safari"':/Android/i.test(t)?'Tap ⋮ (menu) → "Open in Browser"':"Open this page in your default browser",n=document.createElement("div");return n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.9);padding:20px;",n.innerHTML='
    🌐

    Open in Browser

    Sign-in doesn\'t work inside apps. '+o+'

    ',void document.body.appendChild(n)}var i=/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||""),a=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(i||a)try{showToast("⏳ Opening sign-in...");const t=auth.currentUser;t&&t.isAnonymous&&(localStorage.setItem("btc_anon_uid",t.uid),db.collection("users").doc(t.uid).get().then(function(e){e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}).catch(function(){}));try{const t=await auth.signInWithPopup(e);if(t&&t.user){const{anonUid:e,anonData:o}=await s();return void await r(t.user,e,o)}}catch(t){return console.log("[Auth] Mobile popup failed, falling back to redirect:",t.code),sessionStorage.setItem("btc_redirect_pending","1"),localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}}catch(e){return console.error("Mobile sign-in error:",e),void showToast("Sign-in failed: "+(e.message||"Unknown error"))}try{const{anonUid:t,anonData:o}=await s(),n=await auth.signInWithPopup(e);await r(n.user,t,o)}catch(t){if(console.error("Provider sign-in error:",t.code,t.message,t),"auth/popup-blocked"===t.code||"auth/cancelled-popup-request"===t.code||"auth/popup-closed-by-user"===t.code||"auth/internal-error"===t.code){try{showToast("⏳ Opening sign-in page...");const t=auth.currentUser;if(t&&t.isAnonymous){localStorage.setItem("btc_anon_uid",t.uid);try{const e=await db.collection("users").doc(t.uid).get();e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}catch(e){}}return localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}catch(e){console.error("Redirect fallback also failed:",e),showToast("Sign-in failed. Please try a different browser.")}return}if("auth/popup-closed-by-user"===t.code)return;"auth/unauthorized-domain"===t.code?showToast("⚠️ This domain is not authorized for sign-in. Please contact support."):"auth/operation-not-allowed"===t.code?showToast("⚠️ This sign-in method is not enabled. Try a different option."):"auth/account-exists-with-different-credential"===t.code?showToast("⚠️ An account with this email exists using a different sign-in method. Try another option."):"auth/network-request-failed"===t.code?showToast("⚠️ Network error. Check your connection and try again."):showToast("Sign-in error ("+(t.code||"unknown")+"). Please try again.")}}async function r(e,t,o){return _handleSignInResultGlobal(e,t,o)}async function s(){return _saveAnonDataGlobal()}}function showGiveawayPrompt(e,t){const o=document.getElementById("usernameModal");o.querySelector(".username-box").innerHTML="

    🎉 Welcome, "+t+'!

    Your account is all set. Want to enter the giveaway?

    Enter a Lightning address so we can send you the sats if you win! 🏆

    ',o.classList.add("open"),document.getElementById("giveawayCheckboxProvider").addEventListener("change",function(){document.getElementById("giveawayLnProvider").parentElement.style.display=this.checked?"flex":"none"})}async function submitGiveawayProvider(e,t){var o=document.getElementById("giveawayCheckboxProvider"),n=document.getElementById("giveawayLnProvider"),i=n?n.value.trim():"";if(o&&o.checked){if(!i)return n&&(n.style.borderColor="#ef4444"),void showToast("⚡ Please enter a Lightning address!");try{await db.collection("users").doc(e).update({lightningAddress:i,giveaway:{entered:!0,lightningAddress:i,enteredAt:(new Date).toISOString()}}),void 0!==currentUser&¤tUser&&(currentUser.lightningAddress=i),await db.collection("giveaway_entries").doc(e).set({username:t,lightningAddress:i,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:e}),showToast("🎉 You're entered for the 25,000 sats giveaway! Good luck!")}catch(e){console.log("Giveaway save error:",e)}}hideUsernamePrompt(),showToast("✅ Signed in as "+t);var a=document.getElementById("giveawayBanner");a&&(a.style.display="none")}async function sendMagicLink(e){const t={url:window.location.origin+window.location.pathname+"?signin_email="+encodeURIComponent(e),handleCodeInApp:!0};try{return await auth.sendSignInLinkToEmail(e,t),localStorage.setItem("btc_signin_email",e),!0}catch(e){return console.log("Magic link error:",e),!1}}function loadUserLocal(e){var t=parseInt(localStorage.getItem("btc_points")||"0"),o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");currentUser={uid:e,points:t,channelsVisited:o.length,readChannels:o,totalVisits:parseInt(localStorage.getItem("btc_total_visits")||"1"),streak:parseInt(localStorage.getItem("btc_streak")||"0"),lastVisit:localStorage.getItem("btc_last_visit")||"",_isLocal:!0},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,restoreVisitedUI(),updateRankUI(),_checkCapOnLoad(),updateAuthButton(),"function"==typeof renderProgressRings&&renderProgressRings(),"function"==typeof renderExplorationMap&&renderExplorationMap(),startReadTimer()}async function loadUser(e,t){const o=t||await db.collection("users").doc(e).get();if(o.exists){currentUser={uid:e,...o.data()},currentUser.visitedChannelsList&¤tUser.visitedChannelsList.forEach(e=>allTimeChannels.add(e));const t=auth.currentUser&&!auth.currentUser.isAnonymous;var n=[...new Set([...Array.isArray(currentUser.visitedChannelsList)?currentUser.visitedChannelsList:[],...Array.isArray(currentUser.readChannels)?currentUser.readChannels:[]])];if(n.length>0){if(t)localStorage.setItem("btc_visited_channels",JSON.stringify(n));else{let e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=[...new Set([...e,...n])];localStorage.setItem("btc_visited_channels",JSON.stringify(t))}restoreVisitedUI()}else t&&(localStorage.setItem("btc_visited_channels","[]"),restoreVisitedUI());if(currentUser.favorites){if(t)localStorage.setItem("btc_favs",JSON.stringify(currentUser.favorites));else{let e=JSON.parse(localStorage.getItem("btc_favs")||"[]"),t=[...new Set([...e,...currentUser.favorites])];localStorage.setItem("btc_favs",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else t&&(localStorage.setItem("btc_favs","[]"),"function"==typeof renderFavs&&renderFavs());if(currentUser.bookmarks){if(t)localStorage.setItem("btc_bookmarks",JSON.stringify(currentUser.bookmarks));else{let e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]"),t=currentUser.bookmarks.concat(e.filter(function(e){return!currentUser.bookmarks.some(function(t){return t.channel===e.channel&&t.idx===e.idx})}));localStorage.setItem("btc_bookmarks",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else if(t){var i=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");i.length>0&&db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({bookmarks:i}).catch(function(){})}if(currentUser.username&&localStorage.setItem("btc_username",currentUser.username),currentUser.streak>0&&!currentUser.bestStreak&&(currentUser.bestStreak=currentUser.streak),rankingReady=!0,updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),awardVisitPoints(),startReadTimer(),auth.currentUser.isAnonymous||db.collection("users").doc(e).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),t){if(currentUser.hiddenBadges){var a=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),r=[...new Set([...a,...currentUser.hiddenBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(r))}if(currentUser.donationBadges&¤tUser.donationBadges.length>0){var s=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),c=[...new Set([...s,...currentUser.donationBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(c))}if(currentUser.visibleBadges){var l=JSON.parse(localStorage.getItem("btc_badges")||"[]"),d=[...new Set([...l,...currentUser.visibleBadges])];localStorage.setItem("btc_badges",JSON.stringify(d))}if(currentUser.spinClosetItems){var u=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]"),p=[...new Set([...u,...currentUser.spinClosetItems])];localStorage.setItem("btc_spin_closet_items",JSON.stringify(p))}if(currentUser.scholarPassed&&localStorage.setItem("btc_scholar_passed","true"),currentUser.nachoMilestones&&localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(currentUser.nachoMilestones)),currentUser.celebratedState){var m=currentUser.celebratedState;m.nachoMilestones&&localStorage.setItem("btc_nacho_milestones",JSON.stringify(m.nachoMilestones)),m.nachoCatComplete&&localStorage.setItem("btc_nacho_cat_complete",JSON.stringify(m.nachoCatComplete)),m.nachoLevelCelebrated&&localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(m.nachoLevelCelebrated)),m.nachoItemsNotified&&localStorage.setItem("btc_nacho_items_notified",JSON.stringify(m.nachoItemsNotified))}if(currentUser.nachoInteractions){var g=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),h=currentUser.nachoInteractions||0;localStorage.setItem("btc_nacho_interactions",Math.max(g,h).toString())}if(currentUser.nachoQuestions){var f=parseInt(localStorage.getItem("btc_nacho_questions")||"0"),y=currentUser.nachoQuestions||0;localStorage.setItem("btc_nacho_questions",Math.max(f,y).toString())}}if(localStorage.setItem("btc_pvp_wins",String(currentUser.pvpWins||0)),localStorage.setItem("btc_pvp_losses",String(currentUser.pvpLosses||0)),currentUser.nachoNickname&&(localStorage.setItem("btc_nacho_nickname",currentUser.nachoNickname),"function"==typeof updateNachoNameUI&&updateNachoNameUI(currentUser.nachoNickname)),t){if(currentUser.lastSpinDate){var v=localStorage.getItem("btc_last_spin")||"";currentUser.lastSpinDate>v&&localStorage.setItem("btc_last_spin",currentUser.lastSpinDate),"function"==typeof updateSpinBanner&&updateSpinBanner()}if(currentUser.prediction&&(localStorage.getItem("btc_prediction")||localStorage.setItem("btc_prediction",JSON.stringify(currentUser.prediction))),currentUser.nachoStoryDays&&Array.isArray(currentUser.nachoStoryDays)){var b=safeJSON("btc_nacho_story_days",[]);currentUser.nachoStoryDays.length>b.length&&localStorage.setItem("btc_nacho_story_days",JSON.stringify(currentUser.nachoStoryDays))}if(currentUser.nachoStoryProgress){var w=parseInt(localStorage.getItem("btc_nacho_story_highest")||"0");currentUser.nachoStoryProgress>w&&localStorage.setItem("btc_nacho_story_highest",currentUser.nachoStoryProgress.toString())}if(currentUser.nachoStoryDate){var x=localStorage.getItem("btc_nacho_story_date")||"";currentUser.nachoStoryDate>x&&localStorage.setItem("btc_nacho_story_date",currentUser.nachoStoryDate)}}window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0;var k=getLevel(currentUser.points||0);lastLevelName=k.name,lastLevelMin=k.min,localStorage.getItem("btc_highest_level_seen")||localStorage.setItem("btc_highest_level_seen",k.min.toString()),setTimeout(function(){levelUpReady=!0},3e3),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showContinueReading&&showContinueReading(),updateAuthButton(),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging()}else{const t=auth.currentUser;if(t&&!t.isAnonymous){const o={username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};await db.collection("users").doc(e).set(o),currentUser={uid:e,...o},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton()}}}window.fbAsyncInit=function(){FB.init({appId:FB_APP_ID,cookie:!0,xfbml:!1,version:"v19.0"})},window.signInWithFacebook=async function(){if("undefined"!=typeof FB)try{return void await signInWithFBSDK()}catch(e){if("Facebook login cancelled"===e.message)return;console.warn("[Auth] FB SDK failed:",e)}await signInWithProvider(new firebase.auth.FacebookAuthProvider)},window.signInWithNostr=async function(){if(checkRateLimit()){var e=!!window.nostr,t=document.createElement("div");t.id="nostrAuthOverlay",t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

    🟣 Sign in with Nostr

    '+(e?'':'
    🔌
    No Extension Detected
    Install Alby or nos2x for one-click login
    ')+'
    or
    🔒 Your nsec is used only in your browser to sign a one-time login event. It is never sent to our servers or stored anywhere.
    or
    ',document.body.appendChild(t)}},window.nostrSignInWithExtension=async function(){if(window.nostr){var e=document.getElementById("nostrAuthStatus");e&&(e.innerHTML='Requesting key from extension...');try{var t=await window.nostr.getPublicKey();if(!t||!/^[a-f0-9]{64}$/.test(t))return void(e&&(e.innerHTML='Could not get public key'));e&&(e.innerHTML='Signing auth event...');var o=await window.nostr.signEvent({kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:t});if(!o||!o.sig)return void(e&&(e.innerHTML='Signing cancelled'));await nostrCompleteAuth(t,o.sig,o)}catch(t){console.error("Nostr extension error:",t),e&&(e.innerHTML='Extension error: '+(t.message||"Unknown")+"")}}else showToast("Extension not found")},window.nostrSignInWithNsec=async function(){var e=(document.getElementById("nostrNsecInput").value||"").trim(),t=document.getElementById("nostrAuthStatus"),o=document.getElementById("nostrNsecBtn");if(e)if(e.startsWith("nsec1")){o.disabled=!0,o.textContent="Loading crypto library...",t&&(t.innerHTML='Loading...');try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.integrity="sha384-GwmNxV/GnZt+zRBR/Hhtu5D4MKfbxeJSApW44ARryGYtj3MFheHMFgiEZ7tVnrln",o.crossOrigin="anonymous",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools;t&&(t.innerHTML='Decoding nsec...'),o.textContent="Signing...";var i=n.nip19.decode(e);if(!i||"nsec"!==i.type)return t&&(t.innerHTML='Invalid nsec'),o.disabled=!1,void(o.textContent="Sign In with nsec");var a=i.data;"string"!=typeof a&&(a=Array.from(new Uint8Array(a)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""));var r=n.getPublicKey(a),s={kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:r};s.id=n.getEventHash(s),s.sig=n.signEvent(s,a),document.getElementById("nostrNsecInput").value="",t&&(t.innerHTML='Verifying signature...'),await nostrCompleteAuth(r,s.sig,s)}catch(e){console.error("Nostr nsec error:",e),t&&(t.innerHTML='Error: '+(e.message||"Failed to sign")+""),o.disabled=!1,o.textContent="Sign In with nsec"}}else t&&(t.innerHTML='Invalid nsec format. Must start with nsec1');else showToast("Please paste your nsec")},window.nostrSignInWithNpub=async function(){var e=(document.getElementById("nostrNpubInput").value||"").trim(),t=document.getElementById("nostrAuthStatus");if(e){var o=e;if(e.startsWith("npub1"))try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools.nip19.decode(e);n&&"npub"===n.type&&"string"!=typeof(o=n.data)&&(o=Array.from(new Uint8Array(o)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""))}catch(e){return void(t&&(t.innerHTML='Invalid npub format'))}if(/^[a-f0-9]{64}$/.test(o)){t&&(t.innerHTML='Linking Nostr identity...');try{auth.currentUser||await auth.signInAnonymously();var i=auth.currentUser.uid;await db.collection("users").doc(i).set({nostr:o,lastLogin:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0}),currentUser&&(currentUser.nostr=o);var a=document.getElementById("nostrAuthOverlay");a&&a.remove(),showToast("🟣 Nostr identity linked! (npub)")}catch(e){t&&(t.innerHTML='Error: '+(e.message||"Unknown")+"")}}else t&&(t.innerHTML='Invalid public key')}else showToast("Please paste your npub")},window.nostrCompleteAuth=async function(e,t,o){var n=document.getElementById("nostrAuthStatus");try{var i=firebase.functions().httpsCallable("nostrAuth"),a=await i({pubkey:e,sig:t,event:o});if(a.data&&a.data.token){await auth.signInWithCustomToken(a.data.token);var r=a.data.uid,s=await db.collection("users").doc(r).get();if(!s.exists||!s.data().username){var c={username:"npub..."+e.substring(0,8),nostr:e,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};s.exists||(c.points=0,c.channelsVisited=0,c.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(r).set(c,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(r),hideUsernamePrompt();var l=document.getElementById("nostrAuthOverlay");l&&l.remove(),showToast("🟣 Signed in with Nostr!")}else n&&(n.innerHTML='Auth failed — no token received')}catch(e){console.error("Nostr auth error:",e),n&&(n.innerHTML='Verification failed: '+(e.message||"Unknown")+"")}},window.signInWithLightning=async function(){if(checkRateLimit()){var e=document.createElement("div");e.id="lnAuthModal",e.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.8);",e.onclick=function(t){t.target===e&&e.remove()},e.innerHTML='

    Lightning Login

    Scan this QR code with your Lightning wallet (Alby, Zeus, Phoenix, BlueWallet, etc.)

    Generating challenge...

    Connecting to server...

    ',document.body.appendChild(e);try{var t=firebase.functions().httpsCallable("lnAuthChallenge"),o=await t();if(!document.getElementById("lnAuthModal"))return;if(!o.data||!o.data.k1||!o.data.lnurl)return"function"==typeof showToast&&showToast("Failed to generate login challenge"),void e.remove();var n=o.data.k1,i=o.data.lnurl,a=document.getElementById("lnAuthQR");if(a)if(a.innerHTML="",a.style.display="inline-block","function"==typeof _renderQRCode)_renderQRCode(a,"lightning:"+i,220);else{var r=document.createElement("img");r.src="https://api.qrserver.com/v1/create-qr-code/?size=220x220&data="+encodeURIComponent("lightning:"+i),r.width=220,r.height=220,r.alt="Lightning Auth QR",r.style.cssText="border-radius:8px;",a.appendChild(r)}var s=document.getElementById("lnAuthCopyWrap");s&&(s.style.display="block",s.innerHTML="");var c=document.getElementById("lnAuthStatus");c&&(c.textContent="Waiting for wallet...",c.style.color="var(--accent)");var l=firebase.functions().httpsCallable("lnAuthVerify"),d=0,u=setInterval(async function(){if(++d>60||!document.getElementById("lnAuthModal"))clearInterval(u);else try{var e=await l({k1:n});if(e.data&&e.data.token){clearInterval(u);var t=document.getElementById("lnAuthStatus");t&&(t.textContent="✅ Authenticated!"),await auth.signInWithCustomToken(e.data.token);var o=e.data.uid,i=await db.collection("users").doc(o).get();if(!i.exists||!i.data().username){var a={username:"⚡anon-"+n.substring(0,8),authMethod:"lightning",totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};i.exists||(a.points=0,a.channelsVisited=0,a.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(o).set(a,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(o),hideUsernamePrompt(),setTimeout(function(){var e=document.getElementById("lnAuthModal");e&&e.remove()},1e3),"function"==typeof showToast&&showToast("⚡ Signed in with Lightning!")}}catch(e){"not-found"!==e.code&&console.log("LN auth poll:",e.message)}},2e3)}catch(e){console.error("Lightning auth error:",e),"function"==typeof showToast&&showToast("Lightning sign-in failed. Try again.");var p=document.getElementById("lnAuthModal");p&&p.remove()}}},window.sendReturningMagicLink=async function(){var e=document.getElementById("returningEmailInput");if(e){var t=e.value.trim();if(!t||!t.includes("@"))return showToast("📧 Please enter a valid email address"),void(e&&(e.style.borderColor="#ef4444"));e.disabled=!0;var o=e.nextElementSibling;o&&(o.disabled=!0,o.textContent="Sending..."),await sendMagicLink(t)?(showToast("📧 Magic link sent! Check your email to sign in."),o&&(o.textContent="✅ Sent!"),hideUsernamePrompt()):(showToast("❌ Could not send magic link. Try again."),e.disabled=!1,o&&(o.disabled=!1,o.textContent="Send Link"))}};var _authBtnSignedIn=!1;function updateAuthButton(){const e=document.getElementById("authBtn");if(e){var t=auth&&auth.currentUser,o=t&&!t.isAnonymous,n=currentUser&¤tUser.username,i=localStorage.getItem("btc_username"),a=n||i||t&&t.displayName||"",r=t&&t.uid&&(t.uid.startsWith("nostr:")||t.uid.startsWith("ln:"));if(o||r||a)_authBtnSignedIn=!0;else{if(_authBtnSignedIn&&t)return;t||(_authBtnSignedIn=!1)}if(_authBtnSignedIn){var s=a||"My Account";e.innerHTML="⚙️ "+("function"==typeof escapeHtml?escapeHtml(s):s)+" — Settings",e.onclick=function(){showSettings()},e.style.display=window.innerWidth<=900?"none":"block",e.style.background="none",e.style.border="2px solid #3b82f6",e.style.color="#3b82f6",e.onmouseover=function(){this.style.background="#3b82f6",this.style.color="#fff"},e.onmouseout=function(){this.style.background="none",this.style.color="#3b82f6"}}else(!t||t&&t.isAnonymous)&&(e.textContent="Create Free Account / Sign In",e.style.display="block",e.style.background="var(--accent)",e.style.border="none",e.style.color="#000",e.onmouseover=function(){this.style.transform="scale(1.02)"},e.onmouseout=function(){this.style.transform="scale(1)"});var c=document.getElementById("guestPointsBanner");c&&_authBtnSignedIn&&(c.style.display="none");var l=document.getElementById("giveawayBanner");l&&_authBtnSignedIn&&(currentUser&¤tUser.giveaway?(l.innerHTML='
    🎉 25,000 SATS GIVEAWAY 🎉
    You\'re entered! Good luck! 🍀
    ✅ Entered
    ',l.onclick=function(){showSettings()}):(l.querySelector("div:last-child")&&(l.querySelector("div:last-child").textContent="⚙️ View Your Profile →"),l.onclick=function(){showSettings()}))}}function sanitizeInput(e){return e.replace(/<[^>]*>/g,"").replace(/[<>"'&]/g,"").trim()}window.sanitizeInput=sanitizeInput,window.syncCelebratedState=function(){if(void 0!==db&&auth&&auth.currentUser){var e={nachoMilestones:safeJSON("btc_nacho_milestones",[]),nachoCatComplete:safeJSON("btc_nacho_cat_complete",[]),nachoLevelCelebrated:safeJSON("btc_nacho_level_celebrated",[]),nachoItemsNotified:safeJSON("btc_nacho_items_notified",[])};db.collection("users").doc(auth.currentUser.uid).update({celebratedState:e}).catch(function(){})}};const PROFANITY_LIST=["fuck","shit","ass","bitch","dick","cock","pussy","cunt","damn","hell","bastard","slut","whore","fag","faggot","nigger","nigga","retard","retarded","penis","vagina","porn","sex","anal","cum","jizz","dildo","tits","boob","nude","naked","hentai","milf","orgasm","erect","molest","rape","pedo","nazi","hitler","kkk","jihad","terrorist","kill","murder","suicide","die","stfu","gtfo","wank","twat","bollocks","arse","shag","piss","crap","douche","skank","thot","incel","simp","onlyfans","xnxx","pornhub","xvideos","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","aroused","erection","erectile","climax","ejaculat","deepthroat","rimjob","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes","twerk","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","zipperhead","jap","paki","wop","dago","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","acab","supremacy","genocide","lynch"];function containsProfanity(e){const t=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g," "),o=t.split(/\s+/);for(const e of o)if(PROFANITY_LIST.includes(e))return!0;const n=t.replace(/\s/g,"");for(const e of PROFANITY_LIST)if(e.length>=4&&n.includes(e))return!0;return!1}async function createUser(e,t,o,n,i){if(void 0===auth||!auth)return showToast("⏳ Loading... please try again in a moment."),void("function"==typeof initRanking&&initRanking());if(!auth.currentUser)try{await auth.signInAnonymously(),auth.currentUser||await new Promise(e=>{const t=auth.onAuthStateChanged(o=>{o&&(t(),e())});setTimeout(()=>{e()},3e3)})}catch(e){return console.log("Anonymous sign-in error:",e),void showToast("Error creating account. Please try again.")}if(!auth.currentUser)return void showToast("Error: Could not authenticate. Please refresh and try again.");const a=auth.currentUser.uid;if(clearUserData(),!(e=(e=sanitizeInput(e)).replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim())||e.length<2)return void showToast("⚠️ Username must be at least 2 characters (letters, numbers, basic symbols only).");if(containsProfanity(e))return void showToast("⚠️ That username is not allowed. Please choose another.");t&&(t=sanitizeInput(t));const r={username:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};if(t&&(r.email=t),i&&(r.country=i),window._signupFaction&&(r.faction=window._signupFaction,window._signupFaction=null),o&&n){r.lightningAddress=n,r.giveaway={entered:!0,lightningAddress:n,enteredAt:(new Date).toISOString()};try{await db.collection("giveaway_entries").doc(a).set({username:e,lightningAddress:n,email:t||null,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:a})}catch(e){console.log("Giveaway entry save error:",e)}}await db.collection("users").doc(a).set(r);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}currentUser={uid:a,...r},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton(),awardPoints(POINTS.visit,"Welcome bonus!"),startReadTimer(),hideUsernamePrompt();try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},800)}catch(e){}var s=document.getElementById("giveawayBanner");s&&(s.style.display="none"),"function"==typeof attachReferral&&attachReferral(a),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging();try{var c=JSON.parse(localStorage.getItem("btc_buddy_pending")||"null");c&&c.goal&&(localStorage.removeItem("btc_buddy_pending"),"function"==typeof _submitBuddyFromOnboarding&&setTimeout(function(){_submitBuddyFromOnboarding(c.level||"beginner",c.goal)},2e3))}catch(e){}}async function awardVisitPoints(){if(!currentUser)return;const e=(new Date).toISOString().split("T")[0],t=new Date(Date.now()-864e5).toISOString().split("T")[0];if(currentUser.lastVisit===e)return;let o=!1,n=0,i=POINTS.visit,a=1;if(currentUser.lastVisit===t)a=(currentUser.streak||0)+1,a%7==0?(n=Math.min(25,5*Math.floor(a/7)),o=!0):a%5==0&&(i+=POINTS.streak,o=!0);else if(currentUser.lastVisit!==e){var r=currentUser.streak||0;currentUser.streakFreezes>0?(a=r+1,currentUser.streakFreezes--,o=!0,setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze ticket was used to save your "+a+"-day streak! ("+(currentUser.streakFreezes||0)+" freezes remaining)")},3e3)):r>1&&setTimeout(function(){showToast("💔 Your "+r+"-day streak was broken! Earn 🧊 Freeze Tickets from the Daily Spin to protect your streak next time.")},3e3)}if(currentUser._isLocal);else{try{var s=firebase.functions().httpsCallable("recordDailyVisit"),c=await s({});if(c.data&&c.data.success&&!c.data.alreadyVisited){a=c.data.streak||1,n=c.data.bonusTickets||0;var l=c.data.bestStreak||a;currentUser.streak=a,currentUser.bestStreak=l,currentUser.lastVisit=e,currentUser.totalVisits=c.data.totalVisits||(currentUser.totalVisits||0)+1,n>0&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+n),c.data.usedFreeze&&(currentUser.streakFreezes=Math.max(0,(currentUser.streakFreezes||0)-1),setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze was used to save your "+a+"-day streak!")},3e3))}}catch(e){console.warn("[VISIT] Cloud Function failed:",e.message)}var d=i+5*n;d>0&&await awardPoints(d,"✅ Daily visit"+(a>1?" ("+a+"-day streak!)":""))}n>0?("function"==typeof notifySelfStreak&¬ifySelfStreak(a),setTimeout(function(){showToast("🔥 STREAK MILESTONE! Day "+a+": Earned +"+n+" Bonus Tickets! 🎟️")},3500)):o&&showToast("🔥 Day "+currentUser.streak+" streak! +"+(POINTS.visit+POINTS.streak)+" XP"),updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen()}async function awardPoints(e,t,o,n,i){if(currentUser&&rankingReady&&(e=parseInt(e),!(isNaN(e)||e<0||e>2200)&&(0!==e||n||i))){window._pointAwardTimes=window._pointAwardTimes||[];var a=Date.now();if(window._pointAwardTimes=window._pointAwardTimes.filter(function(e){return a-e<6e4}),!(window._pointAwardTimes.length>=20)){if(window._pointAwardTimes.push(a),currentUser._isLocal){var r=500,s=(new Date).toISOString().split("T")[0],c="btc_daily_pts_"+s,l=parseInt(localStorage.getItem(c)||"0",10);isNaN(l)&&(l=0);var d={tctv_watch_10m:6e5,daily_spin:864e5,daily_visit:72e6}[t];if(d){var u="btc_cd_"+t,p=parseInt(localStorage.getItem(u)||"0",10);if(p&&Date.now()-p0&&f&&f!==s){h-=y=Math.min(h,r);try{localStorage.setItem(m,String(h))}catch(e){}}var v=e,b=0;if(l>=r?(v=0,b=e):l+e>r&&(b=e-(v=r-l)),(_=v+y)>0){var w=(parseInt(localStorage.getItem("btc_points")||"0",10)||0)+_;try{localStorage.setItem("btc_points",String(w)),v>0&&localStorage.setItem(c,String(l+v))}catch(e){}currentUser.points=w,_showPointsToast(v,t),"function"==typeof notifySelfPoints&¬ifySelfPoints(v,t),y>0&&"function"==typeof showToast&&setTimeout(function(){showToast("♻️ +"+y+" overflow pts redeemed from prior day!",4e3)},1200)}if(b>0){h+=b;try{localStorage.setItem(m,String(h)),localStorage.setItem(g,s)}catch(e){}var x="btc_overflow_notified_"+s;if(!localStorage.getItem(x)){try{localStorage.setItem(x,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap reached (500)! +"+b+" XP banked as overflow — they roll over tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}else if(l+v>=r){var k="btc_daily_cap_notified_"+s;if(!localStorage.getItem(k)){try{localStorage.setItem(k,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}return updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),void("function"==typeof nachoOnPoints&&nachoOnPoints(e))}auth.currentUser.isAnonymous||db.collection("users").doc(auth.currentUser.uid).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),e>0&&t&&"function"==typeof notifySelfPoints&¬ifySelfPoints(e,t);try{var T=firebase.functions().httpsCallable("awardPoints"),S={pts:e,action:t||"",reason:t||""};o&&(S.channelId=o),n&&(S.tickets=n),i&&(S.streakFreezes=i);var B=await T(S);if(B.data&&B.data.dailyActionCapped&&"function"==typeof showToast&&showToast("⏳ "+(B.data.error||"Daily limit reached for this action."),6e3),B.data&&B.data.cooldown&&"function"==typeof showToast&&showToast("⏳ "+(B.data.error||"Slow down a bit."),4e3),B.data&&B.data.success){v=B.data.awarded||0,y=B.data.overflowRedeemed||0,b=B.data.overflowAdded||0;var _,I=B.data.pendingOverflow||0;if((_=v+y)>0&&(currentUser.points=(currentUser.points||0)+_,_showPointsToast(v,t),y>0&&setTimeout(function(){showToast("♻️ +"+y+" overflow pts redeemed from prior day!",4e3)},1200)),b>0){m="btc_overflow_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(m)||(localStorage.setItem(m,"1"),showToast("🎯 Daily cap reached (500)! +"+b+" XP banked as overflow — they roll over tomorrow.",8e3),_updateCapIndicator(!0));try{localStorage.setItem("btc_pts_overflow",String(I))}catch(e){}}else B.data.capped&&(k="btc_daily_cap_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(k)||(localStorage.setItem(k,"1"),showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow.",8e3),_updateCapIndicator(!0)))}}catch(e){console.warn("[POINTS] Cloud Function failed:",e.message),"function"==typeof showToast&&showToast("⏳ XP will sync when connection restores")}updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),"function"==typeof nachoOnPoints&&nachoOnPoints(e)}}}function _showPointsToast(e,t){var o=!1;e>=25?o=!0:t&&t.length>0&&(window._lastPtsToast=window._lastPtsToast||0,Date.now()-window._lastPtsToast>3e4&&(o=!0)),o&&t&&(window._lastPtsToast=Date.now(),showToast("+"+e+" XP — "+t,2500))}function refreshLeaderboardIfOpen(){var e=document.getElementById("leaderboard");if(e&&e.classList.contains("open")&&!e.classList.contains("minimized")){window._lbCache=null,window._lbCacheTime=null;var t=e.querySelector(".lb-me .lb-score");t&¤tUser&&(t.textContent=(currentUser.points||0).toLocaleString()+" XP")}}async function onChannelOpen(e){if("function"==typeof nachoOnChannel&&nachoOnChannel(e),currentUser&&rankingReady){if(!allTimeChannels.has(e)){allTimeChannels.add(e),sessionChannels.add(e);let t=POINTS.openChannel;if(window._dailyBoosts&&window._dailyBoosts.includes(e)&&(t*=2,setTimeout(()=>{showToast("⚡ 2X XP! Daily boost applied! +"+t+" XP")},2e3)),currentUser._isLocal,currentUser.channelsVisited=(currentUser.channelsVisited||0)+1,currentUser.readChannels?-1===currentUser.readChannels.indexOf(e)&¤tUser.readChannels.push(e):currentUser.readChannels=[e],Array.isArray(currentUser.visitedChannelsList)||(currentUser.visitedChannelsList=[]),-1===currentUser.visitedChannelsList.indexOf(e)&¤tUser.visitedChannelsList.push(e),await awardPoints(t,"📖 New channel explored",e),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showToast){const e=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,t=Math.round(allTimeChannels.size/e*100);showToast("🗺️ Exploration Map: "+allTimeChannels.size+" channels reached ("+t+"%)")}10===allTimeChannels.size&&await awardPoints(POINTS.explore10,"Explorer bonus! 10 topics 🎉")}readSeconds=0,lastReadAward=0,syncReadToFirebase(e),"function"==typeof onChannelVisitForQuest&&onChannelVisitForQuest(e)}}async function syncReadToFirebase(e){}async function syncFavsToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_favs")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({favorites:e})}catch(e){}}async function syncBookmarksToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({bookmarks:e})}catch(e){}}function restoreVisitedUI(){JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})})}window.notifySelfPoints=function(e,t){if(e&&!(e<1)&&t&&""!==t){var o={pts:e,reason:t,ts:Date.now(),read:!1};try{var n=JSON.parse(localStorage.getItem("btc_points_log")||"[]");n.push(o),n.length>100&&(n=n.slice(n.length-100)),localStorage.setItem("btc_points_log",JSON.stringify(n))}catch(e){}"function"==typeof _updatePointsBadge&&_updatePointsBadge()}},window.syncBookmarksToFirebase=syncBookmarksToFirebase;let lastActivityTime=Date.now(),lastScrollPos=0,hasScrolledSinceLastAward=!1;function trackActivity(){lastActivityTime=Date.now()}function trackScroll(){const e=document.getElementById("main");e&&Math.abs(e.scrollTop-lastScrollPos)>30&&(lastScrollPos=e.scrollTop,hasScrolledSinceLastAward=!0,lastActivityTime=Date.now())}function startReadTimer(){readTimer&&clearInterval(readTimer),readTimer=setInterval(async()=>{if(currentUser&&rankingReady&&!document.hidden&&!((Date.now()-lastActivityTime)/1e3>45)&&hasScrolledSinceLastAward&&(readSeconds++,sessionStorage.setItem("btc_channel_read_seconds",readSeconds.toString()),readSeconds-lastReadAward>=30)){lastReadAward=readSeconds,hasScrolledSinceLastAward=!1;var e="btc_read_cap_"+(window.currentChannelId||"unknown")+"_"+(new Date).toISOString().split("T")[0],t=parseInt(localStorage.getItem(e)||"0");if(t>=5)return;localStorage.setItem(e,(t+1).toString()),await awardPoints(POINTS.readTime,"")}},1e3)}function getLevel(e){let t=LEVELS[0];for(const o of LEVELS)e>=o.min&&(t=o);const o=LEVELS.indexOf(t)+1,n=o
    '+o.emoji+''+t.toLocaleString()+' XP
    Sign in to keep your XP & get on the leaderboard!
    Sign Up Free →
    ",e.style.display="flex"}}else e&&(e.style.display="none");else e&&(e.style.display="none")}function _updateCapIndicator(e){var t=document.getElementById("userDisplay");if(t){var o,n="btc_daily_pts_"+(new Date).toISOString().split("T")[0],i=parseInt(localStorage.getItem(n)||"0"),a=parseInt(localStorage.getItem("btc_pts_overflow")||"0");e||i>=500?(t.style.borderColor="#ef4444",t.style.boxShadow="0 0 12px rgba(239,68,68,0.3)",t.title="🎯 Daily XP cap reached (500/500)"+(a>0?"\n💫 Overflow: "+a+" pts (rolls over tomorrow)":""),document.getElementById("dailyCapBadge")||((o=document.createElement("span")).id="dailyCapBadge",o.style.cssText="position:absolute;top:-6px;left:-6px;background:#ef4444;color:#fff;font-size:0.55rem;font-weight:800;padding:2px 6px;border-radius:8px;z-index:2;pointer-events:none;",o.textContent="CAP",t.style.position="fixed",t.appendChild(o))):(t.style.borderColor="var(--border)",t.style.boxShadow="0 2px 10px rgba(0,0,0,0.2)",t.title="",(o=document.getElementById("dailyCapBadge"))&&o.remove())}}function _checkCapOnLoad(){var e="btc_daily_pts_"+(new Date).toISOString().split("T")[0];parseInt(localStorage.getItem(e)||"0")>=500&&setTimeout(function(){_updateCapIndicator(!0)},2e3)}function updateRankUI(){if(!currentUser)return;var e=document.getElementById("giveawayBanner");e&¤tUser.username&&(e.style.display="none");const t=getLevel(currentUser.points||0);!lastLevelName&&t.name&&(lastLevelName=t.name,lastLevelMin=t.min),updateGuestPointsBanner(),updateUserDisplay(t);const o=parseInt(localStorage.getItem("btc_highest_level_seen")||"0");if(levelUpReady&&lastLevelName&&lastLevelName!==t.name&&t.min>lastLevelMin&&t.min>o){showLevelUpCelebration(t),localStorage.setItem("btc_highest_level_seen",t.min.toString()),"function"==typeof notifySelfLevelUp&¬ifySelfLevelUp(t.min,t.name,t.emoji);var n=currentUser&¤tUser.username?currentUser.username:null,i=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:"";if(n&&"function"==typeof window.nachoGlobalAnnounce&&window.nachoGlobalAnnounce(t.emoji+" @"+n+" just leveled up to "+t.emoji+" "+t.name+"! Congrats! 🎉",i),"function"==typeof window.contributeSatoshiFavor){var a=t.name||"",r=null;["Pleb","Pleb II","Pleb III","Stacker","Stacker II","Stacker III"].includes(a)?r="level_up":["Maxi","Maxi II","Maxi III"].includes(a)?r="level_up_5":["Papa John","Full Node","Whale","Sovereign","Cypherpunk","Satoshi"].includes(a)&&(r="level_up_10"),r&&window.contributeSatoshiFavor(r,a)}}lastLevelName=t.name,lastLevelMin=t.min;const s=document.getElementById("rankBar");if(!s)return;let c="";t.next&&(c='
    '+(t.next.min-currentUser.points)+" XP to "+t.next.emoji+" "+t.next.name+"
    ");const l=auth.currentUser&&auth.currentUser.isAnonymous&¤tUser.username?'':"",d=currentUser.streak||0,u=d>0&&(d%7==0||30===d||100===d||365===d),p=currentUser.bestStreak||0,m=d>0||p>0?'🔥 '+d+(p>0?"("+p+")":"")+" day streak"+(u?" ✨":"")+"":"",g=(currentUser.orangeTickets||0)>0?''+currentUser.orangeTickets+"":"";s.innerHTML='
    '+t.emoji+" "+t.name+''+escapeHtml(currentUser.username||"Anon")+''+(currentUser.points||0).toLocaleString()+" XP"+m+g+"
    "+c+l,s.style.display="flex"}function getUserDisplayEmoji(e){var t=void 0!==currentUser&¤tUser?currentUser.displayBadge:null;if(t){if(void 0!==BADGE_DEFS)for(var o=0;o0?'🔥'+currentUser.streak+"":"",s=getUserDisplayEmoji(e);let c=document.getElementById("userDisplay");if(c||(c=document.createElement("div"),c.id="userDisplay",document.body.appendChild(c)),n||auth.currentUser&&auth.currentUser.isAnonymous&&!i){if(l=window.innerWidth<=900)return c.setAttribute("data-mob-hidden","1"),void(c.style.display="none");if("1"===sessionStorage.getItem("btc_signin_banner_dismissed"))return c.classList.add("user-hidden"),void(c.style.display="none");c.classList.remove("user-hidden"),c.setAttribute("data-anon","1"),l?c.style.cssText="position:fixed;bottom:70px;left:12px;right:12px;z-index:200;display:flex;align-items:center;gap:10px;padding:10px 16px;background:linear-gradient(135deg,#1a1a2e,#2d1f4e);border:2px solid #f7931a;border-radius:14px;box-shadow:0 4px 20px rgba(247,147,26,0.3);font-size:0.85rem;cursor:pointer;":((u=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((p=document.createElement("div")).id="userDisplayContainer",p.style.padding="0 20px 16px",p.style.borderBottom="1px solid var(--border)",u.parentNode.insertBefore(p,u.nextSibling),p.appendChild(c)),c.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:12px;background:rgba(247,147,26,0.05);border:1px solid rgba(247,147,26,0.2);border-radius:12px;cursor:default;transition:0.3s;width:100%;"),c.onclick=function(e){!l&&e.target.closest("button")||showSettingsPage("account")},c.innerHTML=(l?'':"")+'
    '+e.emoji+'GUEST'+a.toLocaleString()+" XP
    "+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
    ';return e&&(o+='
    $'+Math.round(e).toLocaleString()+"
    "),t&&(o+='⛓️ '+t.toLocaleString()+""),o+"
    "}()+(l?'
    Sign in to keep XP & enter giveaway!
    ':"")+"
    "+(l?"":'
    ')+(l?"":'
    SIGN UP
    ')+(l?'
    Sign Up →
    ':"")}else{c.removeAttribute("data-anon"),c.removeAttribute("data-mob-hidden");var l=window.innerWidth<=900,d=document.getElementById("dashboardFloatBtn");d||((d=document.createElement("div")).id="dashboardFloatBtn",d.onclick=function(){"function"==typeof toggleDashboard&&toggleDashboard()},document.body.appendChild(d)),d.style.cssText="position:fixed;bottom:10px;right:76px;z-index:200001;background:linear-gradient(135deg,#f97316,#eab308);color:#fff;border:none;border-radius:50%;width:48px;height:48px;font-size:1.4rem;cursor:pointer;font-family:inherit;box-shadow:0 4px 20px rgba(249,115,22,0.4);display:flex;align-items:center;justify-content:center;transition:0.2s;-webkit-transform:translateZ(0);transform:translateZ(0);",d.innerHTML="📊",d.title="Bitcoin Metrics";var u,p,m=document.getElementById("dashBtnCSS");if(m||((m=document.createElement("style")).id="dashBtnCSS",m.textContent="@media(max-width:900px){#dashboardFloatBtn{bottom:70px!important;right:72px!important;}}",document.head.appendChild(m)),l)return void(c.style.display="none");if(l)c.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:8px;padding:8px 14px;background:var(--bg-side);border:1px solid var(--border);border-radius:10px;font-size:0.8rem;cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,0.2);";else(u=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((p=document.createElement("div")).id="userDisplayContainer",p.style.padding="0 20px 16px",p.style.borderBottom="1px solid var(--border)",u.parentNode.insertBefore(p,u.nextSibling),p.appendChild(c)),c.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:10px;background:rgba(255,255,255,0.03);border:1px solid var(--border);border-radius:10px;cursor:pointer;width:100%;";c.onclick=function(e){e.target.closest("a")||showSettings()};var g,h=currentUser.username||auth.currentUser&&auth.currentUser.displayName||"Anon";g=currentUser.displayBadge?''+s+' '+e.emoji+"":''+e.emoji+"",c.innerHTML='
    '+g+''+escapeHtml(h)+""+(r?''+r+"":"")+"
    "+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
    ';return e&&(o+='
    $'+Math.round(e).toLocaleString()+"
    "),t&&(o+='⛓️ '+t.toLocaleString()+""),(o+=''+a.toLocaleString()+" XP")+"
    "}()+"
    "+(l?"":'
    ')}c.style.display="flex";const f=document.getElementById("mobileUserInfo");if(f&&window.innerWidth<=900){var y=s;currentUser.displayBadge&&(y+=" "+e.emoji),a=currentUser.points||0;var v=parseFloat(localStorage.getItem("btc_last_price"))||0,b=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(v=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(b=nachoLiveData.blockHeight);var w=''+y+" "+escapeHtml(currentUser.username||(n?"Anonymous":"Anon"))+"";v&&(w+=' $'+Math.round(v).toLocaleString()+""),b&&(w+=' ⛓️ '+b.toLocaleString()+""),w+=' '+a.toLocaleString()+" XP",f.innerHTML=w,f.style.display="inline",f.style.maxWidth="none"}const x=document.getElementById("welcomeBanner");if(x&¤tUser.username){updateAuthButton();const t=currentUser.streak||0,o=currentUser.bestStreak||0,n=t>0||o>0?' · 🔥 '+t+(o>0?"("+o+")":"")+" day streak":"";x.innerHTML=''+e.emoji+' Welcome back, '+escapeHtml(currentUser.username||"Anon")+'! · '+e.name+" · "+(currentUser.points||0).toLocaleString()+" XP"+n+'
    ⚙️ Tap here for Account & Settings
    ',x.style.display="block",x.removeAttribute("data-simplified-hidden")}}document.addEventListener("mousemove",trackActivity),document.addEventListener("keydown",trackActivity),document.addEventListener("touchstart",trackActivity,{passive:!0}),document.addEventListener("click",trackActivity),setInterval(trackScroll,2e3),window.toggleGuestPointsBanner=function(){var e=document.getElementById("guestPointsBanner");if(e){var t=!e.classList.contains("banner-min");e.classList.toggle("banner-min",t);try{localStorage.setItem("btc_signin_banner_min",t?"1":"0")}catch(e){}updateGuestPointsBanner()}};let lbAutoShown=!1;function showLeaderboardAuto(){lbAutoShown||(lbAutoShown=!0,document.getElementById("leaderboard").classList.contains("open")||toggleLeaderboard())}function expandLeaderboard(e){e&&e.stopPropagation(),document.querySelectorAll(".lb-extra").forEach(e=>e.style.display="flex");const t=document.getElementById("lbShowMore");t&&t.remove()}function minimizeLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}function hideLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}function _lbOutsideClose(e){var t=document.getElementById("leaderboard");if(t&&t.classList.contains("open")&&!t.classList.contains("minimized")&&!t.contains(e.target)){var o=document.getElementById("rankBar");if(!o||!o.contains(e.target)){var n=document.getElementById("lbFloatBtn");n&&n.contains(e.target)||document.getElementById("userProfileModal")||(t.classList.remove("open"),t.classList.remove("minimized"),n&&(n.style.display="flex"))}}}function applyOLEDTheme(){const e="true"===localStorage.getItem("btc_theme_oled"),t="light"!==document.body.getAttribute("data-theme");e&&t?document.body.classList.add("oled-theme"):document.body.classList.remove("oled-theme")}function _lbBadgeEmoji(e){var t=[],o="undefined"!=typeof Intl&&Intl.Segmenter?Array.from(new Intl.Segmenter("en",{granularity:"grapheme"}).segment(e)).map(function(e){return e.segment}):null;o?t=o:t=e.match(/\p{Emoji_Presentation}(\u200d\p{Emoji_Presentation})*/gu)||[e];if(t.length<=1)return e;var n=2===t.length?"0.6rem":"0.5rem";return''+t.map(function(e){return""+e+""}).join("")+""}async function toggleLeaderboard(){const e=document.getElementById("leaderboard");if(!e)return;const t=document.getElementById("lbFloatBtn");if(e.classList.contains("open")&&!e.classList.contains("minimized"))return e.classList.remove("open"),e.classList.remove("minimized"),void(t&&(t.style.display="flex"));if(e.classList.remove("minimized"),e.innerHTML='
    Loading leaderboard...
    ',e.classList.add("open"),t&&(t.style.display="none"),("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{window._sharedAudioCtx||(window._sharedAudioCtx=new(window.AudioContext||window.webkitAudioContext));var o=window._sharedAudioCtx;"suspended"===o.state&&o.resume();const e="undefined"!=typeof audioVolume?audioVolume:.5,t=o.currentTime,n=o.createOscillator(),i=o.createGain();n.connect(i),i.connect(o.destination),n.type="sine",n.frequency.setValueAtTime(200,t),n.frequency.exponentialRampToValueAtTime(800,t+.15),i.gain.setValueAtTime(.08*e,t),i.gain.exponentialRampToValueAtTime(.001,t+.2),n.start(t),n.stop(t+.2),[880,1175].forEach((n,i)=>{const a=o.createOscillator(),r=o.createGain();a.connect(r),r.connect(o.destination),a.type="triangle",a.frequency.value=n,r.gain.setValueAtTime(.1*e,t+.1+.08*i),r.gain.exponentialRampToValueAtTime(.001,t+.1+.08*i+.3),a.start(t+.1+.08*i),a.stop(t+.1+.08*i+.3)})}catch(e){}try{var n=Date.now(),i=window._lbCache&&window._lbCacheTime&&n-window._lbCacheTime<12e4;let t=[];i?t=window._lbCache:((await db.collection("users").orderBy("points","desc").limit(150).get()).forEach(e=>{const o=e.data(),n=auth.currentUser&&e.id===auth.currentUser.uid;o.points>0&&(!o.ghostMode||n)&&t.push({id:e.id,...o})}),window._lbCache=t,window._lbCacheTime=n);let o='
    🏆 Leaderboard — tap to expand
    ';o+='

    🏆 Leaderboard

    ',o+='
    ',Math.min(10,t.length),t.forEach((e,t)=>{const n=t+1,i=getLevel(e.points||0),a=auth.currentUser&&e.id===auth.currentUser.uid;a&¤tUser&&(e.points||0)>(currentUser.points||0)&&(currentUser.points=e.points,updateRankUI());const r=1===n?"🥇":2===n?"🥈":3===n?"🥉":"#"+n,s=n>10?' style="display:none;" class="lb-row lb-extra'+(a?" lb-me":"")+'"':' class="lb-row'+(a?" lb-me":"")+'"';var c="function"==typeof onlineStatusDot?onlineStatusDot(e.lastSeen):"";let l="";e.earnedHidden&&e.earnedHidden.includes("cert_scholar")&&(l+=" 🎓"),e.earnedHidden&&e.earnedHidden.includes("cert_tech")&&(l+=" 🛠️");var d=e.profilePic?'':"",u=JSON.stringify({recipientName:e.username||"Anon",recipientUid:e.id,lightningAddress:e.lightningAddress||e.lightning||"",context:"leaderboard",label:"Tip "+(e.username||"Anon")}).replace(/'/g,"'").replace(/"/g,"""),p=e.faction?window._factionNameStyle(e.faction):"";o+="'+r+''+_lbBadgeEmoji(i.emoji)+'"+(d?d+" ":"")+escapeHtml(e.username||"Anon")+c+l+''+(e.points||0).toLocaleString()+' XP
    '}),t.length>10&&(o+='"),o+="","function"==typeof getBadgeHTML&&(o+='

    Your Badges

    '+getBadgeHTML()+"
    "),o+='

    ⚔️ PVP Leaderboard

    Loading PVP rankings...
    ',o+='

    Levels

    ';for(const e of LEVELS)o+='
    '+e.emoji+" "+e.name+""+(0===e.min?"0 XP":e.min+"+ XP")+"
    ";o+="
    ",e.innerHTML=o,_loadPVPLeaderboard()}catch(t){console.error("[Leaderboard] Error:",t),e.innerHTML='
    Error loading leaderboard: '+(t.message||"Unknown error")+"
    "}}async function _loadPVPLeaderboard(){var e=document.getElementById("pvpLeaderboardList");if(e)try{var t,o,n=Date.now();window._pvpLbCache&&window._pvpLbCacheTime&&n-window._pvpLbCacheTime<3e5?(t=window._pvpLbCache.wins,o=window._pvpLbCache.losses):([t,o]=await Promise.all([db.collection("users").where("pvpWins",">",0).orderBy("pvpWins","desc").limit(50).get(),db.collection("users").where("pvpLosses",">",0).orderBy("pvpLosses","desc").limit(50).get()]),window._pvpLbCache={wins:t,losses:o},window._pvpLbCacheTime=n);var i={},a=auth.currentUser?auth.currentUser.uid:null;function r(e){if(!i[e.id]){var t=e.data();if(!t.ghostMode||e.id===a){var o=t.pvpWins||0,n=t.pvpLosses||0,r=o+n;if(0!==r){var s=r>0?o/r*100:0;i[e.id]={id:e.id,username:escapeHtml(t.username||"Anon"),wins:o,losses:n,total:r,winRate:s,isMe:e.id===a,lightningAddress:t.lightningAddress||t.lightning||""}}}}}t.forEach(r),o.forEach(r);var s=Object.values(i);if(0===s.length)return void(e.innerHTML='
    No PVP battles yet — be the first to compete!
    ');s.sort(function(e,t){return t.winRate-e.winRate||t.wins-e.wins});var c="";s.forEach(function(e,t){var o=t+1,n=1===o?"🥇":2===o?"🥈":3===o?"🥉":"#"+o,i=e.wins>=100?"👑":e.wins>=50?"🏆":e.wins>=25?"🏟️":e.wins>=5?"🥊":"⚔️",a=o>10?' style="display:none;" class="lb-row pvp-lb-extra'+(e.isMe?" lb-me":"")+'"':' class="lb-row'+(e.isMe?" lb-me":"")+'"',r=JSON.stringify({recipientName:e.username,recipientUid:e.id,lightningAddress:e.lightningAddress,context:"pvp",label:"Tip "+e.username}).replace(/'/g,"'").replace(/"/g,""");c+="'+n+''+i+''+e.username+''+e.wins+"W – "+e.losses+'L'}),s.length>10&&(c+=""),e.innerHTML=c||'
    No PVP battles yet!
    '}catch(l){e.innerHTML='
    No PVP battles yet — be the first to compete!
    '}}document.addEventListener("mousedown",_lbOutsideClose,!0),document.addEventListener("touchstart",_lbOutsideClose,!0),window.toggleOLEDTheme=function(){const e="true"===localStorage.getItem("btc_theme_oled");localStorage.setItem("btc_theme_oled",!e),applyOLEDTheme(),showSettingsPage("prefs"),showToast(e?"Deep sea mode disabled":"🖤 Midnight OLED enabled!")},document.addEventListener("DOMContentLoaded",applyOLEDTheme),window.showDeleteAccountConfirm=function(){var e=document.createElement("div");e.id="deleteAccountOverlay",e.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;",e.onclick=function(t){t.target===e&&e.remove()};var t=currentUser&¤tUser.username?currentUser.username:"your account",o=currentUser&¤tUser.points||0,n=currentUser&¤tUser.streak||0;e.innerHTML='
    ⚠️

    Delete Your Account?

    This will permanently delete everything associated with '+escapeHtml(t)+':
    '+o.toLocaleString()+" XP and all badges
    "+(n>0?"
    "+n+"-day streak
    ":"")+'
    ❌ All forum posts and replies
    ❌ Marketplace listings
    ❌ DM conversations
    ❌ Nacho chat history
    ❌ Leaderboard ranking
    ❌ Orange Tickets and quest progress
    ⚠️ This action is IRREVERSIBLE. There is no undo.
    ',document.body.appendChild(e)},window.confirmDeleteAccount=async function(){var e=document.getElementById("deleteConfirmInput");if(e&&"DELETE"===e.value){var t=document.getElementById("deleteConfirmBtn");t&&(t.disabled=!0,t.textContent="Deleting...");try{var o=auth.currentUser;if(!o)throw new Error("Not signed in");var n=o.uid;try{await db.collection("users").doc(n).delete()}catch(e){console.warn("User doc delete failed:",e)}try{var i=await db.collection("forum_posts").where("authorId","==",n).get(),a=db.batch();i.forEach(function(e){a.delete(e.ref)}),i.empty||await a.commit()}catch(e){console.warn("Forum posts delete failed:",e)}try{var r=await db.collection("forum_replies").where("authorId","==",n).get(),s=db.batch();r.forEach(function(e){s.delete(e.ref)}),r.empty||await s.commit()}catch(e){console.warn("Forum replies delete failed:",e)}try{var c=await db.collection("marketplace").where("sellerUid","==",n).get(),l=db.batch();c.forEach(function(e){l.delete(e.ref)}),c.empty||await l.commit()}catch(e){console.warn("Marketplace delete failed:",e)}try{var d=await db.collection("conversations").where("participants","array-contains",n).get(),u=db.batch();d.forEach(function(e){u.delete(e.ref)}),d.empty||await u.commit()}catch(e){console.warn("DM delete failed:",e)}try{var p=await db.collection("suggestions").where("uid","==",n).get(),m=db.batch();p.forEach(function(e){m.delete(e.ref)}),p.empty||await m.commit()}catch(e){console.warn("Suggestions delete failed:",e)}for(var g=[],h=0;hclick to ask!'),document.querySelectorAll('[id*="nachoCloset"]').forEach(function(t){var o=t.querySelector('[style*="letter-spacing"]');o&&-1!==o.textContent.indexOf("'s Closet")&&(o.textContent="🦌 "+e+"'s Closet")}),document.querySelectorAll('[style*="font-weight:800"]').forEach(function(t){-1!==t.textContent.indexOf("'s Story")&&(t.textContent=e+"'s Story")})}};var _toastQueue=[];function showToast(e,t){window._directLinkMode||(window._nachoBusy?_toastQueue.push({msg:e,duration:t}):_showToastNow(e,t))}function _showToastNow(e,t){var o=t||2500;const n=document.createElement("div");n.className="rank-toast";var i="object"==typeof e?e.msg:e;n.innerHTML=i.replace(/<(script|svg|img|iframe|object|embed|form|input|link|style|meta|base)[^>]*>/gi,"").replace(/on\w+\s*=/gi,"data-blocked="),"object"==typeof e&&e.duration&&(o=e.duration),document.body.appendChild(n),requestAnimationFrame(()=>n.classList.add("show")),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>n.remove(),400)},o)}function showUsernamePrompt(){try{if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)return void showAccountInfo();if(currentUser&¤tUser.username)return void showAccountInfo();if(!redirectResultResolved)return showToast("⏳ Loading account..."),void redirectResultPromise.then(function(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous||currentUser&¤tUser.username?showAccountInfo():(document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash))});document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash)}catch(e){"function"==typeof showToast&&showToast("Settings error: "+e.message),console.error("showUsernamePrompt error:",e)}}function showAccountInfo(){showSettingsPage("account")}setInterval(function(){!window._nachoBusy&&_toastQueue.length>0&&_showToastNow(_toastQueue.shift())},2e3),window.showSignInOnly=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)showAccountInfo();else{var e=document.getElementById("usernameModal");e&&(e.classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash),setTimeout(function(){var t=e.querySelector(".username-box");if(t){var o=t.querySelector("h2"),n=t.querySelector("p"),i=document.getElementById("usernameInput"),a=document.getElementById("emailInput"),r=document.getElementById("giveawaySection"),s=t.querySelector('button[onclick="submitUsername()"]'),c=a?a.nextElementSibling:null;c&&"P"===c.tagName&&(c.style.display="none"),o&&(o.style.display="none"),n&&(n.style.display="none"),i&&(i.style.display="none"),a&&(a.style.display="none"),r&&(r.style.display="none"),s&&(s.style.display="none");var l=r?r.nextElementSibling:null;l&&"SCRIPT"===l.tagName&&(l.style.display="none");var d=document.getElementById("signInOnlyHeader");d||((d=document.createElement("div")).id="signInOnlyHeader",d.innerHTML='
    🔐

    Welcome Back!

    Sign in to your account

    ',t.insertBefore(d,t.firstChild));var u=document.getElementById("emailSignInSection");if(u){var p=u.querySelector("p");p&&(p.innerHTML='Sign in with your email:')}var m=document.getElementById("signInOnlyNewHere");if(!m){(m=document.createElement("div")).id="signInOnlyNewHere",m.innerHTML='
    ';var g=t.querySelector(".skip");g?t.insertBefore(m,g):t.appendChild(m)}}},50))}},window._restoreSignUpForm=function(){var e=document.getElementById("usernameModal");if(e){var t=e.querySelector(".username-box");if(t){var o=document.getElementById("signInOnlyHeader");o&&o.remove();var n=document.getElementById("signInOnlyNewHere");n&&n.remove();var i=t.querySelector("h2"),a=t.querySelector("p"),r=document.getElementById("usernameInput"),s=document.getElementById("emailInput"),c=document.getElementById("giveawaySection"),l=t.querySelector('button[onclick="submitUsername()"]'),d=s?s.nextElementSibling:null;d&&"P"===d.tagName&&(d.style.display=""),i&&(i.style.display=""),a&&(a.style.display=""),r&&(r.style.display=""),s&&(s.style.display=""),c&&(c.style.display=""),l&&(l.style.display="");var u=document.getElementById("emailSignInSection");if(u){var p=u.querySelector("p");p&&(p.innerHTML="Already have an account? Sign in with your email:")}}}};let settingsTab="account";function shortcutRow(e,t){return'
    '+e+'
    '+t+"
    "}function showSettingsPage(e){try{settingsTab=e||"account";const Ye=document.getElementById("usernameModal"),Je=Ye.querySelector(".username-box");if(!Ye)return void("function"==typeof showToast&&showToast("Error: modal not found"));if(!Je)return void("function"==typeof showToast&&showToast("Error: username-box not found"));const Xe=void 0!==auth&&auth?auth.currentUser:null;if(!Xe)return void Ye.classList.add("open");const Ke=getLevel(currentUser&¤tUser.points||0);let $e="";if($e+='
    ',["account","scholar","sats","prefs","security","data"].forEach(e=>{const t=settingsTab===e;$e+=""}),$e+="
    ","account"===settingsTab){var t=Xe.isAnonymous,o=getUserDisplayEmoji(Ke),n=currentUser&¤tUser.profilePic||"",i=n?'':'
    '+o+"
    ";$e+='
    '+i+'
    '+(currentUser&¤tUser.username||"Bitcoiner")+'
    '+Ke.name+" · "+(currentUser&¤tUser.points||0).toLocaleString()+" XP"+(currentUser&¤tUser.faction?" · "+("cyber_hornets"===currentUser.faction?"🐝 Cyber Hornets":"🦡 Honey Badgers"):"")+"
    ";var a=currentUser&¤tUser.country||"";$e+='
    🌍 Country
    Optional · Shown on your public profile
    ';var r=currentUser&¤tUser.faction||"";$e+='
    ⚔️ Faction
    Choose your allegiance! New faction features coming soon — no competitive advantage to either choice.
    🐝
    Cyber Hornets
    The swarm protects the network
    '+("cyber_hornets"===r?'
    ✓ Joined
    ':"")+'
    🦡
    Honey Badgers
    Honey badger don\'t care
    '+("honey_badgers"===r?'
    ✓ Joined
    ':"")+"
    ",$e+='
    📷 Profile Picture
    '+(n?'':'
    👤
    ')+'
    "+(n?' ':"")+'
    Square image recommended · Max 2MB
    ';var s="",c='
    Account Details
    ';Xe.email&&(c+='
    Email'+Xe.email+"
    "),Xe.displayName&&(c+='
    Name'+Xe.displayName+"
    ");let Ze="Anonymous";if(Xe.providerData&&Xe.providerData.length>0){const et=Xe.providerData[0].providerId;"google.com"===et?Ze="Google":"twitter.com"===et?Ze="Twitter/X":"github.com"===et?Ze="GitHub":"facebook.com"===et?Ze="Facebook":"password"===et&&(Ze="Email")}if(c+='
    Sign-in method'+Ze+"
    ",currentUser&¤tUser.created&&(c+='
    Member since'+(currentUser.created.toDate?currentUser.created.toDate().toLocaleDateString():new Date(currentUser.created).toLocaleDateString())+"
    "),s+=c+="
    ",!t){var l=currentUser&¤tUser.displayBadge||"",d=[];void 0!==earnedBadges&&void 0!==BADGE_DEFS&&BADGE_DEFS.forEach(function(e){earnedBadges.has(e.id)&&d.push({id:e.id,emoji:e.emoji,name:e.name})});var u=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]");if(void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){-1!==u.indexOf(e.id)&&d.push({id:e.id,emoji:e.hidden&&e.revealEmoji||e.emoji,name:e.hidden&&e.revealName||e.name})}),d.length>0){var p=Ke.emoji+" Rank (default)";if(l){var m=d.find(function(e){return e.id===l});m&&(p=m.emoji+" "+m.name)}if(s+='
    🏅 Display Badge
    '+p+'
    '+(window._expanded_badges?"▾":"▸")+"
    ",window._expanded_badges){s+='
    Choose a badge to show next to your name instead of your rank emoji.
    ',s+='
    '+Ke.emoji+'
    '+Ke.name+' (Default)
    Your current rank emoji
    '+(l?"":'')+"
    ";for(var g=0;g'+h.emoji+'
    '+h.name+"
    "+(f?'':"")+"
    "}s+="
    "}s+="
    "}}s+='
    ✏️ Change Username
    Current username: '+(currentUser&¤tUser.username||"")+'
    ',s+='';var y=currentUser&¤tUser.bio||"",v=[],b=[];[{k:"website",e:"🌐",l:"Website",p:"https://yoursite.com",m:100,t:"url"},{k:"twitter",e:"𝕏",l:"Twitter/X",p:"@yourusername",m:30},{k:"nostr",e:"🟣",l:"Nostr",p:"npub... or NIP-05",m:80},{k:"instagram",e:"📸",l:"Instagram",p:"@yourusername",m:30},{k:"tiktok",e:"🎵",l:"TikTok",p:"@yourusername",m:30},{k:"github",e:"🐙",l:"GitHub",p:"yourusername",m:40},{k:"contactEmail",e:"📧",l:"Email",p:"you@example.com",m:80,t:"email",note:"public"},{k:"lightning",e:"⚡",l:"Lightning",p:"you@walletofsatoshi.com",m:80}].forEach(function(e){currentUser&¤tUser[e.k]?v.push(e):b.push(e)}),$e+='
    📝 Public Profile
    Visible when someone clicks your name on the leaderboard
    ",$e+='
    🔗 Links & Socials
    ',$e+='
    ',v.forEach(function(e){var t=currentUser&¤tUser[e.k]||"";$e+=''}),$e+="
    ",b.length>0&&($e+='
    "),$e+='
    ',currentUser&&(currentUser.lightning||currentUser.lightningAddress)||($e+='
    Connect a Lightning Wallet
    Tip other users and receive tips from the community!
    '),$e+="",$e+='",$e+=''}else if("_artist_removed"===settingsTab){var w=currentUser&¤tUser.artistProfile||{};void 0!==db&&auth&&auth.currentUser&&auth.currentUser.uid,$e+='
    🎸
    Artist Profile
    Set up your artist presence on Bitcoin Beats
    ',$e+='
    🎤 Stage Name
    Shows on your tracks and artist page. Leave blank to use your username.
    ',$e+='
    📝 Artist Bio
    Music-specific bio. Your general bio is in Account tab.
    ',$e+='
    🎵 Genres
    Comma-separated. Shows as tags on your artist page.
    ',$e+='
    🔗 Music Links
    🌊
    🟢
    🎵
    📺
    🔗
    ',$e+='
    Lightning Tips
    '+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?"✅ Lightning Address set: "+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ No Lightning Address set. Go to Account tab or set up in ⚡ Wallet to receive tips!")+"
    ",$e+='',$e+="'}else if("scholar"===settingsTab){$e+='
    🎓
    Bitcoin Scholar

    Master Bitcoin through quests, certifications, and flashcards.

    ',$e+='
    Channel Quests

    Test your knowledge on any Bitcoin topic with guided quiz questions.

    ';var x="true"===localStorage.getItem("btc_scholar_prop_passed");$e+='
    '+(x?"✅":"📜")+'
    Bitcoin Scholar Certification

    25 questions on the economic properties and scarcity of Bitcoin. 80% to pass. One attempt per day.

    ";var k="true"===localStorage.getItem("btc_scholar_tech_passed");$e+='
    '+(k?"✅":"🛠️")+'
    Bitcoin Protocol Expert

    25 questions on highly technical topics: BIPs, Script, SegWit, Taproot, and Networking.

    ",$e+="

    Prepare for quests and exams with interactive flashcards.

    ",[{name:"Bitcoin Basics",emoji:"₿"},{name:"Security & Storage",emoji:"🔑"},{name:"Lightning Network",emoji:"⚡"},{name:"Mining & Energy",emoji:"⛏️"},{name:"Economics & Money",emoji:"💰"},{name:"History & Culture",emoji:"📜"},{name:"Privacy & Sovereignty",emoji:"🕵️"},{name:"Nodes & P2P",emoji:"📡"},{name:"Wallets & Tools",emoji:"💼"},{name:"Common Myths",emoji:"🚫"},{name:"Austrian Economics",emoji:"🇦🇹"},{name:"Cypherpunk History",emoji:"🔐"},{name:"Bitcoin Governance",emoji:"🏛️"},{name:"Satoshi Nakamoto",emoji:"🦸"},{name:"Global Impact",emoji:"🌍"},{name:"El Salvador & Adoption",emoji:"🇸🇻"},{name:"Technical Deep Dives",emoji:"🔬"}].forEach(function(e){$e+=""}),$e+="
    ",$e+="",$e+='"}else if("signal"===settingsTab){var B;$e+='
    📡
    The Weekly Signal

    Curated Bitcoin insights and site updates.

    ',T=null===(B=localStorage.getItem("btc_ticker_enabled"))?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===B,$e+="
    📊Live Ticker on Home
    ",$e+='
    📡 Live Signals
    ',$e+='
    ',$e+="",$e+='
    📚 Featured Deep Dives
    ',[{date:"Feb 26, 2026",title:"Why Proof of Stake is just Fiat 2.0",snippet:"Most cryptos claim to be better than Bitcoin because they use less energy. But Gigi explains why energy IS the point — PoW converts real-world resources into unforgeable security.",channel:"pow-vs-pos"},{date:"Feb 19, 2026",title:"The Great Definancialization",snippet:"Parker Lewis breaks down why we don't need thousands of stocks, bonds, and derivatives if we have one form of hard money that can't be debased.",channel:"problems-of-money"},{date:"Feb 12, 2026",title:"The 21 Million Cap is Inviolate",snippet:"Why even if every miner in the world wanted to change the supply, they couldn't. The users run the rules.",channel:"scarce"},{date:"Feb 5, 2026",title:"Not Your Keys, Not Your Coins",snippet:"After another exchange collapse, the importance of self-custody has never been clearer. Here's how to take control.",channel:"self-custody"},{date:"Jan 29, 2026",title:"The Halving: Scarcity You Can Verify",snippet:"Every 210,000 blocks, the supply issuance gets cut in half. No vote. No committee. Just code.",channel:"difficulty-adjustment"}].forEach(function(e){$e+='
    '+e.date.toUpperCase()+'
    '+e.title+'
    '+e.snippet+"
    '}),setTimeout(function(){var e=document.getElementById("signalLiveNews");e&&fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=(e.snippet||"").replace(/<[^>]+>/g,""),a=e.link||"";n+='
    SIGNAL #'+(t+1)+''+(e.date||"").toUpperCase()+'
    '+o+"
    "+(i?'
    '+i+"
    ":"")+(a?'
    Read full article →
    ':"")+"
    "}),o.innerHTML=n;var i=function(){var t=document.getElementById("signalArrowL"),o=document.getElementById("signalArrowR");t&&o&&(e.scrollWidth>e.clientWidth+10?(t.style.display=e.scrollLeft>10?"flex":"none",o.style.display=e.scrollLeft+e.clientWidth✅ You\'re subscribed to The Signal!':'
    📧
    Get The Signal via Email

    Weekly curated Bitcoin insights. No spam, pure signal.

    '}else if("tickets"===settingsTab){const tt=!Xe||Xe.isAnonymous;tt?$e+='
    Orange Tickets
    Sign in with Google, Twitter, or GitHub to start earning Orange Tickets and get your referral link!
    ':($e+="function"==typeof renderTicketsSection?renderTicketsSection():"",$e+="function"==typeof renderReferralSection?renderReferralSection():"",$e+='
    How to Earn Tickets
    📅 Daily Login: +1 ticket just for visiting.
    🎡 Spin the Wheel: Spin daily for bonus tickets!
    👥 Referrals: Earn 50 tickets per friend who signs up and reaches Maxi rank (2,140+ pts). Verified automatically.
    🏅 Badges: Unlock at 25 🐟, 50 🦈, and 100 🐋 tickets.
    ⭐ Bonus: Each ticket = +5 XP towards your rank.
    🏆 Giveaways: More tickets = higher chance of winning sats!
    '),tt||"function"!=typeof loadReferralStatsUI||setTimeout(loadReferralStatsUI,100)}else if("sats"===settingsTab){var _=window._satsSubTab||"claim",I=(t=Xe.isAnonymous,currentUser&¤tUser.points||0),C=currentUser&¤tUser.pointsClaimed||0,E=currentUser&¤tUser.pointsDonated||0,A=I-C,M=currentUser&¤tUser.satsWithdrawn||0,z=Math.floor(Math.max(0,A)/10),L="function"==typeof getSatCap?getSatCap():1e4,P=Math.max(0,L-M),U=Math.min(z,500,P),N=currentUser&¤tUser.lastSatsClaim||null,H=N?new Date(N.seconds?1e3*N.seconds:N).getTime()+864e5:0,q=Date.now(),D=N&&qR&&(R=F.length)}catch(ot){}var W=Xe.metadata&&Xe.metadata.creationTime?new Date(Xe.metadata.creationTime):null,V=W?Math.floor((q-W.getTime())/864e5):0,G=Xe.email&&Xe.emailVerified,Q=!t&&G&&V>=7&&R>=10,Y=z>=100;if($e+='
    ',$e+='',$e+='',$e+="
    ","donate"!==_){$e+='
    ',$e+='
    ',$e+='
    Claim Real Sats
    ',$e+='
    Earn XP → Convert to real Bitcoin over Lightning
    ',$e+="
    ",$e+='
    ',$e+='
    Your Balance
    ',$e+='
    ⚡ '+z.toLocaleString()+" claimable sats
    ",$e+='
    '+A.toLocaleString()+" unclaimed XP of "+I.toLocaleString()+" total
    ",$e+='
    Lifetime withdrawn: '+M.toLocaleString()+" / 10,000 sats
    ",$e+="
    ",$e+=!t&&Q&&Y&&!D&&U>=100?'":D?'
    ⏳ Next claim in '+O+"
    ":!Y&&Q?'
    Need '+(100-z)+" more sats ("+10*(100-z)+" XP) to reach minimum claim
    ":'
    Complete requirements below to claim
    ',$e+='
    ',$e+='
    📋 Requirements
    ',[{met:!t,label:"Signed in (not anonymous)",detail:t?"Sign in with email, Google, etc.":"✓ Signed in"},{met:G,label:"Email verified",detail:G?"✓ "+Xe.email:"Link & verify your email in Account tab"},{met:V>=7,label:"Account age ≥ 7 days",detail:V>=7?"✓ "+V+" days old":V+"/7 days — "+(7-V)+" more to go"},{met:R>=10,label:"Read ≥ 10 topics",detail:R>=10?"✓ "+R+" topics read":R+"/10 topics — read "+(10-R)+" more"},{met:Y,label:"Minimum 100 sats (1,000 pts)",detail:Y?"✓ "+z+" sats available":z+"/100 sats — earn "+10*(100-z)+" more XP"}].forEach(function(e){$e+='
    ',$e+=''+(e.met?"✅":"⬜")+"",$e+='
    '+e.label+"
    ",$e+='
    '+e.detail+"
    "}),$e+="
    ",$e+='
    ',$e+='
    ⚡ How It Works
    ',$e+='
    ',$e+="• 1,000 XP = 100 sats — earn XP by reading, quests, and daily visits
    ",$e+="• Min claim: 100 sats (1,000 XP)
    ",$e+="• Max claim: 500 sats/day
    ",$e+="• 1 claim per 24 hours
    ",$e+="• Lifetime max: 10,000 sats per account
    ",$e+="• Daily XP cap: 500 XP (50 sats worth) to prevent abuse
    ",$e+="• Unclaimed sats roll over — no expiration
    ",$e+="• Payouts via Lightning Network ⚡
    ",$e+="
    ",$e+='
    ',$e+="💚 Zero fees for you! We pay all Lightning network fees so you receive the full amount you claim. You earned it!",$e+="
    ",$e+='
    ',$e+="",$e+='
    ",$e+='
    ',$e+='
    📜 Withdrawal History
    ',$e+='
    Loading...
    ',$e+="
    ";var X=currentUser&&(currentUser.lightning||currentUser.lightningAddress)||"";$e+='
    ',$e+='
    Lightning Address
    For receiving tips from other users
    ',X&&($e+='
    '+escapeHtml(X)+"
    "),$e+='
    ',$e+='
    ',X||($e+='
    💡 Get one from Wallet of Satoshi, Alby, Coinos, or Strike.
    '),$e+="
    "}else{var K=Math.max(0,I-C-E);r=currentUser&¤tUser.faction||"",$e+='
    ',$e+='
    ❤️
    ',$e+='
    Donate XP for Charity
    ',$e+='
    1,000 XP = 1,000 sats donated — 10× more impact than claiming
    ',$e+="
    ",$e+='
    ',$e+='
    Available to Donate
    ',$e+='
    ❤️ '+K.toLocaleString()+" XP
    ",$e+='
    '+I.toLocaleString()+" total − "+C.toLocaleString()+" claimed − "+E.toLocaleString()+" donated
    ",$e+="
    ",t?$e+='
    🔐 Sign in to donate XP
    ':r?($e+='
    ',[5,10,25,50,100].forEach(function(e){var t=Math.floor(K*e/100);$e+='"}),$e+="
    ",$e+='
    ',$e+='',$e+="
    ",$e+='
    ',$e+='',$e+="
    ",$e+='',E>0&&($e+='
    '+E.toLocaleString()+" XP already donated — thank you! ❤️
    ")):($e+='
    ',$e+='
    ⚔️
    ',$e+='
    Choose Your Faction First
    ',$e+='
    Your faction’s donation total is tracked for the community leaderboard.
    ',$e+='',$e+="
    "),$e+='
    ',$e+='',$e+='',$e+="
    "}}else if("prefs"===settingsTab){const nt="light"!==document.body.getAttribute("data-theme"),it="true"===localStorage.getItem("btc_theme_oled"),at=localStorage.getItem("btc_font_size")||"medium";$e+="
    🎨 Appearance
    Theme
    Font Size
    ',["small","medium","large"].forEach(function(e){var t=at===e,o=e.charAt(0).toUpperCase()+e.slice(1);$e+=""}),$e+="
    ",$e+='
    🌐 Language
    Translate the site to your preferred language
    ',setTimeout(function(){const e=document.getElementById("langSelect"),t=localStorage.getItem("btc_lang")||"";e&&(e.value=t)},50);const rt="undefined"==typeof audioEnabled||audioEnabled,st="undefined"!=typeof audioVolume?audioVolume:.5;$e+='
    🔊 Sound
    Sound Effects
    Volume
    ',$e+="",$e+='"}else $e+=""}var Fe=localStorage.getItem("btc_nacho_nickname")||"Nacho";if($e+='
    🏷️ Name Your Buck
    Currently: '+escapeHtml(Fe)+'
    ',"function"==typeof getNachoStoryProgress){var We=getNachoStoryProgress(),Ve=We>=10,Ge=escapeHtml(Fe);$e+='
    📖
    '+Ge+'\'s Story
    '+(Ve?"✅ Complete!":"A new chapter unlocks every day!")+'
    '+We+'/10
    "}"function"==typeof renderNachoClosetUI&&(void 0===window._expanded_closet&&(window._expanded_closet=!1),window._pendingClosetScroll&&(window._expanded_closet=!0),$e+='
    👗 '+escapeHtml(Fe)+'\'s Closet
    '+(window._expanded_closet?"▾":"▸")+"
    ",window._expanded_closet&&($e+='
    '),$e+="
    "),"function"==typeof renderStickerBook&&($e+='
    🎨 Sticker Book
    '+(window._expanded_stickers?"▾":"▸")+"
    ",window._expanded_stickers&&($e+='
    '+renderStickerBook()+"
    "),$e+="
    "),$e+='
    🔒 Privacy
    We do not sell, share, or monetize your data. Ever.
    The only data we store is your username, points, and progress — just enough to power your experience. No tracking, no ads, no third-party analytics. Your data is yours.
    ',$e+="",$e+='",$e+="",$e+='"}if($e+='Close',Je.innerHTML=$e,Ye.classList.add("open"),"sats"===settingsTab&&"function"==typeof loadSatsHistory&&setTimeout(loadSatsHistory,100),"sats"===settingsTab&&(window._toggleSatsCharityNote=function(){var e=document.getElementById("satsCharityNote"),t=document.getElementById("satsCharityNoteArrow");if(e){var o="none"!==e.style.display;e.style.display=o?"none":"block",t&&(t.textContent=o?"▼":"▲")}},window._satsCharitySetAmt=function(e){var t=document.getElementById("satsCharityAmtInput");t&&(t.value=e>0?e:"")},window._satsCharitySubmit=function(){if("undefined"!=typeof firebase&&firebase.functions){var e=document.getElementById("satsCharityAmtInput"),t=parseInt(e?e.value:"")||0,o=void 0!==currentUser&¤tUser?Math.max(0,(currentUser.points||0)-(currentUser.pointsClaimed||0)-(currentUser.pointsDonated||0)):0;if(!t||t<1)"function"==typeof showToast&&showToast("Enter a valid amount");else if(t>o)"function"==typeof showToast&&showToast("Not enough available XP ("+o.toLocaleString()+" available)");else{var n=!!document.getElementById("satsCharityAnonToggle")&&document.getElementById("satsCharityAnonToggle").checked,i=document.querySelector('[onclick="window._satsCharitySubmit()"]');i&&(i.disabled=!0,i.textContent="Donating..."),firebase.functions().httpsCallable("donatePoints")({amount:t,anonymous:n}).then(function(e){void 0!==currentUser&¤tUser&&(currentUser.pointsDonated=(currentUser.pointsDonated||0)+t,e.data&&e.data.bonusPts&&(currentUser.points=(currentUser.points||0)+e.data.bonusPts));var o=e.data&&e.data.newBadges&&e.data.newBadges.length>0?" +"+e.data.newBadges.length+" badge"+(e.data.newBadges.length>1?"s":"")+" unlocked!":"";"function"==typeof showToast&&showToast("❤️ Thank you! "+t.toLocaleString()+" XP donated ("+t.toLocaleString()+" sats pledged to charity)."+o,5e3),"function"==typeof window._charityThankYou&&window._charityThankYou(t,e.data&&e.data.newBadges||[],e.data&&e.data.bonusPts||0);var n=e.data&&e.data.newBadges||[];if(n.length>0&&"function"==typeof window.contributeSatoshiFavor){var i={donor_100:"🤷 Giving Pleb",donor_500:"💛 Stack Sharer",donor_1000:"🧡 Community Builder",donor_5000:"❤️ Archive Patron",donor_10000:"🔥 Sats Saint",donor_25000:"⚡ Lightning Philanthropist",donor_50000:"🏆 Satoshi's Steward",donor_100000:"👑 Legend of the Archive"};n.forEach(function(e){i[e]&&window.contributeSatoshiFavor("badge_earned",i[e]).catch(function(){})})}void 0!==window._charityStatsLoaded&&(window._charityStatsLoaded=!1),showSettingsPage("sats")}).catch(function(e){i&&(i.disabled=!1,i.textContent="❤️ Donate XP for Charity"),"function"==typeof showToast&&showToast("❌ "+(e.message||"Donation failed. Try again."),4e3)})}}}),"data"===settingsTab&&"function"==typeof loadReferralStatsUI&&Xe&&!Xe.isAnonymous&&setTimeout(loadReferralStatsUI,100),"data"===settingsTab&&"function"==typeof renderNachoClosetUI){var Qe=document.getElementById("nachoClosetContainer");Qe&&(renderNachoClosetUI(Qe),window._pendingClosetScroll&&setTimeout(function(){Qe.scrollIntoView({behavior:"smooth",block:"center"}),window._pendingClosetScroll=!1},300))}}catch(Bt){"function"==typeof showToast&&showToast("Settings page error: "+Bt.message),console.error("showSettingsPage error:",Bt)}}function changeLanguage(e){const t=document.getElementById("langStatus");if(!e){const e=document.querySelector(".goog-te-banner-frame");e&&e.remove();var o=document.querySelector("iframe.goog-te-banner-frame");o&&o.remove();var n=document.querySelector(".skiptranslate");return n&&n.remove(),document.body.style.top="",document.body.style.position="",document.documentElement.style.overflow="",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=."+location.hostname,localStorage.setItem("btc_lang",""),t&&(t.innerHTML='✅ Switched to English'),document.documentElement.classList.remove("translated-ltr","translated-rtl"),document.querySelectorAll('font[style*="vertical-align: inherit"]').forEach(function(e){var t=e.parentNode;t&&t.replaceChild(document.createTextNode(e.textContent),e)}),void setTimeout(function(){showSettingsPage("prefs")},200)}if(localStorage.setItem("btc_lang",e),document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname,t&&(t.innerHTML='Translating...'),document.getElementById("gtranslate"))triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!');else{const o=document.createElement("script");o.id="gtranslate",o.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(o),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget"),setTimeout(()=>{triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!')},1500)};const n=document.createElement("div");n.id="gtranslateWidget",n.style.display="none",document.body.appendChild(n)}}function triggerGoogleTranslate(e){const t=document.querySelector(".goog-te-combo");t&&(t.value=e,t.dispatchEvent(new Event("change")))}function setFontSize(e){localStorage.setItem("btc_font_size",e);const t="small"===e?"14px":"medium"===e?"16px":"18px";document.documentElement.style.fontSize=t,showSettingsPage("prefs")}async function saveProfile(){var e=document.getElementById("profileStatus");if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in with Google, Facebook, Twitter, or email to save your profile!"),e&&(e.innerHTML='🔒 Create a free account to save your profile'),void("function"==typeof showUsernamePrompt&&setTimeout(showUsernamePrompt,1500));var t=auth.currentUser.uid,o=document.getElementById("profileBio")?document.getElementById("profileBio").value.trim():"",n=document.getElementById("countryInput"),i=n?n.value.trim().substring(0,60):"";if(i&&window._countryList&&-1===window._countryList.indexOf(i))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void n.focus();var a={bio:o,country:i};["website","twitter","nostr","instagram","tiktok","github","contactEmail","lightning"].forEach(function(e){var t,o=document.getElementById("profile_"+e);if(o){var n=o.value.trim();"lightning"===e?(n=n.replace(/[\\'"<>]/g,""))&&!n.match(/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)&&(n=""):n="contactEmail"===e||"nostr"===e?n.replace(/[\\'"<>]/g,""):(t=n)?(t=t.trim(),/^(javascript|data|vbscript|blob):/i.test(t)?"":t):"",a[e]=n}else currentUser&&void 0!==currentUser[e]&&(document.querySelector('.pf-link-row[data-key="'+e+'"]')||(a[e]=""))});try{e&&(e.innerHTML='Saving...'),await db.collection("users").doc(t).update(a),Object.assign(currentUser,a),e&&(e.innerHTML='✅ Profile saved!'),"function"==typeof showToast&&showToast("✅ Profile saved successfully!"),setTimeout(function(){e&&(e.innerHTML=""),showSettingsPage("account")},1500)}catch(t){console.error("Error saving profile:",t),e&&(e.innerHTML='❌ Error saving'),"function"==typeof showToast&&showToast("❌ Error saving profile")}}function _pasteFieldFallback(e){e.focus(),e.value="",e.setSelectionRange(0,0);try{document.execCommand("paste")}catch(e){}"function"==typeof showToast&&showToast("📋 Field ready — tap and hold, then tap Paste",5e3)}function clearUserLocalStorage(){for(var e=["btc_theme_oled","btc_font_size","btc_volume","btc_lang","btc_haptic","btc_soundscape","btc_ticker_enabled","btc_ios_a2hs_dismissed","btc_pwa_dismissed","btc_swipe_hint_shown","btc_last_auth_uid","btc_signin_email","btc_pending_email","btc_pending_username","btc_pending_giveaway"],t=[],o=0;o
    Scan this QR code with your authenticator app:
    Or enter this key manually: '+(t.data.secret||"")+'
    ')}}catch(e){showToast("Error setting up authenticator: "+(e.message||"try again"))}}async function verifyTotpSetup(){var e=document.getElementById("totpVerifyCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpVerify");await t({code:e.value.trim()}),showToast("✅ Authenticator app enabled!"),showSettingsPage("security")}catch(e){showToast("Invalid code. Try again.")}else showToast("Enter a 6-digit code")}async function disableTotp(){var e=document.getElementById("totpDisableCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpDisable");await t({code:e.value.trim()}),showToast("Authenticator app disabled"),showSettingsPage("security")}catch(e){showToast("Invalid code")}else showToast("Enter your current code")}function clearUserData(){["btc_visited_channels","btc_favs","btc_hidden_badges","btc_asked_questions","btc_scholar_passed","btc_scholar_attempt_date","btc_badges","btc_last_channel","btc_signin_email","btc_nacho_equipped","btc_nacho_items_notified","btc_points","btc_total_visits","btc_streak","btc_last_visit"].forEach(function(e){localStorage.removeItem(e)}),currentUser=null}function showSignInPrompt(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous?showSettings():showUsernamePrompt()}function _generateDeviceFingerprint(){try{var e=document.createElement("canvas"),t=e.getContext("2d");t.textBaseline="top",t.font="14px Arial",t.fillText("Bitcoin Education 🦌",2,2);for(var o=e.toDataURL(),n=[navigator.userAgent||"",screen.width+"x"+screen.height,screen.colorDepth,(new Date).getTimezoneOffset(),navigator.language||"",navigator.hardwareConcurrency||0,(navigator.deviceMemory||0).toString(),void 0!==window.ontouchstart?"touch":"no-touch",o.substring(o.length-50)].join("|"),i=0,a=0;a{const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.frequency.value=o,i.type=n<3?"sine":"triangle",a.gain.setValueAtTime(.12*e,t.currentTime+.1*n),a.gain.exponentialRampToValueAtTime(.001,t.currentTime+.1*n+.6),i.start(t.currentTime+.1*n),i.stop(t.currentTime+.1*n+.6)})}catch(e){}"function"==typeof launchConfetti&&launchConfetti();const o=document.createElement("div");o.id="levelUpModal",o.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;animation:fadeIn 0.4s;",o.innerHTML='
    '+e.emoji+'
    ⬆️ LEVEL UP!
    '+e.name+'
    You\'ve reached '+e.min.toLocaleString()+'+ XP!
    '+getLevelFlavor(e.name)+'
    ',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function getLevelFlavor(e){return{Curious:"You're starting to see what all the fuss is about.",Pleb:"Welcome to the pleb life. You're one of us now.","Pleb II":"170 — the block height when Satoshi mined the first 1,000 blocks. You're going deeper.","Pleb III":"256 — the number of bits in a private key. You're becoming unbreakable.",Stacker:"Stacking sats and stacking knowledge. Impressive.","Stacker II":"Double stacking! 1913 — the year the Fed was born. You know why that matters.","Stacker III":"Triple stack mode. 2016 — the year the halving changed everything.",Maxi:"2140 — when the last sat is mined. There is no second best. You know it.","Maxi II":"6102 — Executive Order 6102 banned gold. They can't ban Bitcoin. Double the conviction.","Maxi III":"8888 — triple maxi. The signal only gets stronger.","Papa John":"10,000 BTC for two pizzas. Never forget. 🍕 You've earned your slice.","Full Node":"18,333 — port 18333. You verify everything yourself. Don't trust, verify.",Whale:"50,000 strong. You move markets. Unstoppable, just like Bitcoin.",Sovereign:"Self-sovereign. 100K channels deep. No permission needed. You ARE the bank.",Cypherpunk:"133,337 — leet beyond leet. Privacy is a right, not a privilege. Code is law.",Satoshi:"The pinnacle. You've achieved legendary status."}[e]||"You're leveling up!"}window.showSettings=function(){if(void 0===auth||!auth)return"function"==typeof showToast&&showToast("⚠️ Firebase not ready. Retrying..."),"function"==typeof initRanking&&initRanking(),void setTimeout(function(){void 0!==auth&&auth?showUsernamePrompt():"function"==typeof showToast&&showToast("❌ Could not load. Please refresh the page.")},2e3);showUsernamePrompt()},window._countryList=["Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burundi","Cabo Verde","Cambodia","Cameroon","Canada","Central African Republic","Chad","Chile","China","Colombia","Comoros","Congo","Costa Rica","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Eswatini","Ethiopia","Fiji","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Grenada","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Ivory Coast","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","North Korea","North Macedonia","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","Sudan","Suriname","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor-Leste","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Yemen","Zambia","Zimbabwe"],window._filterCountryList=function(){var e=document.getElementById("countryInput"),t=document.getElementById("countryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
    '+c+"
    "}n.length>8&&(i+='
    +'+(n.length-8)+" more — keep typing
    "),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectCountry=function(e){var t=document.getElementById("countryInput"),o=document.getElementById("countryDropdown");t&&(t.value=e),o&&(o.style.display="none")},window._selectFaction=async function(e){try{var t=auth?auth.currentUser:null;if(!t)return void("function"==typeof showToast&&showToast("Sign in to choose a faction"));if(t.isAnonymous)return void("function"==typeof showToast&&showToast("Create an account to choose a faction"));await db.collection("users").doc(t.uid).update({faction:e}),currentUser&&(currentUser.faction=e),"function"==typeof showToast&&showToast("cyber_hornets"===e?"🐝 Welcome to the Cyber Hornets!":"🦡 Welcome to the Honey Badgers!"),showSettingsPage("account")}catch(e){console.error("Faction select error:",e),"function"==typeof showToast&&showToast("Error saving faction")}},window._filterSignupCountry=function(){var e=document.getElementById("signupCountryInput"),t=document.getElementById("signupCountryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
    '+c+"
    "}n.length>8&&(i+='
    +'+(n.length-8)+" more — keep typing
    "),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectSignupCountry=function(e){var t=document.getElementById("signupCountryInput"),o=document.getElementById("signupCountryDropdown");t&&(t.value=e),o&&(o.style.display="none")},document.addEventListener("click",function(e){[["countryDropdown","countryAutocomplete"],["signupCountryDropdown","signupCountryAutocomplete"]].forEach(function(t){var o=document.getElementById(t[0]),n=document.getElementById(t[1]);o&&n&&!n.contains(e.target)&&(o.style.display="none")})}),function(){const e=localStorage.getItem("btc_lang");if(e){document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname;const t=document.createElement("script");t.id="gtranslate",t.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(t),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget")};const o=document.createElement("div");o.id="gtranslateWidget",o.style.display="none",document.body.appendChild(o)}}(),window.setSoundscape=function(e){localStorage.setItem("btc_soundscape",e),"function"==typeof updateSoundscape&&updateSoundscape(e),showSettingsPage("prefs")},window._removedProfileLinks={},window.profileLinkRemoved=function(e){window._removedProfileLinks[e]=!0},window.addProfileLink=function(e,t,o,n,i,a){var r=document.getElementById("profileLinksArea");if(r){var s=document.createElement("div");s.className="pf-link-row",s.setAttribute("data-key",e),s.style.cssText="display:flex;align-items:center;gap:12px;margin-bottom:12px;background:rgba(255,255,255,0.02);padding:10px;border-radius:12px;border:1px solid var(--border);",s.innerHTML=''+t+'',r.appendChild(s);var c=document.getElementById("addLinkMenu");c&&(c.style.display="none");var l=document.getElementById("profile_"+e);l&&l.focus()}},window.handleProfilePicUpload=function(e){var t=e.files&&e.files[0];if(t){var o=document.getElementById("pfpUploadStatus");if(t.type.match(/^image\//))if(t.size>2097152)o&&(o.innerHTML='❌ Image too large (max 2MB)');else{o&&(o.innerHTML='Processing...');var n=new FileReader;n.onload=function(e){var t=new Image;t.onload=function(){var e=128,n=document.createElement("canvas");n.width=e,n.height=e;var i,a,r=n.getContext("2d"),s=Math.min(t.width,t.height);i=(t.width-s)/2,a=(t.height-s)/2,r.drawImage(t,i,a,s,s,0,0,e,e);var c=n.toDataURL("image/jpeg",.8);auth&&auth.currentUser?db.collection("users").doc(auth.currentUser.uid).update({profilePic:c}).then(function(){currentUser&&(currentUser.profilePic=c),window._lbCache=null,o&&(o.innerHTML='✅ Profile picture saved!'),"function"==typeof showToast&&showToast("📷 Profile picture updated!"),setTimeout(function(){showSettingsPage("account")},1e3)}).catch(function(e){o&&(o.innerHTML='❌ Save failed: '+e.message+"")}):o&&(o.innerHTML='❌ Not signed in')},t.onerror=function(){o&&(o.innerHTML='❌ Could not load image')},t.src=e.target.result},n.readAsDataURL(t)}else o&&(o.innerHTML='❌ Please select an image file')}},window.removeProfilePic=function(){auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({profilePic:""}).then(function(){currentUser&&(currentUser.profilePic=""),window._lbCache=null,"function"==typeof showToast&&showToast("📷 Profile picture removed"),showSettingsPage("account")}).catch(function(){})},window.showArtistProfileModal=function(){if(auth&&auth.currentUser){var e=document.getElementById("artistProfileModal");e&&e.remove();var t=currentUser&¤tUser.artistProfile||{},o=auth.currentUser.uid,n=document.createElement("div");n.id="artistProfileModal",n.style.cssText="position:fixed;inset:0;z-index:500000;background:rgba(0,0,0,0.85);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",n.onclick=function(e){e.target===n&&n.remove()},n.innerHTML='
    🎸
    Artist Profile
    Set up your artist presence on Bitcoin Beats
    🎤 Stage Name
    Leave blank to use your username.
    📝 Artist Bio
    🎵 Genres
    🔗 Music Links
    🌐
    𝕏
    📸
    '+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?'✅ Lightning: '+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ Set a Lightning Address in Account or Wallet to receive tips!")+'
    ',document.body.appendChild(n)}else"function"==typeof showToast&&showToast("Sign in first")},window.saveArtistProfile=function(){if(auth&&auth.currentUser&&void 0!==db){var e=document.getElementById("artistSaveBtn");e&&(e.disabled=!0,e.textContent="Saving...");var t={stageName:(document.getElementById("artistStageName").value||"").trim().substring(0,40),bio:(document.getElementById("artistBio").value||"").trim().substring(0,500),genres:(document.getElementById("artistGenres").value||"").trim().substring(0,100),website:(document.getElementById("artistLinkWebsite").value||"").trim().substring(0,200),x:(document.getElementById("artistLinkX").value||"").trim().substring(0,50),instagram:(document.getElementById("artistLinkInstagram").value||"").trim().substring(0,50)};db.collection("users").doc(auth.currentUser.uid).update({artistProfile:t}).then(function(){currentUser&&(currentUser.artistProfile=t),"function"==typeof showToast&&showToast("🎸 Artist profile saved!"),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")}).catch(function(t){console.error("Artist profile save error:",t),"function"==typeof showToast&&showToast("Error saving: "+(t.message||"Unknown")),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")})}else"function"==typeof showToast&&showToast("Sign in to save your artist profile")},window.pasteToField=function(e){var t=document.getElementById(e);t&&(navigator.clipboard&&navigator.clipboard.readText?navigator.clipboard.readText().then(function(e){e?(t.value=e.trim(),t.style.borderColor="var(--accent)",t.dispatchEvent(new Event("input",{bubbles:!0})),"function"==typeof showToast&&showToast("📋 Pasted!")):_pasteFieldFallback(t)}).catch(function(){_pasteFieldFallback(t)}):_pasteFieldFallback(t))},window.loadSignalContent=function(){var e=document.getElementById("signalLiveNews");e&&!e.getAttribute("data-loaded")&&(e.setAttribute("data-loaded","1"),fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=e.link||"";n+='
    SIGNAL #'+(t+1)+'
    '+o+"
    "+(i?'
    Read →
    ':"")+"
    "}),o.innerHTML=n}}).catch(function(){}))},window.expandSignUpBanner=function(){sessionStorage.removeItem("btc_signin_banner_dismissed");var e=document.getElementById("mobileSignUpPill");e&&e.remove();var t=document.getElementById("userDisplay");t&&t.classList.remove("user-hidden"),"function"==typeof updateUserDisplay&&updateUserDisplay()},window.minimizeSignUpBanner=function(){sessionStorage.setItem("btc_signin_banner_dismissed","1");var e=document.getElementById("userDisplay");if(window.innerWidth<=900){e&&(e.classList.add("user-hidden"),e.style.display="none");var t=document.getElementById("mobileSignUpPill");t||((t=document.createElement("div")).id="mobileSignUpPill",document.body.appendChild(t)),t.style.cssText="position:fixed;bottom:70px;left:12px;z-index:200;display:flex;align-items:center;gap:6px;padding:8px 12px 8px 16px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",t.innerHTML='🔐 Sign Up',t.onclick=function(){window.expandSignUpBanner()}}else{if(!e)return;e.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:6px;padding:6px 14px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",e.innerHTML='🔐 Sign Up',e.onclick=function(){window.expandSignUpBanner()}}},window.clearUserLocalStorage=clearUserLocalStorage,window.hideUsernamePrompt=function(){const e=document.getElementById("usernameModal");if(e&&e.classList.remove("open"),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn(),"function"==typeof window._onSettingsClose){var t=window._onSettingsClose;window._onSettingsClose=null,setTimeout(t,150)}},window.submitUsername=async function(){try{var e=document.getElementById("usernameInput")||document.getElementById("newUsername");if(!e)return void console.error("[submitUsername] No input found");var t=e.value.trim();if(!t)return void showToast("Please enter a username!");if(t.length<2)return void showToast("Username must be at least 2 characters");if(t.length>20)return void showToast("Username must be 20 characters or less");if(containsProfanity(t))return void showToast("⚠️ That username is not allowed.");if(document.getElementById("usernameInput")){var o=document.getElementById("emailInput"),n=o?o.value.trim():"",i=document.getElementById("signupCountryInput"),a=i?i.value.trim().substring(0,60):"";if(a&&window._countryList&&-1===window._countryList.indexOf(a))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void i.focus();var r=document.getElementById("giveawayCheckbox"),s=document.getElementById("giveawayLnAddress"),c=r&&r.checked,l=s?s.value.trim():"";return c&&!l?(s&&(s.style.borderColor="#ef4444",s.focus()),void showToast("⚡ Enter a Lightning address to enter the giveaway, or uncheck the box to skip.")):n&&await sendMagicLink(n)?(localStorage.setItem("btc_pending_username",t),localStorage.setItem("btc_pending_email",n),c&&l&&localStorage.setItem("btc_pending_giveaway",l),showToast("📧 Check your email for a verification link!"),hideUsernamePrompt(),void await createUser(t,n,c,l,a)):void await createUser(t,n,c,l,a)}if(!currentUser||currentUser._isLocal)return void showToast("Sign in first to change username");var d=document.getElementById("usernameStatus");d&&(d.innerHTML="Saving...");try{await db.collection("users").doc(currentUser.uid).update({username:t,username_lower:t.toLowerCase()}),currentUser.username=t,updateAuthButton(),updateRankUI(),d&&(d.innerHTML="✅ Username updated!"),showToast("✅ Username changed to "+t)}catch(e){d&&(d.innerHTML="❌ Error saving"),showToast("Error updating username. Try again.")}}catch(e){console.error("[submitUsername] Uncaught error:",e),"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown error. Please try again."))}},window.exportUserData=function(){if(!currentUser)return;const e=JSON.stringify(currentUser,null,2),t=new Blob([e],{type:"application/json"}),o=URL.createObjectURL(t),n=document.createElement("a");n.href=o,n.download="bitcoin_archive_user_data.json",n.click()},(!localStorage.getItem("btc_last_price")||Date.now()-parseInt(localStorage.getItem("btc_price_ts")||"0")>3e5)&&fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd&&(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),localStorage.setItem("btc_price_ts",Date.now().toString()))}).catch(function(){}),(!localStorage.getItem("btc_last_height")||Date.now()-parseInt(localStorage.getItem("btc_height_ts")||"0")>3e5)&&fetch("https://mempool.space/api/blocks/tip/height").then(function(e){return e.text()}).then(function(e){var t=parseInt(e);t&&(localStorage.setItem("btc_last_height",t.toString()),localStorage.setItem("btc_height_ts",Date.now().toString()))}).catch(function(){}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",initRanking):initRanking(),void 0!==toggleLeaderboard&&(window.toggleLeaderboard=toggleLeaderboard),void 0!==showUsernamePrompt&&(window.showUsernamePrompt=showUsernamePrompt),window.setDisplayBadge=function(e){currentUser&&(currentUser.displayBadge=e||"",void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({displayBadge:e||""}).catch(function(){}),localStorage.setItem("btc_display_badge",e||""),updateRankUI(),updateAuthButton(),showSettingsPage("account"),showToast(e?"🏅 Display badge updated!":"🏅 Using default rank emoji"))},"undefined"==typeof changeUsername&&(window.changeUsername=async function(e){if(!e){var t=document.getElementById("newUsername");t&&(e=t.value.trim())}if(e&&(e=e.replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim()),!e||e.length<2)showToast("Username must be at least 2 characters (ASCII only)");else if(e.length>20)showToast("Username max 20 characters");else if(containsProfanity(e))showToast("⚠️ That username is not allowed.");else if("function"!=typeof isCleanText||isCleanText(e)){if(localStorage.setItem("btc_username",e),currentUser&&(currentUser.username=e),updateAuthButton(),updateRankUI(),auth&&auth.currentUser&&db)try{await db.collection("users").doc(auth.currentUser.uid).update({username:e,username_lower:e.toLowerCase()})}catch(e){console.warn("Username Firestore save failed:",e)}showToast("✅ Username updated to "+e);var o=document.querySelector('[id="currentUsernameLabel"]');o||document.querySelectorAll("div, span").forEach(function(e){-1===e.textContent.indexOf("Current username:")||o||(o=e)}),o&&(o.innerHTML='Current username: '+("function"==typeof escapeHtml?escapeHtml(e):e)+"");var n=document.querySelector('button[onclick*="changeUsername"]');n&&(n.textContent="✅ Saved!",n.style.background="#22c55e",setTimeout(function(){n.textContent="Save New Username",n.style.background="var(--accent)"},2e3))}else showToast("Username contains inappropriate language")}),window.togglePushNotifications=async function(){try{if(!("Notification"in window))return void showToast("Notifications not supported in this browser");"granted"===await Notification.requestPermission()?(localStorage.setItem("btc_push_enabled","true"),showToast("🔔 Notifications Enabled!")):(localStorage.setItem("btc_push_enabled","false"),showToast("❌ Notification permission denied")),showSettingsPage("prefs")}catch(e){console.error(e)}},"undefined"==typeof sendEmailVerification&&(window.sendEmailVerification=function(){auth&&auth.currentUser&&auth.currentUser.sendEmailVerification&&auth.currentUser.sendEmailVerification().then(function(){showToast("📧 Verification email sent!")}).catch(function(){showToast("Could not send verification email")})}),"undefined"==typeof disable2FA&&(window.disable2FA=function(){showToast("2FA management coming soon")}),"undefined"==typeof startMFAEnroll&&(window.startMFAEnroll=function(){showToast("2FA enrollment coming soon")}),"undefined"==typeof verifyMFACode&&(window.verifyMFACode=function(){showToast("2FA verification coming soon")}),"undefined"==typeof sendPasswordReset&&(window.sendPasswordReset=function(){auth&&auth.currentUser&&auth.currentUser.email&&auth.sendPasswordResetEmail(auth.currentUser.email).then(function(){showToast("📧 Password reset email sent!")}).catch(function(){showToast("Could not send reset email")})}),"undefined"==typeof confirmDeleteAccount&&(window.confirmDeleteAccount=function(){if(confirm("Are you sure you want to delete your account? This cannot be undone.")&&auth&&auth.currentUser){var e=auth.currentUser.uid;db.collection("users").doc(e).delete().then(function(){return auth.currentUser.delete()}).then(function(){localStorage.clear(),location.reload()}).catch(function(e){showToast("Error: "+e.message)})}}),window.saveSatsLnAddress=async function(){var e=document.getElementById("satsLnAddrInput"),t=document.getElementById("satsLnAddrStatus");if(e){var o=e.value.trim();if(o&&(!o.includes("@")||o.length<5))t&&(t.innerHTML='Enter a valid Lightning Address (e.g. you@walletofsatoshi.com)');else if(void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{t&&(t.innerHTML='Saving…'),await db.collection("users").doc(auth.currentUser.uid).update({lightning:o}),void 0!==currentUser&¤tUser&&(currentUser.lightning=o),o?(t&&(t.innerHTML='✅ Lightning Address saved!'),"function"==typeof showToast&&showToast("⚡ Lightning Address saved!"),"true"!==localStorage.getItem("btc_lightning_setup")&&(localStorage.setItem("btc_lightning_setup","true"),"function"==typeof awardPoints&&awardPoints(100,"⚡ Lightning wallet setup!"),"function"==typeof showToast&&setTimeout(function(){showToast("⚡🏅 Lightning Rod badge earned! +100 pts")},1500),"function"==typeof initBadges&&setTimeout(initBadges,2e3))):t&&(t.innerHTML='Lightning Address removed.')}catch(e){t&&(t.innerHTML='Error saving — try again')}else t&&(t.innerHTML='Sign in to save your Lightning Address')}},window.initSatsClaim=function(){if(console.log("[SATS] initSatsClaim called",{currentUser:!!currentUser,auth:!!auth,authUser:!!auth?.currentUser,isAnon:auth?.currentUser?.isAnonymous}),!currentUser||!auth||!auth.currentUser||auth.currentUser.isAnonymous)return console.log("[SATS] BLOCKED: auth check failed"),void showToast("Sign in to claim sats");var e=(currentUser.points||0)-(currentUser.pointsClaimed||0),t=Math.floor(Math.max(0,e)/10),o=currentUser.satsWithdrawn||0,n="function"==typeof getSatCap?getSatCap():1e4,i=Math.max(0,n-o),a=Math.min(t,500,i);if(console.log("[SATS] maxClaim:",a,"| satsBalance:",t,"| lifetimeLeft:",i,"| satsWithdrawn:",o),a<100)return console.log("[SATS] BLOCKED: maxClaim < 100"),void showToast("⚡ Need at least 100 claimable sats (1,000 unclaimed XP) to withdraw. Keep earning!",5e3);console.log("[SATS] Passed all checks, showing overlay");var r=document.createElement("div");r.id="satsClaimOverlay",r.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:10002;display:flex;align-items:center;justify-content:center;padding:16px;",setTimeout(function(){r.onclick=function(e){e.target===r&&r.remove()}},200);var s='
    ';s+='
    Claim Sats
    ',s+='
    ',s+='
    You can claim up to
    ',s+='
    ⚡ '+a+" sats
    ",s+="
    ",s+='',s+='',s+='
    Open your Lightning wallet, create an invoice for the amount you want (100-'+a+' sats), and paste it here.
    💚 Zero fees — we pay all Lightning network fees so you receive the full amount!
    ',s+='',s+='',s+='',s+="
    ",r.innerHTML=s,document.body.appendChild(r)},window._satsClaimInProgress=!1,window.submitSatsClaim=async function(){if(!window._satsClaimInProgress){var e=document.getElementById("satsClaimBtn"),t=document.getElementById("satsClaimInvoice"),o=document.getElementById("satsClaimError");if(e&&t){var n=t.value.trim();if(n&&n.toLowerCase().startsWith("lnbc")){o&&(o.style.display="none"),window._satsClaimInProgress=!0,e.disabled=!0,e.textContent="⏳ Sending sats...",e.style.opacity="0.6";try{var i=firebase.functions().httpsCallable("claimSats"),a=_generateDeviceFingerprint(),r=await i({invoice:n,fingerprint:a});if(r.data&&r.data.success){var s=r.data.amount||0;currentUser.pointsClaimed=(currentUser.pointsClaimed||0)+10*s,currentUser.satsWithdrawn=(currentUser.satsWithdrawn||0)+s,currentUser.lastSatsClaim=new Date,document.getElementById("satsClaimOverlay").remove(),window._satsClaimInProgress=!1,"function"==typeof notifySelfSatsClaim&¬ifySelfSatsClaim(s),"function"==typeof launchConfetti&&launchConfetti();var c=currentUser.satsWithdrawn||s,l="function"==typeof getSatCap?getSatCap():1e4,d=Math.max(0,l-c),u=document.createElement("div");u.id="satsCelebration",u.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.3s;",u.onclick=function(e){e.target===u&&u.remove()},u.innerHTML='
    ⚡🎉

    Sats Claimed!

    '+s+' sats
    sent to your Lightning wallet ⚡
    Check your wallet to confirm!
    ⚡ '+d.toLocaleString()+' sats remaining to claim!
    '+c.toLocaleString()+' / 10,000 lifetime total claimed
    🧡 Thank you for learning Bitcoin with us!
    ',document.body.appendChild(u),setTimeout(function(){showSettingsPage("sats")},500)}else{var p=r.data&&r.data.error?r.data.error:"Claim failed — try again";o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}catch(t){console.error("Sats claim error:",t),p=t.message||"Claim failed — try again",o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}else o&&(o.textContent="Please paste a valid Lightning invoice (starts with lnbc...)",o.style.display="block")}}},window.loadSatsHistory=function(){var e=document.getElementById("satsHistory");e&¤tUser&&db?db.collection("users").doc(currentUser.uid).collection("sats_withdrawals").orderBy("timestamp","desc").get().then(function(t){if(t.empty)e.textContent="No withdrawals yet";else{var o=0,n="function"==typeof getSatCap?getSatCap():1e4,i="";t.forEach(function(e){var t=e.data(),n=parseInt(t.amount)||0;o+=n;var a=t.timestamp?new Date(1e3*t.timestamp.seconds).toLocaleDateString():"—";i+='
    '+a+'⚡ '+n+" sats
    "});var a=Math.max(0,n-o),r=Math.min(100,Math.round(o/n*100)),s=r>=90?"#ef4444":r>=60?"#eab308":"#22c55e",c='
    Lifetime Claimed⚡ '+o.toLocaleString()+" / "+n.toLocaleString()+' sats
    '+r+'% used'+a.toLocaleString()+" sats remaining
    ";e.innerHTML=c+i}}).catch(function(){e.textContent="Could not load history"}):e&&(e.textContent="Sign in to view history")};const BADGE_DEFS=[{id:"pow_first_step",name:"First Step",emoji:"👟",desc:"Synced your first walk via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_marathoner",name:"Marathoner",emoji:"🏃‍♂️",desc:"Hit the 42km daily cap in Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_streak_3",name:"3-Day Streak",emoji:"🔥",desc:"Synced walks 3 days in a row via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_streak_7",name:"7-Day Streak",emoji:"🔥",desc:"Synced walks 7 days in a row via Proof of Walk",check:()=>!1,pts:300,hidden:!1},{id:"pow_streak_30",name:"30-Day Streak",emoji:"💎",desc:"Synced walks 30 days in a row via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_10",name:"10 km Club",emoji:"🥾",desc:"Walked 10 km lifetime via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_km_50",name:"50 km Club",emoji:"🚶",desc:"Walked 50 km lifetime via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_km_100",name:"Century Walker",emoji:"🏅",desc:"Walked 100 km lifetime via Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_km_500",name:"500 km Legend",emoji:"🏔️",desc:"Walked 500 km lifetime via Proof of Walk",check:()=>!1,pts:500,hidden:!1},{id:"pow_km_1000",name:"1,000 km Titan",emoji:"🌍",desc:"Walked 1,000 km lifetime via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_5000",name:"To the Moon",emoji:"🌕",desc:"Walked 5,000 km lifetime via Proof of Walk",check:()=>!1,pts:2500,hidden:!1},{id:"first_channel",name:"First Steps",emoji:"👶",desc:"Opened your first channel",check:e=>e.length>=1,pts:10},{id:"explorer_10",name:"Explorer",emoji:"🧭",desc:"Visited 10 topics",check:e=>e.length>=10,pts:15},{id:"explorer_25",name:"Trailblazer",emoji:"🗺️",desc:"Visited 25 topics",check:e=>e.length>=25,pts:30},{id:"explorer_50",name:"Pathfinder",emoji:"🏕️",desc:"Visited 50 topics",check:e=>e.length>=50,pts:50},{id:"explorer_100",name:"Cartographer",emoji:"🌍",desc:"Visited 100 topics",check:e=>e.length>=100,pts:100},{id:"explorer_all",name:"Completionist",emoji:"🗝️",desc:"Visited every single topic",check:(e,t)=>e.length>=t,pts:500},{id:"foundation_builder",name:"Foundation Builder",emoji:"🧱",desc:"Read all Layer 1 Properties (Orange)",check:e=>["whitepaper","decentralized","scarce","secure","money","peaceful","dominant","organic","supranational","programmable","use-cases"].every(t=>e.includes(t)),pts:75},{id:"experienced_pro",name:"Deep Diver",emoji:"🤿",desc:"Read all Experienced Topics (Purple)",check:e=>["maximalism","problems-of-money","self-custody","privacy-nonkyc","nodes","mining","pow-vs-pos","energy","difficulty-adjustment","layer-2-lightning","fedi-ark","chaumian-mints","ctv-covenants","extension-blocks","op-codes","bitvm","layer-3-sidechains","stablecoins","smart-contracts","blockchain-timechain","regulation","cryptography","core-source-code","developers","investment-strategy","evidence-against-alts","consensus"].every(t=>e.includes(t)),pts:150},{id:"librarian",name:"The Librarian",emoji:"📚",desc:"Read all Resource topics (Blue)",check:e=>["one-stop-shop","faq-glossary","nostr","misconceptions-fud","books","videos","podcasts","articles-threads","informational-sites","curriculum","research-theses","games","music","movies-tv","hardware","poems-stories","apps-tools","projects-diy","art-inspiration","graphics","charts","swag-merch","jobs-earn","social-media","fun-facts","news-adoption","history","international","satoshi-nakamoto","giga-chad","health","web5","memes-funny"].every(t=>e.includes(t)),pts:150},{id:"quest_1",name:"Quester",emoji:"⚔️",desc:"Completed your first Quest",check:(e,t,o)=>o>=1,pts:10},{id:"quest_3",name:"Quest Master",emoji:"📜",desc:"Completed 3 Quests",check:(e,t,o)=>o>=3,pts:25},{id:"quest_5",name:"Quest Legend",emoji:"🏰",desc:"Completed 5 Quests",check:(e,t,o)=>o>=5,pts:50},{id:"bookworm",name:"Bookworm",emoji:"📖",desc:"Saved 5 topics to favorites",check:()=>JSON.parse(localStorage.getItem("btc_favs")||"[]").length>=5,pts:20},{id:"night_owl",name:"Night Owl",emoji:"🦉",desc:"Browsing between midnight and 5am",check:()=>{const e=(new Date).getHours();return e>=0&&e<5},pts:15},{id:"early_bird",name:"Early Bird",emoji:"🐦",desc:"Browsing between 5am and 7am",check:()=>{const e=(new Date).getHours();return e>=5&&e<7},pts:15},{id:"cert_scholar",name:"Bitcoin Scholar",emoji:"🎓",desc:"Passed the Bitcoin Scholar Certification",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed"),pts:50},{id:"tctv_tuned_in",name:"Tuned In",emoji:"📺",desc:"Watched 10 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=10,pts:10},{id:"tctv_couch_potato",name:"Couch Potato",emoji:"🛋️",desc:"Watched 60 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=60,pts:25},{id:"tctv_binge_watcher",name:"Binge Watcher",emoji:"🍿",desc:"Watched 5 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=300,pts:50},{id:"tctv_couch_king",name:"Couch King",emoji:"🛌",desc:"Watched 24 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=1440,pts:100},{id:"tctv_satellite",name:"Satellite",emoji:"🛰️",desc:"Watched 100 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=6e3,pts:750},{id:"cert_tech",name:"Protocol Expert",emoji:"🛠️",desc:"Passed the Technical Protocol Expert Certification",check:()=>"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:100},{id:"nacho_chatterbox",name:"Nacho Chatterbox",emoji:"🦌",desc:"Interacted with Nacho 50+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=50,pts:30},{id:"nacho_bestie",name:"Nacho's Bestie",emoji:"🧡",desc:"Interacted with Nacho 250+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=250,pts:200},{id:"chat_first",name:"First Words",emoji:"💦",desc:"Sent your first message in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=1,pts:10},{id:"chat_10",name:"Chatty",emoji:"🗣️",desc:"Sent 10 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=10,pts:15},{id:"chat_50",name:"Conversationalist",emoji:"💬",desc:"Sent 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=50,pts:25},{id:"chat_100",name:"Town Crier",emoji:"📢",desc:"Sent 100 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=100,pts:50},{id:"chat_500",name:"Chat Legend",emoji:"📯",desc:"Sent 500 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=500,pts:250},{id:"chat_streak_3",name:"Regular",emoji:"📅",desc:"Chatted 3 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=3,pts:20},{id:"chat_streak_7",name:"Devoted Chatter",emoji:"💪",desc:"Chatted 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=7,pts:50},{id:"chat_streak_30",name:"Chat Addict",emoji:"💠",desc:"Chatted 30 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=30,pts:300},{id:"dj_first",name:"First Set",emoji:"🎧",desc:"DJed for the first time in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=1,pts:25},{id:"dj_5",name:"Resident DJ",emoji:"🎛️",desc:"DJed 5 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=5,pts:50},{id:"dj_25",name:"Club Legend",emoji:"🎶",desc:"DJed 25 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=25,pts:300},{id:"dj_songs_10",name:"Playlist Pro",emoji:"📻",desc:"Broadcast 10 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=10,pts:30},{id:"dj_songs_50",name:"Jukebox Hero",emoji:"🎵",desc:"Broadcast 50 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=50,pts:75},{id:"dj_songs_100",name:"Vinyl Master",emoji:"🎼",desc:"Broadcast 100 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=100,pts:400},{id:"dj_listener",name:"Good Listener",emoji:"🔊",desc:"Tuned in to 10 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=10,pts:20},{id:"dj_listener_50",name:"Groupie",emoji:"🤘",desc:"Tuned in to 50 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=50,pts:150},{id:"producer_1",name:"Producer",emoji:"🎤",desc:"Uploaded your first song to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=1,pts:50},{id:"producer_10",name:"Discographer",emoji:"💿",desc:"Uploaded 10 songs to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=10,pts:100},{id:"pvp_first",name:"First Blood",emoji:"🩸",desc:"Won your first PVP battle",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=1,pts:25},{id:"pvp_5",name:"Contender",emoji:"🥊",desc:"Won 5 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=5,pts:50},{id:"pvp_25",name:"Gladiator",emoji:"🏟️",desc:"Won 25 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=25,pts:100},{id:"pvp_50",name:"Champion",emoji:"🏆",desc:"Won 50 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=50,pts:200},{id:"pvp_100",name:"PVP Legend",emoji:"🥇",desc:"Won 100 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=100,pts:1e3},{id:"forum_5",name:"Voice of the People",emoji:"📣",desc:"Made 5 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=5,pts:25},{id:"forum_25",name:"Thought Leader",emoji:"🧠",desc:"Made 25 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=25,pts:75},{id:"article_1",name:"Author",emoji:"✍️",desc:"Published your first article",check:()=>parseInt(localStorage.getItem("btc_articles_published")||"0")>=1,pts:50},{id:"streak_7",name:"Week Warrior",emoji:"🔥",desc:"7-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=7,pts:50},{id:"streak_30",name:"Monthly Maxi",emoji:"🦾",desc:"30-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=30,pts:150},{id:"streak_100",name:"Diamond Hands",emoji:"💎",desc:"100-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=100,pts:1e3},{id:"streak_365",name:"HODLer Supreme",emoji:"🪩",desc:"365-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=365,pts:5e3},{id:"irl_host",name:"Event Host",emoji:"🎪",desc:"Hosted your first IRL event",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=1,pts:50},{id:"irl_host_5",name:"Community Builder",emoji:"🏗️",desc:"Hosted 5 IRL events",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=5,pts:150},{id:"sats_first",name:"First Sats",emoji:"🪙",desc:"Claimed your first sats from the faucet",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1,pts:25},{id:"sats_1k",name:"Stacker",emoji:"📦",desc:"Claimed 1,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e3,pts:100},{id:"sats_5k",name:"Sat Whale",emoji:"🧊",desc:"Claimed 5,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=5e3,pts:250},{id:"predict_1",name:"Oracle",emoji:"🎱",desc:"Made your first price prediction",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.total||0)>=1,pts:10},{id:"predict_correct_5",name:"Crystal Ball",emoji:"🏐",desc:"5 correct predictions",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.correct||0)>=5,pts:75},{id:"first_purchase",name:"Bitcoiner",emoji:"🛒",desc:"Completed the First Bitcoin Purchase guide",check:()=>"true"===localStorage.getItem("btc_fp_completed"),pts:100},{id:"lightning_setup",name:"Lightning Rod",emoji:"⚡",desc:"Set up a Lightning wallet or added a Lightning address",check:()=>"true"===localStorage.getItem("btc_lightning_setup"),pts:100},{id:"trail_meadow",name:"Meadow Walker",emoji:"🌿",desc:"Completed The Meadow trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("meadow")}catch(e){return!1}},pts:200},{id:"trail_mountain",name:"Mountain Climber",emoji:"⛰️",desc:"Completed The Mountain trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("mountain")}catch(e){return!1}},pts:400},{id:"trail_summit",name:"Summit Conqueror",emoji:"🏔️",desc:"Completed The Summit trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("summit")}catch(e){return!1}},pts:750},{id:"trail_all",name:"Trail Master",emoji:"🏁",desc:"Completed all three Nacho's Trails",check:()=>{try{var e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]");return e.includes("meadow")&&e.includes("mountain")&&e.includes("summit")}catch(e){return!1}},pts:500},{id:"tip_first",name:"First Tip",emoji:"💸",desc:"Sent your first Lightning tip",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=1,pts:25},{id:"tip_10",name:"Generous Pleb",emoji:"💛",desc:"Tipped 10 times",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=10,pts:75},{id:"tip_whale",name:"Whale Tipper",emoji:"🐳",desc:"Tipped 1,000+ sats total",check:()=>parseInt(localStorage.getItem("btc_tips_total_sats")||"0")>=1e3,pts:150},{id:"tip_magnet",name:"Tip Magnet",emoji:"🧲",desc:"Received 10 tips from others",check:()=>parseInt(localStorage.getItem("btc_tips_received")||"0")>=10,pts:100},{id:"referral_1",name:"First Referral",emoji:"🔗",desc:"Referred 1 friend who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=1,pts:50},{id:"referral_5",name:"Connector",emoji:"🤝",desc:"Referred 5 friends who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=5,pts:100},{id:"referral_10",name:"Network Effect",emoji:"🌐",desc:"Referred 10 friends to Bitcoin education",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=10,pts:200},{id:"referral_25",name:"Orange Pill Machine",emoji:"💊",desc:"Orange-pilled 25 people via your link",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=25,pts:500},{id:"referral_50",name:"Super Spreader",emoji:"📡",desc:"Referred 50 people — legend status",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=50,pts:1e3},{id:"referral_100",name:"Viral Plebian",emoji:"👑",desc:"Referred 100 people — you are the movement",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=100,pts:2500},{id:"referred",name:"Referred Friend",emoji:"🫂",desc:"Joined Bitcoin Education Archive via a referral link",check:()=>void 0!==currentUser&¤tUser&&!!currentUser.referredBy,pts:25},{id:"dm_first",name:"DM Starter",emoji:"✉️",desc:"Sent your first direct message",check:()=>parseInt(localStorage.getItem("btc_dms_sent")||"0")>=1,pts:15},{id:"react_50",name:"Reaction King",emoji:"❤️",desc:"Reacted to 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_reactions")||"0")>=50,pts:50},{id:"predict_streak_3",name:"Oracle Streak",emoji:"🎯",desc:"3 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=3,pts:50},{id:"predict_streak_10",name:"Nostradamus",emoji:"🔮",desc:"10 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=10,pts:250},{id:"spin_30",name:"Lucky Spinner",emoji:"🎰",desc:"Spun the wheel 30 days total",check:()=>parseInt(localStorage.getItem("btc_spin_count")||"0")>=30,pts:75},{id:"spin_streak_7",name:"Spin Streak",emoji:"🎡",desc:"Spun 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_spin_streak")||"0")>=7,pts:50},{id:"spin_jackpot",name:"Jackpot Winner",emoji:"🌟",desc:"Hit the RARE drop on the spin wheel",check:()=>"true"===localStorage.getItem("btc_spin_hit_rare"),pts:100},{id:"cert_double",name:"Double Scholar",emoji:"🏛️",desc:"Earned both Scholar AND Protocol Expert certifications",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed")&&"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:250},{id:"sf_first_hash",name:"First Hash",emoji:"⛏️",desc:"Generated your first hash during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1,pts:10},{id:"sf_10_hashes",name:"Pickaxe Swinger",emoji:"💥",desc:"Generated 10 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=10,pts:25},{id:"sf_50_hashes",name:"Mine Foreman",emoji:"🪨",desc:"Generated 50 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=50,pts:75},{id:"sf_100_hashes",name:"Hash Machine",emoji:"🔩",desc:"Generated 100 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=100,pts:150},{id:"sf_500_hashes",name:"ASIC Mode",emoji:"🖥️",desc:"Generated 500 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=500,pts:500},{id:"sf_1000_hashes",name:"Mining Rig",emoji:"🏭",desc:"Generated 1,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e3,pts:1e3},{id:"sf_10000_hashes",name:"Hash Lord",emoji:"☄️",desc:"Generated 10,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e4,pts:2100},{id:"sf_low_hash",name:"Lucky Strike",emoji:"⭐",desc:"Mined a hash under 1,000,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e6,pts:50},{id:"sf_ultra_low",name:"Golden Nonce",emoji:"✨",desc:"Mined a hash under 100,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e5,pts:200},{id:"sf_block_solver",name:"Block Solver",emoji:"🌞",desc:"Solved a block! Hash under the difficulty target",check:()=>"true"===localStorage.getItem("btc_sf_solved_block"),pts:1e3},{id:"sf_contributor",name:"Community Miner",emoji:"🤝",desc:"Contributed to activating Satoshi's Favor 3 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=3,pts:50},{id:"sf_contributor_10",name:"Favor Champion",emoji:"🏅",desc:"Contributed to activating Satoshi's Favor 10 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=10,pts:200},{id:"raid_first",name:"Raid Recruit",emoji:"🛡️",desc:"Dealt damage to your first Raid Boss",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=1,pts:10},{id:"raid_5",name:"Raid Warrior",emoji:"🗡️",desc:"Dealt 5 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=5,pts:50},{id:"raid_10",name:"Raid Veteran",emoji:"⚙️",desc:"Dealt 10 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=10,pts:100},{id:"raid_25",name:"Raid Commander",emoji:"⚜️",desc:"Dealt 25 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=25,pts:250},{id:"raid_50",name:"Raid Legend",emoji:"👑",desc:"Dealt 50 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=50,pts:750},{id:"raid_100",name:"Raid Warlord",emoji:"🔱",desc:"Dealt 100 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=100,pts:1500},{id:"raid_boss_slayer",name:"Boss Slayer",emoji:"💀",desc:"Participated in defeating a Raid Boss",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=1,pts:50},{id:"raid_boss_slayer_5",name:"Boss Hunter",emoji:"🐉",desc:"Participated in defeating 5 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=5,pts:150},{id:"raid_boss_slayer_10",name:"Dragon Slayer",emoji:"🐲",desc:"Participated in defeating 10 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=10,pts:500},{id:"raid_winner",name:"Raid Champion",emoji:"🎖️",desc:"Won the sats lottery after a Raid Boss defeat",check:()=>"true"===localStorage.getItem("btc_raid_winner"),pts:250}];let earnedBadges=new Set,badgeCheckInterval=null;function initBadges(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(e=>earnedBadges.add(e)),badgeCheckInterval=setInterval(checkBadges,3e4),setInterval(function(){if(window._visibleBadgeQueue&&0!==window._visibleBadgeQueue.length&&!window._nachoBusy){var e=document.getElementById("nacho-bubble");e&&e.classList.contains("show")||document.getElementById("badgeCelebration")||showBadgeToast(window._visibleBadgeQueue.shift())}},5e3)}function checkBadges(){if(!window._visibleBadgesReady)return;if(window._nachoBusy)return;const e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=void 0!==completedQuests?completedQuests.size:0;for(const a of BADGE_DEFS)if(!earnedBadges.has(a.id))try{if(a.check(e,t,o)){earnedBadges.add(a.id),localStorage.setItem("btc_badges",JSON.stringify([...earnedBadges])),"function"==typeof window._raidOnBadgeEarned&&window._raidOnBadgeEarned(),"function"==typeof window.contributeSatoshiFavor&&(void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username,window.contributeSatoshiFavor("badge_earned",a.emoji+" "+a.name).catch(function(){}));var n=document.getElementById("nacho-bubble");window._nachoBusy||n&&n.classList.contains("show")?(window._visibleBadgeQueue||(window._visibleBadgeQueue=[]),window._visibleBadgeQueue.push(a)):showBadgeToast(a);var i=a.pts||20;if("function"==typeof awardPoints&&awardPoints(i,"Badge: "+a.name+" "+a.emoji),void 0!==db&&void 0!==auth&&auth.currentUser)try{db.collection("users").doc(auth.currentUser.uid).update({visibleBadges:firebase.firestore.FieldValue.arrayUnion(a.id)})}catch(e){}}}catch(e){}}window._visibleBadgesReady=!1,window.markVisibleBadgesReady=function(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(function(e){earnedBadges.add(e)});var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>e.length&&(e=currentUser.readChannels),void 0!==CHANNELS&&Object.keys(CHANNELS).length,void 0!==completedQuests&&completedQuests.size;var t=!1,o=[];void 0!==currentUser&¤tUser&¤tUser.visibleBadges&&(o=currentUser.visibleBadges);for(var n=0;n𝕏 Share on Twitter'),o.innerHTML='
    '+e.emoji+'
    🎉 Badge Earned!
    '+e.name+'
    '+e.desc+'
    +20 XP
    '+r+'
    ',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function copyBadgeLink(e,t){const o="I earned the "+e+" "+t+" badge on Bitcoin Education Archive!\nhttps://bitcoineducation.quest";navigator.clipboard.writeText(o).then(()=>{"function"==typeof showToast&&showToast("📋 Copied to clipboard!")})}function launchConfetti(){const e=document.createElement("canvas");e.id="confettiCanvas",e.style.cssText="position:fixed;inset:0;z-index:500;pointer-events:none;",e.width=window.innerWidth,e.height=window.innerHeight,document.body.appendChild(e);const t=e.getContext("2d"),o=[],n=["#f7931a","#ea580c","#fbbf24","#f59e0b","#ff6b00","#ff9500","#ffb800","#fff"];for(let t=0;t<120;t++)o.push({x:e.width/2+100*(Math.random()-.5),y:e.height/2,vx:16*(Math.random()-.5),vy:16*(Math.random()-1)-4,size:8*Math.random()+3,color:n[Math.floor(Math.random()*n.length)],rotation:360*Math.random(),rotSpeed:12*(Math.random()-.5),gravity:.12+.08*Math.random(),opacity:1,shape:Math.random()>.5?"rect":"circle"});let i=0;requestAnimationFrame(function n(){t.clearRect(0,0,e.width,e.height);let a=!1;o.forEach(o=>{o.x+=o.vx,o.vy+=o.gravity,o.y+=o.vy,o.rotation+=o.rotSpeed,o.vx*=.99,i>40&&(o.opacity-=.015),o.opacity>0&&o.y{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=o,i.type="sine",a.gain.setValueAtTime(.15*t,e.currentTime+.12*n),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.12*n+.5),i.start(e.currentTime+.12*n),i.stop(e.currentTime+.12*n+.5)})}catch(e){}}function getBadgeHTML(){var e={};function t(t,o){var n=t.filter(function(t){return!e[t.id]&&o(t)});return n.forEach(function(t){e[t.id]=!0}),n}const o={"🧭 Discovery":t(BADGE_DEFS,e=>e.id.includes("explorer")||"first_channel"===e.id||"bookworm"===e.id),"🧠 Knowledge":t(BADGE_DEFS,e=>e.id.includes("builder")||e.id.includes("diver")||e.id.includes("librarian")||e.id.includes("quest")||e.id.includes("cert_")),"🦌 Trails":t(BADGE_DEFS,e=>e.id.startsWith("trail_")),"💬 Global Chat":t(BADGE_DEFS,e=>e.id.startsWith("chat_")),"🦌 Nacho":t(BADGE_DEFS,e=>e.id.startsWith("nacho_")),"📺 Timechain TV":t(BADGE_DEFS,e=>e.id.startsWith("tctv_")),"🎧 DJ Mode":t(BADGE_DEFS,e=>e.id.startsWith("dj_")),"🎵 Music":t(BADGE_DEFS,e=>e.id.startsWith("producer")),"⚔️ PVP":t(BADGE_DEFS,e=>e.id.startsWith("pvp_")),"📝 Forum":t(BADGE_DEFS,e=>e.id.startsWith("forum_")||e.id.startsWith("article_")),"🔥 Streaks":t(BADGE_DEFS,e=>e.id.startsWith("streak_")),"🤝 Community":t(BADGE_DEFS,e=>e.id.startsWith("irl_")||e.id.startsWith("referral_")),"⚡ Sats & Lightning":t(BADGE_DEFS,e=>e.id.startsWith("sats_")||"lightning_setup"===e.id||e.id.startsWith("tip_")),"🔮 Predictions":t(BADGE_DEFS,e=>e.id.startsWith("predict_")),"💬 Social":t(BADGE_DEFS,e=>e.id.startsWith("dm_")||"react_50"===e.id),"🎡 Spin Wheel":t(BADGE_DEFS,e=>e.id.startsWith("spin_")),"⛏️ Satoshi's Favor":t(BADGE_DEFS,e=>e.id.startsWith("sf_")),"🐲 Raid Boss":t(BADGE_DEFS,e=>e.id.startsWith("raid_")),"🌙 Fun":t(BADGE_DEFS,e=>"night_owl"===e.id||"early_bird"===e.id),"🏆 Milestones":t(BADGE_DEFS,t=>!e[t.id])};let n='';var i=0;for(const[e,t]of Object.entries(o)){if(0===t.length)continue;var a="bc_"+ ++i;const o=t.filter(e=>earnedBadges.has(e.id)).length,r=o===t.length;n+='
    ',n+="",n+='
    "}if(void 0!==HIDDEN_BADGES){const e=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),t=HIDDEN_BADGES.filter(function(e){return!e.hidden});if(t.length>0){var r="bc_"+ ++i,s=t.filter(function(t){return e.includes(t.id)}).length,c=s===t.length;n+='
    ',n+="",n+='
    "}const o=HIDDEN_BADGES.filter(function(e){return e.hidden}),a=o.some(function(t){return e.includes(t.id)}),u=o.length,p=o.filter(function(t){return e.includes(t.id)}).length;var l="bc_"+ ++i,d=p===u;if(n+='
    ',n+="",n+='
    "}return n}setTimeout(initBadges,2e3);const TICKET_CONFIG={dailyLogin:1,referral:50,referralSignupBonus:50,referralPointsThreshold:2140,pointsPerTicket:5};function getReferralCode(){return currentUser&¤tUser.uid?currentUser.uid.substring(0,8):null}function getReferralLink(){const e=getReferralCode();return e?window.location.origin+window.location.pathname+"?ref="+e:""}function captureReferralCode(){const e=new URLSearchParams(window.location.search).get("ref");if(e&&e.length>=6&&(localStorage.setItem("btc_referral_code",e),window.history&&window.history.replaceState)){const e=window.location.pathname+window.location.hash;window.history.replaceState({},"",e)}}async function awardDailyTicket(){try{if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;const e=(new Date).toISOString().split("T")[0];if(currentUser.lastTicketDate===e)return;const t=TICKET_CONFIG.dailyLogin,o=t*TICKET_CONFIG.pointsPerTicket,n=(currentUser.orangeTickets||0)+t;if("function"==typeof awardPoints){const e=await awardPoints(o,"🎟️ Daily tickets",null,t);if(!e||!e.success)return}currentUser.lastTicketDate=e,currentUser.orangeTickets=(currentUser.orangeTickets||0)+t,setTimeout(function(){"function"==typeof showToast&&showToast("🎟️ +1 Orange Ticket — Welcome back! (Total: "+n+")")},2500),"function"==typeof updateRankUI&&updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}catch(e){console.warn("Daily ticket error:",e)}}async function attachReferral(e){const t=localStorage.getItem("btc_referral_code");if(t&&!e.startsWith(t))try{const o=await db.collection("users").where("referralCode","==",t).limit(1).get();let n=null;n=o.empty?null:o.docs[0].id,await db.collection("users").doc(e).update({referredBy:t,referralVerified:!1}),await db.collection("referrals").doc(e).set({referredUser:e,referrerCode:t,referrerUid:n||"",createdAt:firebase.firestore.FieldValue.serverTimestamp(),verified:!1,ticketsAwarded:!1}),localStorage.removeItem("btc_referral_code")}catch(e){console.log("Referral attach error:",e)}}async function checkReferralQualifications(){if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;if(window._referralChecked)return;window._referralChecked=!0;const e=getReferralCode();if(e)try{const t=await db.collection("referrals").where("referrerCode","==",e).where("ticketsAwarded","==",!1).get();if(t.empty)return;let o=0;for(const e of t.docs){const t=e.data().referredUser,n=await db.collection("users").doc(t).get();if(!n.exists)continue;const i=n.data();(i.points||0)>=TICKET_CONFIG.referralPointsThreshold&&(i.totalVisits||0)>=2&&(o+=TICKET_CONFIG.referral,await db.collection("referrals").doc(e.id).update({verified:!0,ticketsAwarded:!0,verifiedAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("users").doc(t).update({referralVerified:!0}))}if(o>0){const e=o*TICKET_CONFIG.pointsPerTicket;currentUser.orangeTickets,"function"==typeof awardPoints&&await awardPoints(e,"🎟️ Referral tickets",null,o),currentUser.orangeTickets=(currentUser.orangeTickets||0)+o,showToast("🎟️ +"+o+" Orange Tickets — Referral"+(o>50?"s":"")+" verified!"),"function"==typeof notifySelfReferral&¬ifySelfReferral(o),updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}}catch(e){console.log("Referral check error:",e)}}async function ensureReferralCode(){if(currentUser&&db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&!currentUser.referralCode){const e=getReferralCode();e&&(await db.collection("users").doc(currentUser.uid).update({referralCode:e}),currentUser.referralCode=e)}}async function getReferralStats(){if(!currentUser||!db)return{total:0,verified:0,pending:0};const e=getReferralCode();if(!e)return{total:0,verified:0,pending:0};try{const t=await db.collection("referrals").where("referrerCode","==",e).get();let o=t.size,n=0,i=0;return t.forEach(e=>{e.data().verified?n++:i++}),{total:o,verified:n,pending:i}}catch(e){return{total:0,verified:0,pending:0}}}function renderTicketsSection(){return'
    Orange Tickets
    '+(currentUser&¤tUser.orangeTickets||0)+'
    Earn tickets by logging in daily (+1), spinning the daily wheel, and referring friends (+50 per verified referral!). Each ticket earned also awards 5 bonus points!

    🏆 The more tickets you have, the higher your chance of winning our 25,000 sats giveaways!
    📅
    Daily Login
    +1 ticket
    🤝
    Referral
    +50 tickets
    '}function renderReferralSection(){const e=getReferralLink();return getReferralCode()?'
    🔗 Referral Program
    Share your link with friends. Earn 50 Orange Tickets for each referral who logs in and earns 2,140+ points (Maxi rank).
    Loading referral stats...
    ':""}function copyReferralLink(){const e=document.getElementById("referralLinkInput");e&&(navigator.clipboard?navigator.clipboard.writeText(e.value).then(function(){showToast("🔗 Referral link copied!")}):(e.select(),document.execCommand("copy"),showToast("🔗 Referral link copied!")))}async function loadReferralStatsUI(){const e=document.getElementById("referralStats");if(!e)return;const t=await getReferralStats();0===t.total?e.innerHTML='No referrals yet. Share your link to start earning!':e.innerHTML='
    👥 Total: '+t.total+'✅ Verified: '+t.verified+'⏳ Pending: '+t.pending+"
    "}async function onUserLoadedTickets(){currentUser&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(await ensureReferralCode(),await awardDailyTicket(),checkReferralQualifications().catch(function(){}))}function getEquippedItems(){try{return JSON.parse(localStorage.getItem("btc_nacho_equipped_multi")||"{}")}catch(e){return{}}}function getEquippedItem(){var e=getEquippedItems();return Object.values(e)[0]||localStorage.getItem("btc_nacho_equipped")||null}window.awardTickets=async function(e,t){if(e&&!(e<1)&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&void 0!==currentUser&¤tUser){currentUser.orangeTickets;var o=e*TICKET_CONFIG.pointsPerTicket;try{"function"==typeof awardPoints&&await awardPoints(o,"🎟️ "+(t||"Orange Tickets"),null,e),currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,"function"==typeof updateRankUI&&updateRankUI()}catch(e){console.warn("[tickets] Award error:",e)}"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Tickets! "+(t||""))}},"undefined"!=typeof window&&captureReferralCode(),function(){const e=function(){const e=(new Date).toISOString().split("T")[0];if(void 0===CHANNELS)return[];const t=Object.keys(CHANNELS),o=[];let n=0;for(let t=0;t{const t=document.querySelector("[onclick*=\"go('"+e+"'\"]");if(t){const e=document.createElement("span");e.style.cssText="position:absolute;top:4px;right:4px;background:#f7931a;color:#fff;font-size:0.55rem;font-weight:900;padding:2px 5px;border-radius:4px;box-shadow:0 0 10px rgba(247,147,26,0.4);",e.textContent="2X PTS",t.style.position="relative",t.appendChild(e)}}),window._dailyBoosts=e}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}(),function(){let e={price:null,blockHeight:null,fees:null,mempoolSize:null,lastFetch:0};const t=3e5;async function o(){const o=Date.now();if(!(o-e.lastFetch900:"true"===e)){var t=document.getElementById("btcTicker");return t&&t.remove(),void document.body.classList.remove("ticker-visible")}var n=document.getElementById("btcTicker");n||((n=document.createElement("div")).id="btcTicker",document.body.prepend(n)),document.body.classList.add("ticker-visible"),n.style.cssText="position:fixed;top:0;left:0;right:0;z-index:10005;background:#030712;border-bottom:1px solid #f7931a;padding:0;height:32px;overflow:hidden;display:flex;align-items:center;font-family:inherit;font-size:0.75rem;color:#94a3b8;line-height:32px;";var i=document.createElement("div");i.id="tickerScroller",i.style.cssText="display:flex;white-space:nowrap;width:max-content;animation:btcTickerScroll 25s linear infinite;will-change:transform;";const a='\n
    \n \n 📡 LOADING SIGNAL...\n \n
    ';i.innerHTML=a+a+a+a,n.innerHTML="",n.appendChild(i);var r=document.getElementById("btcTickerStyle");r||((r=document.createElement("style")).id="btcTickerStyle",document.head.appendChild(r)),r.textContent="\n @keyframes btcTickerScroll { 0% { transform: translateX(0); } 100% { transform: translateX(-50%); } }\n #btcTicker:hover #tickerScroller { animation-play-state: paused; }\n @media(max-width:900px) { \n body.ticker-visible .mobile-bar { top: 32px !important; }\n body.ticker-visible main { padding-top: 130px !important; }\n body.ticker-visible aside { top: 130px !important; z-index: 10006; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n #btcTicker { font-size: 0.65rem; height: 32px; }\n body.ticker-visible .progress-bar { top: 118px !important; }\n }\n @media(min-width:901px) { \n body.ticker-visible aside { padding-top: 32px; }\n body.ticker-visible main { padding-top: 32px; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n body.ticker-visible .progress-bar { top: 32px !important; }\n }",fetch("newsletter-data.json?v="+Date.now()).then(e=>e.json()).then(e=>{const t=n.querySelectorAll(".t-news-items");if(t&&e.news){let o="";e.news.forEach((e,t)=>{var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #'+(t+1)+""+n+""}),t.forEach(e=>e.innerHTML=o)}}).catch(e=>{n.querySelectorAll(".t-news-items").forEach(e=>e.innerHTML="📡 TECHNICAL SIGNAL OFFLINE")}),o(),setInterval(function(){o()},6e4);var s="";setInterval(function(){fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(e){var t=document.querySelectorAll(".t-news-items");if(t.length>0&&e.news&&e.news.length>0){var o="";if(e.news.slice(0,3).forEach(function(e,t){var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #'+(t+1)+""+n+""}),o!==s){s=o;var n=document.getElementById("tickerScroller");t.forEach(function(e){e.innerHTML=o}),n&&(n.style.animation="none",n.offsetHeight,n.style.animation="btcTickerScroll 25s linear infinite")}}}).catch(function(){})},18e5)}function i(e){return e?e>=1e3?"$"+Math.round(e).toLocaleString():"$"+e.toFixed(2):null}window.getNachoLiveData=function(){return e},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",n):n(),window.nachoLiveAnswer=function(t){var o=t.toLowerCase();if(/price|how much is|what.?s bitcoin at|current price|btc price|bitcoin worth|bitcoin cost/.test(o)){var n,a=e.price;if(a||(n=parseFloat(localStorage.getItem("btc_last_price")))&&n>0&&(a=n),!a)return null;var r=i(a),s=["Bitcoin is currently at "+r+"! Still early, {name}. 📈🦌","The current BTC price is "+r+". Number go up technology! 📊","Right now, 1 BTC = "+r+". How many sats are you stacking, {name}? ⚡"];return{answer:s[Math.floor(Math.random()*s.length)],channel:"charts",channelName:"Charts"}}if(/block height|current block|what block|how many blocks|latest block/.test(o))return e.blockHeight?{answer:"We're currently at block "+e.blockHeight.toLocaleString()+"! Every block is history being written, {name}. ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:(n=localStorage.getItem("btc_last_height"))?{answer:"I'm still syncing, but the last block I saw was "+parseInt(n).toLocaleString()+"! ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:null;if(/halving|halvening|next halving|when.*halving|halving countdown/.test(o)){var c=function(){var t=e.blockHeight;if(!t)return null;var o=21e4*Math.ceil(t/21e4),n=o-t;return{nextHalving:o,blocksLeft:n,daysLeft:Math.round(10*n/1440)}}();return c?{answer:"The next halving is at block "+c.nextHalving.toLocaleString()+" -- that's "+c.blocksLeft.toLocaleString()+" blocks away (~"+c.daysLeft+" days). Tick tock, {name}! ⏰",channel:"scarce",channelName:"Scarce"}:null}return null},window.nachoLiveMessage=function(){if(Math.random()>.15)return null;if(o(),!e.price)return null;var t=[];if(e.price){var n=i(e.price);t.push({pose:"cool",text:"BTC is at "+n+" right now, {name}. Just thought you should know. 😎📈"})}return e.blockHeight&&t.push({pose:"brain",text:"We just passed block "+e.blockHeight.toLocaleString()+". Every block is a heartbeat of the network. ⛓️💓"}),0===t.length?null:t[Math.floor(Math.random()*t.length)]},setTimeout(o,3e3),setInterval(o,t),window.toggleTickerSetting=function(){var e=localStorage.getItem("btc_ticker_enabled");if(null===e?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===e){localStorage.setItem("btc_ticker_enabled","false");var t=document.getElementById("btcTicker");t&&t.remove(),document.body.classList.remove("ticker-visible"),"function"==typeof showToast&&showToast("📡 Signal ticker hidden. Refresh to fully apply.")}else localStorage.setItem("btc_ticker_enabled","true"),window._tickerInitialized=!1,n(),"function"==typeof showToast&&showToast("📡 Signal ticker enabled!");"function"==typeof showSettingsPage&&showSettingsPage("prefs")}}(),function(){const e="\"Nacho\"🦌');\">",t='
    🛋️
    🍿
    ';function o(){return"timechain-tv"===window.currentPage||"#timechain-tv"===window.location.hash}const n={default:"🦌",wave:"👋",think:"🤔",celebrate:"🎉",point:"👆",eyes:"👀",fire:"🔥",brain:"🧠",cool:"😎",sleep:"💤",cheese:"🧀",love:"🧡"};window._btcData={price:null,height:null,halvingBlocks:null,lastUpdate:0};const i={whitepaper:{pose:"brain",text:"It looks like you're reading the whitepaper! This is where it all started — 9 pages that changed the world! 📜"},"self-custody":{pose:"point",text:"It looks like you're learning about self-custody! Remember: Nacho keys, nacho cheese. 🧀🔑"},"investment-strategy":{pose:"think",text:"It looks like you're planning your stack strategy! Pro tip: DCA and chill. Time in the market beats timing the market. 📈"},mining:{pose:"fire",text:"It looks like you're exploring mining! Every 10 minutes a new block is born. Beautiful, isn't it? ⛏️"},"privacy-nonkyc":{pose:"eyes",text:"It looks like you value your privacy! Good. A wise buck never reveals his forest location. 🕵️"},"layer-2-lightning":{pose:"celebrate",text:"It looks like you're exploring Lightning! This is how Bitcoin scales to millions of transactions per second! ⚡⚡"},"fun-facts":{pose:"cool",text:"It looks like you're browsing fun facts! This channel is my personal favorite. Don't tell the others. 🤫"},history:{pose:"brain",text:"It looks like you're studying Bitcoin history! Those who don't learn history are doomed to repeat it. 📚"},charts:{pose:"eyes",text:"It looks like you're checking the charts! Number go up technology, am I right? 📊"},"problems-of-money":{pose:"think",text:"It looks like you're learning why fiat is broken! This is where many people get orange-pilled. 🟠"},"giga-chad":{pose:"fire",text:"It looks like you're in the Giga Chad channel! Based and orange-pilled. 💪"},"memes-funny":{pose:"celebrate",text:"It looks like you're looking at memes! A deer of culture, I see. 😏"},"evidence-against-alts":{pose:"cool",text:"It looks like you're reading about altcoins! Spoiler: there's only Bitcoin. 🦌"},scarce:{pose:"brain",text:"It looks like you're learning about scarcity! Only 21 million will ever exist. Even I can't make more. 💎"},decentralized:{pose:"fire",text:"It looks like you're exploring decentralization! No single point of failure. Like a forest — cut one tree, the rest stand strong. 🌲"},secure:{pose:"point",text:"It looks like you're reading about Bitcoin's security! More computing power secures this network than anything else on Earth. 🔒"},money:{pose:"think",text:"It looks like you're learning what money really is! Hint: it's not what the government tells you. 💰"},programmable:{pose:"brain",text:"It looks like you're exploring programmable money! Smart contracts on Bitcoin — the future is being built right here. 🔧"},consensus:{pose:"think",text:"It looks like you're studying consensus! This is how thousands of nodes agree without a boss. Democracy at the protocol level. 🤝"},"difficulty-adjustment":{pose:"brain",text:"It looks like you're learning about the difficulty adjustment! The most elegant part of Bitcoin's design, in my humble deer opinion. ⚙️"},"blockchain-timechain":{pose:"fire",text:"It looks like you're reading about the timechain! Fun fact: many Bitcoiners prefer 'timechain' over 'blockchain.' ⛓️"},"pow-vs-pos":{pose:"cool",text:"It looks like you're comparing PoW vs PoS! Spoiler: Proof of Work wins. Always has. 🏆"},"articles-threads":{pose:"brain",text:"It looks like you're browsing articles! This channel has some of the best Bitcoin writing ever published. Take your time! 📰"},books:{pose:"love",text:"It looks like you're checking out Bitcoin books! The Bitcoin Standard changed my life. Well, my deer life. 📖"},podcasts:{pose:"cool",text:"It looks like you're browsing podcasts! Great for learning while you graze... I mean, commute. 🎧"},"movies-tv":{pose:"celebrate",text:"It looks like you're looking at Bitcoin movies! Grab some popcorn (and cheese). 🍿🧀"},"one-stop-shop":{pose:"point",text:"It looks like you're in the one-stop shop! This is the starter pack — everything a newcomer needs. 🎁"},regulation:{pose:"think",text:"It looks like you're reading about regulation! Governments are slowly figuring out they can't stop Bitcoin. 🏛️"},nodes:{pose:"fire",text:"It looks like you're learning about nodes! Running your own node = verifying everything yourself. Trust no one! 🖥️"},geopolitics___macroeconomics:{pose:"brain",text:"It looks like you're exploring the macro picture! Bitcoin isn't just money — it's a geopolitical shift. 🌍"},"jobs-earn":{pose:"celebrate",text:"It looks like you're checking out Bitcoin jobs! Get paid in sats — the dream! 💼⚡"},"apps-tools-services-models":{pose:"point",text:"It looks like you're browsing Bitcoin tools and apps! So many ways to use the network. 🛠️"},music:{pose:"celebrate",text:"It looks like you're checking Bitcoin music! Yes, there are Bitcoin songs. And yes, they slap. 🎵"},"art-inspiration":{pose:"love",text:"It looks like you're browsing Bitcoin art! Creativity meets sound money. Beautiful. 🎨"},games:{pose:"cool",text:"It looks like you're checking out Bitcoin games! Learn while you play — my kind of strategy. 🎮"},health:{pose:"love",text:"It looks like you're in the health channel! Sound money, sound body, sound mind. 🏋️"},nostr:{pose:"fire",text:"It looks like you're exploring Nostr! Decentralized social media — Bitcoin's best friend. 💜"},curriculum:{pose:"brain",text:"It looks like you're looking at Bitcoin education materials! Perfect for teachers and students! 📝"},"misconceptions-fud":{pose:"cool",text:"It looks like you're fighting FUD! Arm yourself with facts. This channel is your ammo. 🛡️"},cryptography:{pose:"brain",text:"It looks like you're diving into cryptography! This is the math that makes Bitcoin unbreakable. 🔢"},"tail-emission":{pose:"think",text:"It looks like you're reading about tail emission! A big debate in the Bitcoin world. What do you think? 🤔"},stablecoins:{pose:"eyes",text:"It looks like you're reading about stablecoins! Useful on-ramps, but remember — Bitcoin is the exit. 🚪"}},a=[{pose:"brain",text:"📜 Have you read Bitcoin's Whitepaper? It's only 9 pages and it started a revolution! Read it here → 🦌"},{pose:"fire",text:'🔥 Pro tip: Read the Bitcoin Whitepaper — it\'s the Genesis document! Only 9 pages changed the world forever. Check it out →'},{pose:"point",text:"💡 Tip: The sidebar on the left has ALL topics organized by category. Tap a category to expand it!"},{pose:"point",text:"💡 Tip: Click the 🎲 dice button to jump to a random channel — great for discovering new topics!"},{pose:"point",text:"💡 Tip: Use the 🔍 search button to find any subject across all 146+ topics instantly!"},{pose:"point",text:"💡 Tip: Click the Bitcoin logo at the top to return to the homepage anytime!"},{pose:"point",text:"💡 Tip: Hit the ⭐ button on any channel to save it to your favorites for quick access!"},{pose:"point",text:"💡 Tip: Your Exploration Map on the homepage shows every channel you've visited. Try to light them all up! 🗺️"},{pose:"point",text:"💡 Tip: Channels you've already read get a ✓ checkmark in the sidebar. Track your progress!"},{pose:"brain",text:"💡 Tip: You earn XP by visiting daily (+5), opening new topics (+10), and reading (+15 per 30 sec)!"},{pose:"point",text:"💡 Tip: Check the leaderboard to see how you rank against other Bitcoiners! Click your rank bar at the bottom."},{pose:"fire",text:"💡 Tip: Keep a daily streak going! Every 5 days in a row = bonus 100 points! 🔥"},{pose:"point",text:"💡 Tip: There are 9 rank levels from Normie to Satoshi. What level are you? Check Settings → Data!"},{pose:"cheese",text:"💡 Tip: Earn Orange Tickets daily just by logging in! More tickets = higher giveaway chances! 🎟️"},{pose:"point",text:"💡 Tip: Share your referral link (Settings → Tickets) and earn 50 tickets for each verified friend!"},{pose:"celebrate",text:"💡 Tip: Each Orange Ticket also gives you 5 bonus XP! Tickets + points = double reward! 🎟️⭐"},{pose:"brain",text:"💡 Tip: Hit 'Start a Quest' in the sidebar to test your Bitcoin knowledge and earn XP! ⚡"},{pose:"fire",text:"💡 Tip: The Bitcoin Scholar Certification Quest is the ultimate test — pass it to earn the 🎓 badge + 300 points!"},{pose:"eyes",text:"💡 Tip: There are 9 hidden badges to unlock! Each one awards points. Explore the site to discover them all! 🏅"},{pose:"point",text:"💡 Tip: Badges scale in points from 25 to 1,000! The hardest ones are worth the most! 💰"},{pose:"point",text:"💡 Tip: Click your username or the sign-in button to access your Settings — Account, Tickets, Prefs, Security, Data!"},{pose:"point",text:"💡 Tip: You can switch between dark and light theme in Settings → Prefs! 🌙☀️"},{pose:"point",text:"💡 Tip: The site works offline too! Add it to your home screen as an app! 📱"},{pose:"point",text:"💡 Tip: You can export all your data anytime in Settings → Data. Your data is yours! 📥"},{pose:"point",text:"💡 Tip: Don't like me? Long-press to hide me. But I'll miss you. 🥺 (You can bring me back in Settings → Prefs)"},{pose:"brain",text:"💡 Tip: YouTube videos are embedded right in the channels — click to play without leaving the site! 🎬"},{pose:"point",text:"💡 Tip: Tweets are embedded too! Click '▶ Click to display tweet' to expand them. 🐦"},{pose:"fire",text:'📺 Tip: Timechain TV streams 21 curated channels 24/7 — earn 10 pts per 10 min watched! Tune in →'},{pose:"cheese",text:'🛋️ Tip: Couch with me on Timechain TV — I react to every channel you tune into! 🍿 Let\'s chill →'},{pose:"point",text:"💡 Tip: Timechain TV has a global clock — every viewer on the same channel sees the same moment. True synchronized TV! ⏰"},{pose:"celebrate",text:"👑 Tip: Watch 24 hours on Timechain TV to unlock the 👑 Couch King badge + 100 points!"},{pose:"point",text:"💡 Tip: The Quote of the Day on the homepage changes daily — click it to jump to the related channel! 💬"},{pose:"point",text:"💡 Tip: New to Bitcoin? Start with the 'one-stop-shop' channel — it has everything to get you started! 🎯"},{pose:"brain",text:"💡 Tip: Channels are organized into Properties, Experienced Topics, Resources, and Additional Info. Start with Properties!"},{pose:"point",text:"💡 Tip: Post in the PlebTalk to earn the 📣 Town Crier badge + 100 points! Press T or find it in the sidebar."},{pose:"point",text:"💡 Tip: Reply to PlebTalk posts to earn the 💬 Conversationalist badge + 75 points! Join the discussion!"},{pose:"cheese",text:"💡 Tip: LightningMart lets you buy and sell with Bitcoin! List an item to earn the 🏪 Merchant badge! Press S to check it out."},{pose:"point",text:"💡 Tip: Found something cool on LightningMart? Contact the seller to earn the 🛍️ Shopper badge!"},{pose:"celebrate",text:"💡 Tip: Check out my closet in Settings → Nacho! You can dress me up with items you unlock! 🎽🦌"},{pose:"point",text:"💡 Tip: Closet items are colorable! Equip an item, then tap 🎨 Color to customize it! 🌈"},{pose:"fire",text:"💡 Tip: Spin the Daily Wheel every day for free Orange Tickets! Look for the banner at the top of the homepage! 🎡"},{pose:"fire",text:"💡 Tip: Press N to enter Nacho Mode — a full chat experience where I answer your Bitcoin questions with AI! 🦌🧠"},{pose:"point",text:"💡 Tip: In Nacho Mode, press ↑ to recall your previous questions — just like in a chat app!"},{pose:"brain",text:"💡 Tip: Nacho Mode shows the live Bitcoin price in the header! Check it anytime! ₿"},{pose:"point",text:"💡 Tip: Tap the 🧒 button in Nacho Mode to toggle ELI5 mode — I'll explain everything in super simple language!"},{pose:"celebrate",text:"💡 Tip: In Nacho Mode, tap '🗺️ Start Bitcoin Journey' for a guided 10-step learning path from beginner to pro!"},{pose:"point",text:"💡 Tip: Tap '🎮 Quiz Me' in Nacho Mode to test your knowledge and earn XP! 🏆"},{pose:"point",text:"💡 Tip: Nacho Mode has topic chips — tap them if you don't know what to ask! ⚡ Lightning, ⛏️ Mining, and more!"},{pose:"brain",text:"💡 Tip: Every answer in Nacho Mode has 👍👎 buttons — your feedback helps me get smarter!"},{pose:"point",text:"💡 Tip: You can share any Nacho answer with the 📤 Share button — spread the Bitcoin knowledge! 🌍"},{pose:"fire",text:"💡 Tip: Use your voice! Tap 🎙️ in Nacho Mode to ask me questions by speaking! 🗣️"},{pose:"point",text:"💡 Tip: Nacho Mode saves your full chat history — come back anytime to pick up where you left off!"},{pose:"celebrate",text:"💡 Tip: Ask me 10, 25, 50, or 100 questions in Nacho Mode to unlock special milestones! 🎉"},{pose:"fire",text:"💡 Tip: We have a PlebTalk! Press T or click '🗣️ PlebTalk' in the sidebar to discuss Bitcoin! 💬"},{pose:"point",text:"💡 Tip: In PlebTalk, upvote great posts with ⚡ and earn +10 points for posting, +5 for replying!"},{pose:"brain",text:"💡 Tip: PlebTalk posts can include links! Share interesting Bitcoin articles or resources with the community! 🔗"},{pose:"point",text:"💡 Tip: Set up your profile in Settings → Account! Add a bio, website, Twitter, Nostr, and Lightning address! 📝"},{pose:"eyes",text:"💡 Tip: Click any user on the leaderboard to see their profile — including their bio and social links! 👀"},{pose:"fire",text:"💡 Tip: The Scholar Certification awards 2,100 points — that's 21 million in sats! The magic number! 🎓"},{pose:"cheese",text:"💡 Tip: Dress me up! Check out Nacho's Closet in Settings → Stats/Nacho. Unlock items as our friendship grows! 👔🦌"},{pose:"cool",text:"💡 Tip: I wear my closet items in Nacho Mode too! Equip something and check out my hero section! 🦸"},{pose:"point",text:"💡 Tip: Press ? to see ALL keyboard shortcuts! N=Nacho, T=PlebTalk, P=Donate, L=Leaderboard, and more! ⌨️"},{pose:"point",text:"💡 Tip: Press A to quickly ask me a question from any page — no need to enter Nacho Mode! 🦌"},{pose:"cool",text:"💡 Tip: You can sign in with Nostr! If you have Alby or nos2x, click the 🟣 Nostr button on the sign-in page! ⚡"},{pose:"love",text:"💡 Tip: Press P to open the donation page — support the archive with Lightning! Every sat counts! ⚡🧡"},{pose:"point",text:"💡 Tip: The site supports 15+ languages! Change it in Settings → Prefs. I can even answer in your language! 🌍"},{pose:"point",text:"💡 Tip: You can DM any user! Tap their name on the leaderboard → 💬 Message. Your inbox is in the DMs tab! 📬"},{pose:"eyes",text:"💡 Tip: DMs are protected — you need 50 points and a 24h-old account to message. No scammers allowed! 🛡️"},{pose:"point",text:"💡 Tip: Never share your seed phrase, private keys, or send Bitcoin to strangers in DMs! Stay safe! 🔒"},{pose:"fire",text:"💡 Tip: Challenge other Bitcoiners to PVP trivia battles! Press X or find ⚔️ PVP in the sidebar! Who knows more? 🏆"},{pose:"celebrate",text:"💡 Tip: Win PVP battles to climb the PVP leaderboard! Your wins and losses show on your profile! ⚔️"},{pose:"fire",text:"💡 Tip: Bitcoin Beats is our community music platform! Listen, upload, and discover tracks made by Bitcoiners! 🎸🦌"},{pose:"point",text:"💡 Tip: Tap a song title on Bitcoin Beats to see full track details — artist, genre, play count, and more! 🎵"},{pose:"celebrate",text:"💡 Tip: Upload your own music on Bitcoin Beats! Hit the Upload tab and share your sound with the community! 🎤"},{pose:"point",text:"💡 Tip: Like tracks on Bitcoin Beats with ❤️ and leave comments! Support Bitcoin musicians! 🎶"},{pose:"fire",text:"💡 Tip: IRL Sync helps you find Bitcoin meetups near you! Create events, RSVP, and meet Bitcoiners in person! 🤝"},{pose:"point",text:"💡 Tip: Can't find a meetup near you? Create one on IRL Sync! Be the node that connects your local community! 🌐"},{pose:"point",text:"💡 Tip: Try the Price Prediction game! Guess if Bitcoin goes up or down in 24h and track your accuracy! 📈📉"},{pose:"celebrate",text:"💡 Tip: I have a story to tell! Tap the 📖 next to me for a new chapter every day. It's an adventure! 🦌✨"}],r=[{pose:"celebrate",text:"You're doing great, {name}! Most people never even start learning about Bitcoin. You're already ahead. 🦌💪"},{pose:"fire",text:"Keep going, {name}! You're stacking knowledge like a true pleb! 📚🔥"},{pose:"love",text:"Nacho is proud of your progress, {name}! You're further down the rabbit hole than most. 🐇"},{pose:"cool",text:"Stay humble, stack sats, stack knowledge. You're doing all three, {name}. 😎"},{pose:"celebrate",text:"Every channel you read makes the FUD weaker, {name}! Keep it up! 💪"},{pose:"brain",text:"{name}, your brain is getting more orange-pilled by the minute! 🧠🟠"},{pose:"fire",text:"Tick tock, next block... and you're getting smarter with each one, {name}! ⏰"},{pose:"love",text:"The fact that you're here learning puts you ahead of 99% of people, {name}. For real. 🧡"},{pose:"celebrate",text:"Imagine telling your future self you were learning about Bitcoin in 2026, {name}. They'll thank you! 🙏"},{pose:"fire",text:"{name}, you're building generational knowledge right now. No big deal. 🏗️"},{pose:"cool",text:"Diamond hands start with a diamond mind. You're forging yours right now, {name}! 💎🧠"},{pose:"love",text:"The journey of a thousand sats begins with a single channel, {name}. You've read way more than that! 🦌"},{pose:"celebrate",text:"You're not just learning Bitcoin, {name} — you're opting out of the broken system. Respect. ✊"},{pose:"fire",text:"Number go up, knowledge go up. You're winning on both fronts, {name}! 📈🧠"},{pose:"brain",text:"Every nocioner who ever became a maxi started exactly where you are, {name}. Keep reading! 📖"}],s=[{pose:"cheese",text:"Nacho keys, nacho cheese. It's not just a tagline, it's a lifestyle. 🧀🔑"},{pose:"fire",text:"Nacho sats... They're all mine! 💰🦌"},{pose:"cheese",text:"My seed phrase? 24 different types of cheese. Very secure. Very delicious. 🔐🧀"},{pose:"cheese",text:"Bitcoin fixes everything. Except my cheese addiction. Some things are unfixable. 🧀"},{pose:"cool",text:"Live Free or Die — that's the New Hampshire motto. Also my approach to Bitcoin. 🦌🗻"},{pose:"fire",text:"These antlers aren't just for show. I'm the strongest buck in NH and the most orange-pilled. 💪🦌"},{pose:"default",text:"In a world of unlimited printing, be a limited supply. Like Bitcoin. And like me — there's only one Nacho. 🦌"},{pose:"default",text:"Some people have angel investors. You have an angel deer. You're welcome. 😇🦌"},{pose:"cool",text:"I'm not saying I'm Satoshi, but have you ever seen us in the same room? 🤫"},{pose:"eyes",text:"I've been watching you learn, {name}. Not in a creepy way. In a proud buck way. 👀"},{pose:"sleep",text:"*yawns* Don't mind me, just HODLing this corner of your screen... 💤"},{pose:"fire",text:"Few understand this... but YOU will, {name}. That's why you're here. 🔥"},{pose:"think",text:"What's a deer's favorite block? The next one! ⛏️"},{pose:"celebrate",text:"Why did Bitcoin break up with the dollar? It found someone with less baggage and a fixed supply! 💔😂"},{pose:"cool",text:"I told my friend to buy Bitcoin in 2015. He bought Dogecoin instead. We don't talk anymore. 🐕"},{pose:"think",text:"An altcoiner walks into a bar. Orders a round for everyone. Card declines. 😂"},{pose:"cheese",text:"How does a Bitcoiner cut their pizza? Into 100 million slices. 🍕"},{pose:"cool",text:"My financial advisor said diversify. So I have Bitcoin on a hardware wallet AND a paper backup. 😎"},{pose:"celebrate",text:"Knock knock. Who's there? Fiat. Fiat who? Exactly. Nobody remembers it either. 🪦"},{pose:"think",text:"What's the difference between a dollar and a Bitcoin? One goes to zero, the other came from zero. 📉📈"},{pose:"default",text:"I tried to explain Bitcoin to a goldfish once. Went about as well as explaining it to Peter Schiff. 🐟"},{pose:"cool",text:"Bitcoiners don't have FOMO. They have FONGO — Fear Of Not Getting Orange-pilled. 🟠"},{pose:"brain",text:"₿ Fact: Satoshi Nakamoto's identity is still unknown. Could be one person, could be a group. Could be a deer. 🦌"},{pose:"brain",text:"₿ Fact: The Bitcoin pizza transaction in 2010 used 10,000 BTC for two pizzas. That's billions today. 🍕"},{pose:"brain",text:"₿ Fact: There will only ever be 21 million Bitcoin. About 19.5 million have already been mined! 💎"},{pose:"brain",text:"₿ Fact: Bitcoin's network has never been hacked. Not once. 13+ years of perfect security. 🔒"},{pose:"brain",text:"₿ Fact: The smallest unit of Bitcoin is called a 'satoshi' — 0.00000001 BTC. You can own sats! ⚡"},{pose:"brain",text:"₿ Fact: El Salvador was the first country to make Bitcoin legal tender in 2021! 🇸🇻"},{pose:"brain",text:"₿ Fact: Bitcoin mining uses less energy than clothes dryers in the US. But nobody writes angry articles about dryers. 🧺"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is only 9 pages long. The US tax code is over 75,000 pages. Which one works better? 📜"},{pose:"brain",text:"₿ Fact: 'HODL' came from a typo in a passionate forum post in 2013. It became the most famous word in crypto. 😂"},{pose:"brain",text:"₿ Fact: Bitcoin processes over $10 billion in transactions daily. And it never takes a day off! 💰"},{pose:"brain",text:"₿ Fact: The genesis block contains a hidden message: 'Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"₿ Fact: You can run a full Bitcoin node on a Raspberry Pi for about $50. Be your own bank! 🖥️"},{pose:"brain",text:"₿ Fact: Bitcoin's inflation rate is now lower than gold's. Digital gold? More like better-than-gold. 🥇"},{pose:"brain",text:"₿ Fact: The Lightning Network can handle millions of transactions per second. Visa does about 1,700. ⚡"},{pose:"brain",text:"₿ Fact: About 20% of all Bitcoin is estimated to be permanently lost. That makes yours even more scarce! 🔑"},{pose:"brain",text:"₿ Fact: Bitcoin's first price was $0.000994 — less than a tenth of a penny! For 10 months it had NO price at all. 💰"},{pose:"brain",text:"₿ Fact: The chance of guessing someone's private key is the same as winning Powerball 7 times in a row! 🎰🔐"},{pose:"brain",text:"₿ Fact: The first Bitcoin faucet gave away 5 WHOLE BITCOINS per person just for solving a captcha! 🤯"},{pose:"brain",text:"₿ Fact: You only need the FIRST 4 LETTERS of each seed word to restore your wallet. All 2,048 BIP39 words have unique first 4 letters! 🔑"},{pose:"brain",text:"₿ Fact: 'Bacon' repeated 24 times is technically a valid Bitcoin seed phrase. It passes the checksum! 🥓"},{pose:"brain",text:"₿ Fact: Bitcoin has 99.987% uptime — only 14 hours of downtime in 15+ years. That rivals Google and Amazon! 🏆"},{pose:"brain",text:"₿ Fact: Satoshi's birthday (April 5) is the date of Executive Order 6102, when the US made it ILLEGAL to own gold! 🎂📜"},{pose:"brain",text:"₿ Fact: The difficulty adjustment happens every 2,016 blocks. Read that backwards: 6102 — the gold confiscation order! 🤯"},{pose:"brain",text:"₿ Fact: 2-3 million Bitcoin are permanently lost forever. That makes YOUR sats even more scarce! 💎"},{pose:"brain",text:"₿ Fact: Satoshi wrote 575 forum posts, 31,000 lines of code, used 22,000+ addresses, and never reused one! 📝"},{pose:"brain",text:"₿ Fact: Satoshi's ~1 million Bitcoin have NEVER moved. Not one satoshi. Worth tens of billions. 👑"},{pose:"brain",text:"₿ Fact: 70% of ALL US dollars in circulation were created after 2008. Over 40% since 2020 alone! 💸"},{pose:"brain",text:"₿ Fact: One dollar today buys what 4 CENTS bought in 1913. That's a 96% loss in purchasing power! 📉"},{pose:"brain",text:"₿ Fact: In August 2010, a bug created 184 BILLION fake Bitcoin. The community fixed it in hours! The largest reorg ever — 53 blocks. 😱"},{pose:"brain",text:"₿ Fact: 61% of Ethereum nodes run in the cloud. Amazon alone hosts ~25% of them. Bitcoin nodes run on Raspberry Pis worldwide! ☁️🆚🖥️"},{pose:"brain",text:"₿ Fact: Milton Friedman, Nobel Prize economist, predicted Bitcoin in 1999 — 10 years before it existed! 🔮"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is encoded IN the blockchain at block 230,009. It will exist as long as Bitcoin does! 📄⛓️"},{pose:"brain",text:"₿ Fact: In July 2024, a tiny Bitaxe miner with just 3 TH/s found a block — a 1-in-3,500 YEAR chance! ⛏️🎯"},{pose:"brain",text:"₿ Fact: 99% of all Bitcoin will be mined by 2035. The very last fraction won't be mined until ~2140! ⏳"},{pose:"brain",text:"₿ Fact: The original Bitcoin code contained the beginnings of a POKER GAME that Satoshi started but never finished! 🃏"},{pose:"brain",text:"₿ Fact: Only 0.06% of Bitcoin Core's code remains unchanged from what Satoshi originally wrote. Open source at its finest! 💻"},{pose:"brain",text:"₿ Fact: Christmas lights in the US alone consume more energy than the entire Bitcoin network! 🎄⚡"},{pose:"brain",text:"₿ Fact: Bitcoin mining captures methane that's 84x more warming than CO2, turning waste into sound money! 🌱"},{pose:"brain",text:"₿ Fact: NO ONE who bought Bitcoin and held for 4+ years has EVER lost money. Not once in 15+ years! 📈 (NFA)"},{pose:"brain",text:"₿ Fact: Michael Saylor said The Bitcoin Standard was 'the most impactful on our way of thinking at MicroStrategy.' 📚"},{pose:"brain",text:"₿ Fact: Gigi calls Bitcoin 'an inexhaustible teacher.' His 21 Lessons is free at 21lessons.com! 📖🧡"},{pose:"brain",text:"₿ Fact: Tomer Strolight says Satoshi's coins aren't the real treasure. The real treasure is the journey Bitcoin sends you on! 👑"},{pose:"brain",text:"₿ Fact: Bitcoin is to money what zero was to mathematics — the missing piece that makes everything work better! 🔢"},{pose:"brain",text:"₿ Fact: Every aspect of Bitcoin is TEXT — and text is speech, protected by the First Amendment! You can't ban math. 🗽"},{pose:"brain",text:"₿ Fact: Only about 2-4% of the world owns any Bitcoin. If you hold sats, you're still incredibly early! 🌍"},{pose:"think",text:'"The root problem with conventional currency is all the trust that\'s required to make it work." — Satoshi 🧠'},{pose:"think",text:'"Give me control of a nation\'s money and I care not who makes its laws." — Mayer Rothschild 🏦'},{pose:"think",text:'"We have elected to put our money and faith in a mathematical framework free of politics." — Tyler Winklevoss 🔢'},{pose:"think",text:'"Bitcoin is the most important invention since the internet." 🌐'},{pose:"fire",text:'"Fix the money, fix the world." Simple as that. 🔧🌍'},{pose:"think",text:'"Bitcoin is a swarm of cyber hornets serving the goddess of wisdom." — Michael Saylor 🐝'},{pose:"cool",text:'"Running Bitcoin." — Hal Finney, January 10, 2009. The first tweet about Bitcoin. 🏃'},{pose:"celebrate",text:"HODL your knowledge. Never sell what you've learned! 💎🙌"},{pose:"think",text:"Roses are red, fiat is dead, stack sats instead! 🌹"},{pose:"cool",text:"I've been orange-pilled since the day I grew these antlers. 🟠🦌"},{pose:"celebrate",text:"What's stronger — my antlers or Bitcoin's security? Trick question. Both unbreakable. 💪🔒"},{pose:"default",text:"The deer in New Hampshire are talking about Bitcoin. Okay, it's just me. But still. 🗻🦌"},{pose:"cheese",text:"If I had a satoshi for every time someone asked me about crypto... I'd tell them it's Bitcoin, not crypto. 🧀"},{pose:"cool",text:"My antlers pick up the Bitcoin network signal. That's not true, but it sounds cool. 📡🦌"},{pose:"fire",text:"They said Bitcoin was dead 477 times, {name}. And here we are. Still stacking. 🦌💪"},{pose:"eyes",text:"The forest is full of distractions. I stick to the trail marked ₿. 🌲"},{pose:"celebrate",text:"When in doubt, zoom out, {name}. That goes for the chart AND the rabbit hole. 🔭"},{pose:"cool",text:"Oh deer, another all-time high? I'm not surprised. 🦌📈"},{pose:"cheese",text:"What do you call a deer who loves Bitcoin? A buck-hodler! 🦌💎"},{pose:"celebrate",text:"I'm fawned of Bitcoin. Get it? ...I'll see myself out. 🦌😂"},{pose:"think",text:"People say Bitcoin is hard to understand. I say it's deer-ly obvious! 🦌💡"},{pose:"cool",text:"I don't always check the charts, but when I doe, I HODL. 🦌😎"},{pose:"fire",text:"Just earned some sats! Another buck in the wallet! 💰🦌"},{pose:"cheese",text:"Why do deer make great Bitcoiners? Because we never sell — we just stag-ger through the dips! 🦌📉📈"},{pose:"celebrate",text:"This site really helps you get to the hart of Bitcoin! ...Sorry, deer puns are my specialty. 🦌❤️"},{pose:"think",text:"Fiat currency is on its last legs. Lucky for me, I have four of them! 🦌🏃"},{pose:"cool",text:"Did you hear about the deer who understood Bitcoin? He was considered a doe-cipherpunk! 🦌🛡️"},{pose:"fire",text:"Some say the Bitcoin market is wild. Well, I AM a wild animal, so I fit right in! 🦌🔥"},{pose:"cheese",text:"I tried mining Bitcoin with my hooves. It was un-fawn-tunately not very efficient. ⛏️🦌"},{pose:"celebrate",text:"What's a deer's favorite cryptocurrency? Bit-coin, because we love our bits of grass too! 🌿🦌"},{pose:"think",text:"My financial advice? Be a deer and HODL. That's not real advice though, I'm literally a deer. 🦌📜"},{pose:"cool",text:"They call me a stag-ger-ing intellect when it comes to Bitcoin. Okay, I call myself that. 🦌🧠"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 That's not just my catchphrase — it's financial wisdom from a deer."},{pose:"cheese",text:"Remember folks: Nacho keys, nacho cheese! If you don't hold the keys, you don't hold the cheddar. 🧀"},{pose:"fire",text:"I'm not just any deer. I'm a New Hampshire buck — Live Free or Die. And I choose Bitcoin. 🗻🦌"},{pose:"cool",text:"Why did the deer buy a hardware wallet? Because he was tired of getting buck-ed by exchanges! 🦌🔐"},{pose:"think",text:"What do you call a deer who understands monetary policy? A buck who knows his doe! 🦌💰"},{pose:"celebrate",text:"I told my doe friend about Bitcoin. Now she's a whole doe-llar maximalist! 🦌🟠"},{pose:"cheese",text:"I'm not fawning over altcoins. I'm a Bitcoin-only buck. Always have been, always will be. 🦌"},{pose:"fire",text:"My antlers pick up the Bitcoin signal better than any antenna. Built-in orange frequency! 📡🦌"},{pose:"cool",text:"They say a buck in the hand is worth two in the bush. I say a sat stacked is worth a thousand fiat notes. 💎"},{pose:"think",text:"What's a deer's favorite consensus mechanism? Proof of Antlers! 🦌⛏️ ...okay, it's Proof of Work."},{pose:"celebrate",text:"Just a buck from the Granite State, orange-pilling the internet one human at a time! 🗻🟠"},{pose:"cheese",text:"I tried explaining multisig to a squirrel. He said he'd rather just bury his nuts. Different strokes! 🐿️🦌"},{pose:"default",text:"Some deer migrate south for winter. I migrate to the blockchain. It's warmer there. ⛓️🦌"},{pose:"fire",text:"These antlers have been HODLing since block 1. Diamond antlers. 💎🦌"},{pose:"cool",text:"New Hampshire motto: Live Free or Die. Bitcoin motto: Don't Trust, Verify. Same energy. 🦌🗽"},{pose:"think",text:"What do you get when a deer reads the whitepaper? An un-fawn-gettable experience! 📄🦌"},{pose:"cheese",text:"A buck walks into a bar. Orders a round for everyone. Pays in Lightning. ⚡🦌 Instant. Nearly free."},{pose:"celebrate",text:"I'm the most antler-preneurial deer you'll ever meet. My business? Bitcoin education! 🦌📚"},{pose:"default",text:"Fun deer fact: I shed my antlers every year and grow them back bigger. Just like Bitcoin sheds FUD and grows back stronger! 🦌📈"},{pose:"fire",text:"The forest has bears and bulls. I'm a buck — and bucks are ALWAYS bullish on Bitcoin! 🦌🚀"},{pose:"cool",text:"In NH we have no sales tax and no income tax. We also have me, the most based buck in the state. 🗻🦌"},{pose:"cheese",text:"Nacho keys, nacho cheese! Nacho node, nacho rules! Nacho seed phrase, nacho sats! 🧀🔑🦌"},{pose:"think",text:"What's a deer's least favorite thing? A central bank. We prefer de-deer-centralization! 🦌🏛️"},{pose:"celebrate",text:"Why am I orange? Because I was born orange-pilled, {name}! It's in my fur! 🟠🦌"},{pose:"brain",text:"🧠 Bitcoin fact: The first Bitcoin transaction was 10,000 BTC for two pizzas on May 22, 2010. We celebrate it as Bitcoin Pizza Day every year! 🍕"},{pose:"brain",text:"🧠 Did you know? Satoshi Nakamoto mined ~1.1 million BTC and never moved a single one. That's conviction. 🦌"},{pose:"brain",text:"🧠 Fact: Bitcoin's code has been running since January 3, 2009 with 99.99% uptime. No CEO, no office, no downtime. 🏆"},{pose:"brain",text:"🧠 The Genesis Block contains the message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"🧠 There will only ever be 21 million Bitcoin. Currently ~19.6 million have been mined, and ~4 million are estimated lost forever. 🔢"},{pose:"brain",text:"🧠 Bitcoin's difficulty adjustment happens every 2,016 blocks (~2 weeks). It's the most elegant part of the protocol! ⚙️"},{pose:"brain",text:"🧠 Hal Finney received the first-ever Bitcoin transaction from Satoshi on January 12, 2009. His tweet: 'Running bitcoin.' 🏃"},{pose:"brain",text:"🧠 Bitcoin mining doesn't solve 'complex math problems.' Miners guess random nonces and hash them through SHA-256. It's a brute-force lottery! 🎲"},{pose:"brain",text:"🧠 The Lightning Network can process millions of transactions per second. Visa does about 65,000. ⚡"},{pose:"brain",text:"🧠 Bitcoin uses less than 0.1% of global energy. And over 50% of mining uses renewable energy sources. 🌱"},{pose:"brain",text:"🧠 The smallest unit of Bitcoin is called a 'satoshi' — 1 BTC = 100,000,000 sats. Named after the creator! ⚡"},{pose:"brain",text:"🧠 In 2021, El Salvador became the first country to adopt Bitcoin as legal tender. 🇸🇻"},{pose:"brain",text:"🧠 Fact: Bitcoin has survived over 470+ 'obituaries' — media declaring it dead. It's still here. It's still growing. 💀→🚀"},{pose:"brain",text:"🧠 The Bitcoin network is secured by more computational power than all the world's supercomputers combined. 🛡️"},{pose:"brain",text:"🧠 'Not your keys, not your coins' — this phrase became famous after the Mt. Gox hack in 2014 where 850,000 BTC were lost. 🔑"},{pose:"brain",text:"🧠 Bitcoin's stock-to-flow ratio after the 2024 halving is higher than gold's. It's the hardest money ever created. 💎"},{pose:"brain",text:"🧠 The Blocksize Wars of 2015-2017 proved that users — not miners or corporations — control Bitcoin's rules. 🏛️"},{pose:"brain",text:"🧠 Fun fact: You can run a full Bitcoin node on a $50 Raspberry Pi. Don't trust, verify! 🖥️"},{pose:"brain",text:"🧠 Bitcoin was worth $0 in 2009. If you bought $1 of Bitcoin at $0.001, you'd have billions today. Time in the market beats timing the market! ⏰"},{pose:"brain",text:"🧠 The Cantillon Effect: when governments print money, those closest to the printer benefit first. Bitcoin eliminates this unfair advantage. 💡"},{pose:"brain",text:"🧠 CoinJoin transactions mix multiple users' inputs together, making it nearly impossible to trace who sent what to whom. Privacy matters! 🤫"},{pose:"brain",text:"🧠 Satoshi's last known message was in April 2011: 'I've moved on to other things.' The greatest mic drop in history. 🎤⬇️"},{pose:"brain",text:"🧠 Taproot, activated in 2021, brought Schnorr signatures to Bitcoin — improving privacy and enabling more complex smart contracts. 🧰"},{pose:"brain",text:"🧠 The Bitcoin whitepaper is only 9 pages long. Nine pages that changed the world. Have you read it? 📄"},{pose:"brain",text:"🧠 Bitcoin's hash rate is measured in exahashes per second. One exahash = 1 quintillion hashes. Per SECOND. 🤯"}],c=[{pose:"wave",text:"👋 Hey, {name}! I'm Nacho — a strong buck from New Hampshire! Click me anytime for Bitcoin tips and wisdom. 🦌💪"},{pose:"wave",text:"👋 Welcome back, {name}! Your friendly NH buck missed you! Ready to tackle some Bitcoin knowledge today? 💪"},{pose:"wave",text:"👋 Nacho here, {name}! The strongest buck in New Hampshire and your Bitcoin guide. Let's learn something! 🦌"},{pose:"wave",text:"Hey {name}! 🦌 Back for more? I've got 145 channels of Bitcoin knowledge waiting for you!"},{pose:"cool",text:"Yo {name}! 😎 Nacho's in the house. What are we learning about today?"},{pose:"fire",text:"🔥 {name}! Another day, another sat stacked. Let's make today count!"},{pose:"celebrate",text:"{name}! 🎉 Great to see you. Did you know this archive has over 8,800 Bitcoin messages? Dig in!"},{pose:"brain",text:"Welcome, {name}! 🧠 Fun fact: the more you learn about Bitcoin, the more you realize there's always more to learn."},{pose:"love",text:"🧡 {name}! Nacho here. I've been guarding this archive for you. Let's explore together!"},{pose:"default",text:"Hey {name}! Tick tock, next block. What's on your mind today? 🦌⏰"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 Welcome back, {name}. What are we diving into?"},{pose:"wave",text:"👋 Good to see you, {name}! Remember — every channel you read makes you harder to scam. Knowledge is armor!"},{pose:"fire",text:"{name}! 🦌🔥 The orange pill hits different when you study the fundamentals. Let's go!"}],l=[{pose:"eyes",text:"Great choice, {name}! I'll be over here if you need me. 👀"},{pose:"cool",text:"Ooh, excellent pick, {name}! You've got good taste. 😎"},{pose:"brain",text:"This one's a good read, {name}! Take your time. 🧠"},{pose:"fire",text:"One of my favorites! Dig in, {name}! 🦌🔥"},{pose:"love",text:"Nice, {name}! This channel has great stuff in it. 🧡"}],d=[{pose:"celebrate",text:"Nice, {name}! Points are stacking up! 🎉"},{pose:"fire",text:"{name}, you're on fire! Nacho approves! 🔥"},{pose:"celebrate",text:"Cha-ching, {name}! The knowledge is paying off! 💰"}],u=["default","eyes","default","think","default","cheese","default","cool","default","sleep","default"];let p=0,m=null,g=!0,h=null;window.clearNachoBubbleTimeout=function(){clearTimeout(h),h=null};let f=0,y=0,v=new Set,b=0,w="default";function x(){var n=localStorage.getItem("btc_nacho_hidden");"true"!==n&&"user"!==n||(g=!1);const i=document.createElement("style");i.textContent="\n #nacho-container {\n position: fixed;\n bottom: 80px;\n left: 330px;\n z-index: 250;\n display: flex;\n align-items: flex-end;\n gap: 0;\n pointer-events: none;\n transition: opacity 0.3s, transform 0.3s;\n }\n #nacho-container.hidden { opacity: 0; transform: translateY(30px); pointer-events: none; }\n\n #nacho-avatar {\n width: 110px;\n height: 110px;\n background: none;\n border-radius: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n pointer-events: auto;\n filter: drop-shadow(0 6px 16px rgba(0,0,0,0.5));\n transition: transform 0.15s;\n user-select: none;\n position: relative;\n flex-shrink: 0;\n z-index: 2;\n overflow: visible;\n }\n #nacho-avatar { -webkit-user-select: none; }\n #nacho-avatar:hover { transform: scale(1.08) rotate(-3deg); }\n #nacho-avatar:active { transform: scale(0.93); }\n #nacho-avatar .nacho-btn-stack {\n position: absolute;\n top: -5px;\n right: -4px;\n display: flex;\n flex-direction: column;\n gap: 4px;\n z-index: 5;\n }\n #nacho-avatar .nacho-closet-btn, #nacho-avatar .nacho-story-btn {\n font-size: 0.85rem;\n cursor: pointer;\n pointer-events: auto;\n background: var(--card-bg, #1a1a2e);\n border: 1px solid var(--border, #333);\n border-radius: 50%;\n width: 26px;\n height: 26px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: 0.2s;\n opacity: 0.5;\n position: relative;\n }\n #nacho-avatar .nacho-closet-btn:hover, #nacho-avatar .nacho-story-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n border-color: #f7931a;\n }\n .nacho-notif-dot {\n position: absolute;\n top: -2px;\n right: -2px;\n width: 8px;\n height: 8px;\n background: #ef4444;\n border-radius: 50%;\n border: 1.5px solid var(--card-bg, #1a1a2e);\n z-index: 6;\n pointer-events: none;\n }\n #nacho-avatar .nacho-name {\n position: absolute;\n bottom: -46px;\n left: 50%;\n transform: translateX(-50%);\n font-size: 0.7rem;\n color: #f7931a;\n font-weight: 800;\n letter-spacing: 1.5px;\n white-space: nowrap;\n text-transform: uppercase;\n text-shadow: 0 1px 4px rgba(0,0,0,0.5);\n line-height: 1.3;\n text-align: center;\n pointer-events: auto;\n cursor: pointer;\n padding: 4px 12px;\n border-radius: 8px;\n transition: background 0.2s;\n }\n #nacho-avatar .nacho-name:hover {\n background: rgba(247,147,26,0.15);\n }\n\n /* Nacho speech bubble — high contrast, always readable */\n #nacho-bubble {\n background: #111827;\n border: 2px solid #f7931a;\n border-radius: 16px;\n padding: 16px 20px 16px 18px;\n max-width: 300px;\n min-width: 200px;\n color: #f8f8f8;\n font-size: 0.9rem;\n line-height: 1.55;\n pointer-events: none;\n box-shadow: 0 8px 32px rgba(0,0,0,0.7), 0 0 12px rgba(247,147,26,0.25);\n opacity: 0;\n transform: translateY(8px) scale(0.9);\n transition: opacity 0.35s cubic-bezier(0.34, 1.56, 0.64, 1), transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);\n cursor: pointer;\n position: relative;\n margin-left: -6px;\n margin-bottom: 16px;\n z-index: 1000;\n }\n #nacho-bubble::before {\n content: '';\n position: absolute;\n bottom: 10px;\n left: -10px;\n width: 0; height: 0;\n border-top: 10px solid transparent;\n border-bottom: 10px solid transparent;\n border-right: 10px solid #f7931a;\n }\n #nacho-bubble::after {\n content: '';\n position: absolute;\n bottom: 12px;\n left: -7px;\n width: 0; height: 0;\n border-top: 8px solid transparent;\n border-bottom: 8px solid transparent;\n border-right: 8px solid #111827;\n }\n #nacho-bubble.show { opacity: 1; transform: translateY(0) scale(1); pointer-events: auto; }\n\n .nacho-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 6px;\n }\n .nacho-label {\n font-size: 0.65rem;\n color: #f7931a;\n font-weight: 800;\n text-transform: uppercase;\n letter-spacing: 1px;\n }\n .nacho-x {\n color: var(--text-faint, #666);\n font-size: 0.75rem;\n cursor: pointer;\n opacity: 0.4;\n transition: opacity 0.2s;\n padding: 2px 4px;\n }\n .nacho-x:hover { opacity: 1; }\n #nacho-text { word-wrap: break-word; max-height: 60vh; overflow-y: auto; -webkit-overflow-scrolling: touch; padding-right: 4px; }\n\n /* Clippy-style idle animations — mimic the paper clip's fidgeting */\n\n /* 1. Tap tap — like Clippy tapping on the screen */\n /* Nacho victory flight — Lightning bolt ⚡ across the full screen! */\n @keyframes nachoFly {\n /* ⚡ Lightning bolt: high-energy erratic takeoff, zigzag, and sonic boom reentry \n */\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 5% { transform: translate(-5px, 10px) rotate(-10deg) scale(0.9); }\n 10% { transform: translate(15vw, -20vh) rotate(20deg) scale(1.1); }\n 20% { transform: translate(40vw, -5vh) rotate(-15deg) scale(1); }\n 30% { transform: translate(65vw, -45vh) rotate(35deg) scale(1.2); }\n 45% { transform: translate(90vw, -10vh) rotate(-20deg) scale(1.1); }\n 60% { transform: translate(110vw, -60vh) rotate(45deg) scale(1.4); opacity: 1; }\n 61% { transform: translate(110vw, -60vh); opacity: 0; }\n /* Sonic boom reentry from the top left */\n 85% { transform: translate(-50vw, -50vh) rotate(-45deg) scale(2); opacity: 0; }\n 90% { transform: translate(-10vw, -10vh) rotate(-20deg) scale(1.5); opacity: 1; filter: brightness(3) blur(2px); }\n 95% { transform: translate(0, -20px) rotate(0deg) scale(1.1); filter: brightness(1); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n @keyframes nachoFlyMobile {\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 8% { transform: translate(-2vw, 5vh) rotate(-10deg) scale(0.9); }\n 15% { transform: translate(25vw, -30vh) rotate(15deg) scale(1.1); }\n 30% { transform: translate(60vw, -5vh) rotate(-15deg) scale(1); }\n 50% { transform: translate(85vw, -50vh) rotate(30deg) scale(1.3); }\n 65% { transform: translate(105vw, -20vh) rotate(10deg) scale(1.2); opacity: 1; }\n 66% { transform: translate(105vw, -20vh); opacity: 0; }\n /* Reentry from top */\n 88% { transform: translate(0, -80vh) rotate(0deg) scale(1.5); opacity: 0; }\n 94% { transform: translate(0, -10px) rotate(0deg) scale(1.1); opacity: 1; filter: brightness(2); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n #nacho-avatar.flying {\n animation: nachoFly 2.8s linear forwards;\n z-index: 999;\n filter: drop-shadow(0 0 20px rgba(247,147,26,0.8)) drop-shadow(0 0 40px rgba(234,88,12,0.4));\n }\n @media (max-width: 900px) {\n #nacho-avatar.flying {\n animation: nachoFlyMobile 2.4s linear forwards;\n }\n }\n /* Lightning trail particles */\n .nacho-trail {\n position: fixed;\n pointer-events: none;\n z-index: 998;\n font-size: 1.2rem;\n opacity: 1;\n transition: none;\n animation: nachoTrailFade 0.8s ease-out forwards;\n }\n .nacho-trail.stuck-cleanup { display: none !important; }\n @keyframes nachoTrailFade {\n 0% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(1.3); }\n 100% { opacity: 0; transform: scale(0.3); }\n }\n\n @keyframes nachoTap {\n 0%, 100% { transform: translateY(0); }\n 10% { transform: translateY(-6px); }\n 20% { transform: translateY(0); }\n 30% { transform: translateY(-4px); }\n 40% { transform: translateY(0); }\n }\n /* 2. Lean and look — Clippy tilting to peek at your screen */\n @keyframes nachoLean {\n 0%, 100% { transform: rotate(0deg) translateX(0); }\n 30% { transform: rotate(8deg) translateX(3px); }\n 50% { transform: rotate(8deg) translateX(3px); }\n 80% { transform: rotate(0deg) translateX(0); }\n }\n /* 3. Bored wiggle — Clippy fidgeting when idle */\n @keyframes nachoWiggle {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-6deg); }\n 30% { transform: rotate(5deg); }\n 45% { transform: rotate(-4deg); }\n 60% { transform: rotate(3deg); }\n 75% { transform: rotate(-2deg); }\n 90% { transform: rotate(0deg); }\n }\n /* 4. Bounce — Clippy's excited hop */\n @keyframes nachoBounce {\n 0%, 100% { transform: translateY(0) scale(1); }\n 20% { transform: translateY(-8px) scale(1.05); }\n 40% { transform: translateY(0) scale(0.97); }\n 55% { transform: translateY(-4px) scale(1.02); }\n 70% { transform: translateY(0) scale(0.99); }\n 85% { transform: translateY(-2px) scale(1.01); }\n }\n /* 5. Stretch — Clippy stretching/yawning */\n @keyframes nachoStretch {\n 0%, 100% { transform: scaleY(1) scaleX(1); }\n 25% { transform: scaleY(1.12) scaleX(0.92); }\n 50% { transform: scaleY(0.92) scaleX(1.08); }\n 75% { transform: scaleY(1.05) scaleX(0.97); }\n }\n /* 6. Look around — Clippy looking left and right */\n @keyframes nachoLook {\n 0%, 100% { transform: translateX(0); }\n 20% { transform: translateX(-5px); }\n 40% { transform: translateX(-5px); }\n 60% { transform: translateX(5px); }\n 80% { transform: translateX(5px); }\n }\n /* 7. Wave — Clippy waving at you */\n @keyframes nachoWave {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-12deg); }\n 30% { transform: rotate(10deg); }\n 45% { transform: rotate(-8deg); }\n 60% { transform: rotate(6deg); }\n 75% { transform: rotate(-3deg); }\n }\n /* 8. Sleepy bob — Clippy nodding off */\n @keyframes nachoSleepy {\n 0%, 100% { transform: translateY(0) rotate(0deg); }\n 30% { transform: translateY(2px) rotate(3deg); }\n 50% { transform: translateY(3px) rotate(5deg); }\n 70% { transform: translateY(2px) rotate(3deg); }\n }\n /* 9. Couch sway — for Timechain TV */\n @keyframes nachoSway {\n 0%, 100% { transform: rotate(-1deg) translateY(0); }\n 50% { transform: rotate(1deg) translateY(-3px); }\n }\n\n #nacho-avatar.anim-tap { animation: nachoTap 2s ease-in-out infinite; }\n #nacho-avatar.anim-lean { animation: nachoLean 3.5s ease-in-out infinite; }\n #nacho-avatar.anim-wiggle { animation: nachoWiggle 2.5s ease-in-out infinite; }\n #nacho-avatar.anim-bounce { animation: nachoBounce 1.8s ease-in-out infinite; }\n #nacho-avatar.anim-stretch { animation: nachoStretch 3s ease-in-out infinite; }\n #nacho-avatar.anim-look { animation: nachoLook 4s ease-in-out infinite; }\n #nacho-avatar.anim-wave { animation: nachoWave 1.5s ease-in-out infinite; }\n #nacho-avatar.anim-sleepy { animation: nachoSleepy 4s ease-in-out infinite; }\n\n /* Tablet — sidebar is 280px */\n @media (max-width: 1100px) {\n #nacho-container { left: 290px; }\n #nacho-avatar { width: 95px; height: 95px; }\n }\n /* Mobile — sidebar hidden, Nacho goes bottom-left, above clutter */\n @media (max-width: 900px) {\n #nacho-container { bottom: calc(50vh - 30px); left: 12px; }\n #nacho-avatar { width: 68px; height: 68px; }\n #nacho-bubble {\n position: fixed;\n bottom: calc(50vh + 50px);\n left: 12px;\n right: 12px;\n max-width: calc(100vw - 24px);\n max-height: 40vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n min-width: unset;\n width: auto;\n font-size: 0.9rem;\n padding: 16px 18px;\n margin-left: 0;\n border-radius: 14px;\n }\n #nacho-bubble::before, #nacho-bubble::after { display: none; }\n #nacho-avatar .nacho-name { font-size: 0.7rem; bottom: -44px; padding: 5px 14px; }\n }\n @media (max-width: 480px) {\n #nacho-container { bottom: calc(50vh - 40px); left: 10px; }\n #nacho-avatar { width: 60px; height: 60px; }\n #nacho-bubble {\n bottom: calc(50vh + 30px);\n left: 10px;\n right: 10px;\n max-width: calc(100vw - 20px);\n max-height: 38vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n font-size: 0.85rem;\n padding: 14px 16px;\n }\n #nacho-avatar .nacho-name { font-size: 0.65rem; bottom: -40px; padding: 5px 12px; }\n }\n\n /* Bring-back toggle */\n #nacho-toggle {\n position: fixed; bottom: 80px; left: 330px; z-index: 250;\n width: 52px; height: 52px;\n background: radial-gradient(circle, #fff 60%, rgba(255,255,255,0.85) 100%);\n border: 2px solid rgba(247,147,26,0.5);\n border-radius: 50%; display: none; align-items: center; justify-content: center;\n font-size: 1.6rem; cursor: pointer; opacity: 0.9; transition: all 0.3s;\n box-shadow: 0 2px 12px rgba(0,0,0,0.3), 0 0 0 3px rgba(247,147,26,0.15);\n }\n #nacho-toggle:hover { opacity: 1; transform: scale(1.1); box-shadow: 0 4px 20px rgba(247,147,26,0.4), 0 0 0 4px rgba(247,147,26,0.25); }\n @media (max-width: 1100px) { #nacho-toggle { left: 290px; } }\n @media (max-width: 900px) { #nacho-toggle { bottom: calc(50vh - 30px); left: 12px; width: 46px; height: 46px; font-size: 1.3rem; } }\n @media (max-width: 480px) { #nacho-toggle { bottom: calc(50vh - 40px); left: 10px; width: 44px; height: 44px; font-size: 1.2rem; } }\n ",document.head.appendChild(i);const a=document.createElement("div");a.id="nacho-container",g||a.classList.add("hidden");const r=o()?t:e,s=o()?"width:120px;height:100px;":"";a.innerHTML='
    '+r+'Nacho
    click to ask!
    👔📖
    🦌 '+("function"==typeof nachoNickname?nachoNickname():"Nacho")+' says
    ',document.body.appendChild(a);var l=document.getElementById("nachoClosetBtn");if(l){var d=!1;function h(){window._expanded_closet=!0,window._pendingClosetScroll=!0;try{"function"==typeof showSettings&&showSettings();var e=0;setTimeout(function t(){e++;var o=document.getElementById("usernameModal");o&&o.classList.contains("open")&&"function"==typeof showSettingsPage?showSettingsPage("data"):e<10&&setTimeout(t,150)},200)}catch(e){}"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear()}l.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),l.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d=!0},{passive:!1}),l.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),d&&(d=!1,h())},{passive:!1}),l.addEventListener("click",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d||h(),d=!1},!1)}window.updateNachoNotifs=function(){var e=document.getElementById("nachoStoryNotif");if(e){var t=safeJSON("btc_nacho_story_days",[]),o=(new Date).toISOString().split("T")[0],n=t.length,i=-1===t.indexOf(o)&&n<7,a=0===n,r=localStorage.getItem("btc_nacho_story_notif_dismissed")===o;e.style.display=r||!i&&!a?"none":"block"}var s=document.getElementById("nachoClosetNotif");if(s){var c=safeJSON("btc_spin_closet_items",[]),l=safeJSON("btc_closet_viewed",[]),d=c.some(function(e){return-1===l.indexOf(e)});s.style.display=d?"block":"none"}},window.nachoStoryNotifClear=function(){var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_nacho_story_notif_dismissed",e);var t=document.getElementById("nachoStoryNotif");t&&(t.style.display="none")},window.nachoClosetNotifClear=function(){var e=safeJSON("btc_spin_closet_items",[]);localStorage.setItem("btc_closet_viewed",JSON.stringify(e));var t=document.getElementById("nachoClosetNotif");t&&(t.style.display="none")},setTimeout(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},2e3),setInterval(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},6e4);const f=document.createElement("div");function v(){const e=document.getElementById("nachoModeContainer"),t=document.getElementById("irl-sync-view"),o=document.getElementById("searchOverlay"),n=document.querySelector(".ticker-wrap"),i=e&&"none"!==e.style.display||t&&null!==t.offsetParent||o&&"flex"===o.style.display;if(n){n.style.transition="transform 0.4s ease",n.style.transform=i?"translateY(-100%)":"translateY(0)";const e=document.getElementById("menuToggle");e&&(e.style.opacity=i?"0.2":"1")}}f.id="nacho-toggle",f.innerHTML="🦌",f.title="Bring back Nacho",f.onclick=function(){showNacho()},g||(f.style.display="flex"),document.body.appendChild(f),function(){var e=document.getElementById("nacho-avatar");if(e){var t=null,o=!1;e.addEventListener("touchstart",function(e){o=!1,t=setTimeout(function(){o=!0,"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t),o&&(o=!1)}),e.addEventListener("touchmove",function(){clearTimeout(t)}),e.addEventListener("contextmenu",function(e){e.preventDefault(),"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")})}}(),setTimeout(function(){if(g){var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=0;try{o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length}catch(e){}if(t<=3&&o<5){var n=parseInt(localStorage.getItem("btc_nacho_onboarding")||"1");if(k("wave"),1===n?(S('
    Hey there! I\'m Nacho, your Bitcoin education buddy! 🦌🧡

    Here\'s what you can do here:
    📚 Read 145+ Bitcoin topics — tap any in the sidebar
    🎡 Spin daily for free tickets & rewards
    Take quests to test your knowledge

    '),localStorage.setItem("btc_nacho_onboarding","2")):2===n&&o>=1?(S('
    Nice, you explored your first channel! 🎉

    Keep going — every channel you read earns you +10 XP. Here are some popular ones:

    '),localStorage.setItem("btc_nacho_onboarding","3")):3===n&&o>=3?(k("celebrate"),S('
    You\'re on fire! 🔥 '+o+' channels explored!

    Did you know you can:
    🗣️ Chat in PlebTalk — discuss Bitcoin with the community
    Browse LightningMart — buy & sell for sats
    🎓 Take the Scholar Exam — earn your Bitcoin certification

    '),localStorage.setItem("btc_nacho_onboarding","4")):4===n&&o>=5&&(k("brain"),S('
    You\'re becoming a real Bitcoiner! 🧡

    Pro tips:
    📖 Read Nacho\'s Story — a new chapter unlocks each day
    📚 Study with Flashcards to prepare for quests
    🏆 Check the Leaderboard — see where you rank
    💬 Ask me anything about Bitcoin anytime!

    — End of tour. I\'ll still be here if you need me! 🦌
    '),localStorage.setItem("btc_nacho_onboarding","5")),n<=4)return}k((e="function"==typeof nachoTimeGreeting&&Math.random()<.6?nachoTimeGreeting():U(c)).pose),S(e.text),"function"==typeof nachoPlaySound&&nachoPlaySound("pop"),setTimeout(function(){if("function"==typeof nachoStreakMessage){var e=nachoStreakMessage();e&&T(e.text,e.pose)}},12e3)}},2e3),clearInterval(m),m=setInterval(function(){if(!g)return;const e=document.getElementById("nacho-bubble");if(e&&e.classList.contains("show"))return;const t=document.getElementById("nacho-avatar");if(!t)return;p=(p+1)%u.length,k(u[p]),["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(e=>t.classList.remove(e));const o={default:["anim-tap","anim-look","anim-wiggle"],eyes:["anim-lean","anim-look"],think:["anim-lean","anim-tap"],cheese:["anim-bounce","anim-wiggle"],cool:["anim-lean","anim-tap"],sleep:["anim-sleepy"],wave:["anim-wave"],celebrate:["anim-bounce"],fire:["anim-bounce","anim-wiggle"],love:["anim-stretch","anim-tap"],brain:["anim-lean","anim-look"],point:["anim-tap","anim-lean"]}[w]||["anim-tap","anim-wiggle"];t.classList.add(U(o))},8e3),setInterval(M,55e3);const b=window.enterNachoMode;window.enterNachoMode=function(e){"function"==typeof b&&b(e),setTimeout(v,100)};const x=window.exitNachoMode;window.exitNachoMode=function(e){"function"==typeof x&&x(e),setTimeout(v,100)};const B=window.go;window.go=function(e,t,o){"function"==typeof B&&B(e,t,o),setTimeout(v,100)};const _=window.goHome;window.goHome=function(e){"function"==typeof _&&_(e),setTimeout(v,100)},setTimeout(function(){"undefined"!=typeof APP_PAGES&&APP_PAGES.forEach(e=>{"PlebTalk"===e.title&&(e.title="Pleb Talk"),"LightningMart"===e.title&&(e.title="Lightning Mart")})},2e3),window.addEventListener("beforeunload",function(e){const t=document.getElementById("questModal");t&&t.classList.contains("open")&&(e.preventDefault(),e.returnValue="You have an active Quest! Your progress will be lost.")}),window.showSkeletonLoader=function(e,t){const o=document.getElementById(e);if(!o)return;let n='
    ';for(let e=0;e<(t||6);e++)n+='
    ';n+="
    ",o.innerHTML=n},setInterval(function(){var e=document.getElementById("nacho-bubble");if(!g||e&&e.classList.contains("show"))return;const t=Math.random();if(t<.3)k("wave"),setTimeout(()=>k("neutral"),400);else if(t<.6){const e=document.getElementById("nacho-avatar");e&&(e.style.transform="scale(1.1) rotate(5deg)",setTimeout(()=>e.style.transform="",500))}},2e4),setInterval(function(){if(g&&!(y>=12)&&!(Math.random()>.2||window._lastChannelOpenTime&&Date.now()-window._lastChannelOpenTime<3e4)){var e=document.getElementById("nacho-bubble");if(!(e&&e.classList.contains("show")&&"true"===e.getAttribute("data-interactive")||window._nachoMode)){var t=document.getElementById("questModal");t&&t.classList.contains("open")||"function"==typeof showNachoTrivia&&showNachoTrivia()}}},18e4)}function k(e){w=e||"default";const t=document.getElementById("nacho-pose-emoji");t&&(t.textContent=n[w]||n.default)}function T(e,t){!g||y>=12||Date.now()-f<5e4||v.has(e)||B(e,t)}function S(e,t){if(g){var o=document.getElementById("questModal");o&&o.classList.contains("open")||B(e,t)}}function B(e,t){if(window._nachoDirectLinkCooldown&&Date.now()s.classList.remove(e));var c="";if(-1===e.indexOf("'+l[d].label+"";break}var u=-1!==e.indexOf("60&&Math.abs(o)>2*Math.abs(n)&&hideBubble(!0)}},{passive:!0}),function(){var e=!1,t=0,o=0,n=0,i=0,a=!1,r=null;function s(){return document.getElementById("nacho-container")}function c(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;var n=window.innerWidth-40,i=window.innerHeight-40;t.left>=0&&t.left<=n&&t.top>=0&&t.top<=i&&(o.style.left=t.left+"px",o.style.bottom="auto",o.style.top=t.top+"px",o.style.right="auto")}catch(e){}}function l(){var e=s();if(e){var t=document.getElementById("nacho-bubble");if(t){var o=e.getBoundingClientRect(),n=window.innerWidth;window.innerHeight,o.left>n/2?(t.style.marginLeft="",t.style.marginRight="-6px",t.style.alignSelf="flex-end",t.querySelector(":scope"),t.style.setProperty("--bubble-side","right")):(t.style.marginLeft="-6px",t.style.marginRight="",t.style.alignSelf=""),o.top<200?(t.style.order="2",t.style.marginBottom="0",t.style.marginTop="8px"):(t.style.order="",t.style.marginBottom="16px",t.style.marginTop="")}}}setTimeout(c,500),window.addEventListener("resize",function(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;t.left=Math.max(0,Math.min(t.left,window.innerWidth-60)),t.top=Math.max(0,Math.min(t.top,window.innerHeight-60)),o.style.left=t.left+"px",o.style.top=t.top+"px",localStorage.setItem("btc_nacho_position",JSON.stringify(t))}catch(e){}}),document.addEventListener("touchstart",function(c){var l=document.getElementById("nachoDragHandle");if(l&&l.contains(c.target)){c.preventDefault();var d=s();if(d){a=!1,r=d,t=c.touches[0].clientX,o=c.touches[0].clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,e=!0,d.style.transition="none",d.style.opacity="0.85",l.style.background="rgba(247,147,26,0.9)",l.querySelector("span").style.color="#fff"}}},{passive:!1}),document.addEventListener("touchmove",function(s){if(e&&r){var c=s.touches[0].clientX-t,l=s.touches[0].clientY-o;if(!(!a&&Math.abs(c)<8&&Math.abs(l)<8)){a=!0,s.preventDefault(),s.stopPropagation();var d=Math.max(0,Math.min(n+c,window.innerWidth-60)),u=Math.max(0,Math.min(i+l,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}},{passive:!1}),document.addEventListener("touchend",function(t){if(e){e=!1,r&&(r.style.transition="",r.style.opacity="");var o=document.getElementById("nachoDragHandle");if(o){o.style.background="rgba(255,255,255,0.9)";var n=o.querySelector("span");n&&(n.style.color="#888")}if(a&&r){var i=r.getBoundingClientRect(),s=Math.max(0,Math.min(Math.round(i.left),window.innerWidth-60)),c=Math.max(0,Math.min(Math.round(i.top),window.innerHeight-60));r.style.left=s+"px",r.style.top=c+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:s,top:c})),setTimeout(l,50),t.preventDefault()}r=null}},{passive:!1}),document.addEventListener("mousedown",function(c){var l=document.getElementById("nachoDragHandle");if(l&&l.contains(c.target)){var d=s();if(d){e=!0,a=!1,r=d,t=c.clientX,o=c.clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,d.style.transition="none",c.preventDefault()}}}),document.addEventListener("mousemove",function(s){if(e&&r){var c=s.clientX-t,l=s.clientY-o;if(!(!a&&Math.abs(c)<8&&Math.abs(l)<8)){a=!0;var d=Math.max(0,Math.min(n+c,window.innerWidth-60)),u=Math.max(0,Math.min(i+l,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}}),document.addEventListener("mouseup",function(t){if(e){if(e=!1,r&&(r.style.transition=""),a&&r){var o=r.getBoundingClientRect(),n=Math.max(0,Math.min(Math.round(o.left),window.innerWidth-60)),i=Math.max(0,Math.min(Math.round(o.top),window.innerHeight-60));r.style.left=n+"px",r.style.top=i+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:n,top:i})),setTimeout(l,50)}r=null}});var d=window.showNacho;window.showNacho=function(){d.apply(this,arguments),c(),setTimeout(l,200)},setTimeout(l,1e3),document.addEventListener("dblclick",function(e){var t=document.getElementById("nacho-avatar");if(t&&t.contains(e.target)){localStorage.removeItem("btc_nacho_position");var o=s();o&&(o.style.left="",o.style.top="",o.style.bottom="",o.style.right=""),"function"==typeof showToast&&showToast("🦌 Nacho reset to default position!"),setTimeout(l,100)}})}(),window.hideBubble=function(e){var t=document.getElementById("nacho-bubble");if(e||!t||"true"!==t.getAttribute("data-interactive")){window._nachoBusy=!1,localStorage.setItem("btc_nacho_clicked","true"),setTimeout(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},2e3);var o=document.getElementById("nacho-avatar");t&&t.classList.remove("show"),clearTimeout(h),setTimeout(function(){k("default"),o&&o.classList.add("anim-tap")},500)}};let C=0,E=[],A=0;function M(){if(!g||y>=12)return;if(Math.random()>.3)return;if("function"==typeof nachoCheckMilestone){var e=nachoCheckMilestone();if(e)return S(e.text,e.pose),void setTimeout(nachoFly,500)}if("function"==typeof nachoLiveMessage&&Math.random()<.2){var t=nachoLiveMessage();if(t)return void T(t.text,t.pose)}if("function"==typeof checkNachoNewItems){var o=checkNachoNewItems();if(o)return S(o.text,o.pose),void("function"==typeof nachoPlaySound&&nachoPlaySound("coin"))}var n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var c=Math.random(),l=("new"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&c<.15?NACHO_CLOSET_TIPS:c<.6?a:c<.8?r:s:"regular"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&c<.1?NACHO_CLOSET_TIPS:c<.4?s:c<.7?a:r:"undefined"!=typeof NACHO_CLOSET_TIPS&&c<.15?NACHO_CLOSET_TIPS:c<.65?s:c<.9?r:a).filter(e=>!v.has(e.text));if(0===l.length&&0===(l=[...s,...r].filter(e=>!v.has(e.text))).length)return;const d=U(l);T(d.text,d.pose)}window.nachoClick=function(){if(window._nachoActionClicked)return void(window._nachoActionClicked=!1);const e=Date.now();if(E.push(e),E.length>3&&E.shift(),3===E.length&&E[2]-E[0]<600&&e-A>5e3)return E=[],A=e,b=e,"function"==typeof nachoFly&&nachoFly(),void S(personalize("Wheeeee! ⚡🦌⚡"));if(E.length>=2&&E[E.length-1]-E[E.length-2]<400&&E.length<3)return E=[],b=e,"function"==typeof hideNacho&&hideNacho(),void("function"==typeof showToast&&showToast("🦌 Nacho hidden — tap the 🦌 button to bring him back!"));if(e-b<1500)return;b=e,localStorage.setItem("btc_nacho_clicked","true"),"function"==typeof checkHiddenBadges&&checkHiddenBadges(),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoPlaySound&&nachoPlaySound("click");const t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show"))return void hideBubble();if(C++,C%3==0&&"function"==typeof showNachoInput)return void showNachoInput();var o,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var c=(o="new"===i?[...a,...a,...r,...s]:"regular"===i?[...a,...s,...s,...r]:[...s,...s,...s,...r]).filter(e=>!v.has(e.text));const l=U(c.length>3?c:o);f=0,k(l.pose),S(l.text,l.pose)},window.showNacho=function(){g=!0,localStorage.removeItem("btc_nacho_hidden"),document.getElementById("nacho-container").classList.remove("hidden"),document.getElementById("nacho-toggle").style.display="none",f=0;var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=void 0!==currentUser&¤tUser&¤tUser.channelsVisited||0;if(t<=2&&o<3&&!localStorage.getItem("btc_nacho_tour_shown"))return[{text:"Welcome to the Bitcoin Education Archive, {name}! I'm Nacho, your deer guide! 🦌",pose:"wave",delay:0},{text:"Click the grid icons to explore Bitcoin topics. Start with the orange ones — they're beginner-friendly! 📚",pose:"point",delay:4e3},{text:"See the 🔥 number? That's your streak! Come back daily to keep it growing. ⚡",pose:"fire",delay:8e3},{text:"Tap me anytime to chat, or double-tap to enter Nacho Mode for deep conversations! 💬",pose:"cheese",delay:12e3}].forEach(function(e,t){setTimeout(function(){t>0&&k(e.pose),S(personalize(e.text))},e.delay)}),void localStorage.setItem("btc_nacho_tour_shown","true");if(t>2&&t<=10&&o<10){var n=["Pro tip {name}: Use the ⚡ tab to check the Bitcoin price anytime! 📈","Did you know? Completing a Quest earns you bonus Orange Tickets! 🎟️","Try tapping the Menu (☰) to see your progress on the Exploration Map! 🗺️","You can customize my outfit in Settings → Stats/Nacho → Closet! 👔"];e=n[Math.floor(Math.random()*n.length)],k("cool")}else if(t>20){var i=["Tick tock, next block! Ready for some high-signal learning, {name}? 🧱","Welcome back, master HODLer! I've been keeping the Archive warm for you. 🦌🔥","I noticed you've visited many channels. Want to test your knowledge with a Quest today? ⚡","Back for your daily dose of decentralization? Let's dive in! 📘"];e=i[Math.floor(Math.random()*i.length)],k("brain")}else if(t>5){var a=["Hey {name}, great to see you again! ✨","Welcome back! Ready to stack some more knowledge? 📚","I missed you! Check out my closet if you've earned new items! 👔","You're making great progress on your Exploration Map! 🗺️"];e=a[Math.floor(Math.random()*a.length)],k("wave")}else e="I'm back, {name}! Miss me? 🦌",k("wave");S(personalize(e))},window.hideNacho=function(){g=!1,localStorage.setItem("btc_nacho_hidden","user"),document.getElementById("nacho-container").classList.add("hidden"),document.getElementById("nacho-toggle").style.display="flex"},window.nachoOnPage=function(e){var t;if(g&&("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoNickname&&nachoNickname(),"forum"===e?t=[{pose:"wave",text:personalize("Welcome to PlebTalk, {name}! 🗣️ This is where Bitcoiners discuss ideas. Jump in!")},{pose:"point",text:"💡 Post a new topic to earn +10 points, or reply to an existing one for +5. Quality content gets upvoted!"},{pose:"brain",text:"Remember — this is a Bitcoin-only space. Stay respectful, stay on topic, and attack ideas, not people! 🤝"},{pose:"cheese",text:personalize("Psst {name}... earn the 📣 Town Crier badge by posting in PlebTalk! Your first post counts!")},{pose:"fire",text:"🔥 Pro tip: Upvote posts you find valuable with ⚡ — it helps the best content rise to the top!"}]:"marketplace"===e&&(t=[{pose:"wave",text:personalize("Welcome to LightningMart, {name}! ⚡ Buy and sell with Bitcoin — the way it should be!")},{pose:"point",text:"💡 All prices are in sats. Sellers set their own prices. Payments happen directly between buyer and seller."},{pose:"cheese",text:"🛒 List your first item to earn the 🏪 Merchant badge! Books, hardware, merch — whatever you've got!"},{pose:"brain",text:"🛡️ Safety first! Meet in public for local trades, use Lightning for instant payments, and report suspicious listings."},{pose:"fire",text:personalize("Pro tip {name}: add a Lightning address to your listing so buyers can pay you instantly! ⚡")}]),t)){var o=t[Math.floor(Math.random()*t.length)];S(o.text,o.pose)}},window.nachoOnChannel=function(e){if(g){if("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoChannelIntro){var t=nachoChannelIntro(e);if(t)return void S(t.text,t.pose)}if("function"==typeof nachoCategoryCheck){var o=nachoCategoryCheck(e);if(o)return S(o.text,o.pose),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),void setTimeout(nachoFly,500)}if(i[e]&&Math.random()<.6){const t=i[e];return void T(t.text,t.pose)}if(parseInt(sessionStorage.getItem("btc_channel_read_seconds")||"0")>=30+Math.floor(90*Math.random())&&Math.random()<.3&&"undefined"!=typeof QUEST_QUESTIONS&&QUEST_QUESTIONS.length>0){var n=void 0!==CHANNELS?CHANNELS[e]:null,a=n?n.cat:"",r=QUEST_QUESTIONS.filter(function(e){return e.category&&a&&-1!==e.category.toLowerCase().indexOf(a.toLowerCase().split(" ")[0])});0===r.length&&(r=QUEST_QUESTIONS);for(var s=r[Math.floor(Math.random()*r.length)],c='
    🎮 Quick Quiz!
    '+s.question+"
    ",d=s.options||[],u=0;u'+d[u]+"";return S(c,"brain"),void sessionStorage.setItem("btc_channel_read_seconds","0")}if(Math.random()<.25){const e=U(l);T(e.text,e.pose)}}},window.nachoBubbleQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n=e.parentElement,i=n.querySelectorAll("button");if(i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1";var a=document.createElement("div");a.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#22c55e;",a.textContent="✅ Correct! +5 pts",n.appendChild(a),"function"==typeof awardPoints&&awardPoints(5,"🎮 Quiz correct!"),"function"==typeof haptic&&haptic("success")}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("true")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var r=document.createElement("div");r.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#ef4444;",r.textContent="❌ Not quite! The correct answer is highlighted.",n.appendChild(r)}clearTimeout(h);var s=document.getElementById("nacho-bubble");s&&s.setAttribute("data-interactive","true")},window.nachoOnPoints=function(e){if(!g)return;if(e>=250)return void setTimeout(nachoFly,500);if(Math.random()>.2)return;const t=U(d);T(t.text,t.pose)},window.nachoFly=function(){var e=document.getElementById("nacho-avatar");if(e&&!e.classList.contains("flying")){["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(function(t){e.classList.remove(t)}),e.classList.add("flying");var t="false"!==localStorage.getItem("btc_nacho_sound"),o=[1200,1800,1400,2200,1600,2800];[0,400,800,1200,1600,2e3].forEach(function(n,i){setTimeout(function(){t&&e.classList.contains("flying")&&function(e){if("function"!=typeof canPlaySound||canPlaySound())try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();o.connect(n),n.connect(t.destination),o.frequency.value=e,o.type="sawtooth",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.12),o.start(t.currentTime),o.stop(t.currentTime+.12)}catch(e){}}(o[i])},n)});var n=["⚡","✨","🔥","⚡","💫","⚡"],i=setInterval(function(){if(e.classList.contains("flying")){var t=e.getBoundingClientRect(),o=document.createElement("div");o.className="nacho-trail",o.textContent=n[Math.floor(Math.random()*n.length)],o.style.left=t.left+t.width/2+(20*Math.random()-10)+"px",o.style.top=t.top+t.height/2+(20*Math.random()-10)+"px",document.body.appendChild(o),setTimeout(function(){o.parentNode&&o.remove()},600)}else clearInterval(i)},40);e.addEventListener("animationend",function o(){if(e.classList.remove("flying"),e.classList.add("anim-bounce"),e.removeEventListener("animationend",o),clearInterval(i),t&&("function"!=typeof canPlaySound||canPlaySound()))try{var n=new(window.AudioContext||window.webkitAudioContext),a=n.createOscillator(),r=n.createGain();a.connect(r),r.connect(n.destination),a.frequency.value=300,a.type="sine",r.gain.setValueAtTime(.08,n.currentTime),r.gain.exponentialRampToValueAtTime(.001,n.currentTime+.2),a.start(n.currentTime),a.stop(n.currentTime+.2)}catch(e){}})}},window.nachoOnQuest=function(e){g&&(f=0,e?(k("celebrate"),S(personalize("{name}, you CRUSHED that quest! This buck is VERY impressed! 🦌🎉🔥")),setTimeout(nachoFly,500)):(k("love"),S(personalize("Hey {name}, some questions are hard! Read up and try again — Nacho believes in you! 🦌💪"))))},window.nachoOnSearch=function(){!g||Math.random()>.3||T("Looking for something? I'd help search but I don't have thumbs. Good luck! 🔍🦌","think")},window.nachoOnFinishChannel=function(){if(!g||Math.random()>.3)return;const e=U([{pose:"celebrate",text:"You read the whole thing! Dedicated. I respect that. 🦌👏"},{pose:"point",text:"All done? Hit the 🎲 to find your next channel!"},{pose:"fire",text:"Knowledge: stacked. You're a machine! 💪"}]);T(e.text,e.pose)},window.nachoUserName=function(){return void 0!==currentUser&¤tUser&¤tUser.username?String(currentUser.username).replace(//g,">").replace(/"/g,"""):""};let z=0,L=0,P=!1;function U(e){return e[Math.floor(Math.random()*e.length)]}window.DeviceMotionEvent&&window.addEventListener("devicemotion",function(e){if(g&&!P){var t=e.accelerationIncludingGravity;if(t&&Math.sqrt(t.x*t.x+t.y*t.y+t.z*t.z)>28){var o=Date.now();o-z>1e3&&(L=0),z=o,L++,L>=2&&(P=!0,L=0,"function"==typeof haptic&&haptic("heavy"),"function"==typeof nachoFly&&nachoFly(),S(personalize("Whoa, {name}! Too much coffee? ⚡🦌🌪️")),setTimeout(function(){P=!1},3e3))}}},!0),window.personalize=function(e){var t=nachoUserName();if(e=t?e.replace(/\{name\}/g,t):e.replace(/,?\s*\{name\}\s*,?\s*/g,function(e){return 0===e.indexOf(",")&&e.lastIndexOf(",")>0?", ":","===e.charAt(0)?" ":""}),window._btcData){var o=window._btcData.price;if(!o)try{o=parseFloat(localStorage.getItem("btc_last_price"))}catch(e){}const t=o?"$"+Math.round(o).toLocaleString():"over $60,000",n=window._btcData.height?window._btcData.height.toLocaleString():"over 840,000",i=window._btcData.halvingBlocks?window._btcData.halvingBlocks.toLocaleString():"less than 150,000";e=(e=(e=e.replace(/\{price\}/g,t)).replace(/\{height\}/g,n)).replace(/\{halving\}/g,i)}return e.replace(/ +/g," ").replace(/^ ,/,"").replace(/, ,/g,",").trim()};let N=null;document.addEventListener("DOMContentLoaded",function(){setTimeout(function(){const e=document.getElementById("nacho-avatar");function t(e){"touchstart"===e.type&&e.preventDefault(),N=setTimeout(function(){hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho is hiding. Click the small 🦌 to bring him back!")},800)}function o(){clearTimeout(N)}e&&(e.addEventListener("mousedown",t),e.addEventListener("mouseup",o),e.addEventListener("mouseleave",o),e.addEventListener("touchstart",t,{passive:!1}),e.addEventListener("touchend",o),e.addEventListener("touchmove",o))},1e3)}),document.addEventListener("click",function(e){var t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show")){var o=document.getElementById("nacho-container");o&&o.contains(e.target)||hideBubble(!0)}}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",x):x(),function(){var e="btc_nacho_position",t=null,o=null,n=!1,i=0,a=0,r=0,s=0,c=!1;function l(){return t||(t=document.getElementById("nacho-container")),t}function d(){return o||(o=document.getElementById("nachoDragHandle")),o}function u(){try{var t=JSON.parse(localStorage.getItem(e));if(t&&"number"==typeof t.left&&"number"==typeof t.bottom){var o=l();if(o){var n=window.innerWidth-80,i=window.innerHeight-80,a=Math.max(0,Math.min(t.left,n)),r=Math.max(0,Math.min(t.bottom,i));o.style.left=a+"px",o.style.bottom=r+"px",o.style.right="auto",o.style.top="auto",o.style.position="fixed"}}}catch(e){}}function p(t,o){try{localStorage.setItem(e,JSON.stringify({left:t,bottom:o}))}catch(e){}}function m(e,t){var o=l();if(o){n=!0,c=!1,i=e,a=t;var u=o.getBoundingClientRect();r=u.left,s=window.innerHeight-u.bottom,o.style.transition="none",o.style.cursor="grabbing";var p=d();p&&(p.style.cursor="grabbing")}}function g(e,t){if(n){var o=e-i,d=t-a;if(c||!(Math.abs(o)+Math.abs(d)<8)){c=!0;var u=l();if(u){var p=r+o,m=s-d;p=Math.max(0,Math.min(p,window.innerWidth-80)),m=Math.max(0,Math.min(m,window.innerHeight-80)),u.style.left=p+"px",u.style.bottom=m+"px",u.style.right="auto",u.style.top="auto",u.style.position="fixed"}}}}function h(){if(n){n=!1;var e=l();if(e&&(e.style.transition="",e.style.cursor="",c)){var t=e.getBoundingClientRect();p(t.left,window.innerHeight-t.bottom)}var o=d();o&&(o.style.cursor="grab")}}function f(){var e=d();if(e){if(!e._dragInit){e._dragInit=!0,e.addEventListener("mousedown",function(e){e.preventDefault(),e.stopPropagation(),m(e.clientX,e.clientY)}),document.addEventListener("mousemove",function(e){n&&(e.preventDefault(),g(e.clientX,e.clientY))}),document.addEventListener("mouseup",h),e.addEventListener("touchstart",function(e){1===e.touches.length&&(e.stopPropagation(),m(e.touches[0].clientX,e.touches[0].clientY))},{passive:!0}),document.addEventListener("touchmove",function(e){n&&1===e.touches.length&&g(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("touchend",function(){n&&h()});var t=document.getElementById("nacho-avatar");t&&t.addEventListener("click",function(e){c&&(e.stopPropagation(),e.preventDefault(),c=!1)},!0),u(),function(){var e=document.getElementById("nacho-toggle");if(e&&!e._dragInit){e._dragInit=!0;var t=!1,o=0,n=0,i=0,a=0,r=!1;e.addEventListener("mousedown",function(s){t=!0,r=!1,o=s.clientX,n=s.clientY;var c=e.getBoundingClientRect();i=c.left,a=window.innerHeight-c.bottom,e.style.transition="none"}),e.addEventListener("touchstart",function(s){if(1===s.touches.length){t=!0,r=!1,o=s.touches[0].clientX,n=s.touches[0].clientY;var c=e.getBoundingClientRect();i=c.left,a=window.innerHeight-c.bottom,e.style.transition="none"}},{passive:!0}),document.addEventListener("mousemove",function(e){s(e.clientX,e.clientY)}),document.addEventListener("touchmove",function(e){t&&1===e.touches.length&&s(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("mouseup",c),document.addEventListener("touchend",c),e.addEventListener("click",function(e){r&&(e.stopPropagation(),e.preventDefault(),r=!1)},!0)}function s(s,c){if(t){var l=s-o,d=c-n;if(r||!(Math.abs(l)+Math.abs(d)<8)){r=!0;var u=Math.max(0,Math.min(i+l,window.innerWidth-50)),p=Math.max(0,Math.min(a-d,window.innerHeight-50));e.style.left=u+"px",e.style.bottom=p+"px",e.style.right="auto",e.style.top="auto"}}}function c(){if(t&&(t=!1,e.style.transition="",r)){var o=e.getBoundingClientRect();p(o.left,window.innerHeight-o.bottom)}}}(),window.addEventListener("resize",function(){u()})}}else setTimeout(f,1e3)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(f,500)}):setTimeout(f,500)}(),setInterval(function(){document.querySelectorAll(".nacho-trail").forEach(function(e){e.remove()})},3e3),window.updateNachoAvatarForPage=function(){var n=document.getElementById("nacho-avatar");if(n){var i=o();if(i!==("1"===n.getAttribute("data-tctv"))){n.setAttribute("data-tctv",i?"1":"0"),i?(n.style.width="120px",n.style.height="100px",n.innerHTML=t+'Nacho
    click to ask!
    👔📖
    '):(n.style.width="",n.style.height="",n.innerHTML=e+'Nacho
    click to ask!
    👔📖
    ');var a=document.getElementById("nachoClosetBtn");if(a){var r=!1;a.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),a.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),r=!0},{passive:!1}),a.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),r&&(r=!1,window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},200),"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear())},{passive:!1})}}}};var H=window.go;H&&(window.go=function(){var e=H.apply(this,arguments);return setTimeout(window.updateNachoAvatarForPage,100),e})}(),function(){window.nachoTimeGreeting=function(){var e=(new Date).getHours(),t=((new Date).getDay(),"function"==typeof nachoUserName?nachoUserName():""),o=t?", "+t:"";return e>=5&&e<12?{pose:"wave",text:"Good morning"+o+"! ☀️ Ready to learn some Bitcoin today?"}:e>=12&&e<17?{pose:"wave",text:"Good afternoon"+o+"! 🌤️ Let's stack some knowledge!"}:e>=17&&e<21?{pose:"wave",text:"Good evening"+o+"! 🌅 Great time to dive into some Bitcoin education!"}:e>=21||e<2?{pose:"cool",text:"Late night study session"+o+"? 🌙 Respect! The night owl and the night deer, learning together. 🦉🦌"}:{pose:"sleep",text:"Whoa"+o+", it's the middle of the night! 😴 Your dedication is legendary. Most deer would be asleep right now!"}},window.nachoStreakMessage=function(){if(void 0===currentUser||!currentUser)return null;var e=currentUser.streak||0,t="function"==typeof nachoUserName?nachoUserName():"",o=t?", "+t:"";return e>=30?{pose:"fire",text:e+"-day streak"+o+"! You're absolutely unstoppable! 🔥🦌👑"}:e>=14?{pose:"fire",text:e+"-day streak"+o+"! Two weeks straight! You're a machine! 🔥💪"}:e>=7?{pose:"celebrate",text:e+"-day streak"+o+"! A whole week! Nacho is very impressed! 🎉🔥"}:e>=3?{pose:"love",text:e+"-day streak"+o+"! Keep it going! 🔥"}:null};const e=[100,250,500,1e3,2100,5e3,1e4,21e3];window.nachoCheckMilestone=function(){if(void 0===currentUser||!currentUser)return null;for(var t=currentUser.points||0,o=JSON.parse(localStorage.getItem("btc_nacho_milestones")||"[]"),n="function"==typeof nachoUserName?nachoUserName():"",i=n?", "+n:"",a=[],r=0;r=s&&!o.includes(s)&&(a.push(s),o.push(s))}if(0===a.length)return null;localStorage.setItem("btc_nacho_milestones",JSON.stringify(o)),"function"==typeof syncCelebratedState&&syncCelebratedState();var c=a[0],l="function"==typeof getLevel?getLevel(t):null,d=l?" You're now rank: "+l.emoji+" "+l.name+"!":"";if(a.length>1&&"function"==typeof forceShowBubble)for(var u=1;u=3){var s=r.wrong.slice(0,3),c=Math.floor(4*Math.random());s.splice(c,0,r.a),e.push({q:r.q,options:s,correct:c,pts:10,_fromBank:!0})}}}var l=JSON.parse(localStorage.getItem("btc_nacho_trivia_asked")||"[]");l.length>.8*e.length&&(l=[],localStorage.removeItem("btc_nacho_trivia_asked"));var d=e.filter(function(e,t){return!l.includes(e._fromBank?"qb_"+e.q.substring(0,30):t)});if(0===d.length)return null;var u=d[Math.floor(Math.random()*d.length)],p=u._fromBank?"qb_"+u.q.substring(0,30):e.indexOf(u);return l.push(p),localStorage.setItem("btc_nacho_trivia_asked",JSON.stringify(l)),{trivia:u,index:idx}},window.showNachoTrivia=function(){if(window._nachoBusy)return!1;var e=nachoTrivia();if(!e)return!1;var t=e.trivia,o=document.getElementById("nacho-bubble"),n=document.getElementById("nacho-text");if(!o||!n)return!1;"function"==typeof setPose&&setPose("think"),o.setAttribute("data-interactive","true"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout();for(var i='
    🧠 Quick Trivia! (+'+t.pts+' pts)
    '+t.q+"
    ",a=0;a'+String.fromCharCode(65+a)+". "+t.options[a]+"";return n.innerHTML=i,o.classList.add("show"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout(),!0},window.nachoTriviaAnswer=function(e,t,o,n){for(var i=n.parentElement.querySelectorAll("button"),a=0;a","function"==typeof setPose&&setPose("celebrate");else{var d=Math.max(2,Math.floor(o/3));"function"==typeof awardPoints&&awardPoints(d,"🧠 Nice try!"),s.innerHTML+='
    ❌ Not quite'+l+"! The answer was "+String.fromCharCode(65+t)+". +"+d+" pts for trying! 📚
    ","function"==typeof setPose&&setPose("love")}s.innerHTML+='',s.innerHTML+=''},window.getNachoFriendship=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?{level:5,name:"Best Buds",emoji:"💛"}:e>=350?{level:4,name:"Close Friends",emoji:"🧡"}:e>=100?{level:3,name:"Good Friends",emoji:"😊"}:e>=10?{level:2,name:"Getting Acquainted",emoji:"👋"}:e>=1?{level:1,name:"Just Met",emoji:"🦌"}:{level:0,name:"Strangers",emoji:"❓"}},window.trackNachoInteraction=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0")+1;if(localStorage.setItem("btc_nacho_interactions",e.toString()),window._nachoLastInteraction=Date.now(),void 0!==db&&void 0!==auth&&auth.currentUser){var t=parseInt(localStorage.getItem("btc_nacho_questions")||"0");try{db.collection("users").doc(auth.currentUser.uid).update({nachoInteractions:e,nachoQuestions:t})}catch(e){}}"function"==typeof renderProgressRings&&renderProgressRings()};const i={mining:["How does the difficulty adjustment work?","What is a halving?","Is mining bad for the environment?","What is a nonce?","Can I mine at home?","What is an ASIC?"],wallet:["What is a seed phrase?","What is self-custody?","What is a hardware wallet?","How do I back up my wallet?","What is multisig?","Which wallet is best for beginners?"],lightning:["How fast is Lightning?","What are sats?","How do I get a Lightning Address?","What is a payment channel?","What is LNURL?","Can I tip people with Lightning?"],halving:["What is the block reward?","When is the next halving?","Why does the price go up after halving?","How many halvings are left?","What happens when all Bitcoin are mined?"],price:["Is it too late to buy?","What is DCA?","Why is Bitcoin volatile?","How high can Bitcoin go?","What is stock-to-flow?"],"self-custody":["What is a seed phrase?","What wallets do you recommend?","What does HODL mean?","What is cold storage?","What is a passphrase?"],privacy:["What is CoinJoin?","What is non-KYC Bitcoin?","Is Bitcoin anonymous?","What are silent payments?","What is Nostr?"],basics:["How does mining work?","What is the Lightning Network?","Who created Bitcoin?","What is a sat?","Why is there only 21 million?"],fud:["Is Bitcoin bad for the environment?","Can Bitcoin be hacked?","Will governments ban Bitcoin?","What about quantum computers?","Is Bitcoin a Ponzi scheme?"],node:["Why should I run a node?","What is a full node?","How does consensus work?","What is Nakamoto Consensus?"],taproot:["What is Schnorr?","What are covenants?","What is MuSig2?","What is OP_CAT?"],security:["What is a 51% attack?","How secure is Bitcoin?","What is proof of work?","Can Bitcoin be hacked?"],scarcity:["Why only 21 million?","What makes Bitcoin scarce?","What is inflation?","Bitcoin vs gold?"],layer:["What is Lightning Network?","What are sidechains?","What is the Liquid Network?","What are channel factories?"],economics:["What is sound money?","What is the Cantillon Effect?","What is time preference?","Why is fiat bad?"],satoshi:["Why did Satoshi disappear?","Who is Hal Finney?","What is the Genesis Block?","Is Craig Wright Satoshi?"],nostr:["What is Nostr?","How do I use Nostr?","What are Nostr relays?","Can I sign in with Nostr?"],regulation:["Can Bitcoin be banned?","What happened when China banned Bitcoin?","Is Bitcoin legal?","What about the SEC?"],altcoin:["Why is Bitcoin different from altcoins?","What about Ethereum?","Are meme coins worth it?","Why Bitcoin only?"],invest:["What is DCA?","How much should I invest?","Is now a good time to buy?","What is HODL?"],history:["What is Pizza Day?","What are the blocksize wars?","When was the first transaction?","What is the Genesis Block?"],energy:["Does Bitcoin waste energy?","How much energy does mining use?","Is Bitcoin green?","What is stranded energy?"]};var a=[];window.nachoFollowUps=function(e){if(!e)return[];var t=e.toLowerCase(),o=[];for(var n in i)t.includes(n)&&(o=o.concat(i[n]));0===o.length&&(o=["What is Bitcoin?","How do I get started?","What is the Lightning Network?","Who created Bitcoin?","Why is there only 21 million?","What is self-custody?"]);var r=window._nachoAskedQuestions||[],s=o.filter(function(e){return-1===a.indexOf(e)&&-1===r.indexOf(e.toLowerCase())});s.length<3&&(a=[],s=o.filter(function(e){return-1===r.indexOf(e.toLowerCase())})),0===s.length&&(s=o),s.sort(function(){return Math.random()-.5});var c=Math.min(Math.max(3,s.length),5),l=s.slice(0,c);return(a=a.concat(l)).length>30&&(a=a.slice(-15)),l},window.trackNachoQuestion=function(e,t){try{var o=JSON.parse(localStorage.getItem("btc_nacho_analytics")||"[]");o.push({q:e.substring(0,100),matched:t,t:Date.now()}),o.length>100&&(o=o.slice(-100)),localStorage.setItem("btc_nacho_analytics",JSON.stringify(o))}catch(e){}};let r="false"!==localStorage.getItem("btc_nacho_sound");window.nachoPlaySound=function(e){if(("function"!=typeof canPlaySound||canPlaySound())&&r)try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();if(o.connect(n),n.connect(t.destination),n.gain.value=.08,"pop"===e)o.frequency.value=800,o.type="sine",n.gain.setValueAtTime(.08,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.15),o.start(t.currentTime),o.stop(t.currentTime+.15);else if("coin"===e){o.frequency.value=1200,o.type="sine",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.3),o.start(t.currentTime),o.stop(t.currentTime+.3);var i=t.createOscillator();i.connect(n),i.frequency.value=1600,i.type="sine",i.start(t.currentTime+.1),i.stop(t.currentTime+.3)}else"click"===e?(o.frequency.value=600,o.type="triangle",n.gain.setValueAtTime(.05,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.08),o.start(t.currentTime),o.stop(t.currentTime+.08)):"tctv-beep"===e&&(o.frequency.value=2400,o.type="square",n.gain.setValueAtTime(.03,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.06),o.start(t.currentTime),o.stop(t.currentTime+.06))}catch(e){}},window.toggleNachoSound=function(){return r=!r,localStorage.setItem("btc_nacho_sound",r.toString()),r};let s=[];window.nachoAddContext=function(e){s.push(e),s.length>5&&s.shift()},window.nachoGetContext=function(){return s},setTimeout(function(){if("1"!==localStorage.getItem("btc_ln_prompt_dismissed")){var e=void 0!==currentUser?currentUser:null;if(e&&e.username&&!e.lightning&&!e.lightningAddress){var t=[];try{t=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}t.length<5||"function"==typeof forceShowBubble&&(forceShowBubble("⚡ Hey "+(e.username||"friend")+"! Connect a Lightning wallet to tip other users and receive tips! Tap me to learn how. 🦌",function(){go("lightning")}),localStorage.setItem("btc_ln_prompt_dismissed","1"))}}},3e4),function(){var e="btc_smart_nudges";function t(){try{return JSON.parse(localStorage.getItem(e)||"{}")}catch(e){return{}}}function o(e){var o=t();return!o[e]||Date.now()-o[e]>864e5}function n(){if("function"==typeof forceShowBubble&&!(Date.now()-(window._sessionStart||Date.now())<3e4)){var n=document.getElementById("nacho-bubble");if(!(n&&n.classList.contains("show")||window._nachoBusy)){var i,a,r=[];if(void 0!==BADGE_DEFS&&void 0!==earnedBadges){var s=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length;!earnedBadges.has("explorer_10")&&s>=7&&o("near_explorer_10")&&r.push({id:"near_explorer_10",text:"You've visited "+s+" topics — just "+(10-s)+" more to earn the Explorer badge! 🧭 Keep exploring!"}),!earnedBadges.has("explorer_25")&&s>=20&&s<25&&o("near_explorer_25")&&r.push({id:"near_explorer_25",text:"Only "+(25-s)+" more topics to unlock Trailblazer! 🗺️ You're so close!"});var c=void 0!==currentUser&¤tUser&¤tUser.streak||0;!earnedBadges.has("streak_7")&&c>=5&&c<7&&o("near_streak_7")&&r.push({id:"near_streak_7",text:c+"-day streak! 🔥 Just "+(7-c)+" more days for the Week Warrior badge! Don't break it!"}),!earnedBadges.has("streak_30")&&c>=25&&c<30&&o("near_streak_30")&&r.push({id:"near_streak_30",text:c+"-day streak! 💪 "+(30-c)+" more days to Monthly Maxi! That's legendary dedication!"}),!earnedBadges.has("streak_100")&&c>=90&&c<100&&o("near_streak_100")&&r.push({id:"near_streak_100",text:c+"-day streak! 💎 "+(100-c)+" days from Diamond Hands! You're in the top tier!"});var l=parseInt(localStorage.getItem("btc_chat_msgs")||"0");!earnedBadges.has("chat_50")&&l>=40&&l<50&&o("near_chat_50")&&r.push({id:"near_chat_50",text:l+" chat messages! Just "+(50-l)+" more to become a Conversationalist! 🎤 Head to Global Chat!"});var d=parseInt(localStorage.getItem("btc_pvp_wins")||"0");!earnedBadges.has("pvp_5")&&d>=3&&d<5&&o("near_pvp_5")&&r.push({id:"near_pvp_5",text:d+" PVP wins! ⚔️ "+(5-d)+" more to unlock Contender! Ready for a battle?"});var u=void 0!==completedQuests&&completedQuests.size||0;!earnedBadges.has("quest_3")&&u>=2&&u<3&&o("near_quest_3")&&r.push({id:"near_quest_3",text:"You've completed "+u+" quests! One more for the Quest Master badge! ⚔️ Try a quest after reading!"});var p=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0");!earnedBadges.has("tctv_couch_potato")&&p>=45&&p<60&&o("near_tctv_60")&&r.push({id:"near_tctv_60",text:p+" minutes of Timechain TV! 📺 Just "+(60-p)+" more for Couch Potato! Grab some popcorn! 🍿"}),localStorage.getItem("btc_last_spin_date")!==(new Date).toDateString()&&o("daily_spin")&&r.push({id:"daily_spin",text:"You haven't spun the daily wheel yet! 🎡 Free tickets and prizes await!"})}if(r.length>0){var m=r[Math.floor(Math.random()*r.length)];i=m.id,(a=t())[i]=Date.now(),localStorage.setItem(e,JSON.stringify(a)),forceShowBubble(m.text)}}}}setTimeout(function(){n(),setInterval(n,3e5)},12e4),window.checkSmartNudges=n}()}(),window.nachoNickname=function(){return localStorage.getItem("btc_nacho_nickname")||"Nacho"},function(){const e=[{id:"orange_scarf",category:"shirt",name:"Bitcoin Scarf",emoji:"🧣",desc:"A cozy orange scarf with the ₿ symbol.",level:1,overlay:{top:"68%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"sunglasses",category:"glasses",name:"Cool Shades",emoji:"🕶️",desc:"Sunglasses so cool, even the blockchain can't see through them.",level:1,overlay:{top:"43%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"bowtie",category:"shirt",name:"Fancy Bowtie",emoji:"🎀",desc:"A dapper bowtie for a distinguished buck. Class and sats.",level:1,overlay:{top:"64%",left:"50%",transform:"translateX(-50%)",fontSize:"1.3em"},hidden:!1,colorable:!0},{id:"mining_helmet",category:"hat",name:"Mining Helmet",emoji:"⛑️",desc:"A safety helmet for a hardworking miner. Ready to find the next block!",level:2,overlay:{top:"5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"lightning_chain",category:"glasses",name:"Lightning Chain",emoji:"⚡",desc:"A chain necklace with a Lightning bolt pendant.",level:2,overlay:{top:"65%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"party_hat",category:"hat",name:"Party Hat",emoji:"🎉",desc:"Every day is a party when you're stacking sats!",level:2,overlay:{top:"2%",left:"58%",transform:"translateX(-50%) rotate(15deg)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"hodl_hoodie",category:"shirt",name:"HODL Hoodie",emoji:"🧥",desc:"A hoodie that says HODL on the back. For diamond-handed deer.",level:3,overlay:{top:"72%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1,colorable:!0},{id:"laser_eyes",category:"glasses",name:"Laser Eyes",emoji:"🔴",desc:"The legendary Bitcoin laser eyes. Number go up!",level:3,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"0.9em",custom:"🔴 🔴"},hidden:!1,colorable:!0},{id:"wizard_hat",category:"hat",name:"Wizard Hat",emoji:"🪄",desc:"A mystical wizard hat. Nacho casts spells of financial sovereignty!",level:3,overlay:{top:"-5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!1,colorable:!0},{id:"crown",category:"hat",name:"Royal Crown",emoji:"👑",desc:"Fit for the king of cryptocurrency. There is no second best!",level:3,overlay:{top:"3%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"steak",category:"glasses",name:"Proof of Steak",emoji:"🥩",desc:"A juicy steak for a hardworking buck. Proof of Steak > Proof of Stake!",level:4,overlay:{top:"58%",right:"-18%",fontSize:"1.8em",transform:"rotate(20deg)"},hidden:!1},{id:"diamond_hooves",category:"glasses",name:"Diamond Hooves",emoji:"💎",desc:"Diamond hooves for a deer with diamond hands. Never selling!",level:4,overlay:{bottom:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em",custom:"💎💎"},hidden:!1},{id:"astronaut",category:"hat",name:"Moon Helmet",emoji:"🪖",desc:"To the moon! A space helmet for the ultimate HODLer.",level:4,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1},{id:"cape_permanent",category:"shirt",name:"Hero Cape",emoji:"🦸",desc:"A permanent cape for a Bitcoin hero. Earned, not given!",level:4,overlay:{top:"55%",right:"-15%",fontSize:"2.4em",transform:"rotate(-12deg)"},hidden:!1,colorable:!0},{id:"golden_antlers",category:"hat",name:"???",emoji:"✨",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"0.5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Golden Antlers",revealEmoji:"✨",revealDesc:"Antlers plated in pure gold. Only the closest friends get to see these shine!"},{id:"satoshi_cloak",category:"shirt",name:"???",emoji:"🧥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"68%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Satoshi's Cloak",revealEmoji:"🧥",revealDesc:"A mysterious cloak worn by Satoshi himself. Legend says it grants anonymity to any deer who wears it."},{id:"flame_aura",category:"glasses",name:"???",emoji:"🔥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"25%",left:"50%",transform:"translateX(-50%)",fontSize:"3.5em"},hidden:!0,revealName:"Flame Aura",revealEmoji:"🔥",revealDesc:"A blazing aura of pure Bitcoin energy. The ultimate flex for Nacho's best friend!"},{id:"rainbow_antlers",category:"hat",name:"???",emoji:"🌈",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!0,revealName:"Rainbow Antlers",revealEmoji:"🌈",revealDesc:"Prismatic rainbow antlers that shimmer in every color. Legendary!"},{id:"bitcoin_eyes",category:"glasses",name:"???",emoji:"₿",desc:"How do you find this one?",level:1,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.2em",custom:"₿ ₿"},hidden:!0,revealName:"Bitcoin Eyes",revealEmoji:"₿",revealDesc:"Eyes made of pure Bitcoin. You found the secret! Nacho sees everything in sats now."},{id:"santa_hat",category:"hat",name:"Santa Hat",emoji:"🎅",desc:"Ho ho HODL! A festive Santa hat for the holiday season.",level:1,overlay:{top:"1%",left:"54%",transform:"translateX(-50%) rotate(15deg)",fontSize:"2.2em"},hidden:!1,seasonal:"december"},{id:"pumpkin",category:"hat",name:"Pumpkin Head",emoji:"🎃",desc:"Spooky season! A jack-o-lantern for Halloween.",level:1,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1,seasonal:"october"},{id:"halving_pickaxe",category:"glasses",name:"Golden Pickaxe",emoji:"⛏️",desc:"A golden pickaxe to celebrate the halving! Limited edition.",level:1,overlay:{top:"22%",right:"-15%",fontSize:"2.2em",transform:"rotate(30deg)"},hidden:!1,seasonal:"april"}];var t=document.createElement("style");function o(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?5:e>=350?4:e>=100?3:e>=10?2:e>=1?1:0}t.textContent="\n @keyframes nachoEquipPop {\n 0% { transform: scale(0) rotate(-45deg); opacity: 0; }\n 50% { transform: scale(1.5) rotate(10deg); opacity: 1; }\n 70% { transform: scale(0.9) rotate(-5deg); }\n 100% { transform: scale(1) rotate(0deg); opacity: 1; }\n }\n @keyframes nachoEquipGlow {\n 0% { filter: drop-shadow(0 0 0px transparent); }\n 30% { filter: drop-shadow(0 0 12px rgba(247,147,26,0.8)); }\n 100% { filter: drop-shadow(0 0 4px rgba(247,147,26,0.3)); }\n }\n @keyframes nachoUnequip {\n 0% { transform: scale(1); opacity: 1; }\n 40% { transform: scale(1.3) rotate(15deg); opacity: 0.8; }\n 100% { transform: scale(0) rotate(-30deg); opacity: 0; }\n }\n @keyframes nachoItemFloat {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-3px); }\n }\n @keyframes nachoLaserPulse {\n 0%, 100% { opacity: 0.8; filter: drop-shadow(0 0 4px #ff0000); }\n 50% { opacity: 1; filter: drop-shadow(0 0 10px #ff0000) drop-shadow(0 0 20px #ff3300); }\n }\n @keyframes nachoSparkle {\n 0%, 100% { filter: drop-shadow(0 0 4px rgba(255,215,0,0.3)); }\n 50% { filter: drop-shadow(0 0 10px rgba(255,215,0,0.8)) drop-shadow(0 0 20px rgba(255,215,0,0.4)); }\n }\n @keyframes nachoCloakWave {\n 0%, 100% { transform: translateX(-50%) rotate(-2deg); }\n 50% { transform: translateX(-50%) rotate(2deg); }\n }\n .nacho-overlay-item {\n position: absolute;\n pointer-events: none;\n z-index: 3;\n }\n .nacho-overlay-item.equipping {\n animation: nachoEquipPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards,\n nachoEquipGlow 0.8s ease-out forwards;\n }\n .nacho-overlay-item.unequipping {\n animation: nachoUnequip 0.35s ease-in forwards;\n }\n .nacho-overlay-item.idle-float {\n animation: nachoItemFloat 3s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-laser {\n animation: nachoLaserPulse 1.5s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-sparkle {\n animation: nachoSparkle 2s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-wave {\n animation: nachoCloakWave 4s ease-in-out infinite;\n }\n",document.head.appendChild(t),window.equipNachoItem=function(t){if(!t)return localStorage.removeItem("btc_nacho_equipped_multi"),void renderNachoOverlay();var n=o(),i=e.find(function(e){return e.id===t}),a=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]");if(i&&i.level>n&&-1===a.indexOf(t))showToast("🔒 Need a higher friendship level to wear this!");else{var r=getEquippedItems(),s=i&&i.category||"misc";r[s]===t?(delete r[s],"function"==typeof forceShowBubble&&forceShowBubble("Back to natural in the "+s+" department! 🦌")):(r[s]=t,"function"==typeof forceShowBubble&&forceShowBubble({orange_scarf:"Looking cozy! This scarf really brings out my orange. 🧣🦌",mining_helmet:"Safety first! Time to mine some blocks! ⛑️⛏️",lightning_chain:"Bling bling! Fast as Lightning! ⚡🦌",hodl_hoodie:"HODL gang! This hoodie makes me feel unstoppable! 🧥💎",laser_eyes:"LASER EYES ACTIVATED! Number go up! 🔴🔴🚀",steak:"Mmm, Proof of Steak! Way better than Proof of Stake! 🥩😋",golden_antlers:"These golden antlers are MAGNIFICENT! Only for my best friends! 👑✨",satoshi_cloak:"Who am I? Nobody knows... I am Satoshi Nachoamoto! 🧙🦌"}[t]||"Looking fresh with my "+(i.hidden?i.revealName:i.name)+"! 🦌")),localStorage.setItem("btc_nacho_equipped_multi",JSON.stringify(r)),renderNachoOverlay(!0),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),document.getElementById("nachoClosetGrid")&&renderNachoClosetUI(document.getElementById("nachoClosetGrid").parentElement)}},window.renderNachoOverlay=function(t){document.querySelectorAll(".nacho-overlay-item").forEach(e=>e.remove());var o=getEquippedItems(),n=document.getElementById("nacho-avatar");n&&(Object.values(o).forEach(function(o){var i=e.find(function(e){return e.id===o});if(i){var a=i.hidden?i.revealEmoji:i.emoji,r=function(e){switch(e){case"laser_eyes":return"idle-laser";case"golden_antlers":case"diamond_hooves":return"idle-sparkle";case"satoshi_cloak":return"idle-wave";default:return"idle-float"}}(i.id),s=document.createElement("span");for(var c in s.className="nacho-overlay-item"+(t?" equipping":" "+r),s.id="nacho-overlay-"+i.id,s.textContent=i.overlay.custom||a,i.overlay.custom&&(s.style.letterSpacing="-0.1em",s.style.whiteSpace="nowrap"),i.overlay)"filter"!==c&&"custom"!==c&&(s.style[c]=i.overlay[c]);if(i.colorable){var l=localStorage.getItem("btc_closet_color_"+i.id);l&&"0deg"!==l&&(s.style.filter="hue-rotate("+l+")")}t&&s.addEventListener("animationend",function e(){s.classList.remove("equipping"),s.classList.add(r),s.removeEventListener("animationend",e)},{once:!0}),n.appendChild(s)}}),t&&function(e){for(var t=e.getBoundingClientRect(),o=["✨","⭐","💫","🌟"],n=0;n<6;n++)(function(e){setTimeout(function(){var n=document.createElement("div");n.className="nacho-trail",n.textContent=o[e%o.length],n.style.left=t.left+Math.random()*t.width+"px",n.style.top=t.top+Math.random()*t.height+"px",n.style.fontSize=.8+.8*Math.random()+"rem",document.body.appendChild(n),setTimeout(function(){n.parentNode&&n.remove()},800)},80*e)})(n)}(n))},window.getNachoFriendship=function(){const e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[{name:"Stranger",emoji:"🦌",min:0},{name:"Acquaintance",emoji:"🤝",min:10},{name:"Pleb Friend",emoji:"🧡",min:50},{name:"HODL Buddy",emoji:"💎",min:150},{name:"Maxi Mentor",emoji:"👑",min:500}];let o=t[0];for(const n of t)e>=n.min&&(o=n);return o},window.renderNachoClosetUI=function(t){for(var n=o(),i=getEquippedItems(),a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r="function"==typeof getNachoFriendship?getNachoFriendship():{level:0,name:"Strangers",emoji:"❓"},s=[1,10,100,350,750],c="",l=0;lNext level in '+(s[l]-a)+" more interactions";break}var d="",u=[];Object.values(i).forEach(function(t){var o=e.find(function(e){return e.id===t});if(o){var n=o.hidden?o.revealEmoji:o.emoji;o.overlay.custom&&(n=o.overlay.custom);var i="position:absolute;font-size:"+(o.overlay.fontSize||"1.5rem")+";";if(o.overlay.top&&(i+="top:"+o.overlay.top+";"),o.overlay.bottom&&(i+="bottom:"+o.overlay.bottom+";"),o.overlay.left&&(i+="left:"+o.overlay.left+";"),o.overlay.right&&(i+="right:"+o.overlay.right+";"),o.overlay.transform&&(i+="transform:"+o.overlay.transform+";"),i+="z-index:5;pointer-events:none;",o.colorable){var a=localStorage.getItem("btc_closet_color_"+o.id);a&&"0deg"!==a&&(i+="filter:hue-rotate("+a+");")}d+=''+n+"",u.push(o.hidden?o.revealName:o.name)}});var p="function"==typeof nachoNickname?nachoNickname():"Nacho",m='
    🦌 '+escapeHtml(p)+"'s Closet
    ";m+='
    Nacho'+d+'
    '+(u.length>0?'✨ Wearing: '+u.join(", ")+"":"No item equipped — tap one below!")+"
    ",m+='
    Friendship: '+r.emoji+" "+r.name+''+a+" interactions
    "+c,m+='
    ',m+='
    ';for(var g=(new Date).toLocaleString("en",{month:"long"}).toLowerCase(),h=0;h
    '+x+'
    '+w+"
    "+(v?'
    ✓ EQUIPPED
    ':"")+(v&&f.colorable?"
    🎨 Color
    ':"")+(y||b?"":'
    Lvl '+f.level+"
    ")+(b?'
    🔒
    ':"")+(f.seasonal?'
    🗓️ '+f.seasonal+"
    ":"")+"
    "}}m+="",m+='
    '+(Object.keys(i).length>0?function(){var t=e.find(function(e){return e.id===Object.values(i)[0]});if(!t)return"Tap an item to equip it on "+escapeHtml(p)+"!";var o=t.hidden?t.revealDesc:t.desc;return''+(t.hidden?t.revealName:t.name)+": "+o}():"Tap an unlocked item to equip it on "+escapeHtml(p)+"!
    Tap again to unequip.")+"
    ",t.innerHTML=m};var n="function"==typeof nachoNickname?nachoNickname():"Nacho";window.NACHO_CLOSET_TIPS=[{pose:"cool",text:"Did you know I have a whole closet of outfits, {name}? Check Settings → Stats → "+escapeHtml(n)+"'s Closet to dress me up! 👔🦌"},{pose:"celebrate",text:"The more we interact, the more items you unlock for me to wear! Check my closet in Settings! 🧣⚡"},{pose:"eyes",text:"I heard there are some mystery items in my closet that only my closest friends get to see... 👀🔒"},{pose:"fire",text:"Proof of Steak > Proof of Stake. Ask me about it... or better yet, unlock it in my closet! 🥩🦌"},{pose:"cheese",text:"Fashion tip from a deer: orange goes with everything. Especially Bitcoin orange. Check my closet in Settings! 🟠"}],window.checkNachoNewItems=function(){var t=o(),n=JSON.parse(localStorage.getItem("btc_nacho_items_notified")||"[]"),i=e.filter(function(e){return e.level<=t&&!n.includes(e.id)});if(i.length>0){for(var a=0;a
    '+(a?a.name:"Item")+'
    Choose a color
    ';[{name:"Default",hue:"0deg",color:"#f7931a"},{name:"Bitcoin Orange",hue:"25deg",color:"#ff8c00"},{name:"Crimson",hue:"340deg",color:"#dc2626"},{name:"Royal Purple",hue:"270deg",color:"#7c3aed"},{name:"Ocean Blue",hue:"200deg",color:"#0ea5e9"},{name:"Forest Green",hue:"120deg",color:"#16a34a"},{name:"Gold",hue:"45deg",color:"#eab308"},{name:"Hot Pink",hue:"310deg",color:"#ec4899"},{name:"Cyan",hue:"175deg",color:"#06b6d4"},{name:"Lime",hue:"90deg",color:"#84cc16"}].forEach(function(t){var n=o===t.hue;r+=""}),r+='
    ',i.innerHTML=r,n.appendChild(i),document.body.appendChild(n)},window._applyClosetColor=function(e,t){localStorage.setItem("btc_closet_color_"+e,t);var o=document.querySelector("#nacho-overlay");if(o&&(o.style.filter="0deg"===t?"none":"hue-rotate("+t+")"),"function"==typeof showColorPicker&&showColorPicker(e),"function"==typeof renderNachoClosetUI){var n=document.getElementById("nachoClosetContainer");n&&renderNachoClosetUI(n)}};const QUESTION_BANK={whitepaper:[{q:"When was the Bitcoin Whitepaper published?",a:"October 31, 2008",wrong:["January 3, 2009","March 15, 2007","December 25, 2010"]},{q:"How many pages of text is the Bitcoin Whitepaper?",a:"8 pages",wrong:["20 pages","50 pages","2 pages"]},{q:"The Whitepaper was published on:",a:"A cryptography mailing list",wrong:["Twitter","A Bitcoin forum","The New York Times"]},{q:"What is the title of the Bitcoin Whitepaper?",a:"Bitcoin: A Peer-to-Peer Electronic Cash System",wrong:["Digital Gold: The Future","How to Mine Cryptocurrency","The Blockchain Revolution"]},{q:"The Whitepaper proposed a solution to:",a:"The double-spending problem",wrong:["Climate change","Internet speed","Social media addiction"]}],whitepaper_pt2:[{q:"Who is credited as the author of the Whitepaper?",a:"Satoshi Nakamoto",wrong:["Vitalik Buterin","Elon Musk","Hal Finney"]},{q:"The Whitepaper describes Bitcoin as:",a:"A peer-to-peer electronic cash system",wrong:["A stock trading platform","A social network","A video game currency"]},{q:"What concept does the Whitepaper use to timestamp transactions?",a:"A chain of hashed blocks",wrong:["A central database","Email timestamps","GPS coordinates"]},{q:"The Bitcoin whitepaper solved what previously unsolvable problem?",a:"Digital scarcity without a trusted third party",wrong:["Faster internet speeds","Quantum-proof encryption","Free worldwide communication"]},{q:"What did Satoshi embed in the Genesis Block's coinbase transaction?",a:"A newspaper headline about bank bailouts",wrong:["Their real name","A mathematical formula","Instructions for miners"]}],decentralized:[{q:'How many people are "in charge" of Bitcoin?',a:"No one",wrong:["Satoshi Nakamoto","A board of directors","The Bitcoin Foundation"]},{q:"What is needed for code updates to Bitcoin?",a:"Deep consensus from the network",wrong:["A CEO decision","A government vote","Permission from miners only"]},{q:"Bitcoin is described as:",a:"A protocol, not a company",wrong:["A company based in Japan","A government project","A bank product"]},{q:"Bitcoin nodes are run by:",a:"Anyone who wants to, worldwide",wrong:["Only by miners","Only in the United States","Only by approved operators"]},{q:"If one country shuts down all Bitcoin mining:",a:"The network continues in other countries",wrong:["Bitcoin dies","All coins are lost","The price goes to zero permanently"]}],decentralized_pt2:[{q:"Bitcoin has no:",a:"Central point of failure",wrong:["Users","Transactions","Value"]},{q:"Decentralization means:",a:"No single entity controls the network",wrong:["One company runs everything","The government manages it","Only banks can use it"]},{q:"What happens to Bitcoin if one country bans it?",a:"The network continues operating globally since no single country controls it",wrong:["Bitcoin shuts down in that country","All nodes worldwide go offline","Miners must relocate to that country"]},{q:"How many Bitcoin full nodes are estimated to run worldwide?",a:"Tens of thousands across dozens of countries",wrong:["About 100 in the United States","One per continent","Only miners run nodes"]},{q:"Why is geographic distribution of nodes important?",a:"It prevents any single jurisdiction from shutting down the network",wrong:["It makes Bitcoin faster","It reduces electricity costs","It increases the block size"]}],scarce:[{q:"What is the maximum supply of Bitcoin?",a:"21 million",wrong:["100 million","1 billion","Unlimited"]},{q:"How many Bitcoin are estimated to be lost forever?",a:"2-3 million",wrong:["None","10 million","100,000"]},{q:"Bitcoin's code is:",a:"Open source and auditable by anyone",wrong:["Private and closed","Only visible to developers","Controlled by a company"]},{q:"What event cuts Bitcoin's new supply in half?",a:"The halving",wrong:["The merge","The split","The fork"]},{q:"How often does the halving occur?",a:"Approximately every 4 years",wrong:["Every year","Every 10 years","Every month"]}],scarce_pt2:[{q:"Bitcoin is often compared to which precious metal?",a:"Gold",wrong:["Silver","Platinum","Copper"]},{q:"The last Bitcoin will be mined around the year:",a:"2140",wrong:["2030","2050","2025"]},{q:"Bitcoin scarcity is enforced by:",a:"Math and code",wrong:["Government regulations","A central bank","Mining companies"]},{q:"What is the smallest unit of Bitcoin called?",a:"A satoshi (0.00000001 BTC)",wrong:["A bit (0.01 BTC)","A wei","A gwei"]},{q:"How does Bitcoin's stock-to-flow ratio compare to gold after the 2024 halving?",a:"Bitcoin's stock-to-flow surpassed gold's",wrong:["Gold's is still much higher","They are identical","Stock-to-flow doesn't apply to Bitcoin"]}],secure:[{q:"Bitcoin has been under attack since gaining significant value around:",a:"2013",wrong:["2020","2009","2017"]},{q:"How many potential Bitcoin wallets exist?",a:"2^160",wrong:["21 million","A few billion","2^16"]},{q:"Bitcoin's monetary policy is:",a:"Set in stone and immutable",wrong:["Changed annually","Decided by miners","Flexible based on market"]},{q:"A 51% attack would require:",a:"More computing power than the rest of the network combined",wrong:["A password","Government approval","Hacking one computer"]},{q:"Bitcoin has experienced how many hours of downtime since 2013?",a:"Zero",wrong:["Hundreds","A few days each year","One week"]}],secure_pt2:[{q:"Bitcoin uses which hashing algorithm?",a:"SHA-256",wrong:["MD5","RSA","AES"]},{q:"The cost to attack Bitcoin's network is:",a:"Billions of dollars",wrong:["A few hundred dollars","Free","A few thousand dollars"]},{q:"What is Bitcoin's uptime percentage since launch in 2009?",a:"Over 99.98% — virtually no downtime",wrong:["About 95%","Around 80% due to attacks","100% with zero interruptions"]},{q:"Why does higher hashrate make Bitcoin more secure?",a:"More computational power means an attacker needs proportionally more resources to overpower the network",wrong:["Higher hashrate makes transactions free","It allows more coins to be mined","It reduces the block time to seconds"]},{q:"What makes a 51% attack on Bitcoin impractical?",a:"The enormous cost of acquiring more mining power than all honest miners combined",wrong:["The government protects Bitcoin","Satoshi can reverse any attack","Bitcoin uses a firewall"]}],money:[{q:"How many satoshis are in one Bitcoin?",a:"100,000,000",wrong:["1,000,000","1,000","10,000"]},{q:"Bitcoin payments are compared to:",a:"Email — anyone with your address can send",wrong:["Fax machines","Phone calls","Physical mail"]},{q:"Bitcoin's distribution was fair because:",a:"There was no premine",wrong:["A company sold coins early","The government distributed it","Only miners got coins"]},{q:"A satoshi is named after:",a:"Bitcoin's creator, Satoshi Nakamoto",wrong:["A Japanese emperor","A type of sushi","A programming language"]},{q:"Bitcoin is divisible to how many decimal places?",a:"8",wrong:["2","4","16"]}],money_pt2:[{q:"Bitcoin can function as:",a:"A store of value, medium of exchange, and unit of account",wrong:["Only a store of value","Only for payments","Only for speculation"]},{q:'What makes Bitcoin "sound money"?',a:"Fixed supply and predictable issuance",wrong:["Government backing","Bank guarantees","Corporate ownership"]},{q:"Which property of money does Bitcoin's 21 million cap satisfy?",a:"Scarcity — it cannot be inflated or debased",wrong:["Acceptability — everyone must use it","Portability — it weighs nothing","Cognizability — it looks like gold"]},{q:"Why are satoshis important for Bitcoin as money?",a:"They allow micropayments and make Bitcoin divisible enough for everyday transactions",wrong:["They increase the total supply","They are a separate cryptocurrency","They can only be used on Lightning"]},{q:"What gives Bitcoin its monetary value according to Austrian economics?",a:"Subjective value from its useful properties: scarcity, portability, divisibility, and censorship resistance",wrong:["Government decree","Gold backing","The electricity used to mine it"]}],peaceful:[{q:"When China banned Bitcoin:",a:"Bitcoin just moved and kept going",wrong:["Bitcoin shut down","The price went to zero","The code was deleted"]},{q:"Bitcoin is described as:",a:"Permissionless and borderless",wrong:["Government-regulated","Country-specific","Requiring a bank account"]},{q:"Bitcoin enables protest by:",a:"Allowing people to transact without government permission",wrong:["Sending angry emails","Blocking websites","Hacking banks"]},{q:'Bitcoin is called "peaceful" because:',a:"It opts out of the existing system without force",wrong:["It prevents all crime","It eliminates wars","It makes everyone rich"]},{q:"Bitcoin helps people in authoritarian regimes by:",a:"Providing censorship-resistant money",wrong:["Overthrowing governments","Hacking military systems","Printing local currency"]}],peaceful_pt2:[{q:"Bitcoin adoption is described as:",a:"Voluntary and organic",wrong:["Mandatory and forced","Government-mandated","Corporate-controlled"]},{q:"How does Bitcoin function as a peaceful protest tool?",a:"It allows people to opt out of inflationary monetary systems without violence",wrong:["It funds protest organizations","It blocks government websites","It replaces voting systems"]},{q:'Why is Bitcoin described as "opt-in" money?',a:"Nobody is forced to use it — participation is entirely voluntary",wrong:["You must opt in through a bank","Governments assign Bitcoin to citizens","Mining is mandatory for users"]},{q:"How did Bitcoin help protestors in authoritarian regimes?",a:"It allowed them to receive donations that could not be frozen by the government",wrong:["It gave them free internet access","It replaced their national ID systems","It provided encrypted phone calls"]},{q:'What makes Bitcoin "permissionless"?',a:"Anyone can send, receive, or hold Bitcoin without needing approval from any authority",wrong:["You need a license to own it","Only approved wallets can transact","Miners must approve each transaction manually"]}],dominant:[{q:"∞/21M means:",a:"All world wealth funneling into 21 million coins",wrong:["Bitcoin is infinite","There are infinite users","21 million blockchains"]},{q:"Bitcoin's growth pattern resembles:",a:"A J-shaped curve",wrong:["A straight line","A bell curve","A flat line"]},{q:"Bitcoin is said to change you by:",a:"Lowering your time preference",wrong:["Making you rich instantly","Increasing spending","Nothing changes"]},{q:"Bitcoin's market dominance refers to:",a:"Its share of total cryptocurrency market cap",wrong:["How many users it has","Its mining speed","Its block size"]},{q:"The Lindy Effect suggests Bitcoin:",a:"Will last longer the longer it survives",wrong:["Will die soon","Is a fad","Needs government support"]}],dominant_pt2:[{q:"Bitcoin is considered dominant because:",a:"It has the strongest network effect and security",wrong:["It was the cheapest","A government chose it","It has the most features"]},{q:'What is the "Lindy effect" as applied to Bitcoin\'s dominance?',a:"The longer Bitcoin survives and grows, the more likely it is to continue dominating",wrong:["Old technology always fails eventually","Bitcoin dominance decreases with age","Lindy only applies to physical goods"]},{q:"Why do network effects favor Bitcoin over altcoins?",a:"More users, miners, developers, and infrastructure create a self-reinforcing cycle that's hard for competitors to match",wrong:["Bitcoin has the best marketing team","Altcoins are illegal","Network effects only apply to social media"]},{q:'What does Bitcoin\'s "dominance" metric measure?',a:"Bitcoin's share of total cryptocurrency market capitalization",wrong:["The number of Bitcoin nodes vs altcoin nodes","Bitcoin's hash rate compared to all others","The percentage of merchants accepting Bitcoin"]},{q:"Why has no altcoin overtaken Bitcoin despite thousands of attempts?",a:"Bitcoin's first-mover advantage, network effects, decentralization, and brand recognition create an insurmountable moat",wrong:["The government protects Bitcoin specifically","Altcoins are all scams with no technology","Satoshi prevents forks from succeeding"]}],"use-cases":[{q:"Bitcoin is described as better than gold because:",a:"It can be sent across the planet instantly",wrong:["It's heavier","It's shinier","It's backed by gold"]},{q:"How do Bitcoin remittance fees compare to Western Union?",a:"Much cheaper, nearly free",wrong:["About the same","More expensive","Double the cost"]},{q:"Credit card merchants pay about what fee?",a:"3%",wrong:["0%","10%","25%"]},{q:"Bitcoin can help the unbanked because:",a:"You only need a phone and internet to use it",wrong:["Banks distribute it","The government gives it away","You need a credit score"]},{q:"Bitcoin as a hedge against inflation means:",a:"Its fixed supply protects purchasing power",wrong:["It always goes up","The government guarantees its value","It pays interest"]}],"use-cases_pt2":[{q:"Micropayments on Bitcoin are possible through:",a:"The Lightning Network",wrong:["Visa","PayPal","Wire transfer"]},{q:"Bitcoin enables financial sovereignty by:",a:"Letting you be your own bank",wrong:["Requiring a bank account","Needing government ID","Using credit scores"]},{q:"Why is Bitcoin especially valuable for international remittances?",a:"It settles in minutes with low fees compared to days and high fees with traditional wire transfers",wrong:["It automatically converts to local currency","Banks process Bitcoin remittances for free","It requires no internet connection"]},{q:'How does Bitcoin serve as a "savings technology"?',a:"Its fixed supply and deflationary nature preserve purchasing power over time",wrong:["It pays interest like a savings account","Banks guarantee Bitcoin deposits","It automatically grows by 10% annually"]},{q:"What makes Bitcoin useful for micropayments via Lightning?",a:"Sub-penny transaction fees and instant settlement enable payments too small for traditional systems",wrong:["Lightning removes the need for Bitcoin","Micropayments require on-chain transactions","Only amounts over $1 can be sent"]}],mining:[{q:"What do miners do?",a:"Secure the network and process transactions",wrong:["Create Bitcoin from nothing","Print digital money","Delete old transactions"]},{q:"Miners are paid in:",a:"New Bitcoin and transaction fees",wrong:["US dollars","Ethereum","Company stock"]},{q:"Mining difficulty adjusts approximately every:",a:"2 weeks (2016 blocks)",wrong:["Every day","Every hour","Never"]},{q:"A mining pool is:",a:"A group of miners combining computing power",wrong:["A swimming pool for tech workers","A single powerful computer","A government facility"]},{q:"The mining reward after the 2024 halving is:",a:"3.125 BTC per block",wrong:["6.25 BTC","50 BTC","12.5 BTC"]}],mining_pt2:[{q:"ASIC miners are:",a:"Specialized hardware designed only for mining",wrong:["Regular laptops","Gaming consoles","Smart phones"]},{q:"What prevents miners from cheating?",a:"Other nodes verify their work",wrong:["The honor system","Government oversight","Nothing"]},{q:"What milestone did Bitcoin hash rate reach in September 2025?",a:"1 Zettahash per second",wrong:["500 Exahash","10 Petahash","100 Terahash"]},{q:"Pleb Pool and Atlas Pool are examples of:",a:"Solo Bitcoin mining pools",wrong:["Lightning wallets","Bitcoin exchanges","Hardware wallets"]},{q:"D-Central Technologies specializes in:",a:"Home mining equipment and support",wrong:["Bitcoin trading","Lightning channels","Cold storage"]}],mining_pt3:[{q:"Constellation Heating combines mining with:",a:"Heating swimming pools",wrong:["Cooling data centers","Wind power","Solar panels"]},{q:'What is a "nonce" in Bitcoin mining?',a:'A "number used once" that miners change to find a valid hash',wrong:["A type of mining hardware","A fee paid to nodes","The total number of Bitcoins"]},{q:"Mining pools allow small miners to:",a:"Receive more frequent, smaller payouts",wrong:["Control the entire network","Mine without using electricity","Change the supply of Bitcoin"]},{q:"Bitcoin difficulty adjusts every how many blocks?",a:"2,016 blocks (roughly 2 weeks)",wrong:["210,000 blocks","Only during halvings","Every single block"]},{q:"Bitcoin mining is best described as:",a:"A brute-force lottery of guessing nonces until a valid hash is found",wrong:["Solving complex mathematical equations","Running an algorithm that factors large prime numbers","Decrypting encrypted transaction data"]}],mining_pt4:[{q:"What happens when a miner finds a valid block hash?",a:"They broadcast the block to the network, collect the block reward and transaction fees",wrong:["They must wait for government approval before adding it","The block is sent to Satoshi for verification","All other miners must restart their hardware"]},{q:"Why does Bitcoin mining use so much energy?",a:"Energy expenditure is what gives Bitcoin its security — it makes attacks prohibitively expensive",wrong:["The code is poorly optimized","Miners are required to run 24/7 by law","Each transaction requires its own mining operation"]},{q:'What is "hash rate" in Bitcoin mining?',a:"The total computational power being used to process transactions and secure the network",wrong:["The speed at which new coins are printed","The rate at which transactions are deleted","The number of miners currently online"]},{q:'What is "stranded energy" and why do Bitcoin miners seek it?',a:"Energy produced in remote locations with no local demand — miners can monetize it at low cost",wrong:["Energy that has been stored in batteries","Solar power generated at night","Electricity from decommissioned plants only"]},{q:'What is a mining "share" in a pool?',a:"Proof that a miner contributed valid work toward finding a block, used to split rewards proportionally",wrong:["A stock in the mining company","A partial Bitcoin sent to the miner","A vote on which transactions to include"]}],nodes:[{q:"Running a node lets you:",a:"Verify transactions independently",wrong:["Mine Bitcoin","Print money","Control the network"]},{q:'"Don\'t trust, verify" means:',a:"Run your own node to check the truth",wrong:["Trust your bank","Believe what others say","Ignore Bitcoin"]},{q:"A full node stores:",a:"The entire blockchain history",wrong:["Only your transactions","Just the latest block","Nothing"]},{q:"How many Bitcoin nodes exist approximately?",a:"Tens of thousands worldwide",wrong:["Only 5","Exactly 21 million","One per country"]},{q:"Running a node requires:",a:"A regular computer with enough storage",wrong:["A supercomputer","Government permission","A mining rig"]}],nodes_pt2:[{q:"Nodes enforce:",a:"The consensus rules of Bitcoin",wrong:["Government laws","Company policies","Social media rules"]},{q:"Clark Moody dashboard is useful for tracking:",a:"Bitcoin network stats and Knots adoption",wrong:["Altcoin prices","Social media followers","Email subscribers"]},{q:"Matt Hill is the founder and CEO of:",a:"Start9 (node-in-a-box solution)",wrong:["Bitcoin Magazine","Coinbase","Blockstream"]},{q:"The Bitcoin Commons governance model proposes:",a:"Coordination without authority for Bitcoin implementations",wrong:["Central planning of upgrades","Voting on block size","Government oversight"]},{q:"A pruned node saves space by:",a:"Deleting old block data after validating it",wrong:["Only downloading headers","Charging other nodes for storage","Reducing the frequency of blocks"]}],nodes_pt3:[{q:"A full node is different from a miner because:",a:"It enforces all rules but doesn't create new blocks",wrong:["It is faster than a miner","It requires more electricity","It is only for experts"]},{q:"How does your node know if a transaction is valid?",a:"It checks the signatures and inputs against the consensus rules",wrong:["It asks a central server","It votes with other nodes","It waits for a tweet from Satoshi"]},{q:"What is the main benefit of running your own Bitcoin node?",a:"You verify all transactions and blocks yourself without trusting any third party",wrong:["You earn Bitcoin rewards for running it","You can mine Bitcoin more efficiently","You get faster transaction speeds"]},{q:'What does "initial block download" (IBD) mean?',a:"The process of downloading and validating the entire blockchain when first setting up a node",wrong:["The time it takes to mine the first block","Downloading the Bitcoin software installer","Syncing your wallet with an exchange"]},{q:"How does a Bitcoin node protect you from accepting fake transactions?",a:"It independently validates every transaction against consensus rules before accepting it",wrong:["It contacts Satoshi for verification","It checks with three other nodes and takes a vote","It uses AI to detect fraud patterns"]}],"pow-vs-pos":[{q:"Bitcoin uses which consensus mechanism?",a:"Proof of Work",wrong:["Proof of Stake","Proof of Authority","Proof of Space"]},{q:"In Proof of Work, security comes from:",a:"Computational work and electricity",wrong:["Staking coins","Voting","Government approval"]},{q:"Proof of Stake has been criticized for:",a:"Favoring wealthy holders (the rich get richer)",wrong:["Using too much energy","Being too decentralized","Being too slow"]},{q:"Proof of Work connects Bitcoin to:",a:"The physical world through energy expenditure",wrong:["The stock market","Social media","Government databases"]},{q:"In PoW, you can't fake:",a:"The energy spent to mine a block",wrong:["Your username","Your IP address","The current time"]}],"pow-vs-pos_pt2":[{q:"Proof of Work was chosen because:",a:"It provides unforgeable costliness",wrong:["It was the cheapest option","Satoshi had no other ideas","The government required it"]},{q:"What real-world resource does Proof of Work consume that Proof of Stake does not?",a:"Energy (electricity used for computation)",wrong:["Hard drive space","Internet bandwidth","RAM memory"]},{q:'What is the "nothing at stake" problem in Proof of Stake?',a:"Validators can sign multiple competing chain forks at no cost, weakening consensus",wrong:["Stakers lose all their tokens if they validate","There is no block reward in PoS","Validators must buy mining hardware"]},{q:"Why do PoW proponents argue it provides stronger security guarantees?",a:"Attacking PoW requires massive ongoing real-world energy expenditure that can't be faked",wrong:["PoW has more developers working on it","PoW chains are always faster","PoW was invented first so it must be better"]},{q:"How does Proof of Stake differ from Proof of Work in block producer selection?",a:"PoS selects validators based on the amount of coins they lock up, while PoW requires solving computational puzzles",wrong:["PoS uses random lottery tickets purchased with fiat","PoW lets the richest miner always win","There is no difference in selection mechanism"]}],"layer-2-lightning":[{q:"Lightning is which layer of Bitcoin?",a:"Layer 2",wrong:["Layer 1","Layer 3","Layer 0"]},{q:"Lightning uses what for privacy?",a:"Onion routing",wrong:["GPS tracking","Public ledger","Email verification"]},{q:"Opening a Lightning channel is like:",a:"Opening a bar tab",wrong:["Buying a car","Getting a loan","Opening a bank account"]},{q:"Lightning transactions are:",a:"Nearly instant and very cheap",wrong:["Slow and expensive","Free but take hours","Only for large amounts"]},{q:"Lightning channels are settled on:",a:"The Bitcoin base layer",wrong:["Ethereum","A separate blockchain","A bank ledger"]}],"layer-2-lightning_pt2":[{q:"Lightning enables:",a:"Micropayments as small as 1 satoshi",wrong:["Only large transactions","Only fiat payments","Only international transfers"]},{q:"Lightning capacity refers to:",a:"The total Bitcoin locked in payment channels",wrong:["Internet bandwidth","Mining power","Number of nodes"]},{q:"Satogram allows you to:",a:"Send messages across the Lightning network",wrong:["Mine Bitcoin","Create NFTs","Swap altcoins"]},{q:"Lightning Cats and Lightning Goats let you:",a:"Feed real animals using Lightning payments",wrong:["Trade animal NFTs","Mine with animal power","Buy pets with Bitcoin"]},{q:"Pay With Flash is a service for:",a:"Businesses to accept Bitcoin payments",wrong:["Mining Bitcoin","Cold storage","Coin mixing"]}],"layer-2-lightning_pt3":[{q:"LNgigs is a Bitcoin-powered:",a:"Freelance marketplace",wrong:["Mining pool","Exchange","Hardware wallet"]},{q:"The Lightning Network whitepaper was written by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto","Vitalik Buterin","Adam Back"]},{q:"Lightning Network payment channels work by:",a:"Opening a channel with an on-chain transaction, then transacting off-chain instantly",wrong:["Creating a separate blockchain for each payment","Sending Bitcoin through email servers","Using proof of stake instead of proof of work"]},{q:"Why is Lightning considered a Layer 2 solution?",a:"It builds on top of Bitcoin's base layer without changing the protocol",wrong:["Because it is the second cryptocurrency ever created","Because it requires two confirmations per transaction","Because only two people can use it at a time"]},{q:"A Lightning invoice is:",a:"A payment request containing the amount, destination, and expiry time",wrong:["A monthly bill for using the Lightning Network","A receipt showing your mining rewards","A document required by tax authorities"]}],"self-custody":[{q:'"Not your keys, not your..."',a:"Bitcoin",wrong:["Wallet","Password","Account"]},{q:"The most secure long-term storage is:",a:"Hardware wallet",wrong:["Exchange account","Phone app","Email attachment"]},{q:"A seed phrase is typically:",a:"12 or 24 words that recover your wallet",wrong:["Your email password","A website URL","A phone number"]},{q:"You should store your seed phrase:",a:"On paper or metal in a secure location",wrong:["In a screenshot on your phone","In your email drafts","On social media"]},{q:"Multi-sig means:",a:"Multiple keys required to authorize a transaction",wrong:["Multiple Bitcoin addresses","Multiple blockchains","Multiple exchanges"]}],"self-custody_pt2":[{q:"When an exchange holds your Bitcoin:",a:"You have an IOU, not actual Bitcoin",wrong:["It's completely safe","You own it fully","The government insures it"]},{q:"Cold storage means:",a:"Keeping keys offline, disconnected from the internet",wrong:["Storing Bitcoin in a freezer","A cold climate mining facility","An inactive exchange account"]},{q:"A hardware wallet provides security by:",a:"Keeping private keys on a dedicated device that never exposes them to the internet",wrong:["Storing Bitcoin inside the physical device","Encrypting the blockchain so only you can read it","Requiring government approval for each transaction"]},{q:"If you lose your hardware wallet but have your seed phrase, you can:",a:"Recover all your Bitcoin on a new wallet using the seed phrase",wrong:["Nothing — the Bitcoin is permanently lost","Contact the wallet manufacturer for a replacement","File a claim with Bitcoin insurance"]},{q:"Multisig (multi-signature) wallets require:",a:"Multiple keys to authorize a transaction (e.g., 2-of-3)",wrong:["Multiple Bitcoin addresses to send from","Multiple confirmations from the same key","Multiple mining pools to verify"]}],"privacy-nonkyc":[{q:"KYC stands for:",a:"Know Your Customer",wrong:["Keep Your Coins","Keys You Control","Knowledge Yields Crypto"]},{q:"CoinJoin is used for:",a:"Mixing transactions for privacy",wrong:["Joining mining pools","Merging blockchains","Creating altcoins"]},{q:"Non-KYC Bitcoin means:",a:"Bitcoin acquired without identity verification",wrong:["Stolen Bitcoin","Fake Bitcoin","Government Bitcoin"]},{q:"Bitcoin's blockchain is:",a:"Public — anyone can see transactions",wrong:["Completely private","Only visible to miners","Encrypted and hidden"]},{q:"Why do some people prefer non-KYC Bitcoin?",a:"To maintain financial privacy",wrong:["To pay lower fees","To mine faster","To get a better price"]}],"privacy-nonkyc_pt2":[{q:"A Bitcoin address should ideally be:",a:"Used only once for privacy",wrong:["Shared with everyone","Used for all transactions","Posted on social media"]},{q:"The first recorded address poisoning attack on Bitcoin happened in:",a:"2025",wrong:["2021","2013","2009"]},{q:"Shielded CSV on Bitcoin promises:",a:"Better than Zcash-level privacy as an L1.5",wrong:["Faster mining","Bigger blocks","More altcoins"]},{q:"Briar messenger is engineered for:",a:"Privacy in hostile environments using Tor",wrong:["Fast video calls","Social media sharing","Cloud storage"]},{q:'What is a "Dust Attack"?',a:"Tiny amounts of BTC sent to addresses to track the owner's movement",wrong:["A network overload","A type of mining hardware failure","Deleting your private keys by accident"]}],"privacy-nonkyc_pt3":[{q:'"WabiSabi" and "Whirlpool" are types of:',a:"CoinJoin coordination protocols",wrong:["Mining hardware","Wallet brand names","Bitcoin address formats"]},{q:"KYC (Know Your Customer) in Bitcoin refers to:",a:"Identity verification required by regulated exchanges",wrong:["A type of encryption algorithm","A consensus mechanism used by altcoins","The name of a Bitcoin wallet"]},{q:"Why do some Bitcoiners prefer non-KYC acquisition?",a:"To protect financial privacy and avoid linking identity to Bitcoin holdings",wrong:["Because it is cheaper than using exchanges","Because KYC Bitcoin is worth less","Because non-KYC Bitcoin mines faster"]},{q:'What is "address reuse" and why is it a privacy concern?',a:"Using the same Bitcoin address multiple times lets observers link all those transactions to one entity",wrong:["It causes transactions to fail","It increases mining fees","It violates Bitcoin consensus rules"]},{q:'What does "non-KYC Bitcoin" mean?',a:"Bitcoin acquired without providing identity documents, such as through peer-to-peer trades or mining",wrong:["Bitcoin that has never been in a wallet","Bitcoin mined before 2013","Bitcoin stored on a hardware wallet"]}],"problems-of-money":[{q:"The Cantillon Effect describes:",a:"Those closest to money printing benefit most",wrong:["Bitcoin mining","The halving","Lightning fees"]},{q:"Fractional reserve banking means:",a:"Banks hold only a fraction of deposits",wrong:["Banks hold all deposits","Bitcoin is fractional","Miners keep fractions"]},{q:"Inflation is often called:",a:"A hidden tax on savings",wrong:["A bonus for savers","A mining reward","A blockchain feature"]},{q:"Fiat currency is backed by:",a:"Government decree and trust",wrong:["Gold reserves","Bitcoin","Real estate"]},{q:"The US dollar has lost what percentage of purchasing power since 1913?",a:"Over 96%",wrong:["About 10%","None","About 50%"]}],"problems-of-money_pt2":[{q:"Money printing causes:",a:"Devaluation of existing currency",wrong:["Deflation","Higher savings rates","Stronger currency"]},{q:"Sound money historically meant:",a:"Money that couldn't be easily debased",wrong:["Money that makes noise","Digital currency","Credit cards"]},{q:"The Cantillon Effect describes how:",a:"Those closest to new money benefit most from inflation",wrong:["Bitcoin mining gets harder","Banks lose money","Gold prices drop"]},{q:"ShadowStats.com tracks:",a:"Real inflation rates vs official government numbers",wrong:["Bitcoin mining difficulty","Lightning channel capacity","Altcoin prices"]},{q:'"The Four Horsemen" documentary (2013) exposes:',a:"The fiat monetary system scam",wrong:["Bitcoin mining farms","Social media dangers","Space exploration"]}],"problems-of-money_pt3":[{q:'"Nixon Shock" in 1971 refers to:',a:"The US ending the dollar's convertibility into gold",wrong:["The launch of Bitcoin","A global stock market crash","The creation of the first bank"]},{q:"Gresham's Law states that:",a:'"Bad money drives out good money"',wrong:['"Bitcoin will replace fiat"','"Gold is always better than silver"','"Taxes are voluntary"']},{q:"What happened in 1971?",a:"Nixon ended the gold standard, allowing unlimited fiat money printing",wrong:["Bitcoin was invented","The first digital computer was built","The Euro was introduced"]},{q:'Inflation is often called a "hidden tax" because:',a:"It silently erodes the purchasing power of your savings",wrong:["The IRS taxes Bitcoin gains at a hidden rate","Banks charge fees that are not disclosed","Governments print money in secret locations"]},{q:"What is seigniorage?",a:"The profit a government makes by issuing currency that costs less to produce than its face value",wrong:["A tax on gold mining","Interest earned on savings accounts","The fee banks charge for wire transfers"]}],"investment-strategy":[{q:"DCA stands for:",a:"Dollar Cost Averaging",wrong:["Digital Currency Account","Decentralized Crypto Asset","Direct Coin Access"]},{q:"A common Bitcoin investment strategy is:",a:"Buy regularly and hold long-term",wrong:["Day trade constantly","Sell every week","Only buy at the top"]},{q:"HODL originated from:",a:'A misspelled forum post saying "I AM HODLING"',wrong:["A financial textbook","A government document","A bank term"]},{q:"Bitcoin's 4-year cycle is often tied to:",a:"The halving events",wrong:["US elections","Solar cycles","Stock market seasons"]},{q:"The best time to buy Bitcoin according to Bitcoiners is:",a:"Always — time in the market beats timing the market",wrong:["Only at all-time highs","Only on Mondays","Only in December"]}],"investment-strategy_pt2":[{q:"Stacking sats means:",a:"Accumulating small amounts of Bitcoin over time",wrong:["Building satellite dishes","Stacking physical coins","Creating smart contracts"]},{q:"The biggest drawdown in Bitcoin history was:",a:"94% decline from $32 to $2 in July 2011",wrong:["50% in 2018","70% in 2022","80% in 2014"]},{q:"MNAV.com tracks:",a:"Bitcoin treasury companies and their metrics",wrong:["Lightning channels","Mining pools","Altcoin prices"]},{q:"Lump-sum investing means:",a:"Buying a large amount of Bitcoin all at once",wrong:["Buying a fixed amount every week","Selling all your holdings","Trading only on weekends"]},{q:"Dollar Cost Averaging (DCA) means:",a:"Buying a fixed amount of Bitcoin at regular intervals regardless of price",wrong:["Only buying when the price drops below a target","Investing your entire savings at once","Selling Bitcoin every time it rises 10%"]}],"investment-strategy_pt3":[{q:'The Bitcoin phrase "zoom out" means:',a:"Look at the long-term price trend instead of daily volatility",wrong:["Reduce your Bitcoin position size","Use a magnifying glass to read the whitepaper","Exit the market during a downturn"]},{q:'What does "stacking sats" mean in Bitcoin culture?',a:"Regularly accumulating small amounts of Bitcoin (satoshis) over time",wrong:["Building a stack of physical Bitcoin coins","Storing Bitcoin on multiple exchanges","Running multiple mining rigs simultaneously"]},{q:'Why do Bitcoiners say "time in the market beats timing the market"?',a:"Long-term holders historically outperform those trying to buy dips and sell tops",wrong:["Because Bitcoin's price never goes down","Because exchanges charge timing fees","Because mining rewards increase over time"]},{q:'What is the "HODL" strategy?',a:"Buying Bitcoin and holding it long-term regardless of short-term price volatility",wrong:["A day-trading technique for quick profits","An automated trading bot strategy","Holding exactly 1 Bitcoin at all times"]},{q:"Why is cold storage recommended for long-term Bitcoin holdings?",a:"Keeping private keys offline eliminates the risk of remote hacking or exchange failure",wrong:["Cold storage earns interest on your Bitcoin","It makes transactions faster","Cold wallets automatically back up to the cloud"]}],cryptography:[{q:"Bitcoin uses cryptography that has been:",a:"Used for decades in other applications",wrong:["Invented specifically for Bitcoin","Never tested before","Made by AI"]},{q:"A private key is:",a:"A secret number that controls your Bitcoin",wrong:["Your email password","A physical key","Your bank PIN"]},{q:"A public key is derived from:",a:"The private key using one-way math",wrong:["Your name","Random chance","The blockchain"]},{q:"Digital signatures prove:",a:"You own the private key without revealing it",wrong:["Your identity","Your location","Your bank balance"]},{q:"Hashing is:",a:"Converting data into a fixed-length fingerprint",wrong:["Deleting data","Encrypting emails","Mining Bitcoin"]}],cryptography_pt2:[{q:"Elliptic curve cryptography is used for:",a:"Generating Bitcoin key pairs",wrong:["Mining blocks","Sending emails","Browsing the web"]},{q:"What type of cryptography does Bitcoin use for digital signatures?",a:"Elliptic Curve Digital Signature Algorithm (ECDSA) on the secp256k1 curve",wrong:["RSA 2048-bit encryption","AES-256 symmetric encryption","Triple DES block cipher"]},{q:"What is a hash function's role in Bitcoin?",a:"It creates a fixed-size, unique digital fingerprint of any input data, used for block headers, addresses, and mining",wrong:["It encrypts all Bitcoin transactions end-to-end","It compresses the blockchain to save space","It converts Bitcoin to other cryptocurrencies"]},{q:"Why can't you derive a private key from a public key?",a:"Elliptic curve math is a one-way function — easy to compute forward, computationally infeasible to reverse",wrong:["Because private keys are longer than public keys","Because the blockchain deletes private keys","Because Satoshi encrypted all key pairs"]},{q:"What does SHA-256 stand for and where is it used in Bitcoin?",a:"Secure Hash Algorithm 256-bit — used in mining (proof of work) and creating transaction IDs",wrong:["Super Hash Accelerator — used in wallet encryption only","Satoshi Hash Algorithm — used in signature verification","Shared Hash Array — used in peer-to-peer networking"]}],regulation:[{q:"Bitcoin's response to bans has been:",a:"Moving to friendlier jurisdictions",wrong:["Shutting down","Complying immediately","Becoming illegal forever"]},{q:"El Salvador made Bitcoin:",a:"Legal tender in 2021",wrong:["Illegal in 2020","A national secret","Only for tourists"]},{q:"Bitcoin regulation varies by:",a:"Country — each has different rules",wrong:["There are no rules anywhere","One global law covers it","Bitcoin regulates itself"]},{q:"A Bitcoin ETF allows:",a:"Traditional investors to get Bitcoin exposure through stock markets",wrong:["Free Bitcoin for everyone","Government-controlled mining","Printing new Bitcoin"]},{q:"The SEC has classified Bitcoin as:",a:"A commodity, not a security",wrong:["A security","A currency","Illegal"]}],regulation_pt2:[{q:'What is a "Self-Custody" regulation attempt?',a:"Rules that try to force users to use custodial services",wrong:["Laws that guarantee free Bitcoin","Mining equipment safety standards","Bitcoin price caps"]},{q:"Can a government effectively ban Bitcoin?",a:"They can restrict fiat on-ramps but cannot stop peer-to-peer transactions",wrong:["Yes — turning off the internet kills Bitcoin permanently","Yes — all nodes can be identified and shut down simultaneously","No bans have ever been attempted by any country"]},{q:"China has banned Bitcoin mining multiple times, yet:",a:"Miners relocated and the network hash rate recovered within months",wrong:["Bitcoin permanently lost 50% of its value","All Chinese Bitcoin was confiscated","The Bitcoin network was offline for weeks"]},{q:"How is Bitcoin classified for tax purposes in most jurisdictions?",a:"As property or a capital asset, meaning gains are subject to capital gains tax",wrong:["As currency, exempt from all taxes","As a commodity with no reporting requirements","As digital cash with no tax implications"]},{q:'What does the "Travel Rule" require for crypto transactions?',a:"Regulated exchanges must share sender and receiver identity information for transfers above a threshold",wrong:["Users must physically travel to an exchange to withdraw","Bitcoin can only be sent within your home country","Miners must verify passport numbers for each block"]}],energy:[{q:"Bitcoin mining and energy:",a:"Promotes renewable energy and uses wasted energy",wrong:["Only uses coal","Wastes all energy","Uses no energy"]},{q:"Stranded energy refers to:",a:"Energy produced in remote locations with no buyers",wrong:["Electricity outages","Solar panels at night","Wind on calm days"]},{q:"Bitcoin miners often locate near:",a:"Cheap renewable energy sources",wrong:["Shopping malls","Government buildings","Residential areas"]},{q:"Bitcoin mining can help stabilize:",a:"Electrical grids by acting as a flexible load",wrong:["The stock market","Internet speeds","Political systems"]},{q:"Compared to traditional banking, Bitcoin's energy use is:",a:"Debatable but often comparable or less",wrong:["1000x more","Zero","Exactly the same"]}],energy_pt2:[{q:"Methane flaring and Bitcoin mining:",a:"Miners can capture and use flared gas productively",wrong:["They are unrelated","Mining increases flaring","Flaring powers all mining"]},{q:"Bitcoin mining primarily uses which type of energy?",a:"Over 50% renewable — often stranded or wasted energy",wrong:["100% coal and natural gas","Nuclear power exclusively","Solar panels attached to mining rigs"]},{q:"Bitcoin mining can actually help the environment by:",a:"Monetizing flared methane that would otherwise be released into the atmosphere",wrong:["Reducing the total electricity consumed worldwide","Creating new renewable energy out of thin air","Cooling the planet through heat dissipation"]},{q:"How do Bitcoin miners contribute to grid stability?",a:"They can instantly power down during peak demand, acting as flexible load that balances the grid",wrong:["They generate excess electricity for the grid","They replace power plants entirely","They only mine during off-peak hours by law"]},{q:"What percentage of Bitcoin mining uses renewable energy sources according to recent estimates?",a:"Over 50% and growing, driven by miners seeking the cheapest energy",wrong:["Less than 5%","Exactly 100% — all mining is renewable","About 10%, mostly nuclear"]}],"core-source-code":[{q:"Changes to Bitcoin Core require:",a:"Careful testing and peer review",wrong:["One person's approval","A company decision","Government permission"]},{q:"Bitcoin Core is written primarily in:",a:"C++",wrong:["Python","JavaScript","Java"]},{q:"Anyone can:",a:"Read, review, and propose changes to Bitcoin's code",wrong:["Change Bitcoin without review","Delete the blockchain","Add more coins"]},{q:"A BIP is:",a:"A Bitcoin Improvement Proposal",wrong:["A Bitcoin Investment Plan","A Block Information Protocol","A Banking Integration Process"]},{q:"Bitcoin's code repository is hosted on:",a:"GitHub",wrong:["Facebook","A secret server","The dark web"]}],"blockchain-timechain":[{q:"A new Bitcoin block is produced approximately every:",a:"10 minutes",wrong:["1 second","1 hour","1 day"]},{q:"Each block contains:",a:"A list of transactions and a reference to the previous block",wrong:["Just one transaction","Pictures","Email addresses"]},{q:"The blockchain is often called:",a:"An immutable ledger",wrong:["A cloud server","A website","A database that can be edited"]},{q:"Satoshi originally called it:",a:"A timechain",wrong:["A blockchain","A datachain","A coinchain"]},{q:"The Genesis Block contains a message about:",a:"A newspaper headline about bank bailouts",wrong:["A recipe","A love letter","A stock tip"]}],"blockchain-timechain_pt2":[{q:"Block height refers to:",a:"The sequential number of a block in the chain",wrong:["How tall a server rack is","The size of the block","Mining difficulty"]},{q:"Satoshi originally called the blockchain the:",a:"Timechain",wrong:["Hashchain","Blockweb","Cryptoledger"]},{q:"Each Bitcoin block contains a reference to:",a:"The hash of the previous block, creating an unbreakable chain",wrong:["The next block that will be mined","All future transactions that will occur","A backup of the entire blockchain"]},{q:"The mempool is:",a:"A waiting area where unconfirmed transactions sit until miners include them in a block",wrong:["A type of Bitcoin storage device","The total amount of memory used by Bitcoin nodes","A pool of memory shared between mining hardware"]},{q:'Why did Satoshi originally call it a "timechain" rather than "blockchain"?',a:"Because each block timestamps transactions in chronological order, creating a chain of time-stamped records",wrong:["Because blocks are mined at exactly 10-minute intervals","Because it tracks time zones for each transaction",'Because the name "blockchain" was already trademarked']}],analogies:[{q:"In the airport analogy, Lightning is like:",a:"A bicycle courier in the terminal",wrong:["The runway","A cargo plane","Air traffic control"]},{q:"Bitcoin is often compared to:",a:"Digital gold",wrong:["Digital silver","Digital stocks","Digital bonds"]},{q:"The Bitcoin network is sometimes compared to:",a:"The internet protocol (TCP/IP)",wrong:["A single website","A phone call","A TV channel"]},{q:"Holding Bitcoin is compared to:",a:"Holding property in cyberspace",wrong:["Renting a movie","Subscribing to a service","Opening a bank account"]},{q:"Bitcoin is often compared to digital gold because both are scarce, durable, and serve as stores of value outside government control.",a:"Digital gold",wrong:["Digital cash","Digital silver","Digital oil"]}],byzantine_generals__problem:[{q:"The Byzantine Generals Problem is about:",a:"Reaching agreement when some participants may be dishonest",wrong:["Building castles","Trading gold","Sending emails"]},{q:"Bitcoin solved the Byzantine Generals Problem using:",a:"Proof of Work consensus",wrong:["A voting system","A trusted mediator","Encryption alone"]},{q:"In the analogy, the generals need to:",a:"Coordinate an attack without a trusted messenger",wrong:["Build a wall","Trade horses","Sign a peace treaty"]},{q:"Before Bitcoin, the Byzantine Generals Problem was considered:",a:"Unsolvable in a trustless digital environment",wrong:["Easy to solve","Irrelevant","Already solved by banks"]},{q:"The Byzantine Generals Problem asks how dispersed parties can reach consensus without trusting each other. What mechanism did Bitcoin invent to solve this?",a:"Nakamoto Consensus (proof-of-work + longest chain)",wrong:["Voting by validator nodes","Centralized coordinator server","Proof of stake randomization"]}],game_theory:[{q:"Bitcoin's incentive structure uses:",a:"Game theory to align participants",wrong:["Threats of punishment","Legal contracts","Trust alone"]},{q:"Miners are incentivized to be honest because:",a:"Cheating costs more than playing by the rules",wrong:["They sign contracts","The government watches them","There are no incentives"]},{q:"Nash Equilibrium in Bitcoin means:",a:"No participant benefits from changing their strategy alone",wrong:["Everyone mines equally","Prices never change","All nodes are identical"]},{q:"The prisoner's dilemma relates to Bitcoin because:",a:"Cooperation is more profitable than defection",wrong:["Miners are in prison","Bitcoin is illegal","Users are trapped"]},{q:"What game theory concept explains why Bitcoin miners are incentivized to stay honest rather than attack the network?",a:"Nash equilibrium — attacking costs more than honest mining",wrong:["Prisoner\\'s dilemma","Zero-sum game","Pareto inefficiency"]}],elevator_pitches:[{q:"A good Bitcoin elevator pitch should be:",a:"Simple and compelling in under a minute",wrong:["A 2-hour lecture","Only about price","As technical as possible"]},{q:"When explaining Bitcoin to beginners, start with:",a:"The problem it solves (broken money)",wrong:["Mining algorithms","Cryptographic proofs","Exchange trading"]},{q:"The simplest Bitcoin pitch is often:",a:"Digital money that no one can print or confiscate",wrong:["A get-rich-quick scheme","Internet points","A new bank"]},{q:"How would you explain Bitcoin to a complete newcomer in one sentence?",a:"A digital form of money that no government or company can print, freeze, or control",wrong:["A speculative investment to get rich quick","A credit card for online shopping","A bank account with higher interest"]},{q:"What is the most important feature for Bitcoin newcomers to understand first?",a:"Nobody can confiscate or freeze your bitcoin if you hold your own keys",wrong:["The price will always go up","It\\'s anonymous like cash","Transactions are free"]}],taproot:[{q:"Taproot is a Bitcoin:",a:"Upgrade that improves privacy and smart contracts",wrong:["New cryptocurrency","Mining algorithm","Exchange platform"]},{q:"Taproot was activated in:",a:"November 2021",wrong:["January 2009","March 2015","June 2023"]},{q:"Taproot uses Schnorr signatures which:",a:"Make multi-sig transactions look like regular ones",wrong:["Speed up mining","Create new coins","Delete old blocks"]},{q:"Taproot improves:",a:"Privacy, efficiency, and smart contract capabilities",wrong:["Mining speed only","Block size only","Transaction fees only"]},{q:"What type of signature scheme did Taproot introduce to Bitcoin?",a:"Schnorr signatures",wrong:["RSA signatures","Ring signatures","Lamport signatures"]}],taproot_pt2:[{q:"Taproot improves Bitcoin by:",a:"Enhancing privacy, efficiency, and smart contract capabilities using Schnorr signatures",wrong:["Increasing the total supply above 21 million","Removing the need for mining","Making all transactions completely anonymous"]},{q:"When was the Taproot upgrade activated on Bitcoin?",a:"November 2021 at block 709,632",wrong:["August 2017 with SegWit","January 2009 at genesis","June 2023 with Ordinals"]},{q:"What is MAST (Merkelized Abstract Syntax Trees) in Taproot?",a:"A structure that reveals only the executed spending condition, hiding unused conditions for privacy",wrong:["A new mining algorithm that replaces SHA-256","A type of Lightning channel","A database for storing smart contract state"]},{q:"How does Taproot improve multi-signature transactions?",a:"Schnorr signatures allow multiple signers to produce a single compact signature indistinguishable from a regular one",wrong:["It removes the need for multiple signatures entirely","It stores each signature in a separate block","It requires all signers to be online simultaneously"]},{q:"What is Tapscript?",a:"An updated version of Bitcoin Script that enables new opcodes and improved scripting with Taproot",wrong:["A programming language for building altcoins","A tool for writing Bitcoin Core patches","The scripting language used in Lightning Network"]}],scalability:[{q:"Bitcoin base layer processes roughly:",a:"7 transactions per second",wrong:["7 million per second","1 per minute","100,000 per second"]},{q:"Bitcoin scales primarily through:",a:"Layer 2 solutions like Lightning",wrong:["Making blocks bigger forever","Removing the block limit","Using faster internet"]},{q:"The block size limit exists to:",a:"Keep node requirements low and maintain decentralization",wrong:["Slow down transactions","Limit Bitcoin's value","Help miners make more money"]},{q:"The Blocksize Wars were about:",a:"Whether to increase block size or use Layer 2",wrong:["Mining profitability","Bitcoin's name","Which exchange to use"]},{q:"Bitcoin's block size is limited to approximately:",a:"1-4 MB (with SegWit)",wrong:["100 MB","Unlimited — it grows with demand","1 KB"]}],scalability_pt2:[{q:"What did SegWit (Segregated Witness) do for Bitcoin scalability?",a:"Separated signature data from transaction data, effectively increasing block capacity to ~2 MB equivalent",wrong:["Doubled the block size to 2 MB","Removed the block size limit entirely","Moved all transactions to a sidechain"]},{q:"What is transaction batching?",a:"Combining multiple payments into a single on-chain transaction to save block space and fees",wrong:["Sending the same transaction multiple times for reliability","Grouping transactions by sender country","Waiting until a block is full before broadcasting"]},{q:"Why did the Bitcoin community reject simply raising the block size limit?",a:"Larger blocks increase node operating costs, risking centralization and reducing censorship resistance",wrong:["Larger blocks would break all existing wallets","Satoshi explicitly forbade any block size changes","Larger blocks would reduce the total Bitcoin supply"]},{q:"How does the Lightning Network improve Bitcoin's throughput?",a:"By processing millions of transactions off-chain and only settling final balances on the Bitcoin blockchain",wrong:["By replacing Bitcoin's blockchain with a faster one","By increasing the block size to 100 MB","By reducing the time between blocks to 1 second"]},{q:"What is payment channel batching on Lightning?",a:"Opening or closing multiple channels in a single on-chain transaction to save fees and block space",wrong:["Sending the same payment to multiple recipients","Mining multiple blocks at once","Compressing transaction data for faster processing"]}],utxos:[{q:"UTXO stands for:",a:"Unspent Transaction Output",wrong:["Universal Token Exchange Order","Unified Transaction eXecution Object","Ultra-fast Transfer of eXchange Operations"]},{q:"A UTXO is like:",a:"A specific bill in your wallet that you spend whole",wrong:["A bank balance","A credit limit","An account number"]},{q:"When you spend a UTXO:",a:"It's consumed entirely and change is returned as a new UTXO",wrong:["Part of it disappears","It stays in your wallet","It's deleted from the blockchain"]},{q:"UTXO management matters for:",a:"Privacy and minimizing future transaction fees",wrong:["Mining speed","Block creation","Node operation"]},{q:"What is a UTXO in Bitcoin?",a:"Unspent Transaction Output — the amount of bitcoin remaining after a transaction",wrong:["A type of digital signature","A mining reward token","A user transaction ID"]}],dust:[{q:'Bitcoin "dust" is:',a:"An amount too small to spend because the fee exceeds the value",wrong:["Deleted Bitcoin","A type of mining waste","A security attack"]},{q:"Dust attacks are used to:",a:"Track and deanonymize wallet owners",wrong:["Steal Bitcoin directly","Mine faster","Create new blocks"]},{q:"To avoid dust issues:",a:"Consolidate small UTXOs when fees are low",wrong:["Delete your wallet","Stop using Bitcoin","Only use exchanges"]},{q:'What is a "dust attack" in Bitcoin?',a:"Sending tiny amounts of bitcoin to wallets to track and de-anonymize users",wrong:["Overloading the network with large transactions","Physical dirt damaging mining hardware","A bug in the Bitcoin software"]},{q:"Why should users consolidate small UTXOs when fees are low?",a:"To reduce future transaction costs, as each UTXO adds to transaction size",wrong:["To increase bitcoin value","To improve privacy","To earn mining rewards"]}],rbf:[{q:"RBF stands for:",a:"Replace-By-Fee",wrong:["Really Big Fee","Rapid Block Finality","Return Bitcoin Fast"]},{q:"RBF allows you to:",a:"Bump a stuck transaction's fee to speed confirmation",wrong:["Cancel any transaction","Send Bitcoin for free","Mine your own block"]},{q:"RBF is useful when:",a:"Your transaction is stuck because the fee was too low",wrong:["You want to mine","You need a new wallet","You want to buy altcoins"]},{q:"What does RBF (Replace-by-Fee) allow users to do?",a:"Replace an unconfirmed transaction with a higher-fee version",wrong:["Reverse a confirmed transaction","Increase their total bitcoin balance","Prevent double spending"]},{q:"What is CPFP (Child Pays for Parent) used for?",a:"Accelerating confirmation by spending an unconfirmed output with a high-fee transaction",wrong:["Splitting bitcoin for children","Creating child wallets","Reducing transaction size"]}],time_preference:[{q:"Low time preference means:",a:"Saving for the future instead of spending now",wrong:["Spending everything today","Not caring about money","Only day trading"]},{q:"Bitcoin encourages low time preference because:",a:"Its value tends to increase over time due to scarcity",wrong:["It loses value quickly","It pays interest","The government mandates savings"]},{q:"High time preference leads to:",a:"Overconsumption and debt",wrong:["Wealth building","Better savings","Financial freedom"]},{q:"Fiat currency encourages:",a:"Spending now because money loses value over time",wrong:["Long-term saving","Low time preference","Financial responsibility"]},{q:'What is "low time preference" in Bitcoin culture?',a:"Prioritizing long-term saving over short-term spending",wrong:["Trading Bitcoin frequently for quick profits","Spending all your Bitcoin before the next halving","Checking the price every 5 minutes"]}],time_preference_pt2:[{q:"A Bitcoin standard encourages low time preference because:",a:"Saving is rewarded since the money appreciates over time",wrong:["Bitcoin transactions are extremely slow","The government mandates holding periods","You can only sell Bitcoin once per year"]},{q:'What does "low time preference" mean in the context of Bitcoin?',a:"Prioritizing long-term value and future rewards over immediate gratification",wrong:["Preferring to spend Bitcoin quickly before it loses value","Setting a time limit on how long you hold Bitcoin","Trading Bitcoin on short timeframes"]},{q:"How does fiat money encourage high time preference?",a:"Inflation erodes purchasing power, incentivizing spending now rather than saving for later",wrong:["Fiat money expires after a certain date","Banks charge fees for holding money too long","Governments tax savings but not spending"]},{q:'Why do Bitcoiners say Bitcoin "fixes" time preference?',a:"A deflationary hard money incentivizes saving and long-term thinking since purchasing power increases over time",wrong:["Bitcoin automatically invests your savings","Bitcoin transactions are slower, forcing patience","Bitcoin wallets lock funds for a minimum of one year"]},{q:"How does time preference relate to civilization building?",a:"Lower time preference leads to more capital accumulation, investment, and long-term infrastructure development",wrong:["Higher time preference builds civilizations faster","Time preference has no relationship to economic development","Only governments can lower society's time preference"]}],soft_vs_hard_forks:[{q:"A soft fork is:",a:"Backward-compatible upgrade",wrong:["A completely new blockchain","Deleting Bitcoin","A type of altcoin"]},{q:"A hard fork creates:",a:"A permanent chain split if not everyone upgrades",wrong:["A temporary pause","More Bitcoin","A faster network"]},{q:"Bitcoin Cash was created by:",a:"A hard fork of Bitcoin in 2017",wrong:["Satoshi Nakamoto in 2009","The US government","Ethereum developers"]},{q:"SegWit was activated as:",a:"A soft fork",wrong:["A hard fork","A new blockchain","An altcoin"]},{q:"The key difference between a soft fork and a hard fork is:",a:"Soft forks are backwards-compatible; hard forks are not",wrong:["Soft forks are temporary; hard forks are permanent","Soft forks require less code; hard forks need more","Soft forks are approved by vote; hard forks by mining"]}],soft_vs_hard_forks_pt2:[{q:"The Blocksize Wars resulted in:",a:"Bitcoin Cash splitting off as a hard fork while Bitcoin kept small blocks + SegWit",wrong:["Bitcoin doubling its block size to 2 MB","All miners switching to Bitcoin Cash","The creation of Ethereum"]},{q:"What is a soft fork in Bitcoin?",a:"A backward-compatible protocol upgrade where old nodes still accept new blocks",wrong:["A complete restart of the blockchain","A split that creates a new cryptocurrency","An update that requires all nodes to upgrade immediately"]},{q:"What is a hard fork?",a:"A non-backward-compatible change that requires all nodes to upgrade or they'll follow a different chain",wrong:["A bug fix that doesn't change consensus rules","A minor update to wallet software","A temporary network outage"]},{q:"What was the Bitcoin Cash (BCH) hard fork about?",a:"A disagreement over scaling — BCH proponents wanted larger blocks while Bitcoin kept the 1 MB base limit with SegWit",wrong:["A dispute over who created Bitcoin","A fix for a critical security bug","A change to Bitcoin's monetary policy"]},{q:"Why are soft forks generally preferred over hard forks for Bitcoin upgrades?",a:"They maintain backward compatibility, don't force upgrades, and don't risk splitting the network",wrong:["They are faster to implement","They don't require any code changes","Hard forks are illegal in most countries"]}],fedimints:[{q:"Fedimint helps with:",a:"Community custody with privacy",wrong:["Solo mining","Creating altcoins","Government reporting"]},{q:"A Fedimint uses:",a:"Federated guardians who jointly custody Bitcoin",wrong:["A single custodian","Government vaults","Exchange accounts"]},{q:"Fedimint provides privacy through:",a:"Chaumian eCash tokens",wrong:["Public blockchain","KYC verification","IP tracking"]},{q:"Fedimints are designed for:",a:"Communities that trust each other but want privacy",wrong:["Individual use only","Government agencies","Large corporations"]},{q:"A Fedimint (Federated Mint) provides:",a:"Community-custodial privacy through Chaumian ecash on Bitcoin",wrong:["A new type of Bitcoin mining pool","A government-approved Bitcoin exchange","A way to increase Bitcoin's supply above 21 million"]}],fedimints_pt2:[{q:"Fedimints improve Bitcoin privacy by:",a:"Using blinded signatures so the mint cannot link deposits to withdrawals",wrong:["Deleting transaction data from the blockchain","Requiring all users to share their identity","Converting Bitcoin into a different cryptocurrency"]},{q:"What is a Fedimint?",a:"A federated Chaumian eCash mint where a group of guardians custody Bitcoin and issue private eCash tokens",wrong:["A government-run Bitcoin exchange","A type of Bitcoin mining pool","A centralized bank built on Lightning"]},{q:"How do Fedimints provide privacy?",a:"Using blind signatures so the mint cannot link who deposited Bitcoin with who redeems eCash tokens",wrong:["By encrypting the blockchain","By hiding all transactions from the public","By requiring users to use VPNs"]},{q:"What is the trust model of a Fedimint?",a:"Users trust a federation of guardians (e.g., 3-of-5 multisig) rather than a single custodian",wrong:["Completely trustless like on-chain Bitcoin","Users trust a single company","The government guarantees deposits"]},{q:"How do Fedimints interact with the Lightning Network?",a:"They can send and receive Lightning payments, allowing private transactions with the broader Bitcoin network",wrong:["They replace Lightning entirely","Lightning cannot connect to Fedimints","Fedimints require their own separate payment network"]}],books:[{q:"The Bitcoin Standard is a popular book about:",a:"Sound money and Bitcoin economics",wrong:["Bitcoin mining hardware","How to day trade","Building websites"]},{q:"Mastering Bitcoin by Andreas Antonopoulos is:",a:"A technical deep-dive into how Bitcoin works",wrong:["A children's book","A cookbook","A fitness guide"]},{q:"The Sovereign Individual predicted:",a:"Digital money and the decline of nation-states",wrong:["Social media","Electric cars","Space travel"]},{q:"21 Lessons by Gigi explores:",a:"Philosophical lessons learned from going down the Bitcoin rabbit hole",wrong:["21 mining techniques","21 trading strategies","21 altcoins to buy"]},{q:'"The Bitcoin Standard" by Saifedean Ammous primarily argues:',a:"Bitcoin is the hardest money ever invented and will replace fiat",wrong:["Bitcoin is a useful technology but too volatile to be money","Gold is still superior to Bitcoin as a store of value","Central banks should adopt Bitcoin as a reserve currency"]}],books_pt2:[{q:'Gigi\'s "21 Lessons" is structured around:',a:"21 philosophical, economic, and technical lessons learned from Bitcoin",wrong:["A 21-day guide to becoming a Bitcoin trader","The 21 richest Bitcoin holders and their strategies","The history of 21 failed cryptocurrencies"]},{q:'Who wrote "The Bitcoin Standard"?',a:"Saifedean Ammous",wrong:["Andreas Antonopoulos","Satoshi Nakamoto","Michael Saylor"]},{q:"What book by Jimmy Song teaches Bitcoin programming and development?",a:"Programming Bitcoin",wrong:["The Bitcoin Standard","Digital Gold","Cryptoassets"]},{q:"What book by Lyn Alden provides a broad investment perspective including Bitcoin?",a:"Broken Money",wrong:["The Bitcoin Standard","Digital Gold","The Internet of Money"]},{q:'What is "The Blocksize War" by Jonathan Bier about?',a:"The history of Bitcoin's scaling debate, SegWit activation, and the BCH fork",wrong:["How to increase your Bitcoin block rewards","A fiction novel about cryptocurrency battles","Military applications of blockchain technology"]}],"misconceptions-fud":[{q:"FUD stands for:",a:"Fear, Uncertainty, and Doubt",wrong:["Fully Unified Database","First User Downloaded","Financial Update Daily"]},{q:'"Bitcoin is used by criminals" ignores that:',a:"Cash is used far more for crime and Bitcoin is traceable",wrong:["Bitcoin is untraceable","There are no criminals","Crime doesn't exist"]},{q:'"Bitcoin has no intrinsic value" ignores:',a:"Its network security, scarcity, and utility",wrong:["Its physical weight","Its smell","Its color"]},{q:'"Bitcoin is too volatile" ignores:',a:"Its long-term upward trend and decreasing volatility over time",wrong:["That it never moves","That it only goes down","Government price controls"]},{q:'"Bitcoin wastes energy" ignores:',a:"Its use of stranded/renewable energy and the value it secures",wrong:["That it uses no energy","Solar panels","Wind turbines only"]}],"satoshi-nakamoto":[{q:"Satoshi Nakamoto:",a:"Stepped down and disappeared",wrong:["Is currently the CEO of Bitcoin","Was arrested","Sold all Bitcoin"]},{q:"Satoshi's last known communication was around:",a:"2011",wrong:["2020","2015","2009"]},{q:"Satoshi's Bitcoin holdings are estimated at:",a:"About 1 million BTC that have never moved",wrong:["Zero","100 BTC","All 21 million"]},{q:"Satoshi's disappearance is seen as:",a:"A feature — it made Bitcoin truly decentralized",wrong:["A bug","A crime","A marketing strategy"]},{q:"Satoshi's true identity is:",a:"Unknown — it could be one person or a group",wrong:["Confirmed to be Elon Musk","A CIA agent","The President"]}],"satoshi-nakamoto_pt2":[{q:"Why is it important that Satoshi Nakamoto disappeared?",a:"Bitcoin has no leader who can be arrested, corrupted, or pressured",wrong:["Because they were wanted by law enforcement","So they could secretly accumulate more Bitcoin","Because the code was finished and needed no more work"]},{q:"What evidence suggests Satoshi Nakamoto was likely one person rather than a team?",a:"Consistent writing style, coding patterns, and posting times across years of activity",wrong:["A signed confession published on the Bitcoin Talk forum","DNA evidence found on the original Bitcoin server hardware","A government investigation that confirmed a single identity"]},{q:"When did Satoshi Nakamoto stop posting publicly?",a:"Around December 2010, with a final known post in April 2011",wrong:["January 2009 right after launching Bitcoin","They never stopped and still post today","In 2015 during the block size debate"]},{q:"How many Bitcoin did Satoshi Nakamoto reportedly mine?",a:"Approximately 1 million BTC based on analysis of early mining patterns",wrong:["Exactly 21 million (the entire supply)","Zero — Satoshi never mined","About 100 BTC from the genesis block only"]},{q:"What famous message did Satoshi embed in the Bitcoin genesis block?",a:'"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"',wrong:['"Hello World — Bitcoin is born"','"In code we trust"','"The revolution will not be centralized"']}],history:[{q:"The Bitcoin Genesis Block was mined in:",a:"January 2009",wrong:["October 2008","June 2010","December 2007"]},{q:"The first real-world Bitcoin transaction was:",a:"10,000 BTC for two pizzas",wrong:["1 BTC for a car","100 BTC for a house","1 BTC for a coffee"]},{q:"Bitcoin Pizza Day is celebrated on:",a:"May 22",wrong:["January 3","October 31","December 25"]},{q:"Mt. Gox was:",a:"An early Bitcoin exchange that was hacked and collapsed",wrong:["A mining company","A Bitcoin wallet","A government agency"]},{q:"The first Bitcoin block is called:",a:"The Genesis Block (Block 0)",wrong:["The Alpha Block","Block One","The Origin Block"]}],history_pt2:[{q:"Hal Finney received:",a:"The first Bitcoin transaction from Satoshi",wrong:["The last Bitcoin ever","A medal from the government","The Bitcoin trademark"]},{q:"Laszlo's famous pizza order was called from:",a:"London (Laszlo was in Florida)",wrong:["New York","San Francisco","Tokyo"]},{q:"The Bitcoin Wiki has been online since:",a:"2010",wrong:["2015","2009","2013"]},{q:"Tim Draper is known in Bitcoin for:",a:"Buying seized Silk Road Bitcoin at US Marshals auction",wrong:["Creating the Lightning Network","Writing the whitepaper","Mining the genesis block"]},{q:'The "Lightning Torch" was:',a:"A Lightning payment passed between notable Bitcoiners",wrong:["A mining competition","A hardware wallet","A documentary"]}],_general:[{q:"What is the smallest unit of Bitcoin called?",a:"A satoshi",wrong:["A bit","A wei","A penny"]},{q:"Bitcoin was launched in which year?",a:"2009",wrong:["2008","2010","2012"]},{q:"Bitcoin transactions are recorded on:",a:"A public distributed ledger",wrong:["A private server","A bank database","An email chain"]},{q:"Who can send you Bitcoin?",a:"Anyone who knows your address",wrong:["Only your bank","Only verified users","Only people in your country"]},{q:"Bitcoin operates on:",a:"24/7, 365 days a year",wrong:["Banking hours only","Weekdays only","It shuts down for maintenance"]},{q:"The total number of Bitcoins that will ever exist is:",a:"Exactly 21 million",wrong:["Unlimited","100 million","It changes yearly"]},{q:"Bitcoin is often abbreviated as:",a:"BTC",wrong:["BTN","BCN","BIT"]},{q:"A Bitcoin wallet stores:",a:"Private keys, not actual Bitcoin",wrong:["Physical coins","Digital files of Bitcoin","Pictures of Bitcoin"]},{q:"To receive Bitcoin you need:",a:"A Bitcoin address",wrong:["A bank account","A social security number","A credit card"]},{q:"The Bitcoin network is maintained by:",a:"Thousands of volunteers running nodes worldwide",wrong:["A company in California","The United Nations","A single supercomputer"]},{q:"Bitcoin confirmation time depends on:",a:"Network congestion and fee paid",wrong:["Time of day","Your internet speed","Which country you are in"]},{q:"A mempool is:",a:"Where unconfirmed transactions wait to be included in a block",wrong:["A mining pool","A type of wallet","A cryptocurrency exchange"]},{q:"Bitcoin difficulty adjustment ensures:",a:"Blocks are found roughly every 10 minutes regardless of hash power",wrong:["Prices stay stable","Miners earn the same amount","Transactions are free"]},{q:"SegWit stands for:",a:"Segregated Witness",wrong:["Secure Widget","Sequential Witness","Segment Width"]},{q:"A Bitcoin address starts with:",a:"1, 3, or bc1",wrong:["0x","BTC","Any letter"]},{q:"The Lightning Network whitepaper was published by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto","Vitalik Buterin","Elon Musk"]},{q:"Bitcoin hash rate measures:",a:"The total computing power securing the network",wrong:["Transaction speed","Number of users","Price changes"]},{q:"A nonce in mining is:",a:"A number miners change to find a valid block hash",wrong:["A type of fee","A wallet address","A block reward"]},{q:'The term "NGMI" in Bitcoin culture means:',a:"Not Gonna Make It",wrong:["New Global Money Index","Next Generation Mining Interface","Network Growth Metric Indicator"]},{q:"Hyperbitcoinization refers to:",a:"Mass voluntary adoption of Bitcoin as money",wrong:["A Bitcoin price crash","A mining difficulty spike","A new altcoin launch"]},{q:"Strike, Cash App, and River are all:",a:"Apps that let you buy Bitcoin",wrong:["Mining pools","Altcoins","Bitcoin forks"]},{q:"Nostr is:",a:"A decentralized social protocol popular in the Bitcoin community",wrong:["A mining algorithm","A Bitcoin fork","An exchange"]},{q:'The phrase "fix the money, fix the world" means:',a:"Sound money leads to better societal outcomes",wrong:["Print more money","Ban all currencies","Use only credit cards"]},{q:"A timelock in Bitcoin allows:",a:"Locking funds until a specific block height or time",wrong:["Freezing the blockchain","Stopping mining","Deleting transactions"]},{q:"Block reward plus transaction fees equals:",a:"The total miner revenue per block",wrong:["The Bitcoin price","The network speed","The difficulty level"]},{q:"Ordinals on Bitcoin are:",a:"A way to inscribe data on individual satoshis",wrong:["A ranking system for miners","A type of wallet","A government regulation"]},{q:"A paper wallet is:",a:"A printed private key for cold storage",wrong:["A paper receipt from an ATM","A bank statement","A type of fiat currency"]},{q:"The Lightning Network can theoretically handle:",a:"Millions of transactions per second",wrong:["7 per second","100 per second","1 per minute"]},{q:"A watch-only wallet lets you:",a:"Monitor a balance without being able to spend",wrong:["Mine Bitcoin","Create new coins","Edit the blockchain"]},{q:"Pleb is a term of endearment in Bitcoin meaning:",a:"An everyday Bitcoiner, not wealthy but committed",wrong:["A professional trader","A mining executive","A government official"]},{q:"What is the total number of satoshis that will ever exist?",a:"2.1 quadrillion (2,100,000,000,000,000)",wrong:["21 million","100 billion","21 quadrillion"]},{q:"Bitcoin Pizza Day is celebrated on:",a:"May 22",wrong:["January 3","October 31","April 15"]},{q:"The first Bitcoin exchange rate was established at approximately:",a:"$0.00099 per BTC (less than one penny)",wrong:["$1.00 per BTC","$0.10 per BTC","$100 per BTC"]},{q:"HODL originated from:",a:'A misspelled Bitcoin forum post from 2013 ("I AM HODLING")',wrong:["An acronym created by a Bitcoin company",'A Japanese word meaning "to hold"',"A technical term in Bitcoin's source code"]},{q:'The phrase "Not your keys, not your coins" warns against:',a:"Keeping Bitcoin on exchanges where you don't control the private keys",wrong:["Using physical Bitcoin coins instead of digital","Sharing your public key with other people","Using hardware wallets instead of software"]}],risks__threats__attack_vectors__weaknes:[{q:"Which Bitcoin address type is better for quantum resistance?",a:"SegWit (bc1q) because Taproot exposes the public key",wrong:["Taproot (bc1p)","Legacy (1...)","All are equally vulnerable"]},{q:"BIP 360 proposes:",a:"Pay to Quantum Resistant Hash",wrong:["Bigger blocks","Faster mining","New altcoin support"]},{q:"A 51% attack would require:",a:"Controlling more than half of Bitcoin's total mining hash rate",wrong:["Owning 51% of all existing Bitcoin","Having 51% of all Bitcoin nodes vote together","Hacking 51% of Bitcoin wallets simultaneously"]},{q:"Why is a 51% attack impractical against Bitcoin?",a:"The hash rate is so massive it would cost billions and be unprofitable",wrong:["Because Bitcoin automatically detects and blocks attacks","Because Satoshi built in a secret defense mechanism","Because only 21 mining pools exist worldwide"]},{q:"Quantum computing threatens Bitcoin by potentially:",a:"Breaking ECDSA signatures used to authorize spending",wrong:["Mining all remaining Bitcoin in seconds","Deleting the entire blockchain","Creating unlimited new Bitcoin addresses"]}],"evidence-against-alts":[{q:"Ethereum's original sale page reveals that ETH was:",a:"Pre-sold as a security to fund development",wrong:["Mined fairly like Bitcoin","Distributed equally","Created by Satoshi"]},{q:"What fundamental difference exists between Bitcoin and altcoins regarding decentralization?",a:"Altcoin founders often hold large pre-mines or centralized control",wrong:["Altcoins are too cheap","Bitcoin has better marketing","Altcoins use different blockchains"]},{q:'Why do Bitcoiners say "there is no second best"?',a:"No other crypto achieves Bitcoin's decentralization, security, and immutability",wrong:["Bitcoin was the first, so it automatically wins","The SEC has declared all other cryptos illegal","Satoshi patented the blockchain concept"]},{q:'What is a "pre-mine" and why is it concerning?',a:"Founders allocate coins to themselves before public launch — unfair distribution",wrong:["A technique to speed up transaction processing","A security measure that protects the network","A method of testing the blockchain before launch"]},{q:"Most altcoins are considered securities because:",a:"They have identifiable teams profiting from token sales with promises of returns",wrong:["They use the same code as Bitcoin","The SEC approves them as securities automatically","They are traded on stock exchanges"]}],"smart-contracts":[{q:"Bitcoin's scripting language has supported smart contracts:",a:"Since the beginning — Bitcoin always had them",wrong:["Only after Taproot in 2021","Only after SegWit in 2017","Never — only Ethereum has them"]},{q:"OP_RETURN is used in Bitcoin to:",a:"Embed small amounts of data in transactions",wrong:["Return sent Bitcoin","Cancel transactions","Mine faster"]},{q:"What is Bitcoin\\'s native scripting language called?",a:"Bitcoin Script",wrong:["Solidity","Python Script","JavaScript"]},{q:"What does OP_RETURN allow users to do on Bitcoin?",a:"Embed up to 80 bytes of arbitrary data in a transaction",wrong:["Execute Ethereum-style smart contracts","Change transaction amounts","Create new bitcoins"]},{q:"What are DLCs (Discreet Log Contracts) on Bitcoin?",a:"Smart contracts that settle based on external oracle data without revealing details",wrong:["Private keys stored in logs","Debug contracts for developers","Decentralized lending contracts on Ethereum"]}],"chaumian-mints":[{q:"Cashu is an implementation of:",a:"Chaumian ecash on Bitcoin/Lightning",wrong:["A new blockchain","An altcoin","A mining algorithm"]},{q:"Who invented the blind signature technology used in Chaumian eCash?",a:"David Chaum in 1982",wrong:["Satoshi Nakamoto in 2008","Adam Back in 1997","Hal Finney in 2004"]},{q:"What modern Bitcoin layer implements Chaumian eCash for minting privacy-preserving tokens?",a:"Cashu and Fedimint protocols",wrong:["Lightning Network","Liquid Network","Ethereum ERC-20"]},{q:"Cashu is:",a:"An ecash protocol built on Bitcoin using Chaumian blind signatures",wrong:["A competing cryptocurrency to Bitcoin","A hardware wallet manufacturer","A type of Bitcoin mining software"]},{q:'What are "blind signatures" in ecash?',a:"The mint signs tokens without knowing which user they belong to",wrong:["Signatures that expire after 24 hours","A way to sign transactions without a private key","Signatures that can only be verified by the government"]}],"swag-merch":[{q:"BTCAccepted.org helps you find:",a:"Businesses that accept Bitcoin payments",wrong:["Mining pools","Lightning nodes","Altcoin exchanges"]},{q:"Sats.host offers:",a:"Bitcoin-powered static website hosting",wrong:["Mining services","Cold storage","KYC verification"]},{q:'What annual Bitcoin conference is often called "the Super Bowl of Bitcoin"?',a:"Bitcoin Conference (formerly Miami/Bitcoin 2021)",wrong:["Consensus","DevCon","ETHDenver"]},{q:"What is the significance of wearing an orange pill at Bitcoin conferences?",a:'Signifies being "orange pilled" — awakened to Bitcoin\\\'s importance',wrong:["Medical supplement promotion","Conference staff identifier","VIP pass indicator"]},{q:"What popular Bitcoin merchandise item satirizes central banking?",a:'"End the Fed" t-shirts and posters',wrong:["Bitcoin gaming chairs","Satoshi action figures","Mining rig keychains"]}],"apps-tools":[{q:"PPQ.ai lets you use AI models and pay with:",a:"Bitcoin per prompt — no subscription needed",wrong:["Monthly credit card subscription","Ethereum gas fees","Free but with ads"]},{q:"Angor is a platform for:",a:"Non-custodial Bitcoin crowdfunding",wrong:["Bitcoin mining","Coin mixing","Hardware wallets"]},{q:"What website provides real-time visualization of the Bitcoin mempool?",a:"mempool.space",wrong:["blockchain.com","coinmarketcap.com","bitcoincharts.com"]},{q:"What popular hardware wallet supports both Bitcoin and Lightning?",a:"Coldcard and BitBox02",wrong:["PayPal Card","Venmo Wallet","Apple Pay"]},{q:"What full node implementation is the most widely used for running Bitcoin?",a:"Bitcoin Core",wrong:["Bitcoin Cash","Ethereum Classic","Ripple Node"]}],games:[{q:"Timechain Arcade offers:",a:"Free Bitcoin-themed video games",wrong:["Mining services","Trading tools","Hardware wallets"]},{q:"CanYouBeatBitcoin.com is:",a:"An investing simulator comparing your picks to Bitcoin",wrong:["A mining difficulty calculator","A Bitcoin wallet","A trading bot"]},{q:"What type of Bitcoin games reward players with satoshis?",a:"Play-to-earn Lightning games",wrong:["Casino-style gambling","Console RPGs","Mobile ad games"]},{q:"What popular Bitcoin trivia app lets users earn sats for answering questions?",a:"THNDR Games (like Bitcoin Bounce, Bitcoin Bay)",wrong:["Fortnite","Candy Crush","Minecraft"]},{q:"What is Zebedee known for in the Bitcoin gaming space?",a:"A platform enabling Lightning payments in games",wrong:["Hardware mining rigs","Altcoin exchange","NFT marketplace"]}],"difficulty-adjustment":[{q:"How often does Bitcoin's difficulty adjustment occur?",a:"Every 2,016 blocks (approximately 2 weeks)",wrong:["Every 1,000 blocks","Every month","Every day"]},{q:"What does the difficulty adjustment ensure?",a:"Blocks are found roughly every 10 minutes regardless of hash power changes",wrong:["Transaction fees stay constant","Mining rewards increase","Block size adjusts automatically"]},{q:"Bitcoin's difficulty adjusts every:",a:"2,016 blocks (roughly every 2 weeks)",wrong:["Every single block","Once per year","Every 210,000 blocks (at each halving)"]},{q:"If miners leave the network, difficulty adjustment:",a:"Lowers the difficulty so blocks are found at the target rate",wrong:["Increases difficulty to punish remaining miners","Has no effect — blocks just take longer forever","Automatically doubles the block reward"]},{q:"The target time between Bitcoin blocks is approximately:",a:"10 minutes",wrong:["1 minute","1 hour","30 seconds"]}],nostr:[{q:"Nostr is:",a:"A decentralized social media protocol where no one controls content",wrong:["A Bitcoin mining pool","A Lightning wallet","A blockchain explorer"]},{q:"What makes Nostr unique from typical social media?",a:"Your identity is uncensorable and no single entity controls the platform",wrong:["It pays users in Bitcoin automatically","It only works on mobile","It requires KYC verification"]},{q:"Nostr is best described as:",a:"A decentralized social protocol that cannot be censored",wrong:["A Bitcoin wallet application","A new cryptocurrency competing with Bitcoin","An encrypted messaging app owned by a company"]},{q:"Nostr uses cryptographic keys to:",a:"Allow users to own their identity without a central authority",wrong:["Mine new coins on the Nostr blockchain","Encrypt all messages so no one can read them","Create smart contracts between users"]},{q:"How is Nostr connected to Bitcoin?",a:"Many clients integrate Lightning for tips and payments",wrong:["Nostr runs on the Bitcoin blockchain directly","You must own Bitcoin to create a Nostr account","Nostr mining validates Bitcoin transactions"]}],network_effects:[{q:"Bitcoin's network effect means:",a:"Each new user increases the value and utility for all existing users",wrong:["The internet gets faster","Mining gets easier","Fees decrease to zero"]},{q:"Why is Bitcoin's network effect considered a strong moat?",a:"It creates a self-reinforcing cycle of liquidity, security, and adoption that competitors cannot easily replicate",wrong:["Because Bitcoin has patents","Because the government protects it","Because the code is encrypted"]},{q:"What economic principle explains Bitcoin\\'s value increasing as more people use it?",a:"Metcalfe\\'s Law — network value proportional to connected users squared",wrong:["Moore\\'s Law","Murphy\\'s Law","Pareto Principle"]},{q:"Metcalfe's Law applied to Bitcoin suggests:",a:"Its value grows proportionally to the square of its users",wrong:["The price will always increase linearly","Only the first users receive any benefit","Network effects only apply to social media"]},{q:"What is the flywheel effect in Bitcoin adoption?",a:"More users attract more developers, merchants, and infrastructure, which attracts even more users",wrong:["Mining gets easier as more people join","Transaction fees decrease as the network grows","Bitcoin price always goes up with more users"]}],governance:[{q:"Bitcoin governance is best described as:",a:"Rough consensus among users, developers, miners, and node operators",wrong:["A CEO makes all decisions","Miners vote on everything","A foundation sets the rules"]},{q:"The Blocksize Wars demonstrated that:",a:"Users and node operators ultimately control Bitcoin's rules, not miners alone",wrong:["Miners have absolute power","Developers can force any change","Bitcoin cannot be upgraded"]},{q:"What is the BIP process in Bitcoin?",a:"Bitcoin Improvement Proposals for suggesting protocol changes",wrong:["Bitcoin Investment Plan","Blockchain IP Protection","Banking Integration Protocol"]},{q:"How is Bitcoin governed?",a:"Through rough consensus among users, developers, miners, and node operators",wrong:["By a board of directors at the Bitcoin Foundation","Through shareholder voting like a corporation","By whoever owns the most Bitcoin"]},{q:"A BIP (Bitcoin Improvement Proposal) is:",a:"A formal document proposing changes to Bitcoin's protocol or processes",wrong:["A mandatory update that all nodes must accept","A financial investment in Bitcoin development","A bug report filed to the Bitcoin support team"]}],human_rights__social_justice_and_freedo:[{q:"Bitcoin supports human rights by:",a:"Providing censorship-resistant money that cannot be confiscated by authoritarian regimes",wrong:["Replacing all governments","Eliminating all poverty instantly","Being controlled by the UN"]},{q:"Alex Gladstein advocates for Bitcoin because:",a:"It empowers people living under authoritarian regimes with financial freedom",wrong:["It makes trading stocks easier","It replaces the need for banks in wealthy countries","It was designed as a protest tool"]},{q:"How has Bitcoin helped activists in authoritarian regimes?",a:"By enabling uncensorable fundraising and protecting wealth from seizure",wrong:["By hiding their identity completely","By earning interest from banks","By creating new currencies"]},{q:"How does Bitcoin help people under authoritarian regimes?",a:"It provides censorship-resistant money that governments cannot freeze",wrong:["It automatically reports suspicious activity to authorities","It requires government ID to transact","It only works in democratic countries"]},{q:"Alex Gladstein of the Human Rights Foundation argues that:",a:"Bitcoin is the most important tool for financial freedom globally",wrong:["Only wealthy nations benefit from Bitcoin","Bitcoin should be controlled by human rights organizations","Proof of Stake is better for human rights than Proof of Work"]}],market_cap:[{q:"Bitcoin's market cap is calculated by:",a:"Current price multiplied by total coins in circulation",wrong:["Total transaction volume per day","Number of wallets times average balance","Mining revenue times block height"]},{q:"Why can Bitcoin's market cap potentially exceed gold's?",a:"Bitcoin is more portable, divisible, verifiable, and scarce than gold",wrong:["Because governments will mandate it","Because gold will be banned","Because Bitcoin mining produces gold"]},{q:"What metric compares Bitcoin\\'s market value to all other cryptocurrencies combined?",a:"Bitcoin Dominance Index",wrong:["Coin Market Gap","Crypto Index Fund","Volatility Ratio"]},{q:"Bitcoin's market capitalization represents:",a:"The total value of all existing Bitcoin at the current price",wrong:["The maximum number of coins that can ever exist","The amount of money invested in Bitcoin mining","The total transaction volume over the past year"]},{q:"If Bitcoin captured gold's market cap, each coin would be worth approximately:",a:"Over $500,000",wrong:["$100,000","$50,000","$10,000"]}],the_future:[{q:"Hyperbitcoinization refers to:",a:"Mass voluntary adoption of Bitcoin as the dominant form of money",wrong:["A Bitcoin price crash","A government mandate to use Bitcoin","A technical upgrade to the protocol"]},{q:"Bitcoin is described as 'generational wealth' because:",a:"Its fixed supply and growing adoption may increase its value over decades",wrong:["Only older people can buy it","It expires after one generation","Banks guarantee its value for 100 years"]},{q:"What is hyperbitcoinization?",a:"The hypothetical point where Bitcoin becomes the world\\'s dominant form of money",wrong:["Overheating of mining equipment","Excessive Bitcoin advertising","A type of Bitcoin hack"]},{q:"What happens when the last Bitcoin is mined (~2140)?",a:"Miners will be compensated solely through transaction fees",wrong:["The network will shut down permanently","A new supply of 21 million coins will be created","Mining will become free with no reward"]},{q:"What does hyperbitcoinization refer to?",a:"A theoretical tipping point where Bitcoin becomes the dominant global monetary system",wrong:["Bitcoin reaching a price of one million dollars","Every country banning Bitcoin simultaneously","Bitcoin hash rate exceeding all supercomputers combined"]}],"orange-pilling":[{q:"'Orange-pilling' someone means:",a:"Convincing them to understand and adopt Bitcoin",wrong:["Selling them altcoins","Giving them free Bitcoin","Signing them up for an exchange"]},{q:"The most effective way to orange-pill someone is often:",a:"Starting with the problem Bitcoin solves (broken money) rather than technical details",wrong:["Showing them price charts","Explaining SHA-256 hashing","Telling them to buy immediately"]},{q:'What does "orange pilling" someone mean?',a:"Educating them about Bitcoin until they understand its importance",wrong:["Giving them actual pills","Selling them mining equipment","Creating a Bitcoin wallet for them"]},{q:"What is the best approach when orange-pilling a skeptic?",a:"Start with their specific pain point (inflation, remittances, censorship) rather than technical details",wrong:["Show them price charts and promise guaranteed returns","Pressure them into buying immediately before the next halving","Explain the full UTXO model and Merkle trees first"]},{q:"The most effective orange-pilling strategy is:",a:"Meeting people where they are and addressing their specific concerns",wrong:["Posting price predictions on social media","Telling people they are stupid for not buying","Promising guaranteed financial returns"]}],maximalism:[{q:"Bitcoin maximalism is the belief that:",a:"Bitcoin is the only cryptocurrency that truly matters as sound money",wrong:["You should invest everything in Bitcoin","Bitcoin should replace all technology","Only developers should use Bitcoin"]},{q:"Maximalists argue altcoins are unnecessary because:",a:"Bitcoin's base layer plus additional protocol layers can serve all use cases",wrong:["Because altcoins are illegal","Because Satoshi said so","Because there can only be one blockchain"]},{q:"What is Bitcoin maximalism?",a:"The belief that Bitcoin will be the only cryptocurrency to achieve long-term dominance",wrong:["Investing only in altcoins","Maximizing one\\'s bitcoin holdings at all costs","Running multiple full nodes"]},{q:"Why do deep Bitcoin researchers tend to become maximalists?",a:"They realize no other project achieves true decentralization and immutability",wrong:["They are paid by Bitcoin companies to promote it","They lack knowledge of other technologies","It is required to participate in the Bitcoin community"]},{q:"What is the core argument of Bitcoin maximalists?",a:"Only Bitcoin achieves true decentralization and sound money; altcoins compromise on critical aspects",wrong:["Bitcoin should be the only legal currency","All other technology besides Bitcoin is useless","Maximalists refuse to use the internet"]}],developers:[{q:"Bitcoin Core is primarily written in:",a:"C++",wrong:["Python","JavaScript","Rust"]},{q:"Contributing to Bitcoin open source requires:",a:"Anyone can propose changes — no permission needed",wrong:["A computer science degree","Approval from the Bitcoin Foundation","Purchasing a developer license"]},{q:"Who is considered Bitcoin\\'s lead maintainer as of recent years?",a:"There is no formal leader; Bitcoin Core has multiple maintainers",wrong:["Satoshi Nakamoto","Vitalik Buterin","Elon Musk"]},{q:"What organization has historically funded Bitcoin Core development?",a:"MIT Digital Currency Initiative, Chaincode Labs, Brink, Spiral",wrong:["World Bank","Federal Reserve","Goldman Sachs"]},{q:"Which version control system hosts Bitcoin Core’s source code?",a:"Git",wrong:["SVN","Mercurial","Bazaar"]}],ham_radio:[{q:"Bitcoin transactions can be sent via ham radio, which means:",a:"Bitcoin can work without an internet connection",wrong:["Bitcoin requires satellite dishes","Only miners can use radio","Radio transactions are free"]},{q:"How can Bitcoin transactions be sent without internet?",a:"Via ham radio operators broadcasting signed transactions",wrong:["Via postal mail","Via telephone calls","Via satellite TV only"]},{q:"What mesh network protocol has been used to broadcast Bitcoin transactions?",a:"Blockstream Satellite and goTenna mesh networks",wrong:["Bluetooth Classic","NFC payments","Zigbee home network"]},{q:"What is the benefit of Bitcoin over ham radio?",a:"Censorship resistance even when governments shut down internet",wrong:["Faster than fiber internet","Lower transaction fees","Better for large file transfers"]},{q:"Who demonstrated sending Bitcoin via ham radio in 2019?",a:"Rodolfo Novak co-founder of Coinkite",wrong:["Elon Musk","Jack Dorsey","Andreas Antonopoulos"]}],lightning_node:[{q:"Running a Lightning node allows you to:",a:"Route payments and earn fees while supporting the network",wrong:["Mine Bitcoin faster","Create new Bitcoin","Access the dark web"]},{q:"What is a Lightning node?",a:"Software that routes payments on the Lightning Network using payment channels",wrong:["A physical Bitcoin ATM","A mining rig","A Bitcoin exchange server"]},{q:"What do node operators lock up to open payment channels?",a:"Bitcoin as liquidity for routing payments",wrong:["Ethereum tokens","Fiat currency","Computing power"]},{q:"What fee do Lightning routing nodes typically charge?",a:"Routing fees measured in milli-satoshis (very small fraction of a cent)",wrong:["1% of transaction amount","$5 per payment","No fees allowed"]},{q:"What is inbound liquidity for a Lightning node?",a:"The ability to receive payments based on funds others have locked with you",wrong:["Money coming from bank deposits","Mining rewards","Exchange trading profits"]}],stablecoins:[{q:"Stablecoins in the Bitcoin ecosystem are typically:",a:"Tokens pegged to fiat currency values, sometimes built on Bitcoin layers",wrong:["A type of mining reward","Bitcoins that never change price","Government-issued digital dollars"]},{q:"What backs the majority of USDT (Tether)?",a:"Commercial paper, cash equivalents, and other reserves (historically controversial)",wrong:["100% US dollars in bank","Gold reserves","Bitcoin collateral"]},{q:"What major risk do centralized stablecoins pose?",a:"Issuer can freeze funds or fail to maintain peg",wrong:["They mine too slowly","High transaction fees","Private key loss"]},{q:"What caused USDC to depeg temporarily in March 2023?",a:"Exposure to failed Silicon Valley Bank",wrong:["Bitcoin price crash","Lightning Network bug","Satoshi selling coins"]},{q:"Stablecoins are NOT a threat to Bitcoin because:",a:"They are centralized IOUs that can be frozen, while Bitcoin is permissionless",wrong:["Stablecoins use the same technology as Bitcoin","Bitcoin automatically converts to stablecoins during crashes","Stablecoins have a higher market cap than Bitcoin"]}],consensus:[{q:"Bitcoin consensus means:",a:"All nodes agree on the state of the blockchain without a central authority",wrong:["Everyone votes on transactions","Miners decide which transactions are valid alone","The government approves each block"]},{q:"What is Nakamoto Consensus?",a:"The combination of proof-of-work, longest chain rule, and economic incentives",wrong:["Voting by coin holders","Consensus by the Bitcoin Foundation","Agreement between exchanges"]},{q:"Why does Bitcoin use the longest chain as the valid chain?",a:"Most proof-of-work indicates most energy/computational investment",wrong:["Random selection","Shortest chains are invalid","User voting"]},{q:"Nakamoto Consensus achieves agreement by:",a:"Having nodes follow the longest valid proof-of-work chain",wrong:["Requiring all nodes to vote on each transaction","Letting the wealthiest node decide which blocks are valid","Using a central server to broadcast the correct chain"]},{q:"What happens if two miners find a valid block at nearly the same time?",a:"A temporary fork occurs and resolves when the next block is found",wrong:["Both blocks are permanently added to the chain","The network shuts down until the conflict is resolved","The older miner's block always wins"]}],open_source:[{q:"Bitcoin being open source means:",a:"Anyone can read, audit, and propose changes to the code",wrong:["The code is secret but free to use","Only approved developers can view it","It costs nothing to mine"]},{q:"What license is Bitcoin Core released under?",a:"MIT License (open source)",wrong:["Proprietary commercial license","GPL v3 only","Patent-encumbered license"]},{q:"How can anyone contribute to Bitcoin Core?",a:"Submit pull requests on GitHub after code review",wrong:["Pay a developer fee","Get hired by a bank","Apply for a license"]},{q:"What is the purpose of code review in Bitcoin development?",a:"To catch bugs and security issues before deployment",wrong:["To slow down development","To charge developers money","To keep the code secret"]},{q:"Why is peer review critical in Bitcoin Core development?",a:"It catches bugs and vulnerabilities before they reach production, since changes affect billions in value",wrong:["It is just a formality required by the MIT license","Only one reviewer is needed for minor patches","Peer review slows down development unnecessarily"]}],coin_mixing_coinjoin_coin_control_utxo:[{q:"CoinJoin improves privacy by:",a:"Combining multiple users' transactions so individual spending is hard to trace",wrong:["Encrypting the blockchain","Deleting transaction history","Creating fake transactions"]},{q:"What is CoinJoin?",a:"A privacy technique combining multiple users\\' transactions to break heuristics",wrong:["A cryptocurrency mixer token","A type of hardware wallet","An exchange withdrawal method"]},{q:"What does coin control allow Bitcoin users to do?",a:"Manually select which UTXOs to spend in a transaction",wrong:["Control the price of bitcoin","Limit mining difficulty","Set transaction speed"]},{q:"What privacy benefit does proper UTXO management provide?",a:"Preventing address clustering and transaction graph analysis",wrong:["Increasing mining rewards","Reducing transaction fees","Speeding up confirmations"]},{q:'What is "coin control" in a Bitcoin wallet?',a:"The ability to manually select which UTXOs to spend in a transaction for better privacy",wrong:["A government program to regulate Bitcoin spending","Software that limits how much Bitcoin you can buy","A mining feature that controls block production"]}],environment___energy:[{q:"Bitcoin mining's relationship with renewable energy is:",a:"Miners actively seek cheap renewable and stranded energy, incentivizing green energy development",wrong:["Mining only uses coal","Renewable energy cannot power mining","Mining has no relationship with energy markets"]},{q:"What percentage of Bitcoin mining comes from renewable energy (estimates)?",a:"Estimates range from 50-60% using renewable or stranded energy",wrong:["0% — all coal","100% renewable","Less than 10%"]},{q:'What is "stranded energy" in Bitcoin mining?',a:"Energy that would otherwise go to waste due to lack of transmission infrastructure",wrong:["Energy from broken solar panels","Leftover battery power","Natural gas used for heating"]},{q:"How does Bitcoin mining help stabilize electrical grids?",a:"Miners can rapidly reduce load during peak demand (demand response)",wrong:["By storing electricity in batteries","By donating profits to utilities","By building more coal plants"]},{q:"What common criticism about Bitcoin energy use is often misrepresented?",a:"Per-transaction energy cost (Bitcoin uses same energy regardless of transaction count)",wrong:["It uses no energy at all","All energy comes from coal","Mining makes computers explode"]}],austrian_school_of_economics:[{q:"The Austrian School of Economics relates to Bitcoin because:",a:"It advocates for sound money with limited supply, which Bitcoin embodies",wrong:["It was founded by Satoshi Nakamoto","It requires government-controlled currency","It predicts Bitcoin will fail"]},{q:"Which Austrian economist emphasized the importance of sound money and criticized fiat?",a:"Ludwig von Mises and Friedrich Hayek",wrong:["John Maynard Keynes","Karl Marx","Milton Friedman"]},{q:"The Austrian School of Economics emphasizes:",a:"Sound money, free markets, and the dangers of central banking",wrong:["Government control of all monetary systems","That inflation is beneficial for economic growth","That central banks should print unlimited money"]},{q:'Who wrote "The Theory of Money and Credit"?',a:"Ludwig von Mises",wrong:["John Maynard Keynes","Paul Krugman","Adam Smith"]},{q:"Bitcoin aligns with Austrian economics because:",a:"It has a fixed supply and cannot be debased by any authority",wrong:["It was invented by an Austrian economist","The Austrian government officially endorses it","It uses the Austrian Schilling as its base currency"]}],lindy_effect:[{q:"The Lindy Effect applied to Bitcoin means:",a:"The longer Bitcoin survives, the longer it is expected to continue surviving",wrong:["Bitcoin gets slower over time","Older technology always fails","Bitcoin will expire after 21 years"]},{q:"What is the Lindy Effect?",a:"The longer something survives, the longer its remaining life expectancy",wrong:["A measure of mining difficulty","A type of cryptographic hash","A brand of hardware wallet"]},{q:"How does the Lindy Effect apply to Bitcoin?",a:"Each year without failure increases confidence in future survival",wrong:["Bitcoin becomes less secure over time","Only old coins have value","Newer cryptocurrencies are safer"]},{q:"What concept is closely related to Lindy Effect in Bitcoin?",a:"Antifragility — stress makes the system stronger",wrong:["Inflation targeting","Proof of stake","Central banking"]},{q:"Why is Bitcoin\\'s 15+ year survival significant for the Lindy Effect?",a:"Demonstrates resilience to attacks, bugs, and regulatory pressure",wrong:["Proves it cannot be upgraded","Makes it obsolete","Shows it uses too much energy"]}],softwar:[{q:"Jason Lowery's Softwar thesis argues that:",a:"Proof-of-work is a form of digital power projection analogous to military power in the physical world",wrong:["Bitcoin is a weapon system","Software replaces all hardware","Bitcoin was created by the military"]},{q:'Who authored the "Softwar" thesis about Bitcoin?',a:"Major Jason Lowery of the US Space Force",wrong:["Michael Saylor","Nick Szabo","Elizabeth Warren"]},{q:"What is the core argument of the Softwar thesis?",a:"Proof-of-work is a form of kinetic power projection for cyberspace",wrong:["Bitcoin should be banned","Proof of stake is superior","Bitcoin is a company"]},{q:"What does Softwar compare Bitcoin\\'s hash rate to?",a:"Physical military power projection and deterrence",wrong:["Social media likes","Stock market volume","Bank transaction counts"]},{q:"How does the Softwar thesis view Bitcoin mining in terms of national security?",a:"As a strategic asset that projects power in cyberspace, similar to how militaries project power in physical space",wrong:["As a threat to national security that should be banned","As purely an economic activity with no geopolitical significance","As a replacement for nuclear deterrence"]}],sidechains:[{q:"A Bitcoin sidechain is:",a:"A separate blockchain that is pegged to Bitcoin, enabling additional features while settling back to the main chain",wrong:["A backup copy of the Bitcoin blockchain","A faster version of Bitcoin Core","An altcoin that replaced Bitcoin"]},{q:"What is the Liquid Network?",a:"A federated sidechain enabling faster confidential Bitcoin transactions",wrong:["An Ethereum scaling solution","A mining pool","A hardware wallet"]},{q:"What is RSK (Rootstock)?",a:"A Bitcoin sidechain supporting smart contracts with merged mining",wrong:["A Russian Bitcoin exchange","A hardware wallet brand","A Lightning wallet"]},{q:"How are assets secured when moving to a sidechain?",a:"Through a federated peg locking bitcoin on mainchain",wrong:["By burning bitcoin permanently","By trusting a single company","No security is provided"]},{q:"What is a downside of federated sidechains compared to Bitcoin mainchain?",a:"Less decentralization due to reliance on federation members",wrong:["Higher transaction fees","Slower block times","No programming capabilities"]}],submarine_swap:[{q:"A submarine swap allows you to:",a:"Exchange on-chain Bitcoin for Lightning Bitcoin (or vice versa) trustlessly",wrong:["Mine Bitcoin underwater","Send Bitcoin without internet","Convert Bitcoin to Ethereum"]},{q:"What is a submarine swap?",a:"An atomic swap between on-chain Bitcoin and Lightning Network off-chain",wrong:["A type of mining pool payout","A DeFi lending protocol","An underwater transaction method"]},{q:"What enables submarine swaps to be trustless?",a:"HTLCs (Hash Time Locked Contracts)",wrong:["Centralized exchange custody","Bank wire confirmation","Social media verification"]},{q:"What problem do submarine swaps solve?",a:"Moving funds between on-chain and Lightning without closing channels",wrong:["Mining difficulty adjustment","Exchange rate volatility","Wallet password recovery"]},{q:"What technology makes submarine swaps trustless?",a:"Hash Time-Locked Contracts (HTLCs) that ensure both sides complete or neither does",wrong:["A centralized escrow service that holds funds during the swap","Blockchain validators who verify the exchange manually","Smart contracts on Ethereum that bridge to Bitcoin"]}],supranational:[{q:'What does "supranational" mean in the context of Bitcoin?',a:"It transcends national borders and governments",wrong:["It is backed by the United Nations","It requires international approval to use","It can only be used between countries"]},{q:"The Lindy Effect suggests that Bitcoin:",a:"The longer it survives, the longer it is expected to survive",wrong:["Will eventually be replaced by newer technology","Has a fixed expiration date coded into its protocol","Must be upgraded every 10 years to remain relevant"]},{q:"Bitcoin settlement finality means:",a:"Once confirmed, transactions cannot be reversed",wrong:["Transactions can be disputed within 30 days","A central authority must approve each transaction","Only miners can verify if a transaction is final"]},{q:'Why is Bitcoin considered "supranational" money?',a:"It operates beyond any single nation\\'s jurisdiction or control",wrong:["It is owned by the UN","Only governments can use it","It requires international banking licenses"]},{q:"What makes Bitcoin different from national currencies like the dollar or euro?",a:"No central bank can print more or manipulate its supply",wrong:["It is backed by gold reserves","It requires government approval","It only works online"]}],organic:[{q:"Bitcoin grew organically because:",a:"It had no pre-mine, no ICO, and no marketing budget",wrong:["A major corporation funded its development","Governments agreed to adopt it simultaneously","Social media algorithms promoted it automatically"]},{q:"What makes Bitcoin's distribution unique among cryptocurrencies?",a:"Fair launch — no coins were pre-allocated to founders",wrong:["Satoshi kept 50% of all coins before launch","Venture capitalists funded the initial distribution","Coins were distributed based on national GDP"]},{q:"How has Bitcoin grown without traditional marketing?",a:"Through grassroots adoption and word-of-mouth from users",wrong:["Massive advertising budgets","Celebrity endorsements","Government subsidies"]},{q:"What drives Bitcoin\\'s organic adoption in developing countries?",a:"Real need for inflation protection and remittance savings",wrong:["Central bank mandates","Corporate marketing campaigns","Mandatory school education"]},{q:"What is the role of Bitcoin\\'s open source community?",a:"Volunteer developers contribute code without corporate hierarchy",wrong:["They control Bitcoin Foundation","They receive government salaries","They own all bitcoins"]}],programmable:[{q:"Bitcoin Script is intentionally limited because:",a:"Simplicity reduces attack surface and increases security",wrong:["Satoshi was not a skilled programmer","The blockchain cannot process complex instructions","It was a temporary design meant to be upgraded"]},{q:'What does "Turing-incomplete" mean for Bitcoin Script?',a:"It cannot run arbitrary programs or infinite loops",wrong:["It cannot process any transactions at all","It requires a separate computer to verify","It can only handle one transaction per block"]},{q:"What makes Bitcoin programmable money?",a:"Bitcoin Script enables conditional spending and smart contracts",wrong:["Only banks can program it","It runs Python code directly","Central programmers control all transactions"]},{q:"What are timelocks in Bitcoin?",a:"Conditions preventing spending until a specific time or block height",wrong:["Physical locks on hardware wallets","Password requirements","Banking hours restrictions"]},{q:"What is a multisig (multi-signature) transaction?",a:"Requires multiple private keys to authorize spending",wrong:["Multiple transactions combined","Multiple miners confirming","Multiple exchanges involved"]}],ordinals:[{q:"Bitcoin Ordinals allow:",a:"Inscribing data (images, text) directly on individual satoshis",wrong:["Creating new tokens on the Bitcoin network","Speeding up transaction confirmation times","Reducing the total supply of Bitcoin"]},{q:"Why are Ordinals controversial in the Bitcoin community?",a:"They increase block space demand and fees for financial transactions",wrong:["They change the 21 million supply cap","They require a hard fork to implement","They give miners control over which transactions are valid"]},{q:"What are Bitcoin Ordinals?",a:"A numbering system for satoshis enabling inscription of arbitrary data",wrong:["A type of altcoin token","A mining algorithm","A Lightning channel type"]},{q:"What controversial use case emerged from Ordinals?",a:"BRC-20 tokens creating fungible tokens on Bitcoin",wrong:["Instant payment settlement","Hardware wallet security","Private key encryption"]},{q:"What is the debate around Ordinals inscriptions?",a:"They use block space, potentially raising fees for regular transactions",wrong:["They steal bitcoin from wallets","They hack the blockchain","They prevent mining from working"]}],geopolitics___macroeconomics:[{q:"Why is Bitcoin relevant to geopolitics?",a:"It provides a neutral monetary system outside any nation's control",wrong:["Major governments collectively control Bitcoin's code","Bitcoin mining is only legal in 5 countries","The UN regulates Bitcoin's international transfers"]},{q:'What is the "petrodollar" system?',a:"Oil is priced in US dollars, forcing global demand for the dollar",wrong:["A cryptocurrency backed by oil reserves","A Bitcoin mining technique using petroleum","A tax imposed on Bitcoin by oil-producing nations"]},{q:"Which country was the first to adopt Bitcoin as legal tender?",a:"El Salvador in September 2021",wrong:["United States","Japan","Germany"]},{q:"How do sanctions-evading nations view Bitcoin?",a:"As a way to circumvent SWIFT restrictions and frozen reserves",wrong:["As a threat to their currencies","As a US surveillance tool","As illegal everywhere"]},{q:"What macro trend drives Bitcoin adoption during inflation?",a:"Currency debasement making bitcoin\\'s fixed supply attractive",wrong:["Lower interest rates on bitcoin","Government bitcoin subsidies","Bank account requirements"]}],"op-codes":[{q:"Bitcoin OP_CODES are:",a:"Instructions in Bitcoin's scripting language that define spending conditions",wrong:["Error codes returned when a transaction fails","Codes used to communicate between mining pools","Secret backdoor commands for Bitcoin developers"]},{q:"OP_RETURN allows:",a:"Embedding small amounts of arbitrary data in the blockchain",wrong:["Reversing a confirmed transaction","Returning stolen Bitcoin to its owner","Increasing the block size limit"]},{q:"What is OP_CHECKSIG in Bitcoin Script?",a:"Verifies a digital signature against a public key",wrong:["Creates new bitcoins","Encrypts transaction data","Connects to mining pools"]},{q:"What was the OP_RETURN controversy?",a:"Its limit was reduced to prevent blockchain bloat from non-financial data",wrong:["It was used to hack exchanges","It created unlimited bitcoins","It stopped all transactions"]},{q:"What did Taproot enable for Bitcoin opcodes?",a:"More flexible scripting through Schnorr signatures and Merkle branches",wrong:["Removal of all previous scripts","Conversion to Ethereum compatibility","Centralized script approval"]}],public_key_vs_private_key:[{q:"Your Bitcoin public key is like:",a:"Your email address — you share it so people can send you Bitcoin",wrong:["Your password — never share it with anyone","Your bank PIN number — used to authorize spending","Your social security number — it proves your identity"]},{q:"If someone has your private key, they can:",a:"Spend all the Bitcoin controlled by that key",wrong:["Only view your transaction history","Reset your password and lock you out","Create new Bitcoin out of thin air"]},{q:"What is the relationship between private and public keys?",a:"Public keys are derived from private keys via one-way cryptographic function",wrong:["Private keys are given to everyone","Public keys encrypt private keys","They are identical numbers"]},{q:"What should you do with your private keys?",a:"Keep them secret and secure, never share with anyone",wrong:["Publish them online","Email them to exchanges","Print them on merchandise"]},{q:"What is the purpose of a public key?",a:"To receive bitcoin and verify signatures without revealing the private key",wrong:["To spend bitcoin alone","To mine new blocks","To create private keys"]}],transaction_fees:[{q:"Bitcoin transaction fees are determined by:",a:"The size of the transaction in bytes and current network demand",wrong:["A fixed percentage of the transaction amount","The number of Bitcoin being sent","The geographic distance between sender and receiver"]},{q:"When the mempool is full:",a:"Transactions with higher fees get confirmed first",wrong:["All transactions are rejected until it clears","The block size automatically increases","Transaction fees are refunded to senders"]},{q:"What determines Bitcoin transaction fees?",a:"Transaction size in bytes and current network demand (mempool congestion)",wrong:["Transaction amount in bitcoin","Sender\\'s reputation","Government regulation"]},{q:"What is the mempool?",a:"A waiting area for unconfirmed transactions held by nodes",wrong:["A mining hardware pool","A cryptocurrency exchange","A type of Bitcoin wallet"]},{q:"Why do fees spike during network congestion?",a:"Users compete for limited block space by bidding higher fees",wrong:["Miners arbitrarily raise prices","Exchanges charge extra","Bitcoin supply decreases"]}],philosophy:[{q:'"Don\'t trust, verify" means:',a:"Run your own node to independently verify all Bitcoin rules",wrong:["Never use Bitcoin because it cannot be trusted","Only trust exchanges that are government-regulated","Verify your identity before making transactions"]},{q:'The concept "Bitcoin is Time" by Gigi suggests:',a:"Bitcoin creates a decentralized clock through proof of work",wrong:["Bitcoin transactions can travel back in time","Bitcoin was invented to save people time","Bitcoin mining uses atomic clocks"]},{q:"What is the cypherpunk movement that birthed Bitcoin?",a:"Advocates for privacy through cryptography and code over trust",wrong:["Bankers wanting digital currency","Gamers creating virtual money","Governments tracking transactions"]},{q:'What does "don\\\'t trust, verify" mean in Bitcoin?',a:"Run your own node to validate transactions rather than trusting third parties",wrong:["Trust banks with your bitcoin","Verify your email address","Don\\'t check transactions yourself"]},{q:'What does Bitcoin\\\'s "monetary policy" refer to?',a:"Fixed supply schedule with predictable issuance rate until 21 million",wrong:["Central bank interest rates","Government fiscal policy","Investment fund strategies"]}],halving:[{q:"The Bitcoin halving occurs every:",a:"210,000 blocks (approximately every 4 years)",wrong:["Every calendar year on January 3","Every 100,000 blocks","Whenever the price doubles"]},{q:"After the 2024 halving, the block reward is:",a:"3.125 BTC per block",wrong:["6.25 BTC per block","1.5625 BTC per block","50 BTC per block"]},{q:"The halving is significant because it:",a:"Mathematically enforces Bitcoin's decreasing supply issuance",wrong:["Doubles the total supply of Bitcoin","Reduces the number of active miners by half","Changes Bitcoin's consensus mechanism"]},{q:"What happens during a Bitcoin halving?",a:"Block reward paid to miners is cut in half",wrong:["Transaction fees double","Bitcoin supply doubles","Mining difficulty halves"]},{q:"When will the final bitcoin be mined?",a:"Around year 2140 when all 21 million are issued",wrong:["2025","2040","Never — mining continues forever"]}],bitcoin_vs_real_estate:[{q:"What key property rights advantage does Bitcoin have over real estate?",a:"It cannot be seized, taxed annually, or confiscated via eminent domain",wrong:["Real estate has stronger rights because it is protected by law","Bitcoin and real estate have identical property rights protections","Bitcoin ownership is not recognized by any major legal system"]},{q:"How do maintenance costs compare between Bitcoin and real estate?",a:"Bitcoin has near-zero costs; real estate requires taxes, insurance, and repairs",wrong:["Bitcoin requires expensive monthly server fees to maintain ownership","Real estate has no maintenance costs once the mortgage is paid off","Both assets have roughly equivalent ongoing maintenance expenses"]},{q:"Why is Bitcoin considered superior to real estate in terms of portability?",a:"A seed phrase can be memorized and carried across any border instantly",wrong:["Real estate deeds can be memorized and are just as portable","Bitcoin is less portable because it always requires internet access","Portability is irrelevant when comparing long-term stores of value"]},{q:"How does Bitcoin's divisibility compare to real estate?",a:"Bitcoin divides into 100 million satoshis; real estate cannot be micro-divided",wrong:["Real estate is more divisible because you can rent individual rooms","Bitcoin cannot be divided at all — you must buy a whole coin","Both assets offer identical divisibility through financial derivatives"]},{q:"What risk does real estate face that Bitcoin does not, related to government power?",a:"Eminent domain seizure, property tax liens, and government confiscation",wrong:["Governments can easily confiscate Bitcoin but not real estate","Neither asset faces any confiscation risk in democratic nations","Bitcoin faces greater government risk because it can be fully banned"]}],bitvm:[{q:"What does BitVM enable on Bitcoin without requiring a protocol change?",a:"Arbitrary computation verification through fraud proofs",wrong:["Turing-complete smart contracts executed by miners","On-chain virtual machine execution like the EVM","Zero-knowledge proof generation inside Bitcoin Script"]},{q:"BitVM uses which computational model to verify off-chain computation?",a:"An optimistic model with prover claims and verifier challenges",wrong:["A zero-knowledge model where proofs are posted each block","A consensus model where all nodes re-execute computation","A federated model where trusted signers attest to results"]},{q:"In BitVM, what is the fundamental logic gate used to represent any computable function?",a:"NAND gates",wrong:["AND gates","XOR gates","NOR gates"]},{q:"Who proposed the original BitVM whitepaper?",a:"Robin Linus",wrong:["Peter Todd","Jeremy Rubin","Andrew Poelstra"]},{q:"How does BitVM2 improve upon the original BitVM design?",a:"It reduces on-chain transactions needed for dispute resolution",wrong:["It adds Turing-complete execution directly on base layer","It eliminates the need for a verifier role entirely","It requires a soft fork to enable several new opcodes"]}],"block_time-block-size":[{q:"Why did Satoshi choose approximately 10 minutes for Bitcoin's target block time?",a:"It balances throughput with time needed for global block propagation",wrong:["It was arbitrary with no real technical justification behind it","Faster blocks would make mining unprofitable due to power costs","It matches the average time needed for international wire transfers"]},{q:"What is the difference between block weight and block size in Bitcoin?",a:"Weight counts witness bytes at a discount versus non-witness bytes",wrong:["Block weight and block size are identical with different names","Block weight measures computational effort to validate a block","Block weight only applies to Lightning Network transactions"]},{q:"What is the maximum block weight allowed by Bitcoin's consensus rules?",a:"4 million weight units (4 MWU)",wrong:["1 megabyte of raw data","8 million weight units (8 MWU)","2 million weight units (2 MWU)"]},{q:"Why does SegWit give witness data a discount in the block weight calculation?",a:"Witness data costs less for nodes to process, incentivizing adoption",wrong:["Witness data is encrypted and takes up less physical storage","The discount was a political compromise with no technical basis","Witness data is stored temporarily then deleted after 100 blocks"]},{q:'What is "blockspace economics" in Bitcoin?',a:"The fee market where users bid for limited space in each block",wrong:["A government program subsidizing mining in renewable energy zones","The cost of running a full node in electricity and bandwidth","A pricing model used for Lightning Network channel capacity"]}],burn_bitcoin:[{q:"What is the maximum amount of data that can be stored in an OP_RETURN output?",a:"80 bytes",wrong:["40 bytes","160 bytes","1000 bytes"]},{q:"What does it mean for Bitcoin to be provably unspendable through OP_RETURN?",a:"The output has no valid script path to spend it",wrong:["It requires a special private key to spend","It can only be spent after 100 confirmations","It is temporarily locked until a timelock expires"]},{q:"Roughly how many Bitcoin are estimated to be permanently lost or burned?",a:"Between 3-4 million BTC",wrong:["Less than 1 million BTC","Over 10 million BTC","Exactly 1 million BTC"]},{q:"What type of Bitcoin address output is provably unspendable with no script?",a:"Bare multisig with invalid pubkeys",wrong:["Standard P2PKH addresses","Wrapped P2SH addresses","Native P2WPKH addresses"]},{q:"What is proof of burn in the context of cryptocurrency?",a:"Demonstrating coins were sent to an unspendable address",wrong:["Mining blocks without ever receiving any block rewards","Permanently deleting the private keys to a wallet","Sending coins to a wallet whose owner has died"]}],consensus_pt2:[{q:"What does finality mean in Nakamoto Consensus?",a:"Reversals become exponentially harder with each confirmation",wrong:["Transactions are instantly and permanently irreversible","Miners hold a formal vote on transaction validity","The longest chain is always guaranteed to be correct"]},{q:"What are orphan blocks in Bitcoin?",a:"Valid blocks not included in the main chain",wrong:["Invalid blocks rejected by network nodes","Blocks that contain zero transactions inside","Alternative variants of the genesis block"]},{q:"What is selfish mining in Bitcoin?",a:"Withholding found blocks to gain unfair advantage",wrong:["Mining solo without joining any mining pool","Using only renewable energy sources for mining","Deliberately refusing to validate any transactions"]},{q:"What is the typical Bitcoin block propagation time?",a:"1-10 seconds globally",wrong:["About 60 seconds on average","Nearly instantaneous at all times","Approximately 10 full minutes"]},{q:"What was the FIBRE network designed to improve?",a:"Block propagation speed between miners",wrong:["Lightning Network payment routing","Wallet synchronization with nodes","Mining difficulty adjustment calculations"]}],cryptography_pt3:[{q:"What advantage do Schnorr signatures provide over ECDSA in Bitcoin?",a:"Key aggregation for efficient multi-signature transactions",wrong:["Quantum resistance that ECDSA fundamentally lacks","Smaller size in all cases regardless of signers","Available since day one but never actually used"]},{q:"What is MuSig2 in Bitcoin?",a:"A Schnorr-based multi-sig scheme producing one standard-looking signature",wrong:["A second version of the Bitcoin music streaming protocol","A next-generation mining algorithm replacing SHA-256 hashing","A Lightning Network routing protocol for two-hop payments"]},{q:"What are adaptor signatures used for in Bitcoin?",a:"Conditional payments where signing reveals a secret value",wrong:["Converting old formats to be Taproot-compatible ones","Signing transactions using multiple keys simultaneously","Adapting Script to support Turing-complete contracts"]},{q:"What is a Pedersen commitment?",a:"A commitment that hides a value while allowing math verification",wrong:["A legal agreement between developers to maintain the protocol","A type of fee commitment that is included in every block","A signed pledge by miners to always follow consensus rules"]},{q:"What is the current status of zero-knowledge proofs on Bitcoin?",a:"Being explored via projects like BitVM and validity rollups",wrong:["Fully implemented in Bitcoin Core since the Taproot upgrade","Impossible on Bitcoin due to fundamental Script limitations","Removed from Bitcoin in 2015 due to critical security risks"]}],"ctv-covenants":[{q:"What does BIP-119 (CheckTemplateVerify) allow a Bitcoin output to do?",a:"Commit to a specific future transaction template for spending",wrong:["Execute arbitrary smart contract code when it is spent","Lock funds until a specific block height has been reached","Require multiple signatures from different keys to spend"]},{q:'What is a "covenant" in the context of Bitcoin?',a:"A restriction on how a UTXO can be spent in the future",wrong:["A multisig arrangement between federation member nodes","A legal agreement between Lightning channel counterparties","A time-locked contract that expires after a set period"]},{q:'What Bitcoin use case does CTV enable through "congestion control"?',a:"Batching many payments into one transaction claimable later",wrong:["Auto-adjusting fees based on current mempool congestion","Throttling transactions a wallet can send within a block","Limiting block size during periods of high network load"]},{q:"What is OP_VAULT designed to provide using covenants?",a:"Time-delayed withdrawals with an emergency clawback option",wrong:["A decentralized exchange built for trustless atomic swaps","Cold storage that auto-moves funds to hardware wallets","Multi-party escrow designed for marketplace transactions"]},{q:"Why are covenants considered controversial by some Bitcoiners?",a:"They could enable coin censorship or spending blacklists",wrong:["They require a hard fork that would split the network","They make all transactions public and remove user privacy","They increase block size beyond what nodes can handle"]}],cycles:[{q:"What drives Bitcoin's historically observed ~4-year market cycle?",a:"The halving, which cuts new supply in half every ~4 years",wrong:["Government regulations that shift with 4-year election cycles","A scheduled software update that resets the network state","Random market psychology with no underlying structural driver"]},{q:"How does the Gartner Hype Cycle apply to each Bitcoin halving era?",a:"Each cycle shows trigger, peak hype, disillusionment, then recovery to a plateau",wrong:["Bitcoin skips disillusionment because the price only goes up long-term","The Gartner Hype Cycle only applies to new tech products, not currencies","Each Bitcoin cycle follows the exact same price pattern as the last one"]},{q:'What is the "lengthening cycles" debate in Bitcoin?',a:"The theory that each bull run takes longer to peak with smaller percentage gains",wrong:["The theory that mining cycles get shorter as hardware gets faster","A proposal to extend the halving interval from four years to eight","The idea that transaction confirmation times increase every year"]},{q:"Which on-chain metrics are commonly used to analyze Bitcoin market cycles?",a:"MVRV, NUPL, and the Pi Cycle Top indicator",wrong:["GDP growth, unemployment, and consumer price index","Twitter followers, Google Trends, and Reddit subs","Block size, node count, and developer commit stats"]},{q:'What is the "diminishing returns" theory in Bitcoin cycles?',a:"Each cycle's percentage gain shrinks, though absolute highs keep rising",wrong:["Returns are accelerating each cycle with larger percentage gains","Bitcoin will eventually produce negative returns in every cycle","It refers to decreasing energy efficiency of mining each cycle"]}],derivation_path:[{q:"What does a BIP-32 HD (Hierarchical Deterministic) wallet allow you to do?",a:"Generate unlimited key pairs from a single master seed",wrong:["Store multiple cryptocurrencies in one single private key","Recover funds without a seed phrase using only email","Connect directly to the network without running a node"]},{q:"In the derivation path m/84'/0'/0'/0/0, what does the \"84\" represent?",a:"BIP-84, the Native SegWit (bech32) address standard",wrong:["The year 1984 when public key crypto was standardized","The 84th account stored inside this particular wallet","The total number of addresses that can be derived"]},{q:"Which BIP defines the derivation path standard for Taproot (bc1p) addresses?",a:"BIP-86",wrong:["BIP-84","BIP-49","BIP-44"]},{q:"Why is sharing an xpub (extended public key) a privacy concern?",a:"It lets anyone see all addresses and balances from that account",wrong:["It allows someone to spend your Bitcoin without the private key","It broadcasts your seed phrase to every node on the network","It reveals your real-world name and identity on the blockchain"]},{q:'What is the "gap limit" in HD wallet address discovery?',a:"How many consecutive unused addresses are checked before stopping",wrong:["The maximum number of addresses a wallet can generate total","The time delay required between generating new addresses","The minimum spacing between two UTXOs in a transaction"]}],"difficulty-adjustment_pt2":[{q:"What algorithm does Bitcoin use for difficulty adjustment?",a:"Direct calculation based on actual vs target time",wrong:["PID controller algorithm with feedback loops","Neural network prediction of future hash rate","Moving average of recent hash rate samples"]},{q:"How many blocks is the difficulty retarget period?",a:"2,016 blocks",wrong:["1,008 blocks","4,032 blocks","10,080 blocks"]},{q:"What causes hash rate oscillation between mining pools?",a:"Miners chasing short-term luck variance",wrong:["Scheduled Bitcoin Core software update cycles","Daily difficulty adjustment recalculations","Network communication delays between nodes"]},{q:"What variance measure describes pool mining luck?",a:"Statistical variance around expected block discovery",wrong:["Fixed reward percentage distributed to miners","Difficulty share ratio across pool participants","Network propagation delay between peer nodes"]},{q:"How long does a difficulty epoch typically last?",a:"Approximately 2 weeks",wrong:["Exactly 1 week","About 1 month","Approximately 4 days"]}],dlcs:[{q:"In a Discreet Log Contract (DLC), what role does an oracle play?",a:"It signs a real-world outcome that determines how the contract pays out",wrong:["It holds the funds in escrow until both parties agree on the result","It executes smart contract code on a sidechain to settle the bet","It mines the specific transaction that settles the contract on-chain"]},{q:'What cryptographic technique makes DLCs "discreet" — invisible to the oracle?',a:"Adaptor signatures that use the oracle's attestation privately",wrong:["Zero-knowledge proofs that hide the contract from participants","Ring signatures that mix the contract with unrelated transactions","Homomorphic encryption that processes data without decrypting it"]},{q:"What is a common real-world use case for Discreet Log Contracts?",a:"Financial derivatives and betting settled by price or event data",wrong:["Decentralized file storage using the Bitcoin network as a backend","Privacy-preserving identity verification on the Bitcoin blockchain","Automated market making for Lightning Network liquidity pools"]},{q:"Why is the oracle in a DLC considered more trustworthy than traditional smart contract oracles?",a:"The oracle doesn't know the contract exists or what depends on it",wrong:["The oracle stakes Bitcoin collateral that is slashed if it lies","Multiple oracles must all agree before any payout can occur","The oracle runs inside a trusted execution environment on-chain"]},{q:"DLC.Link enables Discreet Log Contracts to be used primarily for what purpose?",a:"Bridging Bitcoin as collateral into DeFi without giving up custody",wrong:["Mining pool payout distribution based on individual hash rate","Decentralized DNS registration on the Bitcoin base layer","Cross-chain atomic swaps between Bitcoin and Ethereum directly"]}],"dollar-bitcoin_milkshake_theory":[{q:'Who originated the "Dollar Milkshake Theory"?',a:"Brent Johnson of Santiago Capital",wrong:["Ray Dalio of Bridgewater Associates","Michael Saylor of MicroStrategy","Saifedean Ammous of The Bitcoin Standard"]},{q:"What is the core thesis of the Dollar Milkshake Theory?",a:"The dollar strengthens by sucking up global liquidity while other fiat currencies weaken",wrong:["All fiat currencies collapse simultaneously and get replaced by Bitcoin","The dollar weakens as other currencies collectively strengthen against it","Central banks coordinate to create and adopt a single global currency"]},{q:'What is the "dollar strength paradox" in the Milkshake Theory?',a:"The dollar gets stronger vs other currencies while losing purchasing power vs hard assets",wrong:["A strong dollar always means the Bitcoin price will go down in tandem","Dollar strength is a reliable signal that the US economy is healthy","Nobody wants dollars but everyone needs them to service their debts"]},{q:"How does Bitcoin fit into the Dollar Milkshake Theory's endgame?",a:"After the dollar absorbs global liquidity, Bitcoin becomes the ultimate fiat exit",wrong:["Bitcoin is irrelevant to the theory because it isn't a fiat currency","Bitcoin collapses alongside other currencies during the dollar's rise","The theory predicts Bitcoin gets banned and replaced by state CBDCs"]},{q:"Why does global dollar demand play a central role in the Milkshake Theory?",a:"Trillions in dollar-denominated debt forces nations to buy dollars, strengthening it",wrong:["Global dollar demand is declining rapidly as nations actively de-dollarize","Dollar demand only matters for US domestic transactions and trade","The theory says dollar demand is irrelevant — only money supply matters"]}],"el-salvador":[{q:"What was the Chivo wallet in El Salvador's Bitcoin adoption?",a:"A government-issued Lightning wallet that gave citizens $30 in Bitcoin",wrong:["A private hardware wallet manufactured locally in El Salvador","An exchange platform where Salvadorans could trade altcoins","A banking app that only supported US dollar-based transactions"]},{q:'What is "Bitcoin Beach" and why is it significant to El Salvador\'s Bitcoin story?',a:"El Zonte — a village that built a grassroots Bitcoin economy before the national law",wrong:["A luxury resort in San Salvador that exclusively accepts Bitcoin payments","A government-built tourist attraction designed to promote Bitcoin adoption","A cryptocurrency exchange headquartered on the Salvadoran coastal region"]},{q:"What was President Bukele's core strategy behind making Bitcoin legal tender?",a:"Financial inclusion for the unbanked, foreign investment, and cheaper remittances",wrong:["Replacing the US dollar entirely with Bitcoin as the sole currency","Mining Bitcoin profitably using El Salvador's untapped oil reserves","Creating a government-controlled cryptocurrency to replace Bitcoin"]},{q:"How did the World Bank and IMF respond to El Salvador's Bitcoin law?",a:"They pushed back — the World Bank refused help and the IMF warned of risks",wrong:["Both organizations fully endorsed and helped fund the entire initiative","The IMF designed and helped build the Chivo wallet infrastructure","The World Bank provided a $500 million loan specifically for adoption"]},{q:"How did Lightning Network adoption benefit El Salvador's economy?",a:"It enabled fast, near-free payments and remittances, cutting out costly services",wrong:["Lightning was not used — only on-chain Bitcoin transactions were supported","Lightning made transactions faster but significantly more expensive overall","El Salvador banned Lightning in favor of on-chain-only Bitcoin payments"]}],"evidence-against-alts_pt2":[{q:'What is a "premine" and why is it a red flag for altcoins?',a:"Founders create and keep tokens before public launch, giving insiders an unfair edge",wrong:["A premine is a security feature that helps blockchains launch more quickly","A premine means the coin was tested before release, which is good practice","A premine is when miners validate the genesis block without earning fees"]},{q:"Why are many altcoin tokens considered securities under US law?",a:"They pass the Howey Test — buyers expect profits from a centralized team's efforts",wrong:["The SEC automatically classifies every digital asset as a regulated security","Any token traded on a cryptocurrency exchange is legally a security by default","Only tokens with market caps above $1 billion can qualify as securities"]},{q:'What is "VC token dumping" in the altcoin market?',a:"VCs invest early at a discount, then sell their tokens on retail investors at launch",wrong:["VCs donate their discounted tokens to charity projects after launch","VCs permanently lock their tokens to show support for the project","VCs use their tokens to fund open-source Bitcoin core development"]},{q:'Why do Bitcoiners argue that "decentralized governance tokens" are an oxymoron?',a:"Token voting concentrates power with whales and VCs, recreating inequality",wrong:["Governance tokens are too technically complex to ever implement properly","Bitcoin already uses governance tokens internally for protocol upgrades","Governance tokens have been declared illegal in every jurisdiction"]},{q:"What key evidence do Bitcoiners cite about Ethereum's centralization?",a:"A massive premine to insiders, repeated monetary policy changes, and known leadership",wrong:["Ethereum runs on a single server that is controlled by Vitalik Buterin","Ethereum transactions require explicit government approval before processing","Ethereum has fewer active nodes than a typical corporate cloud database"]}],"extension-blocks":[{q:"What are extension blocks in Bitcoin?",a:"Additional block space running alongside the main chain without changing it",wrong:["Larger blocks created by increasing the block size limit via a hard fork","Blocks reserved exclusively for Lightning Network channel operations","Compressed blocks that store only transaction hashes to save space"]},{q:"How do extension blocks differ from a traditional soft fork upgrade?",a:'Old nodes see extension transactions as "anyone-can-spend" outputs',wrong:["Extension blocks require all nodes to upgrade or be forked off the network","Extension blocks reduce the block size to improve network decentralization","Extension blocks are identical to soft forks but use a different label"]},{q:'What is the "space chain" concept related to extension blocks?',a:"A separate chain whose block space is auctioned via the main chain",wrong:["A satellite network that broadcasts Bitcoin blocks from orbit","A virtual reality environment where Bitcoin nodes operate in 3D","A specialized blockchain optimized for storing files over 4MB"]},{q:"What is a key trade-off of extension blocks?",a:"Non-upgraded nodes cannot fully validate extension block transactions",wrong:["All miners must upgrade their hardware simultaneously to participate","The main block size permanently increases for all future blocks","Lightning Network channels become incompatible with the base layer"]},{q:"Why have extension block proposals historically been controversial in Bitcoin development?",a:"They risk creating a second-class zone that weakens full node security",wrong:["They were proposed by altcoin developers trying to undermine Bitcoin","They would eliminate the need for the Lightning Network entirely","They require replacing SHA-256 with a completely different hash algorithm"]}],feedback_loops:[{q:"What is the price-hashrate-security feedback loop in Bitcoin?",a:"Higher price attracts miners, boosting hashrate, security, and confidence in a rising cycle",wrong:["Higher price causes miners to shut down, reducing hashrate and network security","Hashrate and price are completely independent with no meaningful connection","Security drops as price rises because more hackers are attracted to attack"]},{q:"How does the adoption-liquidity-utility feedback loop work in Bitcoin?",a:"More users deepen liquidity, making Bitcoin more useful, which attracts even more users",wrong:["More users raise fees, which drives away users and decreases overall liquidity","Liquidity falls as adoption grows because the total supply is permanently fixed","Adoption and liquidity have an inverse relationship in the Bitcoin network"]},{q:"How does the Lindy Effect create a reinforcing feedback loop for Bitcoin?",a:"Each day Bitcoin survives boosts confidence in its longevity, drawing more adoption",wrong:["The Lindy Effect means Bitcoin gets less reliable as its codebase ages","Older technology always gets replaced, so the Lindy Effect hurts Bitcoin","The Lindy Effect only applies to physical objects, not digital protocols"]},{q:"What is reflexivity in the context of Bitcoin market cycles?",a:"Perceptions influence fundamentals, which reinforce perceptions, creating self-amplifying cycles",wrong:["Reflexivity means Bitcoin's price always reflects its true fundamental value","It describes the tendency of Bitcoin to always revert to the same price","Reflexivity is a mining technique that increases block production speed"]},{q:"Why are Bitcoin's feedback loops considered among the most powerful in economics?",a:"Multiple self-reinforcing loops in price, hashrate, adoption, and security amplify together",wrong:["Bitcoin has only one feedback loop but it happens to be extremely strong","Bitcoin's feedback loops are actually weak compared to traditional market loops","Feedback loops only work in bull markets and reverse completely in bear runs"]}],first_principles:[{q:'What does "first principles thinking" mean when applied to Bitcoin?',a:"Breaking money down to fundamental properties and reasoning up from there",wrong:["Copying the design of existing currencies and then improving them","Following the majority opinion of mainstream economists on money","Starting with government approval and working backward from there"]},{q:"Which philosopher is most associated with the first principles method of reasoning from fundamental truths?",a:"Aristotle",wrong:["Plato","Socrates","Descartes"]},{q:"When reasoning from first principles about what makes good money, which set of properties matters most?",a:"Scarcity, portability, durability, divisibility, and fungibility",wrong:["Government backing, legal enforcement, and central bank control","Physical weight, aesthetic beauty, and historical tradition","Ease of printing, widespread banking, and inflation targeting"]},{q:"First principles thinking reveals what fundamental connection between energy and money?",a:"Money should represent stored energy — unforgeable costliness gives it value",wrong:["Money has no relationship to energy since it is purely a social construct","Only physical commodities can serve as money because they contain atoms","Energy is irrelevant to money if a government declares it legal tender"]},{q:"Why does first principles reasoning tend to lead people toward Bitcoin rather than altcoins?",a:"Bitcoin best satisfies the fundamental properties of sound money from first principles",wrong:["Bitcoin was the first cryptocurrency so it wins by default over altcoins","Altcoins are illegal in most countries so Bitcoin is the only legal option","Bitcoin has the best marketing team and strongest brand awareness overall"]}],foss:[{q:"What type of software license does Bitcoin Core use?",a:"MIT License",wrong:["GPL v3","Apache License 2.0","Creative Commons"]},{q:"Why is it important that Bitcoin Core is free and open-source software (FOSS)?",a:"Anyone can audit the code to verify no backdoors or hidden rules exist",wrong:["It makes Bitcoin free to use with zero transaction fees for users","It allows developers to create unlimited Bitcoin through the code","It means no one actually needs to run the Bitcoin software"]},{q:'What are "reproducible builds" in the context of Bitcoin Core?',a:"A process to compile source code and verify the binary matches the official release",wrong:["A method of mining Bitcoin blocks more efficiently using parallel processing","A way to duplicate Bitcoin wallets for secure backup across multiple devices","A technique for copying the entire blockchain to new nodes more quickly"]},{q:'"Linus\'s Law" states that "given enough eyeballs, all bugs are shallow." How does this apply to Bitcoin?',a:"Thousands of developers review Bitcoin's code, so vulnerabilities get found and fixed faster",wrong:["Linux servers are the only machines capable of running Bitcoin full nodes properly","Linus Torvalds personally reviews and audits every Bitcoin Core release himself","Bitcoin can only run on open-source operating systems like Linux and FreeBSD"]},{q:"Why does open-source matter specifically for money/monetary software like Bitcoin?",a:"Users must verify the rules of their money — no hidden inflation or secret changes",wrong:["Open-source software is always faster and more efficient than proprietary code","It allows banks to freely copy Bitcoin and make their own branded version","It makes Bitcoin significantly easier for governments to regulate and control"]}],geopolitics___macroeconomics_pt2:[{q:"What is the BRICS de-dollarization movement and how does it relate to Bitcoin?",a:"BRICS nations are reducing dollar dependence, creating demand for neutral reserves like Bitcoin",wrong:["BRICS is a Bitcoin mining pool that is jointly operated by five nations","BRICS nations have collectively banned Bitcoin to protect local currencies","BRICS de-dollarization means these countries adopted Bitcoin as legal tender"]},{q:'What is the "strategic Bitcoin reserve" concept that multiple nations are exploring?',a:"Nations accumulating Bitcoin as a reserve asset alongside gold for its scarcity and hedge value",wrong:["A requirement for all nations to back their fiat currency reserves with Bitcoin","A UN mandate requiring every country to hold at least one thousand Bitcoin","A program where central banks replace all existing gold reserves with Bitcoin"]},{q:'What is the "nation-state game theory" argument for Bitcoin adoption?',a:"Early adopter nations gain a massive strategic edge, pressuring others to follow or fall behind",wrong:["Nations banning Bitcoin grow stronger because they fully control their money supply","Game theory proves that no nation will ever voluntarily adopt Bitcoin as a reserve","Nation-state game theory only applies to countries that possess nuclear weapons"]},{q:"How do proponents respond to critics who say Bitcoin is used for sanctions evasion?",a:"Bitcoin's transparent public ledger makes transactions easier to trace than physical cash",wrong:["Bitcoin supporters agree that sanctions evasion is its primary real-world use case","Bitcoin transactions are completely invisible and undetectable to all governments","Sanctions don't apply to digital assets under any current international law"]},{q:"How do institutions like the IMF and World Bank view Bitcoin?",a:"Generally hostile — they've pressured nations like El Salvador to drop Bitcoin legal tender status",wrong:["The IMF and World Bank are actually the largest institutional Bitcoin holders today","Both organizations have publicly endorsed Bitcoin as the future of global finance","The IMF created Bitcoin as a planned replacement for Special Drawing Rights"]}],governance_pt2:[{q:"Who can submit a Bitcoin Improvement Proposal (BIP)?",a:"Anyone in the Bitcoin community",wrong:["Only Bitcoin Core maintainers","Only miners with enough hash rate","Only officially registered developers"]},{q:"What activation method does BIP 9 use?",a:"Miner signaling with version bits",wrong:["User activation without miners","Mandatory soft fork by Core devs","Core developer approval voting"]},{q:"What activation method does BIP 8 use?",a:"Mandatory activation with optional miner signaling",wrong:["Complete miner control over activation timing","Exchange approval and coordinated agreement","Proof of stake voting by Bitcoin holders"]},{q:"What does UASF stand for?",a:"User-Activated Soft Fork",wrong:["Unified Active Soft Fork","Universal Auto Soft Fork","User Approval Soft Fork"]},{q:"What was Speedy Trial used for in Bitcoin?",a:"Taproot activation with a shortened signaling period",wrong:["SegWit activation with extended miner coordination","Lightning Network deployment across mainnet nodes","Difficulty adjustment algorithm changes and updates"]}],hardware:[{q:"What makes the Coldcard hardware wallet stand out among Bitcoin hardware wallets?",a:"It's air-gapped, Bitcoin-only, and supports NFC signing",wrong:["It supports thousands of altcoins and NFTs","It connects directly to the internet for speed","It's the cheapest hardware wallet available"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction) and why is it important for hardware wallets?",a:"A format for building transactions on one device and signing on another",wrong:["A Bitcoin address type exclusive to hardware wallets","A protocol for sending Bitcoin over Bluetooth","A backup format for storing seed phrases digitally"]},{q:"What is SeedSigner?",a:"A DIY, open-source, air-gapped wallet built on a Raspberry Pi",wrong:["A cloud service that generates seed phrases for you","A proprietary hardware wallet made by Ledger","An app that signs transactions via phone fingerprint"]},{q:'What is a "secure element" chip in hardware wallets?',a:"A tamper-resistant chip that stores keys and blocks extraction",wrong:["A chip that connects the wallet to Wi-Fi securely","A component that speeds up transaction processing","A GPS module that tracks the wallet for recovery"]},{q:'What does "air-gapped" mean when describing a hardware wallet like Coldcard or Foundation Passport?',a:"It never connects to internet — data moves via SD card, QR, or NFC",wrong:["The wallet is sealed in a vacuum to prevent tampering","The wallet uses satellite connections instead of Wi-Fi","The wallet can only be used outdoors for security"]}],history_pt3:[{q:"Approximately how many BTC did Mt. Gox lose in its collapse?",a:"850,000 BTC",wrong:["100,000 BTC","2 million BTC","50,000 BTC"]},{q:"What year did the Silk Road marketplace get seized?",a:"2013",wrong:["2011","2015","2017"]},{q:"How many Bitcoins were exchanged for two pizzas on Bitcoin Pizza Day?",a:"10,000 BTC",wrong:["1,000 BTC","100,000 BTC","1,000,000 BTC"]},{q:"What was the main conflict of the Blocksize War?",a:"Whether to increase block size limit",wrong:["Changing Bitcoin to proof of stake","Adding privacy features to Bitcoin","Changing the halving schedule"]},{q:"What was SegWit2x?",a:"Failed agreement to double block size after SegWit",wrong:["Successful hard fork increasing block size","A new proof-of-work mining algorithm","A second layer scaling protocol"]}],improved_incentive_structure:[{q:'How does Bitcoin "fix broken incentives" in the current monetary system?',a:"By removing money printing, it forces honest accounting and ends inflation of debt",wrong:["It gives governments better tools to manage the economy","It doesn't change incentives — just moves them to digital","It fixes incentives by making all transactions government-traceable"]},{q:'What does "low time preference society" mean in the context of a Bitcoin standard?',a:"People plan long-term and save more because their money gains value over time",wrong:["A society that doesn't care about time and works fewer hours","A society where transactions must complete within strict time limits","A society that only uses Bitcoin for short-term speculation"]},{q:'Why is proof of work considered a "fair distribution" mechanism for new Bitcoin?',a:"Anyone can mine by spending real energy — no pre-mines or insider allocations",wrong:["Proof of work gives equal Bitcoin to every person on Earth","Early miners got special privileges that later miners don't","Proof of work distributes Bitcoin based on geographic location"]},{q:"How does sound money (like Bitcoin) change savings and investment behavior?",a:"People save more and only invest in projects with real returns above deflation",wrong:["Sound money discourages saving because money becomes too valuable","Investment behavior stays the same regardless of monetary system","Sound money causes everyone to hoard and collapse the economy"]},{q:"What broken incentive does fiat money create that Bitcoin eliminates?",a:"Fiat rewards borrowing over saving because inflation erodes purchasing power",wrong:["Fiat incentivizes too much saving, which Bitcoin fixes","Fiat money has no broken incentives — it works as designed","Bitcoin creates the same borrow incentive since rates exist"]}],"investment-strategy_pt4":[{q:"What is UTXO management for tax optimization?",a:"Choosing specific UTXOs with known cost bases to minimize capital gains taxes",wrong:["Automatically hiding Bitcoin transactions from the IRS","Converting all UTXOs to altcoins before tax season","Splitting Bitcoin into $600 transactions to avoid reporting"]},{q:'What does "step-up in cost basis" mean for inherited Bitcoin?',a:"Cost basis resets to market price at owner's death, erasing prior gains",wrong:["Inherited Bitcoin is always taxed at the original purchase price","There is no tax on inherited Bitcoin in any jurisdiction","The cost basis doubles each year after inheritance"]},{q:"What is a Bitcoin IRA?",a:"A self-directed retirement account holding Bitcoin with tax advantages",wrong:["A government program that pays retirees in Bitcoin","An insurance policy replacing lost or stolen Bitcoin","A bank savings account that earns interest in Bitcoin"]},{q:"Why do experienced Bitcoiners warn against lending out your Bitcoin?",a:"Lending platforms like Celsius and BlockFi collapsed, losing depositor funds",wrong:["Bitcoin code prevents any form of lending or borrowing","Lending Bitcoin causes the network to slow down significantly","Bitcoin interest rates are always negative so you lose money"]},{q:"Why is cost basis tracking important for Bitcoin investors?",a:"Each purchase creates a separate tax lot needed for capital gains calculations",wrong:["Cost basis tracking is only needed for exchange-held Bitcoin","The IRS uses a flat tax rate on all Bitcoin regardless of price","Cost basis is irrelevant since Bitcoin is classified as currency"]}],laws_of_thermodynamics:[{q:"How does the First Law of Thermodynamics (conservation of energy) relate to Bitcoin mining?",a:"Miners convert electricity into computational work securing the ledger",wrong:["Bitcoin mining creates energy from nothing to power the network","The First Law means Bitcoin can only exist in cold climates","Energy is destroyed during mining, explaining the high usage"]},{q:'What does "unforgeable costliness" mean in Bitcoin\'s thermodynamic context?',a:"Real energy must be spent to produce Bitcoin and this cost can't be faked",wrong:["Bitcoin transactions are free because the network is decentralized","The cost of mining is purely artificial with no security purpose","Unforgeable costliness means Bitcoin wallets cannot be hacked"]},{q:"How does the Second Law of Thermodynamics (entropy always increases) connect to Bitcoin?",a:"Proof of work creates order in the ledger by increasing entropy via energy use",wrong:["Bitcoin violates the Second Law by creating value from nothing","Entropy has no connection to digital systems like Bitcoin","The Second Law means Bitcoin will eventually stop working"]},{q:'Why do some physicists describe proof of work as "thermodynamic security"?',a:"Reversing the chain would require re-spending all the energy that built it",wrong:["Because Bitcoin mining rigs get very hot during operation","Because proof of work requires cooling systems to function","Because thermodynamic equations are used to set transaction fees"]},{q:'What is the "Maxwell\'s Demon" analogy sometimes applied to Bitcoin?',a:"You can't sort molecules or secure a ledger without real energy expenditure",wrong:["Maxwell's Demon is the name of the first Bitcoin mining software","It describes a theoretical AI attack that takes over the network","It refers to Bitcoin price randomness being like particle motion"]}],"layer-2-lightning_pt4":[{q:"What is a submarine swap on the Lightning Network?",a:"A trustless exchange between on-chain and off-chain Bitcoin using HTLCs",wrong:["A method to secretly close Lightning channels without notice","A way to mine Bitcoin directly through Lightning Network nodes","An attack vector that drains funds from open Lightning channels"]},{q:"What is Multi-Path Payments (MPP) on Lightning?",a:"Splitting a payment across multiple routes to exceed single-channel limits",wrong:["Making multiple payments to different recipients simultaneously","A backup payment method used only if Lightning is offline","Sending the same payment through multiple channels for redundancy"]},{q:"What is AMP (Atomic Multi-Path Payments) on Lightning?",a:"A method where split parts are only redeemable together atomically",wrong:["An amplifier that boosts signal strength between Lightning nodes","A method to increase the maximum capacity of any channel","An automatic mining protocol built into the Lightning layer"]},{q:"What is trampoline routing on the Lightning Network?",a:"Delegating route calculation to intermediate nodes for lighter clients",wrong:["Bouncing payments off satellites for wider global coverage area","A routing method that always prioritizes the fastest available path","A security protocol that encrypts all payment amounts in transit"]},{q:"What are channel factories in the Lightning Network?",a:"Opening many channels among multiple parties in one on-chain transaction",wrong:["Physical facilities where Lightning network nodes are manufactured","Automated systems that create channels based on user demand levels","Software that converts on-chain wallets into Lightning-ready wallets"]}],"layer-2-lightning_pt5":[{q:"What is liquidity management on the Lightning Network?",a:"Balancing inbound and outbound capacity to reliably route payments",wrong:["Converting Lightning Bitcoin back to regular on-chain Bitcoin","Managing the total circulating supply of Bitcoin on Lightning","Keeping Lightning nodes continuously connected to the internet"]},{q:"What is channel rebalancing on Lightning?",a:"Moving funds between your own channels to redistribute liquidity",wrong:["Closing and reopening channels with updated funding parameters","Resetting all channel state back to the initial funding amount","Transferring full channel ownership to a different Lightning node"]},{q:"What is a Lightning Service Provider (LSP)?",a:"A service offering liquidity and channel management for easy onboarding",wrong:["An internet service provider that specializes in Bitcoin traffic","A government-licensed operator required to run Lightning nodes","A cloud service that mines Bitcoin using collected Lightning fees"]},{q:"What are zero-conf channels on Lightning?",a:"Channels usable immediately without waiting for on-chain confirmation",wrong:["Channels that require zero Bitcoin as a deposit to open them","Channels that provide completely zero-fee routing for payments","Channels that are permanent and cannot be closed once opened"]},{q:"How do Lightning routing nodes earn revenue?",a:"By charging small fees for forwarding payments through their channels",wrong:["By mining new Bitcoin on the Lightning Network second layer","By collecting a percentage of all Lightning transactions globally","By selling their channel and routing data to analytics companies"]}],"layer-3-sidechains":[{q:"How does the Liquid Network secure its two-way peg to Bitcoin?",a:"Through a federation of functionaries managing the peg via multisig",wrong:["Through merge-mining where Bitcoin miners also validate Liquid","Through a trustless smart contract deployed on Bitcoin's base layer","Through proof-of-stake consensus among Liquid token holder nodes"]},{q:"How does RSK (Rootstock) secure its sidechain?",a:"Through merge-mining where Bitcoin miners also validate RSK blocks",wrong:["Through a federation of trusted companies that collectively sign","Through proof-of-stake where RSK token holders vote on blocks","Through BitVM fraud proofs posted to Bitcoin's main base layer"]},{q:"What consensus mechanism does Stacks use to connect to Bitcoin?",a:"Proof of Transfer (PoX), where miners spend BTC to produce blocks",wrong:["Proof of Work using the same SHA-256 algorithm as Bitcoin mining","Delegated Proof of Stake with community-elected block producers","Proof of Authority using a fixed and permissioned validator set"]},{q:"What are drivechains (BIP-300) designed to enable?",a:"Permissionless sidechains with miner-voted withdrawals to mainchain",wrong:["Faster block times on Bitcoin by reducing difficulty adjustment","A new Lightning channel type that skips on-chain funding steps","Decentralized mining pools that auto-distribute block rewards"]},{q:"What is the primary security concern with federated sidechains like Liquid?",a:"Users must trust federation members not to collude and steal funds",wrong:["The sidechain can reverse Bitcoin base layer transactions at will","Federated sidechains consume more energy than Bitcoin's proof-of-work","The federation has the power to change Bitcoin's 21 million cap"]}],maximalism_pt2:[{q:'What do Bitcoiners mean when they call "toxic maximalism" an immune response?',a:"Aggressive pushback against scams protects newcomers like an immune system",wrong:["Maximalists spread computer viruses to attack competing altcoin networks","Toxic maximalism is a disease Bitcoin developers are actively trying to cure","It means Bitcoin's code automatically rejects transactions from altcoins"]},{q:'What is the "altcoin opportunity cost" argument made by Bitcoin maximalists?',a:"Money spent on altcoins could have gone to Bitcoin, which outperforms long-term",wrong:["Altcoins are free to create so there is no real opportunity cost at all","Bitcoin maximalists believe altcoin trading increases Bitcoin's overall value","Opportunity cost is a fiat concept that does not apply to digital assets"]},{q:"Why do Bitcoin-only companies (like Swan, River, and Unchained) choose not to support altcoins?",a:"They see promoting altcoins as ethically wrong since most will fail and harm users",wrong:["They lack the technical capability needed to support other cryptocurrency tokens","Government regulations currently prohibit companies from offering multiple cryptos","Supporting altcoins would make their exchange and wallet software too slow"]},{q:'What is the "ethical case" for Bitcoin maximalism?',a:"Promoting risky altcoins to unsophisticated investors causes real financial harm",wrong:["Bitcoin maximalists believe they have a religious duty to spread adoption","Ethics demand that all financial technologies be treated equally by default","The ethical case is that Bitcoin miners deserve all cryptocurrency profits"]},{q:'How does Gresham\'s Law ("bad money drives out good") apply to the Bitcoin maximalism argument?',a:"People spend weak fiat and altcoins while hoarding Bitcoin as the hardest money",wrong:["Gresham's Law proves that cheaper altcoins will eventually replace Bitcoin","It means governments will ultimately force citizens to use Bitcoin only","Gresham's Law only applies to physical coins and not digital currencies"]}],mining_pt5:[{q:"What does Stratum V2 allow individual miners to do that Stratum V1 does not?",a:"Choose their own transactions for block templates",wrong:["Mine without needing any internet connection","Bypass the network difficulty adjustment algorithm","Mine multiple different coins at the same time"]},{q:"What is a block template in Bitcoin mining?",a:"A candidate block with selected transactions awaiting a valid hash",wrong:["A design blueprint for building new ASIC mining hardware","A backup copy of the entire Bitcoin blockchain ledger","A reusable template for creating new cryptocurrency mining pools"]},{q:"What is a selfish mining attack?",a:"Withholding discovered blocks to gain an unfair chain advantage",wrong:["Refusing to share mining profits with other pool members","Mining only low-fee transactions for the miner's personal gain","Using stolen electricity to illegally power Bitcoin mining rigs"]},{q:"What is ASICBoost?",a:"A technique that optimizes SHA-256 to reduce energy per hash",wrong:["A specific brand of mining hardware manufactured by Bitmain","A firmware update that automatically doubles any miner's hashrate","A method to cool ASIC miners using advanced liquid nitrogen"]},{q:"What is the difference between overt and covert ASICBoost?",a:"Overt is visible in block headers; covert is hidden from view",wrong:["Overt is legal in all jurisdictions while covert is illegal","Overt uses significantly more energy per hash than covert does","Overt works on any ASIC while covert is Bitmain hardware only"]}],mining_pt6:[{q:'What is "hash price" in Bitcoin mining economics?',a:"Revenue earned per unit of hash rate per day",wrong:["Cost to purchase a single ASIC miner","Bitcoin's price divided by total hash rate","Electricity cost per hash computation"]},{q:"What typically happens to less efficient miners shortly after a Bitcoin halving?",a:"They become unprofitable and may shut down",wrong:["They automatically receive double the reward","Their hash rate doubles to compensate","They permanently switch to mining altcoins"]},{q:"What is the typical operational lifespan of an ASIC miner before it becomes obsolete?",a:"Approximately 3 to 5 years",wrong:["About 6 months on average","Over 20 years with maintenance","Exactly one halving cycle"]},{q:"What is the breakeven electricity cost for Bitcoin mining?",a:"The kWh price where revenue equals costs",wrong:["A fixed rate set by Bitcoin developers","The average electricity cost worldwide","The minimum power to run one ASIC"]},{q:"As block subsidies decrease over time, what must replace them to incentivize miners?",a:"Transaction fees paid by users",wrong:["Government subsidies for miners","Increased mining difficulty","New coins from hard forks"]}],"misconceptions-fud_pt2":[{q:'How do Bitcoiners respond to "Bitcoin is too volatile to be money"?',a:"Every 4-year period has been profitable and volatility decreases over time",wrong:["They agree volatility makes Bitcoin unsuitable as money","They say volatility doesn't exist if you ignore the price","They claim Bitcoin's price is actually fixed by miners"]},{q:'Why is the claim "quantum computers will break Bitcoin" misleading?',a:"Such computers don't exist yet and Bitcoin can upgrade before they do",wrong:["Bitcoin already uses quantum-resistant encryption algorithms","Quantum computers actually strengthen Bitcoin's security","Satoshi designed Bitcoin to be immune to all future computing"]},{q:'What is the rebuttal to "Tether (USDT) props up Bitcoin\'s price"?',a:"Bitcoin grew for years before Tether and kept rising through its controversies",wrong:["Tether holds 100% of its reserves in Bitcoin directly","Bitcoin's price is determined solely by mining costs","Tether was created by Satoshi as part of Bitcoin's design"]},{q:'Why is "Bitcoin is a pyramid scheme" factually wrong?',a:"It has no company, no CEO, no return promises, and no recruitment profits",wrong:["Because early adopters are guaranteed profits by the protocol","Because Satoshi Nakamoto still runs the company behind Bitcoin","Because the Bitcoin protocol pays dividends to long-term holders"]},{q:'What is the strongest argument against "governments will ban Bitcoin"?',a:"China banned it multiple times yet it kept growing, and the US approved ETFs",wrong:["Governments lack the technology to detect Bitcoin transactions","International law prevents any country from banning crypto","Bitcoin automatically shuts down in countries where it's banned"]}],nodes_pt4:[{q:"What is the key difference between a pruned node and an archival (full) node?",a:"A pruned node deletes old block data after verifying it",wrong:["A pruned node skips transaction verification entirely","An archival node only stores the UTXO set","A pruned node cannot validate new transactions"]},{q:"What does BIP 152 (Compact Block Relay) do?",a:"Sends short transaction IDs instead of full transactions",wrong:["Compresses the entire blockchain into smaller files","Allows nodes to skip blocks during initial sync","Encrypts block data for privacy between nodes"]},{q:"What is the Erlay protocol designed to improve?",a:"Transaction relay efficiency between nodes",wrong:["Block mining speed via nonce optimization","Lightning Network channel capacity","Wallet synchronization for mobile devices"]},{q:"What is the UTXO set and why does its size matter for nodes?",a:"All unspent outputs nodes must keep in memory for validation",wrong:["A list of all transactions ever made on Bitcoin","A record of all mining rewards ever distributed","A backup of private keys stored across the network"]},{q:"What is a major concern about running a Bitcoin full node related to bandwidth?",a:"Relaying transactions and blocks uses significant upload bandwidth",wrong:["Nodes must pay per-megabyte fees to the network","Bandwidth usage is zero after initial block download","Only mining nodes consume significant bandwidth"]}],nodes_pt5:[{q:"What programming language is Bitcoin Core primarily written in?",a:"C++",wrong:["Rust","Python","Java"]},{q:"What is btcd?",a:"An alternative Bitcoin full node written in Go",wrong:["A Bitcoin wallet for desktop computers","A command-line tool for Bitcoin mining","A testing framework for Bitcoin Core"]},{q:"What are reproducible builds in the context of Bitcoin Core?",a:"Anyone can compile source and get an identical binary",wrong:["A system where Bitcoin Core auto-updates itself","A method to restore a node from a backup","A way to compile Bitcoin Core faster on CPUs"]},{q:"What is Guix used for in Bitcoin Core development?",a:"A build system for reproducible, verifiable builds",wrong:["A graphical interface for running a Bitcoin node","A security scanner for checking vulnerabilities","A package manager for installing Bitcoin wallets"]},{q:"Why is it important to be able to build Bitcoin Core from source?",a:"To verify the code and ensure your binary matches it",wrong:["Because pre-built binaries aren't available","To get access to hidden developer features","Because source builds make the node faster"]}],"op-codes_pt2":[{q:"What would OP_CAT enable if re-enabled?",a:"Concatenation of data values in script",wrong:["Comparison of timestamp values","Multiplication of numeric values","Direct verification of signatures"]},{q:"What does OP_CHECKSIGFROMSTACK verify?",a:"Arbitrary message signatures on the stack",wrong:["Only standard transaction signatures","Block signatures submitted by miners","Lightning Network commitment signatures"]},{q:"What is Simplicity designed for in Bitcoin?",a:"Formal verification of smart contracts",wrong:["Faster transaction processing speeds","Simplified wallet address formats","Reduced overall block sizes"]},{q:"What is a major limitation of Bitcoin Script?",a:"No loops or complex control flow",wrong:["Maximum of 100 opcodes per script","Cannot handle any signatures","Requires active internet access"]},{q:"Which script type was introduced with Taproot?",a:"P2TR (Pay to Taproot)",wrong:["P2SH (Pay to Script Hash)","P2WSH (Pay to Witness Script)","P2PKH (Pay to Pub Key Hash)"]}],"orange-pilling_pt2":[{q:'What is the "Socratic method" approach to orange-pilling someone about Bitcoin?',a:"Asking questions that lead them to discover Bitcoin's value themselves",wrong:["Quoting ancient Greek philosophers who predicted digital money","Having the person read the Bitcoin whitepaper out loud to you","Debating them aggressively until they agree Bitcoin is good"]},{q:'What is "progressive disclosure" when introducing someone to Bitcoin?',a:"Starting with simple concepts they care about, then going deeper",wrong:["Showing them Bitcoin's full transaction history from genesis","Revealing your entire Bitcoin portfolio to build their trust","Disclosing all of Bitcoin's technical flaws upfront to seem honest"]},{q:"When orange-pilling family members, what is generally the most effective approach?",a:"Focus on what they care about — savings, retirement, their future",wrong:["Send them a 3-hour technical podcast about mining and hashing","Buy them Bitcoin without asking and surprise them with it later","Bring it up at every family dinner until they finally agree"]},{q:"What is one of the biggest mistakes people make when trying to orange-pill someone?",a:"Information overload — dumping too much detail at once",wrong:["Being too patient and waiting for them to ask questions","Starting with how Bitcoin helps people in other countries","Recommending they read a book about the history of money"]},{q:"Which book is widely considered the best starting point for orange-pilling someone interested in economics and sound money?",a:"The Bitcoin Standard by Saifedean Ammous",wrong:["Mastering Bitcoin by Andreas Antonopoulos","Programming Bitcoin by Jimmy Song","The Blocksize War by Jonathan Bier"]}],ordinals_inscriptions:[{q:"Who proposed the Ordinal Theory for Bitcoin?",a:"Casey Rodarmor",wrong:["Adam Back","Pieter Wuille","Satoshi Nakamoto"]},{q:"How are individual satoshis numbered in Ordinal Theory?",a:"Sequentially based on mining order",wrong:["Randomly assigned by the network","By their transaction ID hash","By the receiving wallet address"]},{q:"What do inscriptions attach to specific satoshis?",a:"Arbitrary data like images or text",wrong:["Private keys for spending them","Their full transaction history","Multisig spending conditions"]},{q:"What token standard emerged from Ordinals functionality?",a:"BRC-20",wrong:["ERC-20","RGB","Omni Layer"]},{q:"What was a major criticism of Ordinals regarding block space?",a:"They use limited block space for non-monetary data",wrong:["They significantly reduce mining reward amounts","They break Bitcoin's core consensus rules","They allow theft of other users' funds"]}],philosophy_pt2:[{q:"Who wrote the Cypherpunk Manifesto?",a:"Eric Hughes",wrong:["Timothy May","Julian Assange","Nick Szabo"]},{q:"What concept did Timothy May advocate for in the Crypto-Anarchist Manifesto?",a:"Using cryptography to protect individual privacy",wrong:["Building centralized digital currency systems","Government regulation of all encryption tools","Corporate ownership of communication networks"]},{q:"What was Nick Szabo's Bit Gold concept?",a:"A digital collectible using proof of work",wrong:["A stablecoin backed by physical gold","A centralized government digital currency","A Lightning-style payment channel design"]},{q:"What did Wei Dai propose with b-money?",a:"Anonymous digital cash with decentralized minting",wrong:["A blockchain with standard mining rewards","A central bank controlled digital currency","A system of gold-backed certificates"]},{q:"What was Hal Finney's famous contribution to Bitcoin?",a:"Received the first Bitcoin transaction from Satoshi",wrong:["Wrote the original Bitcoin whitepaper himself","Created the SHA-256 based mining algorithm","Founded the first Bitcoin trading exchange"]}],"privacy-nonkyc_pt4":[{q:"What is a PayJoin (P2EP) transaction?",a:"Both sender and receiver contribute inputs, obscuring who paid whom",wrong:["A payment split equally between two participating parties","A transaction requiring two separate network confirmations","A joint mining operation shared between two mining pools"]},{q:"What are Silent Payments (BIP 352)?",a:"One static address generates a unique on-chain address per payment",wrong:["Transactions that are hidden from the public mempool entirely","Payments delayed until network activity drops to low levels","A method to send Bitcoin without paying any transaction fees"]},{q:"What is the Boltzmann entropy score used for in Bitcoin privacy?",a:"Measuring ambiguity of a transaction's input-output linkages",wrong:["Calculating the thermodynamic energy cost of a transaction","Rating the randomness quality of a wallet's seed phrase","Scoring how quickly a transaction will get confirmed"]},{q:"What does Whirlpool do for Bitcoin privacy?",a:"Mixes UTXOs via CoinJoin to break transaction history links",wrong:["Provides a VPN service designed specifically for Bitcoin nodes","Encrypts Bitcoin transactions end-to-end before broadcast","Runs a privacy coin layer on top of the Bitcoin blockchain"]},{q:"What is CoinSwap and how does it differ from CoinJoin?",a:"Uses atomic swaps so mixing is invisible on-chain, unlike CoinJoin",wrong:["Converts Bitcoin to privacy coins and back for mixing purposes","Is faster but provides less privacy protection than CoinJoin","Requires a trusted third party while CoinJoin does not need one"]}],"problems-of-money_pt4":[{q:"The Cantillon Effect describes how newly printed money benefits those closest to its creation. Who benefits MOST from money printing?",a:"Banks and the politically connected who receive new money first",wrong:["Average workers who receive higher wages from inflation","Retirees on fixed incomes who get cost-of-living adjustments","Small business owners who can raise their prices immediately"]},{q:"What is Quantitative Easing (QE)?",a:"A central bank creating new money to buy bonds, expanding supply",wrong:["A method of reducing government debt by printing less money","A technique for making international trade easier between nations","A system where banks lend to each other at zero percent interest"]},{q:'What is the "repo market" and why does it matter for understanding fiat fragility?',a:"Overnight lending market using bonds as collateral — its 2019 crisis exposed systemic fragility",wrong:["A marketplace where banks sell repossessed homes and vehicles for profit","A government repository that stores and audits physical gold reserves","A database where central banks track and monitor all global transfers"]},{q:'What is the "Eurodollar system"?',a:"US dollars held and created by banks outside the US, forming a shadow system",wrong:["The system that converts Euros to Dollars at European exchange desks","A European Central Bank program to replace the Dollar with the Euro","A cryptocurrency project backed equally by both Euros and US Dollars"]},{q:'What does the decline of the "petrodollar" system mean for global finance?',a:"Oil nations moving away from dollar pricing weakens its reserve status",wrong:["Oil companies are switching from drilling to mining Bitcoin instead","The petrodollar decline means that oil is becoming nearly worthless","European nations are being forced to buy all their oil with gold"]}],regulation_pt3:[{q:"In the US, what is the key difference between SEC and CFTC jurisdiction over digital assets?",a:"SEC regulates securities (most altcoins); CFTC regulates Bitcoin as a commodity",wrong:["SEC handles Bitcoin while CFTC handles all altcoins separately","Both agencies share identical authority over all digital assets","CFTC only regulates physical commodities, not any digital assets"]},{q:"What is the Howey Test and how does it apply to Bitcoin?",a:"A legal test for securities — Bitcoin fails to qualify since it has no central enterprise",wrong:["A technical test that measures a blockchain's degree of decentralization","Bitcoin fails the Howey Test, making it an SEC-regulated security asset","A test that determines the appropriate tax rate on crypto investments"]},{q:'What is the "Travel Rule" in cryptocurrency regulation?',a:"A FATF rule requiring institutions to share sender/receiver identity above a threshold",wrong:["A regulation that limits Bitcoin transfers to within a single country","A requirement for Bitcoin miners to register their physical locations","A law that bans carrying hardware wallets across international borders"]},{q:"What is the FATF and why is it significant for Bitcoin privacy?",a:"An international body pushing KYC/AML standards that threaten self-custodial privacy",wrong:["A global mining consortium that coordinates difficulty adjustment levels","A nonprofit organization promoting Bitcoin adoption in developing nations","A technology standard designed for faster Bitcoin transaction processing"]},{q:"How have US states approached Bitcoin regulation differently from the federal government?",a:"Several states passed pro-Bitcoin laws like reserve bills and transmitter exemptions",wrong:["All 50 states enforce identical cryptocurrency regulations matching federal law","States are constitutionally prohibited from creating crypto-related legislation","Most states have banned Bitcoin mining operations due to energy concerns"]}],rollups:[{q:"What is a validity rollup on Bitcoin?",a:"A system that bundles off-chain transactions and posts a ZK proof to Bitcoin",wrong:["A sidechain that copies Bitcoin's consensus rules exactly as written","A Lightning Network channel that batches together multiple payments","A mining pool feature that combines block templates from miners"]},{q:"How do sovereign rollups differ from validity rollups?",a:"Users verify rollup state themselves rather than relying on the base layer",wrong:["Sovereign rollups use a central authority; validity rollups are decentralized","Sovereign rollups use proof-of-stake; validity rollups use proof-of-work","Sovereign rollups are limited to only seven transactions per second"]},{q:"How could BitVM enable rollups on Bitcoin?",a:"By allowing fraud proofs to verify rollup state without needing new opcodes",wrong:["By adding a Turing-complete VM directly into Bitcoin's consensus layer","By creating a dedicated sidechain specifically for validating rollup data","By replacing Bitcoin's existing Script language with Solidity contracts"]},{q:"How do Bitcoin rollups differ from sidechains?",a:"Rollups post proofs or data to Bitcoin, inheriting its security guarantees",wrong:["Rollups use a separate token for gas while sidechains use native BTC","Rollups need a federation of signers while sidechains are fully trustless","Rollups are faster than sidechains but limited to simple transfers only"]},{q:"What is the main trust assumption difference between a validity rollup and an optimistic rollup?",a:"Validity rollups prove correctness upfront; optimistic rollups assume it until challenged",wrong:["Validity rollups trust a federation of signers; optimistic rollups trust miners","Validity rollups need a soft fork to work; optimistic rollups work on Bitcoin today","Validity rollups are run centrally; optimistic rollups are always fully decentralized"]}],"self-custody_pt3":[{q:"What is Sparrow Wallet known for in multisig coordination?",a:"Deep UTXO management and easy multisig setup with hardware signers",wrong:["A mobile-only wallet with cloud-based multisig coordination","A hardware wallet that stores multiple seed phrases internally","A browser extension designed primarily for Lightning payments"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction)?",a:"A standard format letting a transaction be built and signed by multiple parties",wrong:["A special Bitcoin transaction type that only sends partial amounts","A privacy protocol that hides the identity of a transaction sender","A transaction format exclusively used by mining pool operators"]},{q:"What are output descriptors in Bitcoin?",a:"A standard way to describe how a wallet derives addresses for reliable recovery",wrong:["Labels attached to individual transaction outputs for bookkeeping purposes","A complete list of all outputs ever created on the Bitcoin blockchain","Metadata that mining pools attach to the transactions they broadcast"]},{q:"Why is multisig generally preferred over Shamir Secret Sharing (SSS) for Bitcoin custody?",a:"Multisig never reconstructs the full private key in one place; SSS does when signing",wrong:["Multisig transactions cost significantly less in fees than SSS schemes","SSS requires more hardware devices to operate than multisig setups","Multisig predates SSS and has substantially better documentation available"]},{q:"What is Nunchuk known for in the Bitcoin wallet space?",a:"Easy collaborative multisig setup and built-in inheritance planning",wrong:["Being the first wallet to natively support Lightning payments","A hardware-only wallet designed exclusively for cold storage use","A privacy wallet that uses CoinJoin mixing transactions by default"]}],"self-custody_pt4":[{q:"Why is titanium preferred over stainless steel for seed phrase backup plates?",a:"Higher melting point and better corrosion resistance in extreme conditions",wrong:["Titanium is significantly cheaper and more widely available worldwide","Titanium plates can fit more seed words than steel backup plates","Titanium is the only metal undetectable by standard metal detectors"]},{q:"What is a passphrase (25th word) in Bitcoin seed phrase security?",a:"An extra user-chosen word that generates an entirely different wallet",wrong:["The password you enter to unlock your hardware wallet device","A recovery phrase issued to you by the wallet manufacturer","An encryption key used to protect the local blockchain data"]},{q:"Why is geographic distribution important for Bitcoin seed phrase storage?",a:"It protects against localized disasters destroying all backup copies at once",wrong:["It speeds up the wallet by routing through the nearest Bitcoin nodes","It is a legal requirement enforced in most regulatory jurisdictions","It mathematically increases the entropy of the generated seed phrase"]},{q:"What is a dead man's switch in Bitcoin inheritance planning?",a:"A mechanism that triggers key release if the owner fails to check in",wrong:["A physical switch on hardware wallets that wipes them if tampered","A transaction that auto-sends all Bitcoin to a burn address on a timer","A self-destruct feature built directly into the Bitcoin Core software"]},{q:"What is the biggest risk of not having a Bitcoin inheritance plan?",a:"Your Bitcoin could be permanently lost since no one else has the keys",wrong:["The government will automatically seize all of your Bitcoin holdings","Your Bitcoin gets redistributed among other active network participants","Your Bitcoin will steadily lose value without an actively managed wallet"]}],softwar_pt2:[{q:"What military rank is Jason Lowery?",a:"Major",wrong:["Colonel","Lieutenant","Captain"]},{q:"What university did Jason Lowery work with on his thesis?",a:"MIT",wrong:["Harvard","Stanford","Caltech"]},{q:"According to Softwar, what does proof of work project?",a:"Physical power through cyberspace",wrong:["Financial return on investment","Social consensus via voting","Network speed and throughput"]},{q:"How does Softwar view Bitcoin for nation-states?",a:"A strategic defense technology",wrong:["A replacement for fiat currency","A consumer payment system","An unregulated security asset"]},{q:"What energy concept is central to the Softwar thesis?",a:"Using energy to secure cyberspace property",wrong:["Reducing global carbon emissions","Accelerating solar power adoption","Profiting from energy arbitrage"]}],spv:[{q:"What does SPV (Simplified Payment Verification) allow a lightweight client to do?",a:"Verify transaction inclusion using block headers and Merkle proofs",wrong:["Mine Bitcoin blocks using minimal computing power","Send transactions without paying any network fees","Run a full node on a mobile phone with limited storage"]},{q:"What privacy problem did the original SPV bloom filters (BIP-37) have?",a:"They leaked which addresses the wallet cared about to the server",wrong:["They revealed the user's IP address to every network node","They broadcast the user's seed phrase as part of filter data","They required users to share real names with node operators"]},{q:"What do BIP-157 and BIP-158 (compact block filters) improve over bloom filters?",a:"Clients download pre-computed filters without revealing their addresses",wrong:["They compress the entire blockchain into a single downloadable file","They allow nodes to verify transactions without any network access","They replace Merkle proofs with zero-knowledge proofs for speed"]},{q:"What is Neutrino in the context of Bitcoin light clients?",a:"A light client protocol using BIP-157/158 compact block filters",wrong:["A privacy coin built as a Bitcoin sidechain project","A mining algorithm designed for mobile phone hardware","A wallet that runs a full node in the cloud for you"]},{q:"What is the main security tradeoff of SPV compared to running a full node?",a:"SPV clients trust miners produce valid blocks without full verification",wrong:["SPV clients cannot receive Bitcoin, they can only send it","SPV clients must pay higher transaction fees than full nodes","SPV clients can only connect to one peer node at a time"]}],submarine_swap_pt2:[{q:"What is a Loop Out in Lightning?",a:"Moving funds from Lightning back to on-chain",wrong:["Opening a new payment channel","Receiving inbound Lightning payments","Closing all channels at once"]},{q:"What is Boltz Exchange known for?",a:"Trustless on-chain and Lightning swaps",wrong:["Running a Bitcoin mining pool","Operating a centralized exchange","Selling Bitcoin hardware wallets"]},{q:"What makes submarine swaps trustless?",a:"Atomic hash time-locked contracts",wrong:["Multi-signature escrow wallets","Trusted third-party verification","Proof of stake consensus rules"]},{q:"How do submarine swaps differ from atomic swaps?",a:"They move between layers of the same chain",wrong:["Submarine swaps always require trust","Atomic swaps are significantly faster","Submarine swaps use different coins"]},{q:"What enables cross-chain atomic swaps without intermediaries?",a:"HTLCs combining hashlock and timelock",wrong:["Trusted custodial escrow services","Centralized exchange order books","Smart contract platforms only"]}],tail_emission:[{q:'What is "tail emission" in the context of cryptocurrency monetary policy?',a:"A small perpetual block reward ensuring miners always get some subsidy",wrong:["The final Bitcoin expected to be mined around the year 2140","The process of burning unsold Bitcoin to reduce total supply","A mechanism that increases block rewards over time for miners"]},{q:"Which major cryptocurrency implements tail emission as part of its monetary policy?",a:"Monero, with a permanent minimum reward of 0.6 XMR per block",wrong:["Bitcoin, which added tail emission in the Taproot upgrade","Ethereum, which introduced it during the merge to proof of stake","Litecoin, which activated it after its third halving event"]},{q:"What concern about Bitcoin's long-term security does the tail emission debate address?",a:"Whether fees alone can incentivize miners after block rewards end",wrong:["Whether Bitcoin's encryption can withstand quantum computers","Whether the 21 million supply cap should be raised over time","Whether nodes will have enough storage for the growing chain"]},{q:"What is the main argument AGAINST adding tail emission to Bitcoin?",a:"It would break the 21 million cap and destroy sound money credibility",wrong:["Tail emission would make mining too profitable and attract too many","It would speed up transaction confirmation times excessively","Tail emission is technically impossible to implement on Bitcoin"]},{q:'What is the "fee market sufficiency" argument against the need for tail emission?',a:"Growing adoption and scarce block space will naturally raise fee revenue",wrong:["Miners will voluntarily work for free because they believe in Bitcoin","The government will subsidize mining to keep the network running","New Bitcoin will be discovered on the network like finding new gold"]}],time_preference_pt3:[{q:'According to Saifedean Ammous in "The Bitcoin Standard," what is the relationship between sound money and time preference?',a:"Sound money lowers time preference, encouraging saving and long-term investment",wrong:["Sound money raises time preference because people rush to spend currency","There is no meaningful relationship between money type and time preference","Sound money eliminates time preference, making people totally indifferent"]},{q:"How does Ammous argue that low time preference connects to civilization building?",a:"People invest in long-term projects when money reliably holds its value",wrong:["Civilizations advance fastest when people spend money as quickly as possible","Low time preference leads to stagnation because nobody takes any risks","Civilization building is completely unrelated to the monetary system"]},{q:"What behavioral effect does fiat money have on time preference according to the Austrian economics perspective?",a:"Fiat raises time preference — inflation punishes savers and rewards debtors",wrong:["Fiat lowers time preference because stable inflation aids long-term planning","Fiat has no effect on time preference, which is determined by culture","Fiat encourages saving because interest rates compensate for inflation"]},{q:"How does the concept of delayed gratification relate to Bitcoin and sound money?",a:"Sound money rewards patience by preserving purchasing power over time",wrong:["Delayed gratification is irrelevant to any monetary system design","Bitcoin punishes patience because its price is far too volatile","Sound money discourages waiting by making everything too expensive"]},{q:"What is the key difference between how fiat and Bitcoin influence personal financial behavior?",a:"Fiat incentivizes consumption and debt; Bitcoin incentivizes saving",wrong:["Both systems produce identical behavior — spending stays the same","Bitcoin makes people spend more as they feel wealthy from gains","Fiat encourages saving; Bitcoin encourages spending due to deflation"]}],vbyte:[{q:"What is a virtual byte (vbyte) in Bitcoin?",a:"A unit where 1 vbyte equals 4 weight units, used for fee calculation",wrong:["A compressed byte format that reduces transaction size by 75%","The amount of data a Bitcoin node can process per second","A unit measuring the electricity cost of validating transactions"]},{q:"How did SegWit change the way Bitcoin transaction fees are calculated?",a:"Fees use weight units or vbytes, giving witness data a discount",wrong:["SegWit made all transactions free for the first year after launch","SegWit replaced fee priority with a first-come-first-served queue","SegWit doubled the base fee rate for all transaction types"]},{q:"What is the witness discount ratio in SegWit?",a:"Witness data costs 1 weight unit per byte; non-witness costs 4",wrong:["Witness data is free; non-witness data costs 2 weight units","Both witness and non-witness data cost 2 weight units per byte","Witness data costs 3 weight units; non-witness data costs 4"]},{q:"Why is understanding vbytes important for optimizing Bitcoin transaction costs?",a:"Using SegWit addresses moves data into the discounted witness section",wrong:["Vbytes determine how many confirmations a transaction needs","Using fewer vbytes increases the mining reward for the block","Transactions with more vbytes get higher priority in mempool"]},{q:"A typical single-input, single-output SegWit transaction is approximately how many vbytes?",a:"About 110 vbytes",wrong:["About 500 vbytes","About 10 vbytes","About 1,000 vbytes"]}]},QUEST_TRIGGERS=[5,15,25,40,60,80,100];let currentQuest=null,isRetry=!1,completedQuests=new Set,weeklyCompleted=[],visitedForQuest=[],questCount=0;function _getCurrentWeekKey(){var e=new Date,t=new Date(e.getFullYear(),0,1),o=Math.floor((e-t)/864e5)+1,n=Math.ceil((o+t.getDay())/7);return e.getFullYear()+"-W"+n}function _loadWeeklyCompleted(){var e=safeJSON("btc_quest_week",{}),t=_getCurrentWeekKey();e.week!==t&&(e={week:t,completed:[]},localStorage.setItem("btc_quest_week",JSON.stringify(e))),weeklyCompleted=e.completed||[]}function _saveWeeklyCompleted(e){var t=safeJSON("btc_quest_week",{}),o=_getCurrentWeekKey();t.week!==o&&(t={week:o,completed:[]}),t.completed||(t.completed=[]),-1===t.completed.indexOf(e)&&t.completed.push(e),localStorage.setItem("btc_quest_week",JSON.stringify(t)),weeklyCompleted=t.completed}function initQuests(){safeJSON("btc_visited_channels",[]).forEach(e=>{visitedForQuest.includes(e)||visitedForQuest.push(e)}),void 0!==auth&&auth.currentUser?(loadCompletedQuests(auth.currentUser.uid),_loadWeeklyCompleted()):setTimeout(initQuests,2e3)}function _getDailyActivities(){var e=(new Date).toISOString().split("T")[0],t=safeJSON("btc_daily_activities",{});return t.date!==e&&(t={date:e,quiz:!1,trivia:!1,poll:!1,sfAwarded:!1}),t}function _markDailyActivity(e){var t=_getDailyActivities();t[e]=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(t))}function _checkDailyAllThree(){var e=_getDailyActivities();if(e.quiz&&e.trivia&&e.poll&&!e.sfAwarded){e.sfAwarded=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(e));var t=(new Date).toISOString().split("T")[0];void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({dailyAllThreeDate:t,dailyQuizDone:!0,dailyTriviaDone:!0,dailyPollDone:!0}).catch(function(){}),"function"==typeof window.contributeSatoshiFavor&&window.contributeSatoshiFavor("daily_all_three")}}async function loadCompletedQuests(e){if(db)try{const t=await db.collection("users").doc(e).get();t.exists&&t.data().completedQuests&&(t.data().completedQuests.forEach(e=>completedQuests.add(e)),questCount=completedQuests.size)}catch(e){}}function onChannelVisitForQuest(e){visitedForQuest.includes(e)||visitedForQuest.push(e);const t=visitedForQuest.length;for(const e of QUEST_TRIGGERS)if(t===e&&!currentQuest){setTimeout(()=>{"function"==typeof showToast&&showToast("⚡ You have explored "+e+" channels! A Quest is ready!"),setTimeout(()=>generateAndShowQuest(),3e3)},2e3);break}}function generateAndShowQuest(e,t,o){var n=(new Date).toISOString().split("T")[0],i=safeJSON("btc_quest_daily",{});if(i.date!==n&&(i={date:n,count:0}),i.count>=1&&!o)return void(e&&"function"==typeof showToast&&showToast("⏰ You've completed your daily quiz! Go to Quiz Quests to retake it for a perfect score."));const a=safeJSON("btc_asked_questions",[]);let r=[];if(t&&QUESTION_BANK[t]&&QUESTION_BANK[t].forEach(e=>r.push({...e,source:t})),!t){for(const e of visitedForQuest){const t=QUESTION_BANK[e];t&&t.forEach(t=>r.push({...t,source:e}))}if(QUESTION_BANK._general&&QUESTION_BANK._general.forEach(e=>r.push({...e,source:"_general"})),r.length<5)for(const[e,t]of Object.entries(QUESTION_BANK))if(t.forEach(t=>{r.some(e=>e.q===t.q)||r.push({...t,source:e})}),r.length>=10)break}var s=t?Math.min(3,r.length):5;if(r.length!a.includes(e.q));function l(e){for(var t=e.q.toLowerCase(),o=[[/nostr/i,"nostr"],[/lightning/i,"lightning"],[/halving/i,"halving"],[/mining/i,"mining"],[/node/i,"node"],[/wallet/i,"wallet"],[/seed.?phrase/i,"seed"],[/private.?key/i,"privkey"],[/satoshi/i,"satoshi"],[/block.?chain/i,"blockchain"],[/proof.?of.?work/i,"pow"],[/fud\b/i,"fud"],[/self.?custody/i,"custody"],[/etf/i,"etf"],[/taproot/i,"taproot"],[/difficulty/i,"difficulty"],[/mempool/i,"mempool"],[/hash.?rate/i,"hashrate"],[/white.?paper/i,"whitepaper"],[/21.?million/i,"21m"],[/inflation/i,"inflation"],[/kyc/i,"kyc"],[/privacy/i,"privacy"],[/multisig/i,"multisig"],[/dca|dollar.cost/i,"dca"],[/el.?salvador/i,"elsalvador"]],n=0;nMath.random()-.5);var d=t?Math.min(c.length,5):5,u=[],p={};if(t)for(var m=0;me.q)];localStorage.setItem("btc_asked_questions",JSON.stringify(y));const v=u.map(e=>{const t=[e.a,...e.wrong].sort(()=>Math.random()-.5),o=t.indexOf(e.a);return{q:e.q,options:t,answer:o}});currentQuest={id:f,topicKey:t||null,title:getQuestTitle(questCount,t),questions:v},window._currentQuestServerId=null,"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("startQuest")({questions:v.map(function(e){return{answer:e.answer}}),topicKey:t||null}).then(function(e){window._currentQuestServerId=e.data.questId}).catch(function(e){console.warn("Quest registration failed:",e)}),showQuest(currentQuest,!1)}function getQuestTitle(e,t){if(t&&"_general"!==t){var o={mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",energy:"🔋",cryptography:"🔐",consensus:"🤝",regulation:"⚖️",maximalism:"🔥","difficulty-adjustment":"🎯",books:"📚",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊","smart-contracts":"📝","blockchain-timechain":"⛓️","pow-vs-pos":"⚔️","evidence-against-alts":"⚠️",organic:"🌳",peaceful:"☮️",supranational:"🔔"},n=t.replace(/_pt\d+$/,""),i=o[t]||o[n]||"⚡",a=t.replace(/_pt(\d+)$/,"").replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),r=t.match(/_pt(\d+)$/);return r&&(a+=" (Part "+r[1]+")"),i+" "+a+" Quest"}const s=["₿ Bitcoin Basics Quest","⚡ Lightning Learner Quest","🔒 Security Scholar Quest","💰 Economics Expert Quest","⛓ Technical Titan Quest","🟠 Culture Connoisseur Quest","🛡️ Sovereignty Sage Quest","👑 Satoshi Scholar Quest"];return s[e%s.length]}function playWarriorDrum(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const t=new(window.AudioContext||window.webkitAudioContext),o="undefined"!=typeof audioVolume?audioVolume:.5,n=t.currentTime;function e(e){const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.type="sine",i.frequency.setValueAtTime(150,n+e),i.frequency.exponentialRampToValueAtTime(60,n+e+.15),a.gain.setValueAtTime(.7*o,n+e),a.gain.exponentialRampToValueAtTime(.001,n+e+.4),i.start(n+e),i.stop(n+e+.4);const r=t.createOscillator(),s=t.createGain();r.connect(s),s.connect(t.destination),r.type="sine",r.frequency.setValueAtTime(80,n+e),r.frequency.exponentialRampToValueAtTime(50,n+e+.3),s.gain.setValueAtTime(.5*o,n+e),s.gain.exponentialRampToValueAtTime(.001,n+e+.5),r.start(n+e),r.stop(n+e+.5);const c=Math.floor(.08*t.sampleRate),l=t.createBuffer(1,c,t.sampleRate),d=l.getChannelData(0);for(let e=0;e",i+="

    "+(t?"Retry! Get 3+ correct for 25 XP!":"Answer 5 questions. 3+ correct = 50 XP. All 5 = 100 XP!")+"

    ",i+="",i+='
    ',e.questions.forEach((e,t)=>{i+='
    ',i+='
    Question '+(t+1)+" of 5
    ",i+='
    '+e.q+"
    ",i+='
    ',e.options.forEach((e,o)=>{i+='"}),i+="
    "}),i+="
    ",i+='',i+='',n.innerHTML=i,o.classList.add("open"),window._questAnswers=new Array(5).fill(-1),window._questCorrect=e.questions.map(e=>e.answer)}function selectAnswer(e,t,o){e.parentElement.querySelectorAll(".quest-opt").forEach(e=>e.classList.remove("selected")),e.classList.add("selected"),window._questAnswers[t]=o,window._questAnswers.every(e=>e>=0)&&(document.getElementById("questSubmitBtn").disabled=!1)}async function submitQuest(){if(window._questSubmitted)return;window._questSubmitted=!0;var e=document.getElementById("questSubmitBtn");e&&(e.disabled=!0,e.style.opacity="0.5",e.textContent="Grading...");const t=window._questAnswers,o=window._questCorrect;let n=0,i=0;if(window._currentQuestServerId&&"undefined"!=typeof firebase&&firebase.functions)try{var a=await firebase.functions().httpsCallable("gradeQuest")({questId:window._currentQuestServerId,answers:t,isRetry:!!isRetry});n=a.data.score,i=a.data.pts}catch(e){console.error("Server quest grading failed, falling back:",e),t.forEach((e,t)=>{e===o[t]&&n++})}else t.forEach((e,t)=>{e===o[t]&&n++});document.querySelectorAll(".quest-q").forEach((e,n)=>{e.querySelectorAll(".quest-opt").forEach((e,i)=>{e.disabled=!0,i===o[n]&&e.classList.add("correct"),i===t[n]&&i!==o[n]&&e.classList.add("wrong")})});let r="";var s=5===n,c=!!currentQuest.topicKey;if(isRetry)n>=3?(i||(i=25),r="🎉 "+n+"/5 correct on retry! +"+i+" XP!",!s&&c||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 — Better luck next time! Keep reading and try again.";else if(s){if(i||(i=100),r="🏆 PERFECT! 5/5! +"+i+" XP!",completedQuests.add(currentQuest.id),questCount++,"function"==typeof window.nachoGlobalAnnounce&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var l=void 0!==currentUser&¤tUser&¤tUser.username||auth.currentUser.displayName||"A mystery Bitcoiner",d=currentQuest.title||"a Quiz Quest";window.nachoGlobalAnnounce("🏆 @"+l+" just aced "+d+" with a PERFECT 5/5! Think you can do the same? ➡️ [Quest Hub](#quests)",auth.currentUser.uid)}}else n>=3?(i||(i=50),r="🎉 "+n+"/5 correct! +"+i+" XP!",c||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 — You can retry for 25 XP!";if(i>0){"function"==typeof notifySelfQuest&¬ifySelfQuest(currentQuest.title),"function"==typeof notifySelfPoints&¬ifySelfPoints(i,"🏆 Quest: "+(currentQuest.title||"Quest")),"function"==typeof window._raidOnQuizComplete&&window._raidOnQuizComplete(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(i);var u=(new Date).toISOString().split("T")[0],p=safeJSON("btc_quest_daily",{});p.date!==u&&(p={date:u,count:0}),p.count++,p.lastScore=n,p.lastTopic=currentQuest.topicKey||null,p.lastTitle=currentQuest.title||null,localStorage.setItem("btc_quest_daily",JSON.stringify(p)),_markDailyActivity("quiz"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({questsCompletedToday:p.count||0,lastQuestDate:u}).catch(function(e){console.error("Quest sync failed:",e)})}try{completedQuests.has(currentQuest.id)&&void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&(await db.collection("users").doc(auth.currentUser.uid).update({completedQuests:firebase.firestore.FieldValue.arrayUnion(currentQuest.id)}),db.collection("stats").doc("global").set({questsCompleted:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){}))}catch(e){console.error("Quest completion sync failed:",e)}const m=document.getElementById("questSubmitBtn");m&&(m.style.display="none");const g=document.querySelector(".quest-skip");g&&(g.style.display="none"),window._questScore=n,window._questMsg=r,window._questPts=i;const h=document.querySelector(".quest-header");h&&(h.innerHTML='
    ⚡ QUEST COMPLETE

    '+currentQuest.title+'

    '+(5===n?"🏆":n>=3?"🎉":"😅")+'
    '+n+' / 5 Correct
    Review your answers below — green is correct, red is wrong
    ');const f=document.getElementById("questInner");f&&f.scrollTo({top:0,behavior:"smooth"}),"function"==typeof showToast&&showToast(r)}function playHooraySound(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const e=new(window.AudioContext||window.webkitAudioContext),t="undefined"!=typeof audioVolume?audioVolume:.5,o=e.currentTime;[523,659,784,1047].forEach((n,i)=>{const a=e.createOscillator(),r=e.createGain();a.connect(r),r.connect(e.destination),a.type="sine",a.frequency.value=n,r.gain.setValueAtTime(.15*t,o+.1*i),r.gain.exponentialRampToValueAtTime(.001,o+.1*i+.4),a.start(o+.1*i),a.stop(o+.1*i+.4);const s=e.createOscillator(),c=e.createGain();s.connect(c),c.connect(e.destination),s.type="triangle",s.frequency.value=2*n,c.gain.setValueAtTime(.06*t,o+.1*i),c.gain.exponentialRampToValueAtTime(.001,o+.1*i+.3),s.start(o+.1*i),s.stop(o+.1*i+.3)}),[1047,1319,1568].forEach(n=>{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.type="sine",i.frequency.value=n,a.gain.setValueAtTime(.12*t,o+.45),a.gain.linearRampToValueAtTime(.1*t,o+.7),a.gain.exponentialRampToValueAtTime(.001,o+1.3),i.start(o+.45),i.stop(o+1.3)})}catch(e){}}function _resolveQuestChannel(e){if(!e||void 0===CHANNELS)return null;if(CHANNELS[e])return e;var t=e.replace(/_pt\d+$/,"");if(CHANNELS[t])return t;var o={cycles:"cyles",dlcs:"discrete_log_contracts__dlcs",first_principles:"1_first_principles",foss:"free_and_open_source_software__foss",ordinals_inscriptions:"ordinals",spv:"simplified_payment_verification__spv",halving:"scarce","el-salvador":"regulation"};if(o[e]&&CHANNELS[o[e]])return o[e];if(o[t]&&CHANNELS[o[t]])return o[t];for(var n=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper"],i=0;i=3&&playHooraySound();const n=document.querySelector(".quest-questions");n&&(n.style.display="none");var i=_resolveQuestChannel(currentQuest?currentQuest.topicKey:null);if(!i&&void 0!==CHANNELS){var a=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper","cryptography","philosophy","energy","nodes"].filter(function(e){return!!CHANNELS[e]}).sort(function(){return Math.random()-.5});a.length&&(i=a[0])}var r="";if(i&&void 0!==CHANNELS&&CHANNELS[i]){var s=CHANNELS[i].title;r='
    '+(currentQuest&¤tQuest.topicKey&&_resolveQuestChannel(currentQuest.topicKey)?5===e?"📚 Keep learning":"📖 Study up on":"🔍 Explore next")+'
    '+s+" →
    "}const c=document.querySelector(".quest-header");c&&(c.innerHTML='
    ⚡ QUEST COMPLETE

    '+currentQuest.title+'

    '+(5===e?"🏆":e>=3?"🎉":"😅")+'
    '+e+' / 5 Correct
    '+t+"
    "+(o>0?'
    +'+o+" XP earned!
    ":"")+r+(e<5?'":"")+'');const l=document.getElementById("questInner");l&&(l.scrollTop=0)}function retryQuest(){currentQuest.questions.forEach(e=>{const t=e.options[e.answer];e.options.sort(()=>Math.random()-.5),e.answer=e.options.indexOf(t)}),showQuest(currentQuest,!0)}function startQuestManual(e){if(!currentQuest)if(e){if(generateAndShowQuest(!0,e),"function"==typeof isMobile&&isMobile()){const e=document.getElementById("sidebar");e&&e.classList.remove("open")}}else _showQuestTopicPicker()}function _getDailyRecommendedQuiz(e){if(!e||0===e.length)return null;for(var t=e.map(function(e){return e.key}).sort(),o=t.length,n=new Date("2026-01-01T00:00:00Z").getTime(),i=(new Date).toISOString().split("T")[0],a=new Date(i+"T00:00:00Z").getTime(),r=Math.floor((a-n)/864e5),s=r%o,c=Math.floor(r/o),l=t.slice(),d=7919*c+31337,u=l.length-1;u>0;u--){var p=(d=(16807*d+0)%2147483647)%(u+1),m=l[u];l[u]=l[p],l[p]=m}var g=l[s];return e.find(function(e){return e.key===g})||null}function _showQuestTopicPicker(){var e=[],t={_general:"🌐",mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜","satoshi-nakamoto":"🧩",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",philosophy:"🤔",energy:"🔋",cryptography:"🔐",consensus:"🤝",taproot:"🌳",regulation:"⚖️",maximalism:"🔥",utxos:"📦","difficulty-adjustment":"🎯",transaction_fees:"💳",game_theory:"♟️",books:"📚","orange-pilling":"🍊",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊",geopolitics___macroeconomics:"🌎",human_rights__social_justice_and_freedo:"✊","smart-contracts":"📝",sidechains:"🔗",stablecoins:"🏦",fedimints:"🏛️","pow-vs-pos":"⚔️","blockchain-timechain":"⛓️",softwar:"🪖",time_preference:"⏳",governance:"🏛️","apps-tools":"🧰","misconceptions-fud":"🚫",elevator_pitches:"🗣️"};for(var o in QUESTION_BANK)if("_general"!==o){var n=QUESTION_BANK[o];if(n&&!(n.length<3)){var i=o.replace(/_pt(\d+)$/,"").replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),a=o.match(/_pt(\d+)$/);a&&(i+=" (Part "+a[1]+")");var r=o.replace(/_pt\d+$/,""),s=t[o]||t[r]||"📖",c=completedQuests.has("quest_"+o)||completedQuests.has(o)||-1!==weeklyCompleted.indexOf(o);e.push({key:o,label:i,emoji:s,count:n.length,done:c})}}e.sort(function(e,t){return e.done!==t.done?e.done?1:-1:e.label.localeCompare(t.label)});var l=e.filter(function(e){return e.done}).length,d=document.getElementById("questModal");if(d){var u=document.getElementById("questInner");if(u){var p='

    Choose a Quest Topic

    Pick a Bitcoin topic to test your knowledge

    '+l+"/"+e.length+' topics completed
    ',m=_getDailyRecommendedQuiz(e);m&&(p+=""),p+='',p+='',p+='
    ',e.forEach(function(e){var t=e.done?"rgba(34,197,94,0.06)":"rgba(255,255,255,0.02)",o=e.done?"rgba(34,197,94,0.2)":"var(--border)",n=e.done?'':''+e.count+"Q";p+=""}),p+="
    ",p+='',u.innerHTML=p,setTimeout(function(){var e=document.querySelectorAll("#questTopicList button");e.forEach(function(e){var t=(e.getAttribute("onclick")||"").match(/_startQuestTopic\('([^']+)'\)/);t&&(e.dataset.key=t[1]),e.dataset.label=e.textContent.trim()});var t=document.getElementById("questSearch");t&&t.addEventListener("input",function(){var t=this.value.toLowerCase();e.forEach(function(e){var o=e.dataset.label.toLowerCase();e.style.display=o.includes(t)?"":"none"})})},0),d.classList.add("open")}}}function skipQuest(){closeQuest()}function closeQuest(){document.getElementById("questModal").classList.remove("open"),currentQuest=null,isRetry=!1}function _renderFavorTab(e){if(e){var t="function"==typeof window._resolveFavorState?window._resolveFavorState():null,o=t&&t.favorActive,n=t&&t.points||0,i=Math.min(100,n/21*100),a='
    ✨⛏️
    Satoshi\'s Favor
    Community mining when the community earns 21 points.
    Chance to win 21,000 sats! ⚡
    ';if(o){var r=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();a+='
    🎉 SATOSHI\'S FAVOR IS ACTIVE!
    '+Math.floor(r/6e4)+"m "+Math.floor(r%6e4/1e3)+'s
    Mine below 1,000 to win 21,000 sats!
    ',a+=''}else a+='
    '+n+'/21 points
    '+(21-n)+" more points to activate
    ";if(a+='
    How it works:
    This is a community challenge — everyone\'s points combine!

    • Complete 3 daily quiz quests = 1 point
    • Earn a badge = 1 point
    • Level up to Pleb/Stacker ranks = 1 point each
    • Level up to Maxi ranks = 5 points each
    • Level up to Papa John or higher = 10 points
    • At 21 points, a mining competition opens for 60 minutes
    • Extra points beyond 21 add +3 min each (even while active!)
    • 10 hashes max per minute per user (60 second cooldown)
    • Generate a random hash. Below 1,000 = win 21,000 sats!',a+='
    🏆 All-Time Lowest Hashes
    Loading...
    ',a+='
    ⭐ Your Personal Best
    Loading...
    ',a+="
    ",e.innerHTML=a,_loadFavorLeaderboards(),o){var s=document.getElementById("favorTabTimer");if(s)var c=setInterval(function(){if(s){if(!t||!t.favorActive)return s.textContent="EXPIRED",void clearInterval(c);var e=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();if(e<=0)s.textContent="00:00";else{var o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);s.textContent=o+"m "+n+"s"}}else clearInterval(c)},1e3)}}}window._retakeLastQuiz=function(){var e=safeJSON("btc_quest_daily",{}).lastTopic||null,t=document.getElementById("questHubOverlay");t&&t.remove(),setTimeout(function(){generateAndShowQuest(!0,e,!0)},200)},window._startQuestTopic=function(e){var t=document.getElementById("questModal");if(t&&t.classList.remove("open"),currentQuest=null,!e){var o=[];for(var n in QUESTION_BANK)"_general"!==n&&(QUESTION_BANK[n].length<3||completedQuests.has("quest_"+n)||completedQuests.has(n)||-1!==weeklyCompleted.indexOf(n)||o.push(n));if(o.length>0)e=o[Math.floor(Math.random()*o.length)];else{var i=Object.keys(QUESTION_BANK).filter(function(e){return"_general"!==e&&QUESTION_BANK[e].length>=3});e=i[Math.floor(Math.random()*i.length)]}}setTimeout(function(){generateAndShowQuest(!0,e)},200)},setTimeout(initQuests,3e3),window.closeQuestHubForFavor=function(){var e=document.getElementById("questHubOverlay");e&&e.remove(),window._cleanupRaidBoss&&window._cleanupRaidBoss()};var _favorTopHashesUnsub=null,_favorPBUnsub=null;function _renderTopHashesHTML(e){for(var t=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null,o="",n=0;n
    '+s+''+(l?"🏆 ":"")+c+(a?" (you)":"")+'
    '+i.value.toLocaleString()+"
    "}return o}function _renderPBHTML(e){var t=e<1e3;return'
    '+(t?"🏆 ":"")+e.toLocaleString()+'
    Your all-time lowest hash
    '}function _loadFavorLeaderboards(){if(void 0!==db){_favorTopHashesUnsub&&(_favorTopHashesUnsub(),_favorTopHashesUnsub=null),_favorPBUnsub&&(_favorPBUnsub(),_favorPBUnsub=null),_favorTopHashesUnsub=db.collection("satoshiFavor").doc("topHashes").onSnapshot(function(e){var t=document.getElementById("favorTopHashes");t&&(e.exists&&e.data().entries&&0!==e.data().entries.length?t.innerHTML=_renderTopHashesHTML(e.data().entries):t.innerHTML='
    No hashes yet. Be the first to mine!
    ')},function(){var e=document.getElementById("favorTopHashes");e&&(e.innerHTML='
    Could not load leaderboard
    ')});var e=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null;if(e){var t=!1;_favorPBUnsub=db.collection("satoshiFavor").doc("personalBests").collection("users").doc(e).onSnapshot(function(o){var n=document.getElementById("favorPersonalBest");n&&(o.exists?n.innerHTML=_renderPBHTML(o.data().value):t?n.innerHTML='
    No hashes yet. Start mining!
    ':(t=!0,db.collection("satoshiFavor").doc("personalBests").get().then(function(t){if(n=document.getElementById("favorPersonalBest"))if(t.exists){var o=(t.data().users||{})[e];n.innerHTML=o?_renderPBHTML(o.value):'
    No hashes yet. Start mining!
    '}else n.innerHTML='
    No hashes yet. Start mining!
    '}).catch(function(){})))},function(){var e=document.getElementById("favorPersonalBest");e&&(e.innerHTML='
    Could not load personal best
    ')})}else{var o=document.getElementById("favorPersonalBest");o&&(o.innerHTML='
    Sign in to track your personal best
    ')}}}function _renderQuestHubTab(){var e=window._questHubTab||"quiz";["Quiz","Trivia","Poll","Raid","Favor","Charity"].forEach(function(t){var o=document.getElementById("qhTab"+t);if(o){var n=e===t.toLowerCase(),i="Raid"===t&&n,a="Charity"===t&&n;o.style.background=i?"linear-gradient(135deg,#8b5cf6,#7c3aed)":a?"linear-gradient(135deg,#ef4444,#dc2626)":n?"var(--accent)":"none",o.style.color=n?"#fff":"var(--text-muted)",o.style.borderColor=i?"#8b5cf6":a?"#ef4444":n?"var(--accent)":"var(--border)"}});var t=document.getElementById("questHubBody");t&&("raid"!==e&&window._cleanupRaidBoss(),"quiz"===e?_renderQuizTab(t):"trivia"===e?_renderTriviaTab(t):"poll"===e?_renderPollTab(t):"raid"===e?_renderRaidTab(t):"favor"===e?_renderFavorTab(t):"charity"===e&&_renderCharityTab(t))}void 0!==startQuestManual&&(window.startQuestManual=startQuestManual),void 0!==selectAnswer&&(window.selectAnswer=selectAnswer),void 0!==submitQuest&&(window.submitQuest=submitQuest),void 0!==skipQuest&&(window.skipQuest=skipQuest),void 0!==closeQuest&&(window.closeQuest=closeQuest),void 0!==showQuest&&(window.showQuest=showQuest),void 0!==generateAndShowQuest&&(window.generateAndShowQuest=generateAndShowQuest),void 0!==_showQuestTopicPicker&&(window._showQuestTopicPicker=_showQuestTopicPicker),void 0!==showQuestFinalResults&&(window.showQuestFinalResults=showQuestFinalResults),void 0!==retryQuest&&(window.retryQuest=retryQuest),void 0!==_renderQuestHubTab&&(window._renderQuestHubTab=_renderQuestHubTab),window._questHubTab="quiz",window.showQuestHub=function(){window._chatOverlayOpen&&"function"==typeof toggleChatOverlay&&toggleChatOverlay();var e=document.getElementById("questHubOverlay");e&&e.remove();var t=document.createElement("div");t.id="questHubOverlay",t.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.88);z-index:100000;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(5px);padding:20px;animation:nachoPop 0.25s ease;",t.onclick=function(e){e.target===t&&(window._cleanupRaidBoss(),t.remove())};var o=document.createElement("div");o.style.cssText="background:var(--bg-side,#141425);border:1px solid var(--border);width:100%;max-width:520px;max-height:85vh;border-radius:24px;overflow:hidden;display:flex;flex-direction:column;position:relative;";var n=document.createElement("div");n.style.cssText="padding:20px 24px 0;flex-shrink:0;",n.innerHTML='

    ⚔️ Quest Hub

    Earn XP by testing your Bitcoin knowledge
    ';var i=document.createElement("div");i.id="questHubBody",i.style.cssText="padding:0 24px 24px;overflow-y:auto;flex:1;",o.appendChild(n),o.appendChild(i),t.appendChild(o),document.body.appendChild(t),_renderQuestHubTab()};var _charityStats=null,_charityRecent=[],_charityStatsLoaded=!1;function _loadCharityStats(e){if("undefined"==typeof firebase||!firebase.firestore)return e&&e();var t=firebase.firestore();Promise.all([t.collection("charity_stats").doc("global").get({source:"server"}),t.collection("charity_donations").orderBy("ts","desc").limit(10).get({source:"server"})]).then(function(t){var o=t[0],n=t[1];_charityStats=o.exists?o.data():{totalDonated:0,factionTotals:{}},_charityRecent=[],n.forEach(function(e){_charityRecent.push(e.data())}),_charityStatsLoaded=!0,e&&e()}).catch(function(){e&&e()})}function _renderCharityTab(e){e.innerHTML='
    Loading charity data...
    ',_loadCharityStats(function(){_renderCharityTabInner(e)})}function _renderCharityTabInner(e){var t="function"==typeof escapeHtml?escapeHtml:function(e){return String(e||"").replace(//g,">")},o=void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous,n=void 0!==currentUser&¤tUser&¤tUser.faction||"",i=void 0!==currentUser&¤tUser&¤tUser.points||0,a=void 0!==currentUser&¤tUser&¤tUser.pointsClaimed||0,r=void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,s=Math.max(0,i-a-r),c=_charityStats||{totalDonated:0,factionTotals:{}},l=c.totalDonated||0,d=c.factionTotals&&c.factionTotals.cyber_hornets||0,u=c.factionTotals&&c.factionTotals.honey_badgers||0,p="";p+='
    ❤️
    Donate XP for Charity
    1,000 XP = 1,000 sats donated — 10× more impact than redeeming for yourself
    ',p+='
    🌍 Community Pledge
    '+l.toLocaleString()+' sats pledged
    ('+l.toLocaleString()+" XP donated by the community)
    ";var m=d+u,g=m>0?Math.round(d/m*100):50,h=100-g;p+='
    ⚔️ Faction Giving
    🐝 Cyber Hornets🦡 Honey Badgers
    '+d.toLocaleString()+" XP ("+g+"%)"+u.toLocaleString()+" XP ("+h+"%)
    ",o?n?(p+='
    🎡 Your Donation
    Available to donate: '+s.toLocaleString()+" XP"+(r>0?' ('+r.toLocaleString()+" already donated)":"")+"
    ",p+='
    ',[5,10,25,50,100].forEach(function(e){var t=Math.floor(s*e/100);p+='"}),p+="
    ",p+='
    ',p+='
    ',p+='',p+="
    "):p+="
    ⚔️
    Choose Your Faction First
    Your faction's donation total is tracked for the community leaderboard. Join a side before you donate!
    ":p+='
    🔐 Sign in to donate XP for charity
    ',_charityRecent.length>0&&(p+='
    📜 Recent Donations
    ',_charityRecent.forEach(function(e){var o,n=e.anonymous||!e.uid||"Anonymous"===(e.username||""),i="cyber_hornets"===e.faction?'🐝':"honey_badgers"===e.faction?'🦡':"";o=n?"color:var(--text-muted);":"cyber_hornets"===e.faction?"color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,1px 1px 0 #000,-1px 1px 0 #000;font-weight:700;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;":"honey_badgers"===e.faction?"color:#e5e7eb;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,1px 1px 0 #000,-1px 1px 0 #000;font-weight:700;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;":"color:var(--text);font-weight:600;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;";var a=n?''+t(e.username||"Anonymous")+"":''+t(e.username||"Anonymous")+"";p+='
    '+i+" "+a+'+'+(e.amount||0).toLocaleString()+" XP
    "}),p+="
    "),p+='
    🗳️ Community Charity Vote
    Coming soon — the community will vote on which charities receive our pledged sats. Focused on Bitcoin education and adoption, but not limited to it.
    ',p+="

    Our community will vote on which charities our contributions go to. In Bitcoin, the charities will focus on Bitcoin education and adoption — but our donations are not limited to the Bitcoin ecosystem. We can find charities outside of Bitcoin that we want to support as a community.

    ⚠️ Donations are non-refundable. Donated XP cannot be reclaimed or reversed. Donations are a community pledge and are not tax-deductible. This is not a registered charitable organization and no tax receipts are issued.

    ",p+='
    🏅 Donation Badges
    ';var f="function"==typeof safeJSON?safeJSON("btc_hidden_badges",[]):[];[{id:"donor_100",emoji:"🫷",name:"Giving Pleb",thresh:"100 XP",reward:"50 XP"},{id:"donor_500",emoji:"💛",name:"Stack Sharer",thresh:"500 XP",reward:"150 XP"},{id:"donor_1000",emoji:"🧡",name:"Community Builder",thresh:"1,000 XP",reward:"300 XP"},{id:"donor_5000",emoji:"❤️",name:"Archive Patron",thresh:"5,000 XP",reward:"1,000 XP"},{id:"donor_10000",emoji:"🔥",name:"Sats Saint",thresh:"10,000 XP",reward:"2,000 XP"},{id:"donor_25000",emoji:"⚡",name:"Lightning Philanthropist",thresh:"25,000 XP",reward:"4,000 XP"},{id:"donor_50000",emoji:"🏆",name:"Satoshi's Steward",thresh:"50,000 XP",reward:"7,500 XP"},{id:"donor_100000",emoji:"👑",name:"Legend of the Archive",thresh:"100,000 XP",reward:"15,000 XP"}].forEach(function(e){var t=f.includes(e.id)||void 0!==currentUser&¤tUser&&Array.isArray(currentUser.donationBadges)&¤tUser.donationBadges.includes(e.id);p+='
    '+e.emoji+'
    '+e.name+'
    '+e.thresh+' donated
    +'+e.reward+" reward
    "}),p+="
    ",e.innerHTML=p,window._charitySetAmount=function(e){var t=document.getElementById("charityAmtInput");t&&(t.value=e>0?e:"")},window._submitCharityDonation=function(){if("undefined"!=typeof firebase&&firebase.functions){var e=document.getElementById("charityAmtInput"),t=parseInt(e?e.value:"")||0;if(!t||t<1)"function"==typeof showToast&&showToast("Enter a valid amount");else{var o=Math.max(0,void 0!==currentUser&¤tUser?(currentUser.points||0)-(currentUser.pointsClaimed||0)-(currentUser.pointsDonated||0):0);if(t>o)"function"==typeof showToast&&showToast("Not enough available XP. You have "+o.toLocaleString()+" pts available.");else{var n=!!document.getElementById("charityAnonToggle")&&document.getElementById("charityAnonToggle").checked,i=document.querySelector('[onclick="window._submitCharityDonation()"]');i&&(i.disabled=!0,i.textContent="Donating..."),firebase.functions().httpsCallable("donatePoints")({amount:t,anonymous:n}).then(function(e){void 0!==currentUser&¤tUser&&(currentUser.pointsDonated=(currentUser.pointsDonated||0)+t,e.data&&e.data.bonusPts&&(currentUser.points=(currentUser.points||0)+e.data.bonusPts));var o=e.data&&e.data.newBadges||[],n=o.length>0?" You earned "+o.length+" new badge"+(o.length>1?"s":"")+"!":"";if("function"==typeof showToast&&showToast("❤️ Thank you! "+t.toLocaleString()+" XP donated ("+t.toLocaleString()+" sats pledged to charity)."+n,5e3),window._charityThankYou(t,o,e.data&&e.data.bonusPts||0),o.length>0&&"function"==typeof window.contributeSatoshiFavor){var i={donor_100:{emoji:"🫷",name:"Giving Pleb"},donor_500:{emoji:"💛",name:"Stack Sharer"},donor_1000:{emoji:"🧡",name:"Community Builder"},donor_5000:{emoji:"❤️",name:"Archive Patron"},donor_10000:{emoji:"🔥",name:"Sats Saint"},donor_25000:{emoji:"⚡",name:"Lightning Philanthropist"},donor_50000:{emoji:"🏆",name:"Satoshi's Steward"},donor_100000:{emoji:"👑",name:"Legend of the Archive"}};o.forEach(function(e){var t=i[e];t&&window.contributeSatoshiFavor("badge_earned",t.emoji+" "+t.name).catch(function(){})})}_charityStatsLoaded=!1,_renderCharityTab(document.getElementById("questHubBody"))}).catch(function(e){i&&(i.disabled=!1,i.textContent="❤️ Donate XP for Charity"),"function"==typeof showToast&&showToast("❌ "+(e.message||"Donation failed. Try again."),4e3)})}}}else"function"==typeof showToast&&showToast("Firebase not ready")}}function _renderQuizTab(e){var t=(new Date).toISOString().split("T")[0],o=safeJSON("btc_quest_daily",{}),n=o.date===t?o.count:0,i=completedQuests?completedQuests.size:0,a=o.date===t&&n>=1&&o.lastScore&&o.lastScore<5,r="";if(a){o.lastTopic&&o.lastTopic.replace(/['\\]/g,"");var s=o.lastTitle||"your last quiz";r='
    🔄 You scored '+o.lastScore+"/5 on "+("function"==typeof escapeHtml?escapeHtml(s):s)+'
    Retake it to get a perfect score! +25 XP for improvement
    '}e.innerHTML='
    📝
    Quiz Quests
    1 daily quiz — retake until you ace it!
    '+n+'
    Today
    '+i+'
    All Time
    3+ correct = 50 XP
    Perfect = 100 XP
    '+r+"
    "}function _getTriviaToday(){if("undefined"==typeof TRIVIA_BANK||!TRIVIA_BANK||!TRIVIA_BANK.length)return null;var e=new Date,t=new Date(e.getFullYear(),0,0),o=(7*Math.floor((e-t)/864e5)+e.getFullYear())%TRIVIA_BANK.length;return{index:o,trivia:TRIVIA_BANK[o]}}function _getTriviaState(){try{return JSON.parse(localStorage.getItem("btc_trivia_state")||"{}")}catch(e){return{}}}function _setTriviaState(e){try{localStorage.setItem("btc_trivia_state",JSON.stringify(e))}catch(e){}}function _renderTriviaTab(e){var t=_getTriviaToday();if(t&&t.trivia){var o=_getTriviaState(),n=(new Date).toISOString().split("T")[0],i=o.date===n,a=t.trivia,r='
    🧠
    Trivia Quest
    1 new question every day
    +50 XP correct · +10 XP for trying
    ';r+='
    '+("function"==typeof escapeHtml?escapeHtml(a.q):a.q)+"
    ",r+='
    ';for(var s=0;s
    '+String.fromCharCode(65+s)+''+c+''+(p?''+p+"":"")+"
    "}else r+='"}r+="",i&&void 0!==db&&db.collection("trivia_stats").doc(n).get().then(function(e){var t=e.exists?e.data():{},o=t.total||0;if(!(o<1))for(var n=0;n
    💡 Explanation
    '+("function"==typeof escapeHtml?escapeHtml(a.explanation):a.explanation)+"
    ",r+='
    Come back tomorrow for a new trivia question! 🧠
    '),e.innerHTML=r}else e.innerHTML='
    Trivia questions loading...
    '}function _getPollToday(){if("undefined"==typeof POLL_BANK||!POLL_BANK||!POLL_BANK.length)return null;var e=new Date,t=new Date(e.getFullYear(),0,0),o=(13*Math.floor((e-t)/864e5)+e.getFullYear())%POLL_BANK.length;return{index:o,poll:POLL_BANK[o]}}function _getPollState(){try{return JSON.parse(localStorage.getItem("btc_poll_state")||"{}")}catch(e){return{}}}function _setPollState(e){try{localStorage.setItem("btc_poll_state",JSON.stringify(e))}catch(e){}}function _renderPollTab(e){var t=_getPollToday();if(t&&t.poll){var o=_getPollState(),n=(new Date).toISOString().split("T")[0],i=o.date===n&&"number"==typeof o.chosen,a=t.poll,r='
    📊
    Poll Quest
    Vote daily — see what the community thinks
    +50 XP for voting
    ';if(r+='
    '+("function"==typeof escapeHtml?escapeHtml(a.q):a.q)+"
    ",i)_renderPollResults(e,r,a,o,n);else{var s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null,c=a.id||"poll_day_"+n;s&&void 0!==db?db.collection("poll_votes").doc(c).get().then(function(i){if(i.exists&&i.data().voters&&-1!==i.data().voters.indexOf(s)){var c=o.chosen;_setPollState(o={date:n,index:t.index,chosen:"number"==typeof c?c:-1,pollId:a.id}),_renderPollResults(e,r,a,o,n)}else _showPollVoteButtons(e,r,a)}).catch(function(){_showPollVoteButtons(e,r,a)}):_showPollVoteButtons(e,r,a)}}else e.innerHTML='
    Polls loading...
    '}function _showPollVoteButtons(e,t,o){t+='
    ';for(var n=0;n'+String.fromCharCode(65+n)+""+i+""}t+="
    ",e.innerHTML=t}function _renderPollResults(e,t,o,n,i){var a=o.id||"poll_day_"+i;void 0!==db?db.collection("poll_votes").doc(a).get().then(function(i){var a=i.exists&&i.data().votes||[0,0,0,0],r=a.reduce(function(e,t){return e+t},0)||1;_drawPollResults(e,t,o,a,r,n.chosen)}).catch(function(){_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}):_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}function _drawPollResults(e,t,o,n,i,a){var r=t,s=["#f7931a","#3b82f6","#22c55e","#8b5cf6"];r+='
    ';for(var c=0;c
    '+(u?"✓":String.fromCharCode(65+c))+''+l+'
    '+d+"%
    "}r+="",r+='
    '+i+" total vote"+(1!==i?"s":"")+" · Come back tomorrow for a new poll!
    ",e.innerHTML=r}function _renderRaidTab(e){e.innerHTML='
    Loading Raid Boss...
    ',window._loadRaidBoss()}function _raidEmptyState(){return'
    ⚔️
    Raid Boss
    No active raid boss right now.
    Check back soon for community boss fights!
    '}function _raidVictoryBanner(e){var t="function"==typeof escapeHtml?escapeHtml(e.name||"Raid Boss"):e.name||"Raid Boss",o=_getRaidBossImage(e);return'
    '+(o?'
    '+t+'
    💀
    ':'
    💀
    ')+'
    BOSS DEFEATED! 🎉
    '+t+' has fallen!
    The community worked together and took it down! Great job everyone!
    🏆 Community reward unlocked!
    Extra orange ticket drawing for 21,000 satsthis Friday night!
    '}window._charityThankYou=function(e,t,o){var n=document.getElementById("charityThankYouOverlay");n&&n.remove();var i=document.createElement("div");i.id="charityThankYouOverlay",i.style.cssText="position:fixed;inset:0;z-index:300000;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;padding:20px;";var a=document.createElement("div");a.style.cssText="background:var(--card-bg);border:1px solid rgba(239,68,68,0.4);border-radius:20px;padding:28px 24px;max-width:360px;width:100%;text-align:center;position:relative;";var r='
    ❤️
    Thank You!
    You donated '+e.toLocaleString()+" XP — that's "+e.toLocaleString()+" sats pledged to charity.
    ";o>0&&(r+='
    +'+o.toLocaleString()+" bonus XP earned!
    "),t&&t.length>0&&(r+='
    🏼 New badge'+(t.length>1?"s":"")+" unlocked: "+t.join(", ")+"
    "),r+='
    The community will vote on which charities receive these sats.
    ',a.innerHTML=r,i.appendChild(a),i.addEventListener("click",function(e){e.target===i&&i.remove()}),document.body.appendChild(i)},window._renderCharityHome=function(){var e=document.getElementById("charityDonateHome");e&&"undefined"!=typeof firebase&&firebase.firestore&&firebase.firestore().collection("charity_stats").doc("global").get().then(function(t){var o=t.exists?t.data():{totalDonated:0,factionTotals:{}},n=o.totalDonated||0,i=o.factionTotals&&o.factionTotals.cyber_hornets||0,a=o.factionTotals&&o.factionTotals.honey_badgers||0;e.innerHTML='
    ❤️ Donate XP for Charity
    Tap to donate →
    '+n.toLocaleString()+' sats pledged
    🐝 '+i.toLocaleString()+' XP🦡 '+a.toLocaleString()+" XP
    "}).catch(function(){})},window.triviaAnswer=function(e){var t=_getTriviaToday();if(t&&t.trivia){var o=t.trivia,n=(new Date).toISOString().split("T")[0],i=_getTriviaState();if(i.date!==n){var a=e===o.answer,r=a?50:10;if(_setTriviaState(i={date:n,index:t.index,chosen:e,correct:a}),"function"==typeof awardPoints&&awardPoints(r,a?"🧠 Trivia Quest correct!":"🧠 Trivia Quest attempt"),a&&"function"==typeof window._raidOnTriviaCorrect&&window._raidOnTriviaCorrect(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(r),_markDailyActivity("trivia"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({lastTriviaDate:n,triviaAnswered:firebase.firestore.FieldValue.increment(1),triviaCorrect:firebase.firestore.FieldValue.increment(a?1:0)}).catch(function(){}),void 0!==db){var s={total:firebase.firestore.FieldValue.increment(1)};s["option_"+e]=firebase.firestore.FieldValue.increment(1),db.collection("trivia_stats").doc(n).set(s,{merge:!0}).catch(function(){})}var c=document.getElementById("questHubBody");c&&_renderTriviaTab(c),"function"==typeof showToast&&showToast(a?"✅ Correct! +50 XP 🧠":"❌ Wrong — +10 XP for trying!",3e3)}}},window.pollVote=function(e){var t=_getPollToday();if(t&&t.poll){var o=t.poll,n=(new Date).toISOString().split("T")[0],i=_getPollState();if(i.date!==n||"number"!=typeof i.chosen){var a=document.querySelectorAll("#pollOptions button");a.forEach(function(e){e.disabled=!0,e.style.opacity="0.5",e.style.cursor="default"});var r=o.id||"poll_day_"+n,s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null;if(void 0!==db&&s){var c=db.collection("poll_votes").doc(r);db.runTransaction(function(t){return t.get(c).then(function(n){var i=n.exists?n.data():{},a=i.voters||[];if(-1!==a.indexOf(s))return Promise.reject({code:"already-voted"});var l=i.votes||[0,0,0,0];l[e]=(l[e]||0)+1,a.push(s),t.set(c,{pollId:r,question:o.q,options:o.options,votes:l,voters:a,lastUpdated:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0})})}).then(function(){_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof awardPoints&&awardPoints(50,"📊 Poll Quest vote"),"function"==typeof window._raidOnPollVote&&window._raidOnPollVote(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(50),"function"==typeof showToast&&showToast("📊 Vote recorded! +50 XP",3e3),_markDailyActivity("poll"),_checkDailyAllThree(),auth.currentUser.isAnonymous||db.collection("users").doc(s).update({lastPollDate:n,pollsVoted:firebase.firestore.FieldValue.increment(1)}).catch(function(){});var a=document.getElementById("questHubBody");a&&_renderPollTab(a)}).catch(function(r){if(!r||"already-voted"!==r.code)return console.error("[POLL] Vote failed:",r),"function"==typeof showToast&&showToast("⚠️ Vote failed — try again",3e3),void a.forEach(function(e){e.disabled=!1,e.style.opacity="1",e.style.cursor="pointer"});_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("You already voted on this poll today!",3e3);var s=document.getElementById("questHubBody");s&&_renderPollTab(s)})}else{_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("📊 Vote recorded locally",3e3);var l=document.getElementById("questHubBody");l&&_renderPollTab(l)}}}},window._raidBossUnsub=null,window._raidParticipantsUnsub=null,window._raidTimerInterval=null,window._cleanupRaidBoss=function(){window._raidBossUnsub&&(window._raidBossUnsub(),window._raidBossUnsub=null),window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null),window._raidTimerInterval&&(clearInterval(window._raidTimerInterval),window._raidTimerInterval=null),window._raidDamageDealersOpen=!1},window._loadRaidBoss=function(){window._cleanupRaidBoss();var e=document.getElementById("raidBossContent");e&&(void 0!==db?window._raidBossUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.innerHTML=_raidEmptyState();else{var o=Date.now(),n=null,i=null,a=null;if(t.forEach(function(e){var t=e.data();t._id=e.id;var r=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,s=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime?i.startTime.toMillis?i.startTime.toMillis():i.startTime:0))&&(i=t):t.defeated&&(a||(a=t))}),a&&(i||n)&&!n){window._defeatedBossId=a._id;var r=_raidVictoryBanner(a);e.innerHTML=r;var s=document.createElement("div");return s.id="raidUpcomingSection",e.appendChild(s),window._currentRaidBoss=i||a,void _renderRaidBossCard(s,i)}var c=n||i||a;c?(window._currentRaidBoss=c,_renderRaidBossCard(e,c)):e.innerHTML=_raidEmptyState()}},function(t){console.error("[RAID] Boss listener error:",t),e.innerHTML='
    ⚠️ Failed to load raid boss
    '}):e.innerHTML='
    ⚠️ Database not available
    ')};var RAID_BOSS_IMAGES={"Channel-Crawler":"images/raid-bosses/channel-crawler.png","Quiz-Crusader":"images/raid-bosses/quiz-crusader.png","TV-Titan":"images/raid-bosses/tv-titan.png","Beats-Baron":"images/raid-bosses/beats-baron.png","Flash-Flash":"images/raid-bosses/flash-flash.png","XP-Hoarder":"images/raid-bosses/xp-hoarder.png","Poll-Patroller":"images/raid-bosses/poll-patroller.png","Chat-Charger":"images/raid-bosses/chat-charger.png","Badge-Builder":"images/raid-bosses/badge-builder.png","Streak-Sage":"images/raid-bosses/streak-sage.png","Topic-Explorer":"images/raid-bosses/topic-explorer.png","Lightning-Lancer":"images/raid-bosses/lightning-lancer.png","Forum-Forge":"images/raid-bosses/forum-forge.png","Trivia-Tactician":"images/raid-bosses/trivia-tactician.png","Content-Conqueror":"images/raid-bosses/content-conqueror.png"};function _getRaidBossImage(e){return e.image||RAID_BOSS_IMAGES[e.name]||""}function _renderRaidBossCard(e,t){Date.now();var o=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,n=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0,i=_getRaidBossImage(t);if(t.placeholder){var a=o?new Date(o):null,r=a?a.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"Soon",s=i?''+(t.name||':'
    ⚔️
    ';return e.innerHTML='
    '+s+'
    '+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
    '+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
    '+("function"==typeof escapeHtml?escapeHtml(r):r)+'
    Get ready to team up and take it down!
    🏆 Community Prize
    Defeat the boss = extra orange ticket giveaway for 21,000 sats!
    ',void _startRaidCountdown("raidCountdownPlaceholder",o)}if(t.defeated){var c=t.winners||[],l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null;if(l&&-1!==c.indexOf(l)&&localStorage.setItem("btc_raid_winner","true"),c.length>0)for(var d=0;d'+(t.name||
    💀
    ':'
    💀
    ';return e.innerHTML='
    '+u+'
    DEFEATED!
    '+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
    '+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
    🎉 Community reward unlocked!
    Extra orange ticket giveaway for 21,000 sats!
    ',void(window._defeatedBossId=t._id)}var p=void 0!==t.current?t.current:void 0!==t.currentHP?t.currentHP:0,m=t.target||t.targetHP||1,g=Math.min(100,Math.round(p/m*100)),h=Math.max(0,m-p),f=Math.max(0,100-g),y="function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss",v="function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"",b=i?''+y+'':'
    👹
    ';if(e.innerHTML='
    '+b+'
    '+y+'
    '+v+'
    ❤️ Boss Health'+h.toLocaleString()+" / "+m.toLocaleString()+' HP
    '+g+'% damage dealt
    ⏰ Time Remaining
    🏆 Community Prize
    Defeat the boss and the community earns an extra orange ticket giveaway for 21,000 sats!
    Loading...
    ',!document.getElementById("raidShimmerStyle")){var w=document.createElement("style");w.id="raidShimmerStyle",w.textContent="@keyframes raidShimmer{0%{transform:translateX(-100%)}100%{transform:translateX(100%)}}",document.head.appendChild(w)}_startRaidCountdown("raidTimer",n),window._raidActiveTab="current",window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),_listenRaidParticipants(t._id)}function _startRaidCountdown(e,t){function o(){var o=document.getElementById(e);if(!o)return clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var n=Math.max(0,t-Date.now());if(n<=0)return o.textContent="Time's up!",clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var i=Math.floor(n/864e5),a=Math.floor(n%864e5/36e5),r=Math.floor(n%36e5/6e4),s=Math.floor(n%6e4/1e3);o.textContent=(i>0?i+"d ":"")+(a>0?a+"h ":"")+(r<10?"0":"")+r+"m "+(s<10?"0":"")+s+"s"}window._raidTimerInterval&&clearInterval(window._raidTimerInterval),o(),window._raidTimerInterval=setInterval(o,1e3)}function _listenRaidParticipants(e){window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),void 0!==db&&(window._raidParticipantsUnsub=db.collection("raid_bosses").doc(e).collection("participants").orderBy("contributed","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t)if(e.empty)t.innerHTML='
    No raiders yet — be the first! ⚔️
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,c=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] Participants listener error:",e)}))}function _listenAllTimeRaiders(){window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),void 0!==db&&(window._raidAllTimeUnsub=db.collection("users").where("raidDamageAllTime",">",0).orderBy("raidDamageAllTime","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t&&"alltime"===window._raidActiveTab)if(e.empty)t.innerHTML='
    No all-time damage recorded yet.
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.raidDamageAllTime||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,c=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] All-time raiders listener error:",e);var t=document.getElementById("raidParticipants");t&&"alltime"===window._raidActiveTab&&(t.innerHTML='
    Could not load all-time data.
    ')}))}window._raidDamageDealersOpen=!1,window._raidDamageDealersUnsub=null,window._toggleRaidDamageDealers=function(){var e=document.getElementById("raidDamageDealers"),t=document.getElementById("raidDamageDealersBtn");if(e){if(window._raidDamageDealersOpen=!window._raidDamageDealersOpen,!window._raidDamageDealersOpen)return e.style.display="none",t&&(t.textContent="⚔️ Top Damage Dealers"),void(window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null));e.style.display="block",t&&(t.textContent="▲ Hide Damage Dealers"),e.innerHTML='
    Loading...
    ';var o=window._defeatedBossId||(window._currentRaidBoss&&window._currentRaidBoss._id?window._currentRaidBoss._id:null);o&&void 0!==db?window._raidDamageDealersUnsub=db.collection("raid_bosses").doc(o).collection("participants").orderBy("contributed","desc").limit(30).onSnapshot(function(e){var t=document.getElementById("raidDamageDealers");if(t)if(e.empty)t.innerHTML='
    No damage recorded for this boss.
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,c=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] Damage dealers listener error:",e);var t=document.getElementById("raidDamageDealers");t&&(t.innerHTML='
    Failed to load damage data.
    ')}):e.innerHTML='
    No damage data available.
    '}},window._raidActiveTab="current",window._raidAllTimeUnsub=null,window._switchRaidTab=function(e){if(e!==window._raidActiveTab){window._raidActiveTab=e;var t=document.getElementById("raidTabCurrent"),o=document.getElementById("raidTabAllTime");t&&(t.style.borderBottomColor="current"===e?"#8b5cf6":"transparent",t.style.color="current"===e?"#8b5cf6":"var(--text-faint)"),o&&(o.style.borderBottomColor="alltime"===e?"#8b5cf6":"transparent",o.style.color="alltime"===e?"#8b5cf6":"var(--text-faint)");var n=document.getElementById("raidParticipants");n&&(n.innerHTML='
    Loading...
    '),"current"===e?(window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._currentRaidBoss&&window._currentRaidBoss._id&&_listenRaidParticipants(window._currentRaidBoss._id)):(window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),_listenAllTimeRaiders())}};var RAID_GUIDANCE={uniqueUsers5Topics:{action:"Visit 5+ learning topics to deal damage!",nav:"home"},quizCompletions:{action:"Complete quiz quests to deal damage!",nav:"quests"},watchMinutes:{action:"Watch Timechain TV to deal damage!",nav:"tctv"},beatsMinutes:{action:"Listen to Bitcoin Beats to deal damage!",nav:"beats"},flashcardCompletions:{action:"Complete flashcard sets to deal damage!",nav:"quests"},totalXP:{action:"Earn XP from any activity to deal damage!",nav:"home"},pollVotes:{action:"Vote in Quest Hub polls to deal damage!",nav:"quests"},chatMessages:{action:"Send messages in Global Chat to deal damage!",nav:"chat"},badgesEarned:{action:"Earn badges to deal damage! Find them in the Leaderboard button 🏆",nav:"badges"},streakUsers:{action:"Maintain a 7-day daily visit streak to deal damage!",nav:"home"},uniqueTopicsVisited:{action:"Visit learning topics you haven't read yet!",nav:"home"},tipsSent:{action:"Send Lightning tips to deal damage!",nav:"home"},forumPosts:{action:"Create forum posts to deal damage!",nav:"forum"},triviaCorrect:{action:"Answer trivia correctly in Quest Hub to deal damage!",nav:"quests"},totalTopicReads:{action:"Read learning topics to deal damage!",nav:"home"}};window._contributeRaid=function(){var e=window._currentRaidBoss;if(e){var t=RAID_GUIDANCE[e.metric]||{action:"Complete activities on the site to deal damage!",nav:"home"};"function"==typeof showToast&&showToast("⚔️ "+t.action,3500);var o=document.getElementById("questHubOverlay");if(o&&o.remove(),"badges"===t.nav){if("function"==typeof toggleLeaderboard){var n=document.getElementById("leaderboard");if(n&&n.classList.contains("open")){n.classList.remove("open");var i=document.getElementById("lbFloatBtn");i&&(i.style.display="flex")}toggleLeaderboard(),setTimeout(function(){var e=document.getElementById("leaderboard");if(e)for(var t=e.querySelectorAll("h4"),o=0;o'+i.emoji+'
    '+i.title+'
    '+i.desc+"
    "}t+='',t+="";var a=document.createElement("div");a.id="forumRulesOverlay",a.innerHTML=t,document.body.appendChild(a)}window.acceptForumRules=function(){localStorage.setItem("btc_forum_rules_accepted","true");var e=document.getElementById("forumRulesOverlay");e&&e.remove()},window.showForumRulesBtn=function(){i()};var a=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","retard","nazi","hitler","kkk","porn","hentai","rape","pedo"];function r(e){for(var t=e.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/),o=0;o=4&&-1!==t[o].indexOf(a[n]))return!1}return!0}function s(e){return"function"==typeof escapeHtml?escapeHtml(e):String(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}window.forumBack=function(){history.back()};var c="recent",l=sessionStorage.getItem("btc_forum_category")||"all",d=null,u="discussions",p=["Bitcoin Basics","Lightning","Mining","Privacy","Self-Custody","Economics","Technical","Culture","Opinion","Tutorial","News Analysis"];function m(e,n){if(n)if(0!==e.length){var i="";e.forEach(function(e){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},a=o.find(function(t){return t.id===e.category}),r=a?a.emoji+" "+a.name:"",c=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),l=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid);i+='
    '+(e.upvotes||0)+'
    '+s(e.title)+"
    "+(e.body?'
    '+s(e.body).substring(0,120)+(e.body.length>120?"...":"")+"
    ":"")+"
    '+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'💬 '+(e.replyCount||0)+""+(r?''+r+"":"")+(c?"':"")+"
    "}),n.innerHTML=i}else n.innerHTML='
    🦌
    No posts yet. Be the first to start a discussion!
    '}async function g(e){var o=document.getElementById("forumReplies");if(o)try{var n=await db.collection("forum_replies").where("postId","==",e).orderBy("createdAt","asc").limit(100).get(),i=[];if(n.forEach(function(e){i.push({id:e.id,...e.data()})}),0===i.length)return void(o.innerHTML='
    No replies yet. Be the first!
    ');var a=[],r={};i.forEach(function(e){e.parentReplyId?(r[e.parentReplyId]||(r[e.parentReplyId]=[]),r[e.parentReplyId].push(e)):a.push(e)});var c='
    '+i.length+" "+(1===i.length?"reply":"replies")+"
    ";function l(e,o){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},i=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid),a=s(e.body).replace(/\n/g,"
    ");a=B(a=a.replace(/(https?:\/\/[^\s<]+)/g,'$1'));var r=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),c=auth&&auth.currentUser&&!auth.currentUser.isAnonymous;return'
    '+(e.parentAuthorName?'
    ↩ '+s(e.parentAuthorName)+"
    ":"")+'
    "+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'
    '+a+'
    "+(c?'':"")+(r?"':"")+"
    "}a.forEach(function(e){c+=l(e,!1),(r[e.id]||[]).forEach(function(e){c+=l(e,!0)})}),Object.keys(r).forEach(function(e){a.some(function(t){return t.id===e})||r[e].forEach(function(e){c+=l(e,!1)})}),o.innerHTML=c}catch(d){o.innerHTML='
    Error loading replies
    '}}window.renderForum=function(){var e=document.getElementById("forumContainer");if(e){e.innerHTML="";var t='
    ';if(t+='
    Home
    ',t+='

    🗣️ Pleb Talk

    Discuss Bitcoin with fellow learners
    ',t+='
    ',"stacker"===u){var n=window._snSearchQuery||"";t+='
    ',t+='',t+='',n&&(t+=''),t+="
    ";var a=window._snSub||"",r=[{id:"",label:"All"},{id:"bitcoin",label:"bitcoin"},{id:"lightning",label:"lightning"},{id:"nostr",label:"nostr"},{id:"privacy",label:"privacy"},{id:"tech",label:"tech"},{id:"meta",label:"meta"}];t+='
    ';for(var d=0;d'+S(p.label)+""}if(t+="
    ",n)t+='
    Search results for: '+S(n)+"
    ";else{var g=window._snSort||"top",h=window._snWhen||"day";t+='
    ';for(var f=[{id:"top",label:"🔥 Top"},{id:"recent",label:"🕐 Recent"},{id:"random",label:"🎲 Random"}],y=0;y'+v.label+""}if("top"===g){t+='"}t+='stacker.news ↗',t+="
    "}return t+='
    Loading Stacker News...
    ',t+="
    ",e.innerHTML=t,void(n?function(e){var t=document.getElementById("snFeed");if(t){var o="https://embed-proxy.needcreations.workers.dev/api/sn/search?q="+encodeURIComponent(e);fetch(o).then(function(e){return e.json()}).then(function(o){if(o&&o.data&&o.data.search&&o.data.search.items){var n=o.data.search.items;n.length?t.innerHTML=b(n):t.innerHTML='
    No results found for "'+S(e)+'"
    '}else t.innerHTML='
    No results found
    '}).catch(function(){t.innerHTML='
    Search failed.
    '})}}(n):loadStackerNewsFeed(window._snSort||"top",window._snWhen||"day",a))}"articles"!==u?(t+='
    ',["recent","top","discussed"].forEach(function(e){var o=c===e;t+=""}),t+='
    ",t+='
    Loading posts...
    ',t+="",e.innerHTML=t,document.getElementById("main").scrollTop=0,"true"!==localStorage.getItem("btc_forum_rules_accepted")&&i(),forumLoadPosts()):function(e,t){var o=e;o+='
    ',o+='
    ',["recent","top"].forEach(function(e){var t=c===e;o+=""}),o+="
    ",o+='
    Loading articles...
    ',o+="",t.innerHTML=o,document.getElementById("main").scrollTop=0,async function(){var e=document.getElementById("articlesList");if(e&&void 0!==db)try{var t="top"===c?"upvotes":"createdAt",o=await db.collection("articles").where("status","==","published").orderBy(t,"desc").limit(15).get(),n=[];if(o.forEach(function(e){n.push({id:e.id,...e.data()})}),0===n.length)return void(e.innerHTML='
    📝
    No articles yet
    Be the first to publish a Bitcoin article!
    ');var i="";n.forEach(function(e){var t="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},o=Math.max(1,Math.round((e.wordCount||500)/200)),n=e.createdAt&&e.createdAt.toDate?e.createdAt.toDate().toLocaleDateString():"",a=e.pinned?'📌 PINNED ':"";i+="
    ',e.coverUrl&&(i+='
    '),i+='
    ',i+=a+'

    '+s(e.title)+"

    ",e.subtitle&&(i+='
    '+s(e.subtitle)+"
    "),e.tags&&e.tags.length&&(i+='
    ',e.tags.forEach(function(e){i+=''+s(e)+""}),i+="
    "),i+='
    "+t.emoji+" "+s(e.authorName||"Anon")+"·"+o+" min read"+(n?"·"+n+"":"")+"
    ",i+='
    👍 '+(e.upvotes||0)+"💬 "+(e.replyCount||0)+""+(e.tipTotal?"⚡ "+e.tipTotal+" sats":"")+"
    ",i+="
    "}),e.innerHTML=i}catch(t){console.error("Articles load error:",t),e.innerHTML='
    Error loading articles
    '}}()}(t,e)}},window._forumUnsubscribe=null,window.forumLoadPosts=async function(){document.getElementById("forumPosts")&&void 0!==db&&(window._forumUnsubscribe&&(window._forumUnsubscribe(),window._forumUnsubscribe=null),async function(){var e=document.getElementById("forumPosts");if(e)try{var t="top"===c?"upvotes":"discussed"===c?"replyCount":"createdAt",o=l+"_"+c,n=Date.now();if(window._forumCache&&window._forumCache.key===o&&n-window._forumCache.time<12e4)return window._forumCache.posts,void m(window._forumCache.posts,e);var i="all"!==l?db.collection("forum_posts").where("category","==",l).orderBy(t,"desc").limit(50):db.collection("forum_posts").orderBy(t,"desc").limit(50),a=await i.get(),r=[];a.forEach(function(e){r.push({id:e.id,...e.data()})}),window._forumCache={key:o,time:Date.now(),posts:r},m(r,e)}catch(t){e.innerHTML='
    Error loading posts. Try refreshing.
    '}}())},window.forumSetSort=function(e){c=e,renderForum()},window.forumSetCategory=function(e){l=e,sessionStorage.setItem("btc_forum_category",e),renderForum()},window.forumViewPost=async function(e,o){var n=document.getElementById("forumContainer");if(n&&void 0!==db){o||history.pushState({channel:"forum",forumPost:e},"","#forum/post/"+e),n.innerHTML='
    ';try{var i=await db.collection("forum_posts").doc(e).get();if(!i.exists)return void renderForum();var a={id:i.id,...i.data()};d=a;var r="function"==typeof getLevel?getLevel(a.authorPoints||0):{emoji:"🟢"},c=a.voters&&auth&&auth.currentUser&&-1!==a.voters.indexOf(auth.currentUser.uid),l='
    ';if(l+='
    Home
    ',l+='',l+='

    '+s(a.title)+'

    "+r.emoji+" "+s(a.authorName||"Anon")+''+timeAgo(a.createdAt)+"
    ",a.body){var u=s(a.body).replace(/\n/g,"
    ").replace(/\*\*(.+?)\*\*/g,"$1");l+='
    '+(u=B(u=u.replace(/(https?:\/\/[^\s<]+)/g,'$1')))+"
    "}a.link&&(l+='🔗 '+s(a.link).substring(0,60)+(a.link.length>60?"...":"")+"
    ");var p=auth&&auth.currentUser&&a.authorId===auth.currentUser.uid||t();l+='
    💬 '+(a.replyCount||0)+" replies"+(p?"':"")+"
    ",l+="
    ",auth&&auth.currentUser&&!auth.currentUser.isAnonymous?l+='
    ':l+='
    🔒
    Want to join the conversation?
    ',l+='
    Loading replies...
    ',l+="
    ",n.innerHTML=l,document.getElementById("main").scrollTop=0,g(e)}catch(e){n.innerHTML='
    Error loading post
    '}}},window.forumNewPost=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){history.pushState({channel:"forum-new"},"","#forum");var e=document.getElementById("forumContainer");if(e){var t='
    ';t+='
    Home
    ',t+='',t+='

    📝 Create New Post

    ',t+='
    ';var n="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;";t+='",t+='',t+='',t+='',t+='
    ',t+='',t+='
    ',t+="
    ",window._forumFormOpenTime=Date.now(),e.innerHTML=t,document.getElementById("main").scrollTop=0}}else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
    🔒

    Registration Required

    Create a free account to post in the forum, join discussions, and earn XP! It only takes a few seconds.
    ')}};var h=0;function f(e){if(!e)return"";var t=s(e);return B(t='

    '+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,'$1')).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/(?$1')).replace(/^### (.+)$/gm,'

    $1

    ')).replace(/^## (.+)$/gm,'

    $1

    ')).replace(/^# (.+)$/gm,'

    $1

    ')).replace(/\*\*(.+?)\*\*/g,'$1')).replace(/\*(.+?)\*/g,"$1")).replace(/`(.+?)`/g,'$1')).replace(/^> (.+)$/gm,'
    $1
    ')).replace(/^- (.+)$/gm,'
  • $1
  • ')).replace(/^\d+\. (.+)$/gm,'
  • $1
  • ')).replace(/---/g,'
    ')).replace(/\n{2,}/g,'

    '))+"

    ")}window.forumSubmitPost=async function(){if(!window._forumSubmitting){var e=Date.now();if(e-h<3e4)"function"==typeof showToast&&showToast("⏳ Wait 30 seconds between posts");else{h=e,window._forumSubmitting=!0;var t=document.getElementById("forumPostStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o=document.getElementById("forumHoneypot");if(o&&o.value)t&&(t.innerHTML='Something went wrong. Please try again.');else if(window._forumFormOpenTime&&Date.now()-window._forumFormOpenTime<5e3)t&&(t.innerHTML='Please take a moment to write your post.');else{var n=(document.getElementById("forumNewTitle").value||"").trim(),i=(document.getElementById("forumNewBody").value||"").trim(),a=(document.getElementById("forumNewLink").value||"").trim(),c=document.getElementById("forumNewCat").value;if("function"==typeof sanitizeInput&&(n=sanitizeInput(n),i=sanitizeInput(i)),!n||n.length<5)t&&(t.innerHTML='Title must be at least 5 characters');else if(!r(n)||i&&!r(i))t&&(t.innerHTML='Post contains inappropriate language. Keep it clean!');else{a&&!/^https?:\/\//i.test(a)&&(a="https://"+a);var l=parseInt(localStorage.getItem("btc_forum_post_count")||"0"),d=localStorage.getItem("btc_forum_post_date")||"",u=(new Date).toISOString().split("T")[0];if(d!==u&&(l=0),l>=5)t&&(t.innerHTML='You\'ve reached the daily post limit (5). Try again tomorrow!');else{t&&(t.innerHTML='Posting...');try{var p=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",m=void 0!==currentUser&¤tUser&¤tUser.points||0,g=await db.collection("forum_posts").add({title:n,body:i.substring(0,2e3),link:a.substring(0,200)||null,category:c,authorId:auth.currentUser.uid,authorName:p,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:m,upvotes:0,voters:[],replyCount:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()});if(localStorage.setItem("btc_forum_post_count",(l+1).toString()),localStorage.setItem("btc_forum_post_date",u),"function"==typeof awardPoints&&awardPoints(10,"📝 Forum post"),"function"==typeof awardTickets&&awardTickets(5,"📝 Forum post"),forumNotifyMentions(i,"forum_post",g.id,n),db.collection("users").doc(auth.currentUser.uid).update({forumPosts:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumPosts=(currentUser.forumPosts||0)+1),"function"==typeof window._raidOnForumPost&&window._raidOnForumPost(),"function"==typeof window.nachoGlobalAnnounce){var f=s(n).substring(0,80),y=s(i).substring(0,120);window.nachoGlobalAnnounce("🗣️ New Forum Post: "+f+" by "+s(p)+": "+y+(i.length>120?"...":"")+" ➡️ [Open PlebTalk](#forum)")}forumBack()}catch(e){t&&(t.innerHTML='Error posting. Try again.')}}}}}else t&&(t.innerHTML='You must be signed in')}}},window._forumReplyingTo=null,window.forumReplyToReply=function(e,t){window._forumReplyingTo={replyId:e,authorName:t};var o=document.getElementById("forumReplyIndicator");o&&(o.style.display="flex",o.querySelector("span").textContent="↩ Replying to "+t);var n=document.getElementById("forumReplyInput");n&&(n.focus(),n.placeholder="Reply to "+t+"...")},window.forumCancelReplyTo=function(){window._forumReplyingTo=null;var e=document.getElementById("forumReplyIndicator");e&&(e.style.display="none");var t=document.getElementById("forumReplyInput");t&&(t.placeholder="Write a reply...")},window.forumSubmitReply=async function(e){if(!window._forumReplySubmitting){window._forumReplySubmitting=!0;var t=document.getElementById("forumReplyStatus"),o=document.getElementById("forumReplyInput");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&o){var n=o.value.trim();if(!n||n.length<2)return t&&(t.innerHTML='Reply is too short'),void(window._forumReplySubmitting=!1);if(!r(n))return t&&(t.innerHTML='Reply contains inappropriate language'),void(window._forumReplySubmitting=!1);t&&(t.innerHTML='Posting...');try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0,s={postId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:a,upvotes:0,voters:[],createdAt:firebase.firestore.FieldValue.serverTimestamp()},c=window._forumReplyingTo;c&&c.replyId&&(s.parentReplyId=c.replyId,s.parentAuthorName=c.authorName||""),await db.collection("forum_replies").add(s),await db.collection("forum_posts").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Forum reply");var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";if(c&&c.replyId){try{var u=await db.collection("forum_replies").doc(c.replyId).get();u.exists&&u.data().authorId&&"function"==typeof sendNotification&&sendNotification(u.data().authorId,"reply",l+' replied to your comment on "'+(d?(d.title||"").substring(0,40):"a post")+'"',"forum_post",e)}catch(e){}d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",l+' replied in your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e)}else d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",l+' replied to your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e);forumNotifyMentions(n,"forum_post",e,d?d.title:""),db.collection("users").doc(auth.currentUser.uid).update({forumReplies:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumReplies=(currentUser.forumReplies||0)+1),o.value="",window.forumCancelReplyTo(),t&&(t.innerHTML='✅ Reply posted!'),g(e)}catch(e){t&&(t.innerHTML='Error posting reply')}window._forumReplySubmitting=!1}else window._forumReplySubmitting=!1}},window.forumVotePost=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_posts").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your post "'+(a.title||"").substring(0,40)+'"',"forum_post",e)}}d&&d.id===e?forumViewPost(e):forumLoadPosts()}catch(e){}},window.forumVoteReply=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_replies").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;-1!==n.indexOf(i)?await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)}):await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)}),d&&g(d.id)}catch(e){}},window.forumDeletePost=async function(e){if(auth&&auth.currentUser){var o=t();if(confirm(o?"Admin: Delete this post and all its replies?":"Delete your post? This cannot be undone."))try{var n=await db.collection("forum_replies").where("postId","==",e).get(),i=db.batch();n.forEach(function(e){i.delete(e.ref)}),i.delete(db.collection("forum_posts").doc(e)),await i.commit(),"function"==typeof showToast&&showToast("🗑️ Post deleted"),forumBack()}catch(e){"function"==typeof showToast&&showToast("Error deleting post")}}},window.forumDeleteReply=async function(e,o){if(auth&&auth.currentUser){var n=t();if(confirm(n?"Admin: Delete this reply?":"Delete your reply? This cannot be undone."))try{await db.collection("forum_replies").doc(e).delete(),await db.collection("forum_posts").doc(o).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Reply deleted"),d&&g(o)}catch(e){"function"==typeof showToast&&showToast("Error deleting reply")}}},window.forumSwitchTab=function(e){u=e,renderForum()};var y=["Content must be Bitcoin-focused or Bitcoin-adjacent","Minimum 500 words, maximum 10,000 words","No promotion of altcoins, scams, or affiliate spam","Original content only — no plagiarism","No hate speech or personal attacks","Author grants the archive a non-exclusive license to display the content","Moderators may remove content that violates these guidelines"];async function v(e){var o=document.getElementById("articleReplies");if(o)try{var n=await db.collection("article_replies").where("articleId","==",e).orderBy("createdAt","asc").limit(50).get();if(n.empty)return void(o.innerHTML='
    No comments yet. Be the first!
    ');var i="";n.forEach(function(o){var n=o.data(),a="function"==typeof getLevel?getLevel(n.authorPoints||0):{emoji:"🟢"},r=n.createdAt&&n.createdAt.toDate?"function"==typeof timeAgo?timeAgo(n.createdAt.toDate()):n.createdAt.toDate().toLocaleDateString():"",c=auth&&auth.currentUser&&(auth.currentUser.uid===n.authorId||t());i+='
    "+a.emoji+" "+s(n.authorName||"Anon")+'· '+r+""+(c?"':"")+'
    '+B(s(n.body).replace(/\n/g,"
    ").replace(/(https?:\/\/[^\s<]+)/g,'$1'))+"
    "}),o.innerHTML=i}catch(e){o.innerHTML='
    Error loading comments
    '}}function b(e){for(var t="",o=0;o",t+='
    ',t+='
    ',t+='
    '+T(n.sats)+"
    ",t+='
    sats
    ',t+="
    ",t+='
    ',t+='
    '+S(n.title)+"
    ",t+='
    ',t+='@'+S(n.user.name)+"",t+="·",t+=""+i+"",n.ncomments>0&&(t+="·",t+="💬 "+n.ncomments+""),a&&(t+="·",t+=''+S(a)+""),r&&(t+=''+S(r)+""),t+="
    ",t+='',t+="
    "}return t}function w(e,t){for(var o="",n=0;n',o+='
    ',o+='@'+S(i.user.name)+"",o+="·",o+=""+k(i.createdAt)+"",i.sats>0&&(o+="·",o+='⚡ '+T(i.sats)+""),o+="
    ",i.text&&(o+='
    '+x(i.text)+"
    "),o+="",i.comments&&i.comments.comments&&i.comments.comments.length>0&&(o+=w(i.comments.comments,t+1))}return o}function x(e){if(!e)return"";var t=S(e);return'

    '+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/^#{3}\s+(.+)$/gm,'

    $1
    ')).replace(/^#{2}\s+(.+)$/gm,'
    $1
    ')).replace(/^#{1}\s+(.+)$/gm,'
    $1
    ')).replace(/\*\*\*(.+?)\*\*\*/g,"$1")).replace(/\*\*(.+?)\*\*/g,"$1")).replace(/\*(.+?)\*/g,"$1")).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/`([^`]+)`/g,'$1')).replace(/\n\n/g,'

    ')).replace(/\n/g,"
    "))+"

    "}function k(e){var t=Math.floor((Date.now()-new Date(e).getTime())/1e3);return t<60?"just now":t<3600?Math.floor(t/60)+"m ago":t<86400?Math.floor(t/3600)+"h ago":Math.floor(t/86400)+"d ago"}function T(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"k":String(e)}function S(e){return e?e.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""):""}function B(e){return e&&-1!==e.indexOf("@")?e.replace(/(<[^>]+>)|(@([a-zA-Z0-9_\-\.]{2,20}))/g,function(e,t,o,n){return t||'"+o+""}):e}window.articleNew=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void("function"==typeof showToast&&showToast("🔒 Sign in to write articles"));if((void 0!==currentUser&¤tUser&¤tUser.points||0)<100)"function"==typeof showToast&&showToast("📝 You need 100+ points to publish articles. Keep exploring!");else{var e=null;try{e=JSON.parse(localStorage.getItem("btc_article_draft"))}catch(e){}var t=document.getElementById("forumContainer");if(t){var o="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;",n='
    ';n+='',n+='

    ✍️ Write an Article

    ',n+='
    ',n+='',n+='',n+='
    ';var i=e&&e.tags?e.tags:[];p.forEach(function(e){var t=-1!==i.indexOf(e);n+=""}),n+="
    ",n+='
    ',n+='
    0 words · Min 500
    ',n+='',n+='
    📋 Content Guidelines
    ',y.forEach(function(e){n+='
    • '+e+"
    "}),n+='
    ',n+='
    ',n+='
    ',n+="
    ",t.innerHTML=n,document.getElementById("main").scrollTop=0;var a=document.getElementById("articleBody");a&&(a.addEventListener("input",function(){var e=this.value.trim().split(/\s+/).filter(function(e){return e.length>0}).length,t=document.getElementById("articleWordCount");t&&(t.textContent=e+" words · Min 500")}),window._articleAutoSave=setInterval(function(){articleSaveDraft(!0)},3e4))}}},window.toggleArticleTag=function(e,t){if(-1!==e.style.borderColor.indexOf("var(--accent)")||-1!==e.style.color.indexOf("var(--accent)"))e.style.border="1px solid var(--border)",e.style.background="none",e.style.color="var(--text-muted)";else{if(document.querySelectorAll('#articleTagsContainer button[style*="accent-bg"]').length>=3)return void("function"==typeof showToast&&showToast("Max 3 tags"));e.style.border="1px solid var(--accent)",e.style.background="var(--accent-bg)",e.style.color="var(--accent)"}},window.articleInsert=function(e,t,o){var n=document.getElementById("articleBody");if(n){n.focus();var i=n.selectionStart,a=n.selectionEnd,r=n.value.substring(i,a),s=r||o,c=e+s+t;n.setRangeText(c,i,a,"select"),r||(n.selectionStart=i+e.length,n.selectionEnd=i+e.length+s.length),n.dispatchEvent(new Event("input"))}},window.articleInsertLink=function(){var e=document.getElementById("articleBody");if(e){var t=e.value.substring(e.selectionStart,e.selectionEnd),o=document.getElementById("articleLinkDialog");o&&o.remove();var n=document.createElement("div");n.id="articleLinkDialog",n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",n.onclick=function(e){e.target===n&&n.remove()};var i="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";n.innerHTML='

    🔗 Insert Link

    ',document.body.appendChild(n),setTimeout(function(){document.getElementById("linkDialogUrl").focus()},100)}},window.articleDoInsertLink=function(){var e=(document.getElementById("linkDialogText").value||"").trim()||"link",t=(document.getElementById("linkDialogUrl").value||"").trim();if(t){t.match(/^https?:\/\//)||(t="https://"+t);var o=document.getElementById("articleBody");if(o){var n="["+e+"]("+t+")",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleLinkDialog").remove()}else"function"==typeof showToast&&showToast("Enter a URL")},window.articleInsertImage=function(){var e=document.getElementById("articleImageDialog");e&&e.remove();var t=document.createElement("div");t.id="articleImageDialog",t.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",t.onclick=function(e){e.target===t&&t.remove()};var o="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";t.innerHTML='

    🖼️ Insert Image

    Or upload from device:
    ',document.body.appendChild(t),setTimeout(function(){var e=document.getElementById("imageDialogFile");e&&e.addEventListener("change",function(){var e=this.files[0];if(e)if(e.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var t=document.getElementById("imageDialogPreview"),o=document.getElementById("imageDialogBtn");if(o&&(o.disabled=!0,o.textContent="Uploading..."),"undefined"!=typeof firebase&&firebase.storage&&void 0!==auth&&auth.currentUser)firebase.storage().ref("article-images/"+auth.currentUser.uid+"/"+Date.now()+"_"+e.name.replace(/[^a-zA-Z0-9._-]/g,"_")).put(e).then(function(e){return e.ref.getDownloadURL()}).then(function(e){document.getElementById("imageDialogUrl").value=e,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image"),"function"==typeof showToast&&showToast("✅ Image uploaded!")}).catch(function(e){"function"==typeof showToast&&showToast("Upload failed: "+(e.message||"Unknown error")),o&&(o.disabled=!1,o.textContent="Insert Image")});else{var n=new FileReader;n.onload=function(e){document.getElementById("imageDialogUrl").value=e.target.result,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image")},n.readAsDataURL(e)}}}),document.getElementById("imageDialogUrl").focus()},100)},window.articleDoInsertImage=function(){var e=(document.getElementById("imageDialogUrl").value||"").trim(),t=(document.getElementById("imageDialogAlt").value||"").trim()||"image";if(e){var o=document.getElementById("articleBody");if(o){var n="\n!["+t+"]("+e+")\n",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleImageDialog").remove()}else"function"==typeof showToast&&showToast("Enter an image URL or upload a file")},window.toggleArticlePreview=function(){var e=document.getElementById("articleBody"),t=document.getElementById("articlePreviewArea"),o=document.getElementById("articlePreviewBtn");e&&t&&("none"===t.style.display?(t.innerHTML=f(e.value),t.style.display="block",e.style.display="none",o.textContent="Edit"):(t.style.display="none",e.style.display="",o.textContent="Preview"))},window.articleSaveDraft=function(e){var t=(document.getElementById("articleTitle")||{}).value||"",o=(document.getElementById("articleSubtitle")||{}).value||"",n=(document.getElementById("articleBody")||{}).value||"",i=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&i.push(e.getAttribute("data-tag"))}),(t||n)&&(localStorage.setItem("btc_article_draft",JSON.stringify({title:t,subtitle:o,body:n,tags:i,savedAt:Date.now()})),e||"function"!=typeof showToast||showToast("💾 Draft saved!"))},window.articleSubmit=async function(){if(!window._articleSubmitting){var e=document.getElementById("articleStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var t=(document.getElementById("articleTitle").value||"").trim(),o=(document.getElementById("articleSubtitle").value||"").trim(),n=(document.getElementById("articleBody").value||"").trim(),i=document.getElementById("articleTerms");if(!t||t.length<10)e&&(e.innerHTML='Title must be at least 10 characters');else{var a=n.split(/\s+/).filter(function(e){return e.length>0}).length;if(a<500)e&&(e.innerHTML='Article must be at least 500 words (currently '+a+")");else if(a>1e4)e&&(e.innerHTML='Article must be under 10,000 words');else{var c=[];if(document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&c.push(e.getAttribute("data-tag"))}),c.length<1)e&&(e.innerHTML='Select at least 1 tag');else if(i&&i.checked)if(r(t)&&r(n)){window._articleSubmitting=!0,e&&(e.innerHTML='Publishing...');try{var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",d=void 0!==currentUser&¤tUser&¤tUser.points||0,p=void 0!==currentUser&¤tUser&¤tUser.profilePic?currentUser.profilePic:"",m="",g=document.getElementById("articleCover");if(g&&g.files&&g.files[0]){var h=g.files[0];if(h.size>3145728)return e&&(e.innerHTML='Cover image too large (max 3MB)'),void(window._articleSubmitting=!1);e&&(e.innerHTML='Uploading cover...');try{var f=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),y=await f.put(h);m=await y.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}e&&(e.innerHTML='Publishing article...');var v={title:t.substring(0,120),subtitle:o.substring(0,200),body:n.substring(0,5e4),tags:c.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),authorId:auth.currentUser.uid,authorName:l,authorPoints:d,authorPic:p,upvotes:0,voters:[],replyCount:0,tipTotal:0,status:"published",pinned:!1,agreedToTerms:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp(),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};m&&(v.coverUrl=m),await db.collection("articles").add(v),localStorage.removeItem("btc_article_draft"),window._articleAutoSave&&clearInterval(window._articleAutoSave),"function"==typeof awardPoints&&awardPoints(30,"📝 Article published"),"function"==typeof awardTickets&&awardTickets(20,"📝 Article published");var b=parseInt(localStorage.getItem("btc_articles_published")||"0");localStorage.setItem("btc_articles_published",String(b+1)),"function"==typeof showToast&&showToast("📝 Article published!"),u="articles",renderForum()}catch(t){console.error("Article submit error:",t),e&&(e.innerHTML='Error publishing: '+s(t.message)+"")}window._articleSubmitting=!1}else e&&(e.innerHTML='Content contains inappropriate language');else e&&(e.innerHTML='You must agree to the content guidelines')}}}else e&&(e.innerHTML='Sign in required')}},window.articleView=async function(e){var o=document.getElementById("forumContainer");if(o&&db){o.innerHTML='
    Loading article...
    ';try{var n=await db.collection("articles").doc(e).get();if(!n.exists)return void(o.innerHTML='
    Article not found
    ');var i=n.data();i.id=e;var a="function"==typeof getLevel?getLevel(i.authorPoints||0):{emoji:"🟢"},r=Math.max(1,Math.round((i.wordCount||500)/200)),c=i.createdAt&&i.createdAt.toDate?i.createdAt.toDate().toLocaleDateString():"",l=auth&&auth.currentUser&&auth.currentUser.uid===i.authorId,d=t(),u=auth&&auth.currentUser&&-1!==(i.voters||[]).indexOf(auth.currentUser.uid),p='
    ';if(p+='',i.coverUrl&&(p+='
    Cover
    '),p+='

    '+s(i.title)+"

    ",i.subtitle&&(p+='
    '+s(i.subtitle)+"
    "),p+='
    ',i.authorPic&&(p+=''),p+='
    "+a.emoji+" "+s(i.authorName||"Anon")+'
    '+c+" · "+r+" min read · "+(i.wordCount||0).toLocaleString()+" words
    ",l&&(p+="'),d&&(p+=""),p+="
    ",i.tags&&i.tags.length&&(p+='
    ',i.tags.forEach(function(e){p+=''+s(e)+""}),p+="
    "),p+='
    '+f(i.body)+"
    ",p+='
    ',p+="","function"==typeof tipButtonHtml&&(p+=tipButtonHtml({recipientName:i.authorName,recipientUid:i.authorId,context:"article",contextId:e,label:"⚡ Tip Author",size:"md"})),(l||d)&&(p+="'),p+="
    ",p+='

    💬 Comments

    ',p+='
    Loading comments...
    ',auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(p+='
    '),p+="
    ",o.innerHTML=p,document.getElementById("main").scrollTop=0,v(e),auth&&auth.currentUser){var m="btc_article_read_"+e;localStorage.getItem(m)||setTimeout(function(){document.getElementById("articleReplies")&&(localStorage.setItem(m,"1"),"function"==typeof awardPoints&&awardPoints(5,"📖 Read an article"),"function"==typeof showToast&&showToast("📖 +5 points for reading!"))},6e4)}}catch(e){console.error("Article view error:",e),o.innerHTML='
    Error loading article
    '}}},window.articleVote=async function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{var t=db.collection("articles").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your article "'+(a.title||"").substring(0,40)+'"',"article",e)}}articleView(e)}catch(e){}else"function"==typeof showToast&&showToast("🔒 Sign in to upvote")},window.articleSubmitReply=async function(e){var t=document.getElementById("articleReplyInput"),o=document.getElementById("articleReplyStatus");if(t&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var n=t.value.trim();if(!n||n.length<2)o&&(o.innerHTML='Comment too short');else if(r(n))try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0;await db.collection("article_replies").add({articleId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorPoints:a,createdAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("articles").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Article comment");try{var s=await db.collection("articles").doc(e).get();if(s.exists&&s.data().authorId&&"function"==typeof sendNotification){var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(s.data().authorId,"comment",c+' commented on your article "'+(s.data().title||"").substring(0,40)+'"',"article",e)}forumNotifyMentions(n,"article",e,s&&s.exists?s.data().title:"")}catch(e){}t.value="",o&&(o.innerHTML='✅ Comment posted!'),v(e)}catch(e){o&&(o.innerHTML='Error posting comment')}else o&&(o.innerHTML='Inappropriate language')}},window.articleDeleteReply=async function(e,t){if(confirm("Delete this comment?"))try{await db.collection("article_replies").doc(e).delete(),await db.collection("articles").doc(t).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Comment deleted"),v(t)}catch(e){}},window.articleEdit=async function(e){try{var o=await db.collection("articles").doc(e).get();if(!o.exists)return;var n=o.data();if(auth.currentUser.uid!==n.authorId&&!t())return;localStorage.setItem("btc_article_draft",JSON.stringify({title:n.title,subtitle:n.subtitle||"",body:n.body,tags:n.tags||[]})),window._articleEditId=e,articleNew(),setTimeout(function(){var e=document.querySelector('[onclick="articleSubmit()"]');e&&(e.textContent="✏️ Update Article",e.setAttribute("onclick","articleUpdate()"))},100)}catch(e){"function"==typeof showToast&&showToast("Error loading article for edit")}},window.articleUpdate=async function(){var e=window._articleEditId;if(e){var t=document.getElementById("articleStatus"),o=(document.getElementById("articleTitle").value||"").trim(),n=(document.getElementById("articleSubtitle").value||"").trim(),i=(document.getElementById("articleBody").value||"").trim(),a=i.split(/\s+/).filter(function(e){return e.length>0}).length;if(!o||o.length<10)t&&(t.innerHTML='Title must be at least 10 characters');else if(a<500)t&&(t.innerHTML='Min 500 words');else{var r=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&r.push(e.getAttribute("data-tag"))}),t&&(t.innerHTML='Updating...');try{var s=null,c=document.getElementById("articleCover");if(c&&c.files&&c.files[0]){var l=c.files[0];if(l.size>3145728)return void(t&&(t.innerHTML='Cover too large (max 3MB)'));t&&(t.innerHTML='Uploading cover...');try{var d=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),u=await d.put(l);s=await u.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}var p={title:o.substring(0,120),subtitle:n.substring(0,200),body:i.substring(0,5e4),tags:r.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};s&&(p.coverUrl=s),t&&(t.innerHTML='Saving...'),await db.collection("articles").doc(e).update(p),localStorage.removeItem("btc_article_draft"),window._articleEditId=null,"function"==typeof showToast&&showToast("✏️ Article updated!"),articleView(e)}catch(e){t&&(t.innerHTML='Error updating')}}}},window.articleTogglePin=async function(e,t){try{await db.collection("articles").doc(e).update({pinned:t}),"function"==typeof showToast&&showToast(t?"📌 Article pinned!":"📌 Article unpinned"),articleView(e)}catch(e){}},window.articleDelete=async function(e){if(confirm("Delete this article and all its comments? This cannot be undone."))try{var t=await db.collection("article_replies").where("articleId","==",e).get(),o=db.batch();t.forEach(function(e){o.delete(e.ref)}),o.delete(db.collection("articles").doc(e)),await o.commit(),"function"==typeof showToast&&showToast("🗑️ Article deleted"),u="articles",renderForum()}catch(e){"function"==typeof showToast&&showToast("Error deleting article")}},window.loadStackerNewsFeed=function(e,t,o){var n=document.getElementById("snFeed");if(n){var i="https://embed-proxy.needcreations.workers.dev/api/sn?sort="+encodeURIComponent(e)+"&when="+encodeURIComponent(t)+"&limit=21";o&&(i+="&sub="+encodeURIComponent(o)),fetch(i).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.items&&e.data.items.items){var t=e.data.items.items;t.length?n.innerHTML=b(t):n.innerHTML='
    No posts found
    '}else n.innerHTML='
    Could not load Stacker News feed
    '}).catch(function(){n.innerHTML='
    Failed to load feed.
    '})}},window.snDoSearch=function(){var e=document.getElementById("snSearchInput");if(e){var t=e.value.trim();t.length<2||(window._snSearchQuery=t,renderForum())}},window.snClearSearch=function(){window._snSearchQuery="",renderForum()},window.snOpenPost=function(e){var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading post...
    ',fetch("https://embed-proxy.needcreations.workers.dev/api/sn/item?id="+e).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.item){var o=e.data.item;!function(e,t){var o='
    ';if(o+='',o+='
    ',o+='

    '+S(t.title)+"

    ",o+='
    ',o+='⚡ '+T(t.sats)+" sats",o+="·",o+='@'+S(t.user.name)+"",o+="·",o+=""+k(t.createdAt)+"",t.ncomments>0&&(o+="·",o+="💬 "+t.ncomments+" comments"),o+="
    ",t.url){var n="";try{n=new URL(t.url).hostname.replace("www.","")}catch(e){}o+='🔗 '+S(n||t.url)+" ↗"}t.text&&(o+='
    '+x(t.text)+"
    "),o+='",o+="
    ",t.comments&&t.comments.comments&&t.comments.comments.length>0&&(o+='
    ',o+='
    💬 Comments ('+t.ncomments+")
    ",o+=w(t.comments.comments,0),o+="
    "),o+="
    ",e.innerHTML=o,e.scrollTop=0}(t,o)}else t.innerHTML='
    Post not found.
    '}).catch(function(){t.innerHTML='
    Failed to load post. ·
    '}))},window.forumMentionClick=function(e){e&&void 0!==db&&db.collection("users").where("username","==",e).limit(1).get().then(function(t){t.empty?db.collection("users").where("username_lower","==",e.toLowerCase()).limit(1).get().then(function(t){t.empty?"function"==typeof showToast&&showToast("User @"+e+" not found"):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){}):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){})},window.forumNotifyMentions=async function(e,t,o,n){if(e&&void 0!==db&&auth&&auth.currentUser){var i=e.match(/@([a-zA-Z0-9_\-\.]{2,20})/g);if(i){var a={},r=[];i.forEach(function(e){var t=e.substring(1).toLowerCase();a[t]||(a[t]=!0,r.push(e.substring(1)))});for(var s=auth.currentUser.uid,c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone",l=(n||"").substring(0,40),d=0;d=",e).where("username","<=",e+"").limit(5).get().then(function(e){e.forEach(function(e){var t=e.data();t.username&&!a[e.id]&&(a[e.id]=!0,i.push({uid:e.id,username:t.username,points:t.points||0}))})}).catch(function(){}).then(function(){++r>=t.length&&(i.sort(function(e,t){return(t.points||0)-(e.points||0)}),_.activeTextarea&&function(e,t){if(E(),t&&0!==t.length){_.results=t,_.selectedIdx=0;var o=document.createElement("div");o.id="mentionDropdown",o.style.cssText="position:absolute;z-index:9999;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,0.4);overflow:hidden;max-height:220px;overflow-y:auto;min-width:200px;",t.forEach(function(e,t){var n=document.createElement("div");n.className="mention-item",n.setAttribute("data-idx",t);var i="function"==typeof getLevel?getLevel(e.points||0):{emoji:"🟢"};n.innerHTML=''+i.emoji+' '+s(e.username)+""+(e.points?''+(e.points||0).toLocaleString()+" XP":""),n.style.cssText="padding:10px 14px;cursor:pointer;display:flex;align-items:center;gap:8px;font-size:0.85rem;color:var(--text);transition:background 0.15s;"+(0===t?"background:var(--accent-bg);":""),n.onmouseenter=function(){_.selectedIdx=t,C()},n.onmousedown=function(e){e.preventDefault(),A(t)},o.appendChild(n)});var n=e.getBoundingClientRect();window.pageYOffset||document.documentElement.scrollTop,o.style.position="fixed",o.style.left=n.left+"px",o.style.top=n.bottom+4+"px",o.style.width=Math.min(n.width,320)+"px",document.body.appendChild(o),_.dropdown=o}}(_.activeTextarea,i.slice(0,5)))})})}}(t.prefix)},300))}),e.addEventListener("keydown",function(e){_.dropdown&&("ArrowDown"===e.key?(e.preventDefault(),_.selectedIdx=Math.min(_.selectedIdx+1,_.results.length-1),C()):"ArrowUp"===e.key?(e.preventDefault(),_.selectedIdx=Math.max(_.selectedIdx-1,0),C()):"Enter"===e.key||"Tab"===e.key?_.results.length>0&&_.selectedIdx>=0&&(e.preventDefault(),A(_.selectedIdx)):"Escape"===e.key&&E())}),e.addEventListener("blur",function(){setTimeout(E,200)}))}function z(){var e=["forumNewBody","forumReplyInput","articleReplyInput"];if(e.forEach(function(e){var t=document.getElementById(e);t&&M(t)}),"undefined"!=typeof MutationObserver){var t=new MutationObserver(function(){e.forEach(function(e){var t=document.getElementById(e);t&&M(t)})}),o=document.getElementById("forumContainer");if(o)t.observe(o,{childList:!0,subtree:!0});else{var n=new MutationObserver(function(){var o=document.getElementById("forumContainer");o&&(n.disconnect(),t.observe(o,{childList:!0,subtree:!0}),e.forEach(function(e){var t=document.getElementById(e);t&&M(t)}))});n.observe(document.body,{childList:!0,subtree:!0})}}}var L=document.createElement("style");L.textContent=".forum-mention{color:var(--accent);cursor:pointer;font-weight:600;transition:opacity 0.15s;}.forum-mention:hover{opacity:0.8;text-decoration:underline;}",document.head.appendChild(L),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(z,1e3)}):setTimeout(z,1e3)}(),function(){"use strict";var e=[{emoji:"⚡",title:"Bitcoin Payments Only",desc:"All transactions use Bitcoin (Lightning or on-chain). No fiat payments. Buyers and sellers handle payment directly — LightningMart is not an escrow or payment processor."},{emoji:"🚫",title:"No Illegal or Illicit Items",desc:"Strictly prohibited: drugs, weapons, stolen goods, counterfeit items, hacking tools, malware, pirated content, illegal services of any kind. Violation results in immediate ban and may be reported to authorities."},{emoji:"🔞",title:"No Adult or Sexual Content",desc:"No selling or advertising of sexual services, adult content, escort services, or any sexually explicit material. This is an educational Bitcoin marketplace — keep it appropriate for all ages."},{emoji:"🎭",title:"No Fraud or Misrepresentation",desc:"List items honestly. No fake photos, misleading descriptions, bait-and-switch tactics, or counterfeit goods. If it's used, say so. If it has defects, disclose them."},{emoji:"🛡️",title:"Buyer & Seller Safety",desc:"Meet in public places for local trades. Never share your seed phrase, private keys, or send Bitcoin before receiving the item. Use Lightning for instant, irreversible payments."},{emoji:"💰",title:"No Money Laundering or Wash Trading",desc:"No using the marketplace to launder money, create fake transactions, artificially inflate sales, or manipulate pricing. All listings must represent genuine offers."},{emoji:"📋",title:"Accurate Listings",desc:"Titles must clearly describe the item. Include condition, shipping options, and price in sats. One listing per item — no duplicate spam listings."},{emoji:"🤝",title:"Be Professional & Respectful",desc:"Communicate clearly with buyers/sellers. Respond to messages promptly. No harassment, threats, discrimination, or abusive language in any marketplace interaction."},{emoji:"🚫",title:"No Financial Products or Securities",desc:'No selling of financial instruments, investment schemes, MLM/pyramid schemes, "guaranteed returns," or unregistered securities. This is a marketplace for goods and services, not investments.'},{emoji:"⚖️",title:"Disputes & Moderation",desc:"LightningMart does not mediate disputes. All sales are final between buyer and seller. Report fraudulent listings using the 🚩 button. Moderators may remove listings and ban users without notice."}];function t(t){for(var o='

    LightningMart Rules

    Read before buying or selling
    ',n=0;n'+i.emoji+'
    '+i.title+'
    '+i.desc+"
    "}o+='',o+="
    ";var a=document.createElement("div");a.id="marketRulesOverlay",a.innerHTML=o,document.body.appendChild(a)}function o(){if(!auth||!auth.currentUser)return!1;var e=auth.currentUser.email||"";return"needcreations@gmail.com"===e||"info.603btc@gmail.com"===e}window.acceptMarketRules=function(){localStorage.setItem("btc_market_rules_accepted","true");var e=document.getElementById("marketRulesOverlay");e&&e.remove()},window.showMarketRulesBtn=function(){t()};var n=[{id:"educational",name:"Educational Products",emoji:"🎓",desc:"Learn Bitcoin with the best tools"},{id:"general",name:"Other Products",emoji:"🛒",desc:"Buy & sell everything else"},{id:"merchants",name:"More Bitcoin Merchants",emoji:"🏪",desc:"Browse more Bitcoin merchants"},{id:"noderunners",name:"Even More Merchants",emoji:"🌐",desc:"Bitcoin shops via Node Runners"}],i=[{id:"books",name:"Books",emoji:"📚",section:"educational"},{id:"courses",name:"Courses & Workshops",emoji:"🎓",section:"educational"},{id:"hardware_edu",name:"Hardware Wallets",emoji:"🔐",section:"educational"},{id:"nodes",name:"Node Kits & Guides",emoji:"💻",section:"educational"},{id:"kids",name:"Kids & Family",emoji:"👨‍👩‍👧‍👦",section:"educational"},{id:"tools",name:"Learning Tools",emoji:"🧰",section:"educational"},{id:"edu_other",name:"Other Educational",emoji:"📦",section:"educational"},{id:"mining",name:"Mining Equipment",emoji:"⛏️",section:"general"},{id:"merch",name:"Apparel & Merch",emoji:"👕",section:"general"},{id:"art",name:"Art & Collectibles",emoji:"🎨",section:"general"},{id:"stickers",name:"Stickers & Prints",emoji:"🖼️",section:"general"},{id:"services",name:"Services",emoji:"🛠️",section:"general"},{id:"electronics",name:"Electronics & Tech",emoji:"📱",section:"general"},{id:"other",name:"Other",emoji:"📦",section:"general"}],a=[{id:"new",label:"New",color:"#22c55e"},{id:"like_new",label:"Like New",color:"#84cc16"},{id:"good",label:"Good",color:"#eab308"},{id:"fair",label:"Fair",color:"#f97316"},{id:"for_parts",label:"For Parts",color:"#ef4444"}],r=[{id:"newest",label:"Newest First"},{id:"price_low",label:"Price: Low → High"},{id:"price_high",label:"Price: High → Low"},{id:"popular",label:"Most Saved"}];function s(e,t){"listing"===e?history.pushState({channel:"marketplace",mktView:"listing",listingId:t},"","#marketplace/listing/"+t):"my"===e&&history.pushState({channel:"marketplace",mktView:"my"},"","#marketplace/my")}window.handleMarketplacePopState=function(e,t){if(e&&"listing"===e.mktView&&e.listingId)return renderMarketplace({listingId:e.listingId,_noHistory:!0}),!0;if(e&&"my"===e.mktView)return showMyListings(!0),!0;if(t&&0===t.indexOf("marketplace/listing/")){var o=t.replace("marketplace/listing/","");return renderMarketplace({listingId:o,_noHistory:!0}),!0}return"marketplace/my"===t?(showMyListings(!0),!0):(renderMarketplace({_noHistory:!0}),!0)};var c=!1,l=!1;function d(e,t){var o=document.getElementById(e),n=document.getElementById(t);if(o&&n){var i=n.getBoundingClientRect();o.style.cssText="position:fixed;left:"+i.left+"px;top:"+i.top+"px;width:"+i.width+"px;height:"+i.height+"px;z-index:100;border-radius:12px;overflow:hidden;border:1px solid var(--border);background:var(--card-bg);pointer-events:auto;",o._reposition=function(){var e=n.getBoundingClientRect();o.style.left=e.left+"px",o.style.top=e.top+"px",o.style.width=e.width+"px",o.style.height=e.height+"px"},window.addEventListener("scroll",o._reposition,!0),window.addEventListener("resize",o._reposition)}}function u(e){var t=document.getElementById(e);t&&(t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t._reposition&&(window.removeEventListener("scroll",t._reposition,!0),window.removeEventListener("resize",t._reposition),t._reposition=null))}function p(e){var t=document.getElementById("forumContainer");if(t){t.style.display="block",t.innerHTML="";var c=e.category||"all",l=e.search||"",p=e.sort||"newest",m=e.listingId||null;if(m)return e._noHistory||s("listing",m),void function(e,t){e.innerHTML='
    Loading...
    ',db.collection("marketplace").doc(t).get().then(function(n){if(n.exists){var r={id:n.id,...n.data()},s=a.find(function(e){return e.id===r.condition}),c=s?s.label:"",l=s?s.color:"var(--text-faint)",d=i.find(function(e){return e.id===r.category}),u=d?d.emoji+" "+d.name:"📦 Other",p=-1!==safeJSON("btc_market_saved",[]).indexOf(r.id),m=void 0!==auth&&auth.currentUser&&auth.currentUser.uid===r.sellerUid,h=o(),f=r.priceSats>=1e6?(r.priceSats/1e6).toFixed(2)+"M sats":r.priceSats>=1e3?Math.floor(r.priceSats/1e3)+"K sats":r.priceSats.toLocaleString()+" sats",y="";try{var v=parseFloat(localStorage.getItem("btc_last_price")||"0");v>0&&(y=' (~$'+(r.priceSats/1e8*v).toFixed(2)+")")}catch(e){}var b=g(r.createdAt?r.createdAt.toDate():new Date),w='
    ';w+='',r.imageUrl?w+="
    ]/g,""):"")+"') center/contain no-repeat;background-color:var(--bg-side);border-radius:14px;border:1px solid var(--border);margin-bottom:16px;\">
    ":w+='
    '+(d?d.emoji:"📦")+"
    ",w+='
    '+escapeHtml(r.title)+'
    ⚡ '+f+y+"
    ",w+='
    '+c+''+u+'🕐 '+b+""+(r.shipping?'📦 Ships':"")+(r.localPickup?'📍 Local pickup':"")+"
    ",w+='
    Description
    '+escapeHtml(r.description||"No description provided.")+"
    ",w+='
    Seller
    '+(r.sellerName?r.sellerName.charAt(0).toUpperCase():"?")+'
    '+escapeHtml(r.sellerName||"Anonymous")+"
    "+(r.sellerRank?'
    '+escapeHtml(r.sellerRank)+"
    ":"")+'
    👤
    ',m?w+='
    ':(w+='
    '+(h?"':"")+"
    ",w+='
    🛡️ Safety Tips: Use escrow when possible. Never send payment before receiving the item. Meet in public if trading locally. Report suspicious listings.
    ',r.lightningAddress&&(w+='
    ⚡ This seller accepts Lightning payments
    ')),w+="
    ",e.innerHTML=w,db.collection("marketplace").doc(t).update({views:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})}else e.innerHTML='
    😕
    Listing not found
    '}).catch(function(){e.innerHTML='
    Error loading listing.
    '})}(t,m);var h='
    ';h+='
    Home
    ',h+='
    Lightning Mart
    Buy & sell with Bitcoin ⚡
    ',h+='
    ';var f=e.section||"merchants";if("all"!==c&&"all"===f){var y=i.find(function(e){return e.id===c});y&&(f=y.section)}h+='
    ';for(var v=[{id:"all",name:"All",emoji:"🛒"}].concat(n),b=0;b'+w.emoji+" "+w.name+""}if(h+="
    ",u("gmIframeWrap"),u("nrIframeWrap"),"merchants"===f)return h+='
    ',h+="
    ",t.innerHTML=h,void d("gmIframeWrap","gmIframePlaceholder");if("noderunners"===f)return h+='
    ',h+="",t.innerHTML=h,void d("nrIframeWrap","nrIframePlaceholder");var k="all"===f?i:i.filter(function(e){return e.section===f});h+='
    ',h+="';for(var T=0;T'+S.emoji+" "+S.name+""}h+="
    ","educational"!==f&&"all"!==f||(h+='
    🛒
    603BTC Pleb Shop
    Bitcoin educational products, merch & gear
    '),h+='
    Loading...
    ",h+='
    ',h+="",t.innerHTML=h,function(e,t,o,n){var r=document.getElementById("marketListings"),s=document.getElementById("marketResultCount");if(r&&void 0!==db){for(var c='
    ',l=0;l<6;l++)c+='
    ';c+="
    ",r.innerHTML=c;var d=db.collection("marketplace").where("status","==","active");e&&"all"!==e&&(d=d.where("category","==",e)),(d="price_low"===o?d.orderBy("priceSats","asc"):"price_high"===o?d.orderBy("priceSats","desc"):"popular"===o?d.orderBy("saves","desc"):d.orderBy("createdAt","desc")).limit(50).get().then(function(e){var o=[];if(e.forEach(function(e){o.push({id:e.id,...e.data()})}),n&&"all"!==n){var c=i.filter(function(e){return e.section===n}).map(function(e){return e.id});o=o.filter(function(e){return-1!==c.indexOf(e.category)})}if(t){var l=t.toLowerCase();o=o.filter(function(e){return(e.title||"").toLowerCase().includes(l)||(e.description||"").toLowerCase().includes(l)})}if(s&&(s.textContent=o.length+" listing"+(1!==o.length?"s":"")),0!==o.length){var d=safeJSON("btc_market_saved",[]);r.innerHTML=o.map(function(e){var t,o=-1!==d.indexOf(e.id),n=a.find(function(t){return t.id===e.condition}),r=n?n.color:"var(--text-faint)",s=n?n.label:"",c=i.find(function(t){return t.id===e.category}),l=c?c.emoji:"📦";return t=e.priceSats>=1e6?(e.priceSats/1e6).toFixed(2)+"M sats":e.priceSats>=1e3?Math.floor(e.priceSats/1e3)+"K sats":e.priceSats.toLocaleString()+" sats","
    '+(e.imageUrl?"
    ]/g,""):"")+"') center/cover;border-bottom:1px solid var(--border);\">
    ":'
    '+l+"
    ")+'
    '+escapeHtml(e.title)+'
    ⚡ '+t+"
    "+(satsToUSD(e.priceSats)?'
    '+satsToUSD(e.priceSats)+"
    ":'
    ')+'
    '+s+"'+(o?"❤️":"🤍")+"
    "}).join("")}else r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){console.error("Marketplace load error:",e),r&&("failed-precondition"===e.code?(console.log("Trying fallback marketplace query..."),db.collection("marketplace").orderBy("createdAt","desc").limit(50).get().then(function(e){var t=[];e.forEach(function(e){var o=e.data();o.id=e.id,"active"===o.status&&t.push(o)}),t.length>0?(r.innerHTML=t.map(function(e){return"
    '+escapeHtml(e.title||"Untitled")+'
    ⚡ '+(e.priceSats||0).toLocaleString()+" sats
    "}).join(""),s&&(s.textContent=t.length+" listing"+(1!==t.length?"s":""))):r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){r.innerHTML='
    ⚙️ Marketplace needs a database index.
    This is a one-time setup.

    Click here to create the index manually if requested →
    '})):r.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+". Try refreshing.
    ")})}}(c,l,p,f)}}window._hideMarketIframes=function(){u("gmIframeWrap"),u("nrIframeWrap")},window.renderMarketplace=function(e){if(e=e||{},document.getElementById("forumContainer")){if(c||(c=!0,"true"!==localStorage.getItem("btc_market_rules_accepted")&&t()),function(){if(!l){if(l=!0,!document.getElementById("gmIframeWrap")){var e=document.createElement("div");e.id="gmIframeWrap",e.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",e.innerHTML='',document.body.appendChild(e)}if(!document.getElementById("nrIframeWrap")){var t=document.createElement("div");t.id="nrIframeWrap",t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t.innerHTML='',document.body.appendChild(t)}}}(),"function"==typeof showSkeletonLoader&&!e.listingId&&!e.search)return showSkeletonLoader("forumContainer"),void setTimeout(()=>p(e),300);p(e)}},window.showCreateListing=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to create a listing!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e='
    📝 Create Listing
    — or paste an image URL —
    ',t=document.createElement("div");t.innerHTML=e,document.body.appendChild(t.firstChild)};var m=0;function g(e){var t=Math.floor((new Date-e)/1e3);if(t<60)return"just now";var o=Math.floor(t/60);if(o<60)return o+"m ago";var n=Math.floor(o/60);if(n<24)return n+"h ago";var i=Math.floor(n/24);return i<30?i+"d ago":Math.floor(i/30)+"mo ago"}window.submitListing=function(){if(!window._mktSubmitting){var e=Date.now();if(e-m<6e4)"function"==typeof showToast&&showToast("⏳ Wait 60 seconds between listings");else{m=e;var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim();"function"==typeof sanitizeInput&&(t=sanitizeInput(t),a=sanitizeInput(a));var r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),c=document.getElementById("mktShipping").checked,l=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1||o>1e11)showToast("Price must be between 1 and 100B sats");else{var d=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anonymous",u="";if(void 0!==currentUser&¤tUser&&"function"==typeof getLevel){var p=getLevel(currentUser.points||0);u=p.emoji+" "+p.name}var g={title:t,description:a,priceSats:o,category:n,condition:i,imageUrl:r||null,lightningAddress:s||null,shipping:c,localPickup:l,sellerUid:auth.currentUser.uid,sellerName:d,sellerRank:u,status:"active",views:0,saves:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()};db.collection("marketplace").add(g).then(function(){window._mktUploadedImage=null;var e=document.getElementById("createListingOverlay");e&&e.remove(),"function"==typeof showToast&&showToast("🛒 Listing posted!"),"function"==typeof awardPoints&&awardPoints(15,"🛒 Marketplace listing!"),auth&&auth.currentUser&&(db.collection("users").doc(auth.currentUser.uid).update({marketListings:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketListings=(currentUser.marketListings||0)+1)),renderMarketplace()}).catch(function(e){console.error("Marketplace post error:",e),showToast("Error posting: "+(e.code||e.message||"Unknown error"))})}}}},window.toggleMarketSave=function(e){var t=safeJSON("btc_market_saved",[]),o=t.indexOf(e);-1!==o?(t.splice(o,1),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(-1)}).catch(function(e){console.error("[marketplace] Error:",e)})):(t.push(e),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})),localStorage.setItem("btc_market_saved",JSON.stringify(t)),void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({marketSaved:t}).catch(function(e){console.error("[marketplace] Error:",e)});var n=document.getElementById("forumContainer");n&&n.innerHTML.includes("marketListings")&&renderMarketplace()},window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return showToast("🔒 Sign in to contact sellers"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var o='
    💬 Message '+escapeHtml(t)+'
    ',n=document.createElement("div");n.innerHTML=o,document.body.appendChild(n.firstChild)},window.sendMarketMessage=function(e){var t=(document.getElementById("mktMessage").value||"").trim();if(t){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Buyer";db.collection("marketplace").doc(e).get().then(function(n){if(n.exists){var i=n.data().sellerUid||"";return db.collection("marketplace_messages").add({listingId:e,buyerUid:auth.currentUser.uid,sellerUid:i,buyerName:o,message:t,createdAt:firebase.firestore.FieldValue.serverTimestamp(),read:!1})}showToast("Listing not found")}).then(function(){var t=document.getElementById("contactSellerOverlay");t&&t.remove(),showToast("💬 Message sent to seller!"),"function"==typeof sendNotification&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists&&t.data().sellerUid){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(t.data().sellerUid,"dm","🛒 "+o+" is interested in your listing!","marketplace",e)}}).catch(function(){}),db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1)}).catch(function(){showToast("Error sending message. Try again.")})}else showToast("Please write a message")},window.showMyListings=function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){e||s("my");var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading your listings...
    ',db.collection("marketplace").where("sellerUid","==",auth.currentUser.uid).orderBy("createdAt","desc").get().then(function(e){var o,n='
    ';n+='',n+='
    📋 My Listings
    ',e.empty?n+='
    No listings yet. Create one!
    ':e.forEach(function(e){var t=e.data(),o="active"===t.status?"#22c55e":"sold"===t.status?"#ef4444":"var(--text-faint)";n+='
    '+escapeHtml(t.title)+'
    ⚡ '+(t.priceSats||0).toLocaleString()+' sats
    👁️ '+(t.views||0)+" views · ❤️ "+(t.saves||0)+' saves
    '+(t.status||"active")+""+("active"===t.status?"':"")+"
    "}),n+='
    💬 Messages
    ',n+='
    Loading messages...
    ',n+="
    ",t.innerHTML=n,(o=document.getElementById("myMarketMessages"))&&db.collection("marketplace_messages").orderBy("createdAt","desc").limit(20).get().then(function(e){var t=auth.currentUser.uid,n=[];e.forEach(function(e){var o=e.data();o.buyerUid===t&&n.push({id:e.id,...o,role:"buyer"})}),db.collection("marketplace").where("sellerUid","==",t).get().then(function(i){var a=[];i.forEach(function(e){a.push(e.id)}),e.forEach(function(e){var o=e.data();-1!==a.indexOf(o.listingId)&&o.buyerUid!==t&&n.push({id:e.id,...o,role:"seller"})}),0!==n.length?o.innerHTML=n.map(function(e){var t=e.createdAt?g(e.createdAt.toDate()):"";return'
    '+("seller"===e.role?"📩 From ":"📤 To seller · ")+escapeHtml(e.buyerName||"Buyer")+''+t+'
    '+escapeHtml(e.message)+"
    "}).join(""):o.innerHTML='
    No messages yet.
    '})})}).catch(function(e){console.error("My listings error:",e),"failed-precondition"===e.code?t.innerHTML='
    ⚙️ Setting up marketplace database (index)...
    Please refresh in 1 minute.
    ':t.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+"
    "}))}else showToast("🔒 Sign in to see your listings")},window.markSold=function(e){db.collection("marketplace").doc(e).update({status:"sold"}).then(function(){showToast("✅ Marked as sold!"),showMyListings()})},window.editListing=function(e){auth&&auth.currentUser&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists){var n=t.data();n.sellerUid===auth.currentUser.uid||o()?(showCreateListing(),setTimeout(function(){var t=document.getElementById("mktTitle"),o=document.getElementById("mktPrice"),i=document.getElementById("mktCategory"),a=document.getElementById("mktCondition"),r=document.getElementById("mktDesc"),s=document.getElementById("mktImage"),c=document.getElementById("mktLightning"),l=document.getElementById("mktShipping"),d=document.getElementById("mktLocal");t&&(t.value=n.title||""),o&&(o.value=n.priceSats||"",updateMktPriceUSD()),i&&(i.value=n.category||""),a&&(a.value=n.condition||""),r&&(r.value=n.description||""),s&&n.imageUrl&&!n.imageUrl.startsWith("data:")&&(s.value=n.imageUrl||""),c&&(c.value=n.lightningAddress||""),l&&(l.checked=!!n.shipping),d&&(d.checked=!!n.local);var u=document.getElementById("createListingOverlay");if(u){var p=u.querySelector('div[style*="font-size:1.2rem"]');p&&(p.textContent="✏️ Edit Listing")}var m=u?u.querySelector('button[onclick*="submitListing"]'):null;m&&(m.textContent="✏️ Update Listing",m.onclick=function(){updateExistingListing(e)})},100)):showToast("You can only edit your own listings")}else showToast("Listing not found")}).catch(function(e){showToast("Error loading listing: "+(e.message||"Unknown"))})},window.updateExistingListing=function(e){var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim(),r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),c=document.getElementById("mktShipping").checked,l=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1)showToast("Please enter a price in sats");else{var d={title:t.substring(0,80),priceSats:o,category:n,condition:i,description:a.substring(0,1e3),lightningAddress:s,shipping:c,local:l,updatedAt:firebase.firestore.FieldValue.serverTimestamp()};r&&(d.imageUrl=r),db.collection("marketplace").doc(e).update(d).then(function(){var t=document.getElementById("createListingOverlay");t&&t.remove(),showToast("✅ Listing updated!"),window._mktUploadedImage=null,renderMarketplace({listingId:e})}).catch(function(e){showToast("Error updating: "+(e.message||"Unknown"))})}},window.deleteListing=function(e){if(auth&&auth.currentUser){var t=o();confirm(t?"Admin: Delete this listing?":"Delete this listing?")&&db.collection("marketplace").doc(e).update({status:"deleted",deletedBy:t?"admin":"owner",deletedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){showToast("🗑️ Listing deleted"),renderMarketplace()})}},window.updateMktPriceUSD=function(){var e=parseInt(document.getElementById("mktPrice").value)||0,t=document.getElementById("mktPriceUSD");if(t)if(e<=0)t.textContent="";else{var o=parseFloat(localStorage.getItem("btc_last_price")||"0");if(o<=0)return fetch("https://mempool.space/api/v1/prices").then(function(e){return e.json()}).then(function(e){e&&e.USD&&(localStorage.setItem("btc_last_price",e.USD),updateMktPriceUSD())}).catch(function(e){console.error("[marketplace] Error:",e)}),void(t.textContent="Loading USD price...");var n=e/1e8*o;t.textContent="≈ $"+n.toFixed(2)+" USD"}},window.satsToUSD=function(e){var t=parseFloat(localStorage.getItem("btc_last_price")||"0");return t<=0||!e?"":"~$"+(e/1e8*t).toFixed(2)},window.handleMktImageUpload=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var o=new FileReader;o.onload=function(e){var t=new Image;t.onload=function(){var e=t.width,o=t.height;e>800&&(o=Math.round(800*o/e),e=800);var n=document.createElement("canvas");n.width=e,n.height=o,n.getContext("2d").drawImage(t,0,0,e,o);var i=n.toDataURL("image/jpeg",.8),a=document.getElementById("mktImagePreview"),r=document.getElementById("mktImagePreviewImg");a&&r&&(r.src=i,a.style.display="block"),window._mktUploadedImage=i;var s=document.getElementById("mktImage");s&&(s.value="")},t.src=e.target.result},o.readAsDataURL(t)}},window._plebShopOpen=!1,window._togglePlebShop=function(){var e=document.getElementById("plebShopEmbed"),t=document.getElementById("plebShopToggle");e&&(window._plebShopOpen=!window._plebShopOpen,window._plebShopOpen?(e.style.display="block",e.style.height="calc(100vh - 280px)",e.style.minHeight="500px",e.querySelector("iframe")||(e.innerHTML=''),t&&(t.textContent="Close Shop",t.style.background="var(--border)")):(e.style.height="0",e.style.minHeight="0",setTimeout(function(){e.style.display="none"},300),t&&(t.textContent="Open Shop",t.style.background="var(--accent)")))},window.clearMktImage=function(){window._mktUploadedImage=null;var e=document.getElementById("mktImagePreview");e&&(e.style.display="none");var t=document.getElementById("mktImageFile");t&&(t.value="")}}();var MSG_CONFIG={onlineThreshold:3e5,awayThreshold:9e5,presenceInterval:6e4,maxMsgLength:500,maxMsgsPerHour:30,maxConvoHistory:100,unreadPollInterval:3e4,maxNewConvosPerDay:5,newAccountCooldownMs:864e5,minPointsToDM:50,duplicateWindowMs:5e3},SUSPICIOUS_PATTERNS=[/send\s*(?:me|ur|your)\s*(?:btc|bitcoin|sats|seed|key|phrase)/i,/(?:double|triple|multiply)\s*(?:your|ur)\s*(?:btc|bitcoin|sats|crypto)/i,/(?:free|win|won|claim|airdrop)\s*(?:btc|bitcoin|sats|crypto|nft)/i,/(?:invest|deposit)\s*(?:now|today|here)\b/i,/(?:guaranteed|100%)\s*(?:return|profit|roi)/i,/send\s*\d+\s*(?:btc|sats)\s*(?:to|and)\s*(?:get|receive|earn)/i,/(?:seed|private)\s*(?:phrase|key)\s*(?:here|now|please|share)/i,/(?:validate|verify|sync)\s*(?:your|ur)\s*(?:wallet|account)/i,/(?:connect|link)\s*(?:your|ur)\s*(?:wallet|metamask|phantom)/i,/(?:nigerian|prince|inheritance|lottery)\s*(?:fund|money|payment)/i],SUSPICIOUS_URLS=[/bit\.ly|tinyurl|t\.co|goo\.gl|is\.gd|buff\.ly|ow\.ly|rebrand\.ly/i,/(?:discord\.gift|discordapp\.gift|nitro.*free)/i,/(?:steamcommunity|steampowered).*(?:gift|trade|login)/i,/(?:wallet|connect|validate|sync|claim|airdrop).*(?:\.com|\.io|\.xyz|\.site|\.app)/i,/(?:dapp|defi|swap|bridge|mint).*(?:\.com|\.io|\.xyz|\.site)/i],BLOCKED_CONTENT=[/(?:child|minor|underage).*(?:porn|nude|nsfw)/i,/(?:kill|murder|attack|bomb|shoot).*(?:yourself|someone|them|people|school)/i,/\b(?:doxx|doxing|swat)\b/i,/\b(?:nigger|nigga|faggot|kike|spic|wetback|chink|gook|towelhead|raghead|beaner|coon|darkie|zipperhead)\b/i,/\b(?:white\s*power|white\s*supremacy|sieg\s*heil|race\s*war|ethnic\s*cleansing|final\s*solution)\b/i,/\b(?:gas\s*the|death\s*to)\s+\w+/i,/\b(?:heil\s*hitler|genocide)\b/i,/\b(?:i\s*(?:will|wanna|gonna|want\s*to)\s*(?:kill|hurt|stab|shoot|beat|attack|find)\s*(?:you|u|him|her|them))\b/i,/\b(?:i\s*know\s*where\s*(?:you|u)\s*live)\b/i,/\b(?:watch\s*your\s*back|you(?:'re|\s*are)\s*dead)\b/i,/\b(?:track\s*(?:you|u)\s*down|come\s*find\s*(?:you|u))\b/i,/\b(?:kill\s*myself|cut(?:ting)?\s*myself|slit\s*my\s*wrist|hang\s*myself|end\s*my\s*life)\b/i,/\b(?:want(?:a)?\s*(?:to\s*)?die|kys|kill\s*yourself)\b/i,/\b(?:self[\s-]*harm|overdose\s*on|jump\s*off\s*a)\b/i,/\b(?:blowjob|handjob|gangbang|threesome|deepthroat|rimjob|creampie)\b/i,/\b(?:send\s*(?:me\s*)?nudes|dick\s*pic|show\s*(?:me\s*)?(?:your|ur)\s*(?:body|tits|boobs|ass|pussy|dick))\b/i,/\b(?:wanna|want\s*to|lets)\s*(?:fuck|bang|screw|bone|smash)\b/i,/\b(?:suck\s*my|sit\s*on\s*my|bend\s*over|get\s*on\s*your\s*knees)\b/i,/\b(?:masturbat|fingering|bondage|bdsm|fetish|dominatrix)\b/i,/\b(?:escort|prostitut|hooker|camgirl|sexting)\b/i],PII_PATTERNS=[/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:phone|number|address|email|ssn|social|zip|location|real name|full name|home|where.*live)/i,/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:id|passport|driver.?s?\s*license|bank|routing|account\s*number|credit\s*card|debit\s*card)/i,/(?:dm|message|text|call|contact)\s*(?:me\s+)?(?:on|at|@)\s*(?:whatsapp|telegram|signal|insta|instagram|snap|snapchat|facebook|messenger|wechat|line)\b/i,/(?:my|here(?:'s| is))\s*(?:phone|number|cell|whatsapp|telegram|signal)\s*(?:is|:|\s)\s*[\+\d\(\)\-\s]{7,}/i,/(?:my|here(?:'s| is))\s*(?:email|e-mail)\s*(?:is|:|\s)\s*\S+@\S+\.\S+/i,/(?:my|here(?:'s| is))\s*(?:address|location)\s*(?:is|:)/i];function containsSuspiciousLink(e){for(var t=e.match(/https?:\/\/[^\s<>"{}|\\^`\[\]]+/gi)||[],o=0;o]*>/g,"")).trim()).length>MSG_CONFIG.maxMsgLength&&(e=e.substring(0,MSG_CONFIG.maxMsgLength)),e):""}function containsPII(e){for(var t=0;t"']+)/gi,function(e){return''+e+""})}function _getDailyConvoLog(){try{var e=localStorage.getItem("btc_dm_daily_log");if(!e)return{date:"",recipients:[]};var t=JSON.parse(e),o=(new Date).toISOString().slice(0,10);return t.date!==o?{date:o,recipients:[]}:t}catch(e){return{date:(new Date).toISOString().slice(0,10),recipients:[]}}}function _logNewConvo(e){var t=_getDailyConvoLog();t.date=(new Date).toISOString().slice(0,10),-1===t.recipients.indexOf(e)&&t.recipients.push(e),localStorage.setItem("btc_dm_daily_log",JSON.stringify(t))}function _canStartNewConvo(e){var t=_getDailyConvoLog();return-1!==t.recipients.indexOf(e)||t.recipients.length
    🚨
    "Friends in Distress" Scam
    Scammers will impersonate people you know and trust — your friends, family, even coworkers. They can:
    • Clone their profile picture, name, and bio
    • Copy their writing style and messages
    • Use AI-generated voice clones that sound exactly like them
    • Create fake emergencies — "I\'m stuck," "I need help," "send me Bitcoin and I\'ll pay you back"
    The scammer will pressure you to act fast so you don\'t have time to think or verify. They prey on your emotions and trust.
    🛡️ How to protect yourself:
    NEVER send Bitcoin to anyone claiming to be in distress over a message
    Verify their identity through a separate channel — call them, video chat, or meet in person
    Real friends will understand if you take time to verify
    Bitcoin transactions are irreversible — once sent, it\'s gone forever
    • If it feels urgent and emotional, that\'s exactly what the scammer wants
    ',document.body.appendChild(e.firstChild)};var _lastSentMsg={text:"",time:0};function _isDuplicateMessage(e){var t=Date.now();return e===_lastSentMsg.text&&t-_lastSentMsg.time
    Why are you reporting this user?
    ',i=document.createElement("div");return i.innerHTML=n,void document.body.appendChild(i.firstChild)}},window.submitReport=function(e,t,o){var n=document.getElementById("reportModal");if(n&&n.remove(),db&&auth&&auth.currentUser){var i=void 0!==currentUser&¤tUser?currentUser.username:"Anonymous";db.collection("reports").add({reportedUid:e,reportedName:t,reporterUid:auth.currentUser.uid,reporterName:i,reason:o,createdAt:firebase.firestore.FieldValue.serverTimestamp(),status:"pending"}).then(function(){"function"==typeof showToast&&showToast("🚩 Report submitted. Thank you for keeping the community safe."),blockUser(e,t)}).catch(function(){"function"==typeof showToast&&showToast("Failed to submit report")})}};var _presenceTimer=null;function updatePresence(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e="false"!==localStorage.getItem("btc_online_status");try{e?db.collection("users").doc(auth.currentUser.uid).update({lastSeen:firebase.firestore.FieldValue.serverTimestamp(),isOnline:!0}).catch(function(){}):db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:null}).catch(function(){})}catch(e){}}}function startPresenceTracking(){updatePresence(),_presenceTimer&&clearInterval(_presenceTimer),_presenceTimer=setInterval(updatePresence,MSG_CONFIG.presenceInterval),window.addEventListener("beforeunload",function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db)try{db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){}}),document.addEventListener("visibilitychange",function(){"visible"===document.visibilityState&&updatePresence()})}function profileStat(e,t,o){return'
    '+e+'
    '+t+'
    '+o+"
    "}window.toggleOnlineStatus=function(){updatePresence()},window.getOnlineStatus=function(e){if(!e)return{status:"offline",color:"#6b7280",label:"Offline",dot:"⚫"};var t=e.toDate?e.toDate().getTime():"number"==typeof e?e:new Date(e).getTime(),o=Date.now()-t;return o'},window.showUserProfile=function(e){if(e&&db){var t=document.createElement("div");t.innerHTML='
    Loading profile...
    ',document.body.appendChild(t.firstChild),db.collection("users").doc(e).get().then(function(t){if(!t.exists)return(m=document.getElementById("userProfileModal"))&&m.remove(),void("function"==typeof showToast&&showToast("User not found"));var o=t.data(),n=getOnlineStatus(o.lastSeen),i="function"==typeof getLevel?getLevel(o.points||0):{name:"Newbie",emoji:"🌱"},a=o.createdAt&&o.createdAt.toDate?o.createdAt.toDate().toLocaleDateString():"Unknown",r="function"==typeof escapeHtml?escapeHtml(o.displayBadge||o.equippedBadge||""):(o.displayBadge||o.equippedBadge||"").replace(//g,">").replace(/"/g,"""),s=0;o.visibleBadges&&(s+=o.visibleBadges.length),o.hiddenBadges&&(s+=o.hiddenBadges.length);var c="";if(r){var l=r;if(void 0!==HIDDEN_BADGES&&r.length>5){var d=HIDDEN_BADGES.find(e=>e.id===r);d&&(l=d.emoji)}c='
    '+l+' '+i.emoji+"
    "}else c='
    '+i.emoji+"
    ";var u,p,m,g=auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&auth.currentUser.uid!==e,h=g?_canAccountDM():{ok:!1},f='
    '+c+'
    '+escapeHtml(o.username||"Bitcoiner")+'
    '+i.name+" · "+(o.points||0).toLocaleString()+' XP
    '+n.label+"
    "+(o.bio?'
    About
    '+escapeHtml(o.bio)+"
    ":"")+(o.twitter||o.nostr||o.website?'
    '+(o.twitter?'𝕏 '+escapeHtml(o.twitter)+"":"")+(o.nostr?'🟣 Nostr':"")+(o.website&&!/^(javascript|data|vbscript|blob):/i.test(o.website.trim())?'🌐 Website':"")+"
    ":"")+'
    '+profileStat("🏅",s,"Badges")+profileStat("📖",Array.isArray(o.visitedChannelsList)?o.visitedChannelsList.length:Array.isArray(o.readChannels)?o.readChannels.length:0,"Channels")+profileStat("🎟️",o.orangeTickets||0,"Tickets")+'
    '+profileStat("🗣️",o.forumPosts||0,"Posts")+profileStat("🔥",(o.streak||0)+"("+(o.bestStreak||o.streak||0)+")","Streak")+profileStat("📅",a,"Joined")+"
    "+(o.pvpWins||o.pvpLosses?'
    '+profileStat("⚔️",(o.pvpWins||0)+"W","PVP Wins")+profileStat("💀",(o.pvpLosses||0)+"L","PVP Losses")+profileStat("📊",((o.pvpWins||0)+(o.pvpLosses||0)>0?Math.round((o.pvpWins||0)/((o.pvpWins||0)+(o.pvpLosses||0))*100):0)+"%","Win Rate")+"
    ":"")+(o.predictions&&o.predictions.total?(p=(u=o.predictions).total>0?Math.round(u.correct/u.total*100):0,'
    '+profileStat("📈",u.total,"Predictions")+profileStat("🎯",p+"%","Accuracy")+profileStat("🔥",u.bestStreak||u.streak||0,"Best Streak")+"
    "):"")+(o.lightningAddress||o.lightning?(window._profileTipData={recipientName:o.username||"Bitcoiner",recipientUid:e,lightningAddress:o.lightningAddress||o.lightning||"",label:"Tip "+(o.username||"Bitcoiner"),context:"profile"},'
    '+escapeHtml(o.lightningAddress||o.lightning)+'
    "):"")+(g&&h.ok?"":g&&!h.ok?'
    '+escapeHtml(h.reason)+"
    ":auth&&auth.currentUser&&!auth.currentUser.isAnonymous?"":"")+(g?'
    '+(isUserBlocked(e)?"":"")+"
    ':"")+"
    ";(m=document.getElementById("userProfileModal"))&&m.remove();var y=document.createElement("div");y.innerHTML=f,document.body.appendChild(y.firstChild)}).catch(function(t){console.error("Profile load error:",t);var o=document.getElementById("userProfileModal");o&&o.remove(),"function"==typeof showToast&&showToast("Could not load profile ["+e+"]: "+(t.message||"permission error"))})}},window._tipFromProfile=function(){var e=window._profileTipData;if(e){var t=document.getElementById("userProfileModal");t&&t.remove(),"function"==typeof showTipOverlay?showTipOverlay(e):"function"==typeof showToast&&showToast("⚡ Lightning tips still loading, try again in a moment")}};var _msgSentTimestamps=[];function checkRateLimit(){var e=Date.now();return(_msgSentTimestamps=_msgSentTimestamps.filter(function(t){return e-t<36e5})).length
    💬 '+escapeHtml(o)+'
    ⚠️ Never share your seed phrase, private keys, or send Bitcoin to strangers or "friends in distress."
    ',s=document.createElement("div");s.innerHTML=r,document.body.appendChild(s.firstChild),setTimeout(function(){var e=document.getElementById("dmInput");e&&e.focus()},300),loadDMMessages(e,n,t,o),db.collection("dm_conversations").doc(e).get().then(function(e){if(e.exists&&e.data().isBuddyMatch){var t=document.getElementById("dmWindow");if(!t)return;var o=t.querySelector('div[style*="rgba(234,179,8,0.1)"]');o&&(o.style.background="rgba(34,197,94,0.08)",o.style.borderColor="rgba(34,197,94,0.2)",o.style.color="#22c55e",o.innerHTML="🦌 Nacho is in this chat! Ask any Bitcoin question and Nacho will jump in. Teachers can add context to help learners.")}}).catch(function(){}),db.collection("users").doc(t).get().then(function(e){if(e.exists){var t=getOnlineStatus(e.data().lastSeen),o=document.getElementById("dmStatusDot");o&&(o.innerHTML='')}}).catch(function(){})}function loadDMMessages(e,t,o,n){var i=document.getElementById("dmMessages");i&&(i.innerHTML='
    Loading messages...
    ',window._dmUnsubscribe=db.collection("dm_conversations").doc(e).collection("messages").orderBy("createdAt","asc").limit(MSG_CONFIG.maxConvoHistory).onSnapshot(function(o){if(i.innerHTML="",o.empty)i.innerHTML='
    💬
    Start a conversation with '+escapeHtml(n)+'!
    Messages are private between you two.
    ';else{var a="";o.forEach(function(e){var o=e.data(),n=o.senderUid===t;if(n||o.isNachoAuto||"function"!=typeof isUserBlocked||!isUserBlocked(o.senderUid)){var r=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):new Date,s=r.toLocaleDateString();s!==a&&(i.innerHTML+='
    '+s+"
    ",a=s);var c=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),l="nacho-bot"===o.senderUid||!0===o.isNachoAuto,d=n||l||!containsScamPattern(o.text)&&!containsSuspiciousLink(o.text)?"":'
    ⚠️ This message may contain a scam. Never send money to strangers.
    ',u=n||l||!containsPII(o.text)?"":'
    ⚠️ This person is asking for personal info. Only share details for Lightning Mart transactions.
    ',p=l?"rgba(34,197,94,0.08)":n?"var(--accent)":"var(--card-bg)",m=l?"1px solid rgba(34,197,94,0.25)":"none",g=l?"var(--text)":n?"#fff":"var(--text)",h=l?'
    🦌 Nacho
    ':"",f=linkifyText(escapeHtml(o.text)).replace(/\n/g,"
    "),y="";o.imageUrl&&(y=''),i.innerHTML+='
    '+h+(f||"")+y+d+u+'
    '+c+"
    "}}),i.scrollTop=i.scrollHeight,markDMRead(e,t)}},function(e){i.innerHTML='
    💬
    Start a conversation!
    Send your first message below.
    '}))}window.openDM=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to send messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var o=_canAccountDM();if(o.ok)if(isUserBlocked(e))"function"==typeof showToast&&showToast("🚫 This user is blocked. Unblock them to message.");else if(_canStartNewConvo(e)){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";showDMWindow(getConversationId(n,e),e,t,n,i)}else"function"==typeof showToast&&showToast("⏳ You can only message "+MSG_CONFIG.maxNewConvosPerDay+" new people per day. This helps keep the community safe.");else"function"==typeof showToast&&showToast(o.reason)},window.closeDM=function(){window._dmUnsubscribe&&(window._dmUnsubscribe(),window._dmUnsubscribe=null);var e=document.getElementById("dmWindow");e&&e.remove()},window.handleDMImage=function(e,t,o,n){if(e&&e.files&&e.files[0]){var i=e.files[0];if(e.value="",i.type.startsWith("image/"))if(i.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var a=null;try{a=firebase.storage()}catch(e){}if(a){"function"==typeof showToast&&showToast("📷 Uploading image…");var r=auth.currentUser.uid,s=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",c=i.type.indexOf("png")>-1?"png":i.type.indexOf("gif")>-1?"gif":i.type.indexOf("webp")>-1?"webp":"jpg",l=Date.now()+"_"+Math.random().toString(36).substr(2,6)+"."+c,d=a.ref("dm-images/"+r+"/"+l),u=document.getElementById("dmMessages");u&&(u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML=""),(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),u.innerHTML+='
    📷
    Uploading…
    ',u.scrollTop=u.scrollHeight),d.put(i,{contentType:i.type}).then(function(e){return e.ref.getDownloadURL()}).then(function(e){var i=u&&u.querySelector("[data-dm-img-uploading]");i&&i.remove();var a=db.collection("dm_conversations").doc(t),c={senderUid:r,senderName:s,text:"",imageUrl:e,createdAt:firebase.firestore.FieldValue.serverTimestamp()},l={lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r};return l["unread_"+o]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(o,"dm","📷 Image from @"+s,"dm",t),a.update(l).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[r,o],lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r,participantNames:{}};return t.participantNames[r]=s,t.participantNames[o]=n,t["unread_"+o]=firebase.firestore.FieldValue.increment(1),a.set(t)}throw e}).then(function(){return a.collection("messages").add(c)}).then(function(){"function"==typeof showToast&&showToast("📷 Image sent!"),u&&document.getElementById("dmMessages")&&loadDMMessages(t,r,o,n)})}).catch(function(e){console.error("[DM Image] Upload failed:",e),"function"==typeof showToast&&showToast("Failed to send image: "+(e.message||"upload error"));var t=u&&u.querySelector("[data-dm-img-uploading]");t&&t.remove()})}else"function"==typeof showToast&&showToast("Image upload unavailable")}else"function"==typeof showToast&&showToast("Sign in to send images");else"function"==typeof showToast&&showToast("Only images are allowed")}},window.showDMGifPicker=function(e,t,o){var n=document.getElementById("dmGifPicker");if(n)n.remove();else{var i=document.createElement("div");i.id="dmGifPicker",i.style.cssText="position:fixed;bottom:80px;left:50%;transform:translateX(-50%);z-index:600000;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:16px;padding:12px;width:90%;max-width:360px;max-height:350px;display:flex;flex-direction:column;box-shadow:0 8px 32px rgba(0,0,0,0.5);",window._dmGifConvo={convoId:e,recipientUid:t,recipientName:o},i.innerHTML='
    Type to search or tap a category
    ',document.body.appendChild(i),document.getElementById("dmGifSearchInput").focus()}};var _dmGifSearchTimer=null;function markDMRead(e,t){db.collection("dm_conversations").doc(e).update({["unread_"+t]:0}).catch(function(){})}window.searchDMGifs=function(e){_dmGifSearchTimer&&clearTimeout(_dmGifSearchTimer);var t=document.getElementById("dmGifResults");if(t)if(!e||e.length<2)t.innerHTML='
    Type to search
    ';else{var o=document.getElementById("dmGifSearchInput");o&&o.value!==e&&(o.value=e),t.innerHTML='
    Searching...
    ',_dmGifSearchTimer=setTimeout(function(){fetch("https://g.tenor.com/v1/search?q="+encodeURIComponent(e)+"&key=LIVDSRZULELA&limit=20&media_filter=minimal").then(function(e){return e.json()}).then(function(e){if(e.results&&0!==e.results.length){for(var o="",n=0;n')}t.innerHTML=o||'
    No GIFs found
    '}else t.innerHTML='
    No GIFs found
    '}).catch(function(){t.innerHTML='
    Search failed
    '})},400)}},window.sendDMGifUrl=function(){var e=document.getElementById("dmGifUrlInput");e&&e.value.trim()&&sendDMGif(e.value.trim())},window.sendDMGif=function(e){if(e){var t=window._dmGifConvo;if(t){var o=document.getElementById("dmGifPicker");if(o&&o.remove(),auth&&auth.currentUser){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",a=t.convoId,r=t.recipientUid,s=t.recipientName,c=document.getElementById("dmMessages");if(c){var l=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});c.innerHTML+='
    '+l+"
    ",c.scrollTop=c.scrollHeight}var d=db.collection("dm_conversations").doc(a),u={senderUid:n,senderName:i,text:"",imageUrl:e,isGif:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp()},p={lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n};p["unread_"+r]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(r,"dm","GIF from @"+i,"dm",a),d.update(p).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[n,r],lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n,participantNames:{}};return t.participantNames[n]=i,t.participantNames[r]=s,t["unread_"+r]=firebase.firestore.FieldValue.increment(1),d.set(t)}throw e}).then(function(){return d.collection("messages").add(u)}).then(function(){c&&document.getElementById("dmMessages")&&loadDMMessages(a,n,r,s)}).catch(function(e){console.error("[DM GIF] Send failed:",e),"function"==typeof showToast&&showToast("Failed to send GIF")})}else"function"==typeof showToast&&showToast("Sign in to send GIFs")}else"function"==typeof showToast&&showToast("Error: no conversation context")}},window.sendDM=function(e,t,o){var n=document.getElementById("dmInput");if(n){var i=sanitizeMessage(n.value);if(i)if(i.length>MSG_CONFIG.maxMsgLength)"function"==typeof showToast&&showToast("Message too long (max "+MSG_CONFIG.maxMsgLength+" chars)");else if(_isDuplicateMessage(i))"function"==typeof showToast&&showToast("⏳ Message already sent");else if(isUserBlocked(t))"function"==typeof showToast&&showToast("🚫 You have blocked this user");else if(containsBlockedContent(i))"function"==typeof showToast&&showToast("⛔ Message contains prohibited content");else{if(containsPII(i)&&!confirm("⚠️ This message appears to contain or request personal information (phone numbers, addresses, emails, etc.).\n\nSharing personal info with strangers is risky. Only share contact details for Lightning Mart transactions.\n\nSend anyway?"))return;if(!containsScamPattern(i)||confirm("⚠️ This message contains patterns commonly used in scams. Are you sure you want to send it?"))if(containsSuspiciousLink(i)&&"function"==typeof showToast&&showToast("⚠️ Warning: Suspicious link detected. Be cautious with URLs."),checkRateLimit()){var a=auth.currentUser.uid,r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";n.value="",_msgSentTimestamps.push(Date.now()),_logNewConvo(t);var s=db.collection("dm_conversations").doc(e),c={senderUid:a,senderName:r,text:i,createdAt:firebase.firestore.FieldValue.serverTimestamp()},l={lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a};l["unread_"+t]=firebase.firestore.FieldValue.increment(1);var d={participants:[a,t],lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a,participantNames:{}};d.participantNames[a]=r,d.participantNames[t]=o,d["unread_"+t]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(t,"dm","💬 New message from @"+r,"dm",e);var u=document.getElementById("dmMessages");if(u){u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML="");var p=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),m=(new Date).toLocaleDateString(),g=u.querySelector("div[data-dm-date]:last-of-type");m!==(g?g.getAttribute("data-dm-date"):"")&&(u.innerHTML+='
    '+m+"
    "),u.innerHTML+='
    '+linkifyText(escapeHtml(i))+'
    '+p+"
    ",u.scrollTop=u.scrollHeight}s.update(l).catch(function(e){if("not-found"===e.code||"permission-denied"===e.code||-1!==e.message.indexOf("NOT_FOUND")||-1!==e.message.indexOf("No document to update")||-1!==e.message.indexOf("PERMISSION_DENIED"))return s.set(d,{merge:!0});throw e}).then(function(){return s.collection("messages").add(c)}).then(function(){u&&document.getElementById("dmMessages")&&loadDMMessages(e,a,t,o);var n=parseInt(localStorage.getItem("btc_dms_sent")||"0");localStorage.setItem("btc_dms_sent",String(n+1)),"function"==typeof checkBadges&&setTimeout(checkBadges,500)}).catch(function(e){console.error("DM send error:",e),"function"==typeof showToast&&showToast("Failed to send: "+(e.code||e.message||"Unknown error"));var t=u&&u.querySelector("[data-optimistic]");t&&t.remove()})}else"function"==typeof showToast&&showToast("⏳ Slow down! Max "+MSG_CONFIG.maxMsgsPerHour+" messages per hour.")}}},window.showInbox=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to see messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e=auth.currentUser.uid,t=document.getElementById("dmInbox");t&&t.remove();var o=document.createElement("div");o.innerHTML='
    📬 Messages
    Loading...
    ',document.body.appendChild(o.firstChild),db.collection("dm_conversations").where("participants","array-contains",e).orderBy("lastMessageTime","desc").limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");o&&(console.log("Inbox snap size:",t.size),t.empty?o.innerHTML='
    📬
    No messages yet
    Tap a user on the leaderboard to start chatting!
    ':(o.innerHTML="",t.forEach(function(t){var n=t.data(),i=n.participants.find(function(t){return t!==e}),a=n.participantNames&&n.participantNames[i]||"User",r=n["unread_"+e]||0,s=n.lastMessage||"";s.length>50&&(s=s.substring(0,50)+"...");var c=n.lastMessageTime?timeAgo(n.lastMessageTime):"",l=n.lastSenderUid===e,d=!0===n.isBuddyMatch,u=d?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+';" onmouseover="this.style.background=\'var(--card-bg)\'" onmouseout="this.style.background=\''+(r>0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+'\'">
    '+(d?"🦌":a.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(a)+u+'
    '+c+'
    0?"600":"400")+';white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">'+(l?"You: ":"")+escapeHtml(s)+"
    "+(r>0?'
    '+r+"
    ":"")+"
    "})))}).catch(function(t){console.error("Inbox load error:",t);var o=document.getElementById("dmInboxList");o&&("failed-precondition"!==t.code?o.innerHTML='
    💬
    No messages yet
    Tap a user on the leaderboard or in PlebTalk to start chatting!
    ':db.collection("dm_conversations").where("participants","array-contains",e).limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");if(o)if(t.empty)o.innerHTML='
    📬
    No messages yet
    ';else{o.innerHTML="";var n=[];t.forEach(function(e){n.push({id:e.id,...e.data()})}),n.sort(function(e,t){return(t.lastMessageTime||0)-(e.lastMessageTime||0)}),n.forEach(function(t){var n=t.participants.find(function(t){return t!==e}),i=t.participantNames&&t.participantNames[n]||"User",a=t["unread_"+e]||0,r=t.lastMessage||"";r.length>50&&(r=r.substring(0,50)+"...");var s=t.lastSenderUid===e,c=!0===t.isBuddyMatch,l=c?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":c?"rgba(34,197,94,0.03)":"none")+';">
    '+(c?"🦌":i.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(i)+l+'
    '+(s?"You: ":"")+escapeHtml(r)+"
    "+(a>0?'
    '+a+"
    ":"")+"
    "})}}).catch(function(e){var t=document.getElementById("dmInboxList");t&&(t.innerHTML='
    💬
    No messages yet
    ')}))})};var _unreadCount=0,_unreadTimer=null;function checkUnreadCount(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e=auth.currentUser.uid;db.collection("dm_conversations").where("participants","array-contains",e).get().then(function(t){var o=0;t.forEach(function(t){var n=t.data();o+=n["unread_"+e]||0}),_unreadCount=o,updateUnreadBadge()}).catch(function(){})}}function updateUnreadBadge(){document.querySelectorAll(".dm-unread-badge").forEach(function(e){_unreadCount>0?(e.textContent=_unreadCount>99?"99+":_unreadCount,e.style.display="inline-flex"):e.style.display="none"});var e=document.getElementById("bnavMsgBadge");e&&(_unreadCount>0?(e.textContent=_unreadCount,e.style.display="block"):e.style.display="none")}function startUnreadPolling(){checkUnreadCount(),_unreadTimer&&clearInterval(_unreadTimer),_unreadTimer=setInterval(checkUnreadCount,MSG_CONFIG.unreadPollInterval)}window.initMessaging=function(){startPresenceTracking(),restoreBlockedList(),setTimeout(startUnreadPolling,5e3)},void 0!==auth&&auth&&auth.currentUser&&initMessaging();const HIDDEN_BADGES=[{id:"nacho_friend",name:"Nacho's Friend",emoji:"🦌",pts:25,desc:"Interact with Nacho",hint:"Click on Nacho!",hidden:!1,check:function(){return"true"===localStorage.getItem("btc_nacho_clicked")}},{id:"genesis",name:"Genesis Reader",emoji:"📜",pts:75,desc:"Read the whitepaper channel",hint:"Open the Whitepaper channel",hidden:!1,check:function(){return"undefined"!=typeof currentChannelId&&"whitepaper"===currentChannelId}},{id:"nacho_curious",name:"Curious Deer",emoji:"❓",pts:50,desc:"Ask Nacho your first question",hint:"Ask Nacho anything!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=1}},{id:"ticket_bronze",name:"Ticket Fish",emoji:"🐟",pts:200,desc:"Earn 25 Orange Tickets",hint:"Spin daily + referrals!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=25},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,25)+"/25":"0/25"}},{id:"ticket_silver",name:"Ticket Shark",emoji:"🦈",pts:500,desc:"Earn 50 Orange Tickets",hint:"Keep spinning & referring!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=50},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,50)+"/50":"0/50"}},{id:"ticket_gold",name:"Ticket Whale",emoji:"🐋",pts:1e3,desc:"Earn 100 Orange Tickets",hint:"The ultimate ticket badge!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=100},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,100)+"/100":"0/100"}},{id:"nacho_10q",name:"Inquisitive Buck",emoji:"🔍",pts:200,desc:"Ask Nacho 10 questions",hint:"Keep asking Nacho!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=10},progress:function(){return Math.min(parseInt(localStorage.getItem("btc_nacho_questions")||"0"),10)+"/10"}},{id:"collector",name:"Collector",emoji:"💎",pts:150,desc:"Save 10+ topics to favorites",hint:"Star your favorite topics",hidden:!1,check:function(){return safeJSON("btc_favs",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_favs",[]).length,10)+"/10"}},{id:"first_post",name:"Town Crier",emoji:"📣",pts:100,desc:"Make your first Pleb Talk post",hint:"Post in PlebTalk!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=1||void 0!==currentUser&¤tUser&¤tUser.forumPosts>=1}},{id:"first_reply",name:"Conversationalist",emoji:"💬",pts:75,desc:"Reply to a forum post",hint:"Join a discussion!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.forumReplies>=1}},{id:"market_seller",name:"Merchant",emoji:"🏪",pts:150,desc:"List an item on Lightning Mart",hint:"Sell something for sats on Lightning Mart!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketListings>=1}},{id:"market_buyer",name:"Shopper",emoji:"🛍️",pts:150,desc:"Contact a seller on the marketplace",hint:"Find something to buy!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketMessages>=1}},{id:"donor_100",name:"Giving Pleb",emoji:"🫷",pts:50,desc:"Donate 100 XP for charity",hint:"Donate 100 XP in the Charity tab!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=100},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,100)+"/100"}},{id:"donor_500",name:"Stack Sharer",emoji:"💛",pts:150,desc:"Donate 500 XP for charity",hint:"Keep donating!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=500},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,500)+"/500"}},{id:"donor_1000",name:"Community Builder",emoji:"🧡",pts:300,desc:"Donate 1,000 XP for charity",hint:"A true community builder!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e3)+"/1,000"}},{id:"donor_5000",name:"Archive Patron",emoji:"❤️",pts:1e3,desc:"Donate 5,000 XP for charity",hint:"An archive patron — legendary!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e3)+"/5,000"}},{id:"donor_10000",name:"Sats Saint",emoji:"🔥",pts:2e3,desc:"Donate 10,000 XP for charity",hint:"A sats saint among us!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e4)+"/10,000"}},{id:"donor_25000",name:"Lightning Philanthropist",emoji:"⚡",pts:4e3,desc:"Donate 25,000 XP for charity",hint:"A lightning philanthropist!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=25e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,25e3)+"/25,000"}},{id:"donor_50000",name:"Satoshi's Steward",emoji:"🏆",pts:7500,desc:"Donate 50,000 XP for charity",hint:"Satoshi's Steward — incredible!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e4)+"/50,000"}},{id:"donor_100000",name:"Legend of the Archive",emoji:"👑",pts:15e3,desc:"Donate 100,000 XP for charity",hint:"A true legend of the archive!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e5},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e5)+"/100,000"}},{id:"night_owl",name:"Night Owl",emoji:"🦉",pts:50,desc:"Visit the archive after midnight",hidden:!0,check:function(){return(new Date).getHours()>=0&&(new Date).getHours()<5}},{id:"speed_runner",name:"Speed Runner",emoji:"⚡",pts:100,desc:"Visit 15+ channels in one session",hidden:!0,check:function(){return void 0!==sessionChannels&&sessionChannels.size>=15}},{id:"scholar",name:"Bitcoin Scholar",emoji:"🎓",pts:300,desc:"Pass the Scholar Certification",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_scholar_passed")}},{id:"nacho_20q",name:"20 Questions",emoji:"🏅",pts:500,desc:"Ask Nacho 20 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=20}},{id:"explorer_10",name:"Curious Pleb",emoji:"🗺️",pts:100,desc:"Explore 10 topics",hint:"Keep exploring!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,10)+"/10"}},{id:"explorer_25",name:"Rabbit Holer",emoji:"🐇",pts:250,desc:"Explore 25 topics",hint:"Dive deeper!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=25},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,25)+"/25"}},{id:"explorer_50",name:"Half Stack",emoji:"📚",pts:500,desc:"Explore 50 topics",hint:"Halfway there!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=50},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,50)+"/50"}},{id:"explorer_100",name:"Century Club",emoji:"💯",pts:1e3,desc:"Explore 100 topics",hint:"Almost all of them!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=100},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,100)+"/100"}},{id:"explorer_all",name:"Archive Master",emoji:"👑",pts:2e3,desc:"Explore every single topic",hint:"Visit them all!",hidden:!0,check:function(){return void 0!==CHANNELS&&safeJSON("btc_visited_channels",[]).length>=Object.keys(CHANNELS).length}},{id:"marathon",name:"Marathon Reader",emoji:"🏃",pts:150,desc:"Spent 30+ minutes reading in one session",hidden:!0,check:function(){return Date.now()-(window._sessionStart||Date.now())>18e5}},{id:"early_adopter",name:"Early Adopter",emoji:"🌅",pts:200,desc:"Browsing between 5am and 7am",hidden:!0,check:function(){var e=(new Date).getHours();return e>=5&&e<7}},{id:"weekend_warrior",name:"Weekend Warrior",emoji:"🎉",pts:75,desc:"Learning Bitcoin on a weekend",hidden:!0,check:function(){var e=(new Date).getDay();return 0===e||6===e}},{id:"triple_threat",name:"Triple Threat",emoji:"🎯",pts:300,desc:"Completed a quest, sent a chat message, and read a channel in one session",hidden:!0,check:function(){return"true"===sessionStorage.getItem("btc_quest_done")&&"true"===sessionStorage.getItem("btc_chat_sent")&&void 0!==sessionChannels&&sessionChannels.size>=1}},{id:"nacho_50q",name:"Nacho Sage",emoji:"🧙",pts:500,desc:"Ask Nacho 50 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=50}},{id:"bookmark_collector",name:"Bookmark Hoarder",emoji:"📚",pts:100,desc:"Bookmarked 20+ messages",hidden:!0,check:function(){return safeJSON("btc_bookmarks",[]).length>=20}},{id:"pvp_streak",name:"Undefeated",emoji:"🔱",pts:250,desc:"Won 5 PVP battles in a row",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_pvp_win_streak")||"0")>=5}},{id:"sats_maxed",name:"Faucet King",emoji:"👑",pts:1e3,desc:"Claimed all 10,000 sats from the faucet",hidden:!0,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e4}},{id:"streak_freeze",name:"Ice Shield",emoji:"🧊",pts:50,desc:"Used a streak freeze to save your streak",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_freeze_used")}},{id:"nacho_closet_full",name:"Fashionista",emoji:"👗",pts:200,desc:"Unlocked all Nacho closet items from the spin wheel",hidden:!0,check:function(){return safeJSON("btc_spin_closet_items",[]).length>=10}}];function _syncPredictionToFirestore(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db)return;var t=auth.currentUser.uid;db.collection("users").doc(t).set({predictions:{lastPrediction:{direction:e.direction,price:e.price,time:e.time}}},{merge:!0}).catch(function(){}),db.collection("active_predictions").doc(t).set({uid:t,direction:e.direction,price:e.price,time:e.time,resolved:!1}).catch(function(){})}catch(e){}}function _updatePredictionStats(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db||"undefined"==typeof firebase)return;var t=auth.currentUser.uid,o=firebase.firestore.FieldValue.increment,n=parseInt(localStorage.getItem("btc_predict_streak")||"0"),i=parseInt(localStorage.getItem("btc_predict_best_streak")||"0"),a={"predictions.total":o(1),"predictions.lastResolved":Date.now()};if(e){a["predictions.correct"]=o(1);var r=n+1;a["predictions.streak"]=r,r>i&&(a["predictions.bestStreak"]=r,localStorage.setItem("btc_predict_best_streak",r.toString()))}else a["predictions.streak"]=0;db.collection("users").doc(t).set(a,{merge:!0}).catch(function(){});var s={total:o(1)};e&&(s.correct=o(1)),db.collection("stats").doc("predictions").set(s,{merge:!0}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.predictions||(currentUser.predictions={total:0,correct:0,streak:0,bestStreak:0}),currentUser.predictions.total=(currentUser.predictions.total||0)+1,e?(currentUser.predictions.correct=(currentUser.predictions.correct||0)+1,currentUser.predictions.streak=(currentUser.predictions.streak||0)+1,currentUser.predictions.streak>(currentUser.predictions.bestStreak||0)&&(currentUser.predictions.bestStreak=currentUser.predictions.streak)):currentUser.predictions.streak=0)}catch(e){}}!function(){const e=["🎓 Someone just passed the Bitcoin Basics Certification! Can you?","⚡ A pleb just completed a Lightning Network quest — 50 XP earned!","🗺️ Someone just finished all 10 steps of the Bitcoin Journey!","🎮 A Bitcoiner just aced a quiz in Nacho Mode — 10/10!","📚 A new user just explored their first 3 topics — features unlocking!","🧠 Someone just asked Nacho 100 questions — Bitcoin Scholar status!","🎯 A pleb just scored 5/5 on a Conversation Quest!","📖 Someone just read through the entire Timechain channel!","🔥 A Bitcoiner just hit a 30-day streak! Legendary dedication!","🔥 Someone just started a 7-day streak — can you beat them?","🏆 A pleb just crossed 5,000 XP! Climbing the leaderboard!","⭐ Someone just earned 200 XP in a single session!","🔥 A user just protected their streak with a Freeze Ticket! Smart move.","📈 Someone just jumped 10 spots on the Leaderboard!","🧡 A Bitcoiner just leveled up to Bitcoin Believer!","🏔 Someone just reached Maxi status — top of the mountain!","👑 A pleb just entered the Top 25 on the Leaderboard!","🌱 A brand new user just earned their first 50 XP! Welcome!","🎡 Someone just spun the daily wheel and won 5 Orange Tickets!","🎟️ A pleb just earned bonus tickets from a referral!","🧊 Someone won a Streak Freeze on the daily spin — lucky!","🎡 A Bitcoiner just won a closet item from the spin wheel!","💬 New discussion in PlebTalk: 'Best cold storage for beginners?'","💬 Someone just posted in PlebTalk — join the conversation!","🛒 New listing on LightningMart — check it out!","🤝 A meetup was just created in IRL Sync — find one near you!","💬 A PlebTalk post just got 5 upvotes!","⚡ Someone just tipped a forum post with Lightning!","🦌 Someone just entered Nacho Mode for a 30-minute deep dive!","🎽 A pleb just equipped Diamond Hooves in Nacho's Closet! 💎","🕶️ Someone just unlocked Cool Shades from the spin wheel!","👑 A Bitcoiner just equipped the Royal Crown — looking regal!","🦌 Nacho just helped someone understand seed phrases!","🗺️ Someone just explored their 50th channel — almost full coverage!","🦉 A Night Owl badge was just earned at 2 AM!","🎲 Someone just used Random Channel and discovered 'cypherpunks'!","🎨 A user just browsed the Art Gallery — 200+ Bitcoin artworks!","📡 A Bitcoiner just opted in to The Signal newsletter!","🎉 Over 100 users are learning Bitcoin here right now!","📊 The archive has been visited over 10,000 times this month!","🧡 146 channels of pure Bitcoin education — and growing!","⚡ Over 500 Nacho conversations happened this week!","🏆 The Leaderboard top 10 just shuffled — who's climbing?"];async function t(){const t=safeJSON("btc_visited_channels",[]).length,o=firebase.auth().currentUser&&!firebase.auth().currentUser.isAnonymous;if(t<3&&!o)return;const n=document.getElementById("activity-ticker"),i=document.getElementById("ticker-content");if(n&&i){var a=e.slice();try{var r=firebase.firestore();(await r.collection("forum_posts").orderBy("createdAt","desc").limit(3).get()).forEach(function(e){var t=e.data(),o=t.authorName||"A pleb";a.push("💬 "+o+' just posted in PlebTalk: "'+(t.title||"").substring(0,40)+'..."')});try{(await r.collection("marketplace").where("status","==","active").orderBy("createdAt","desc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🛒 New on LightningMart: "'+(t.title||"Item").substring(0,35)+'" for '+(t.priceSats||t.price||"???")+" sats!")})}catch(e){}try{var s=await r.collection("users").orderBy("points","desc").limit(10).get(),c=[];if(s.forEach(function(e){var t=e.data();t.username&&c.push(t.username)}),c.length>=3){a.push("👑 "+c[0]+" is holding #1 on the Leaderboard! Can you catch them?");var l=c[Math.floor(Math.random()*Math.min(5,c.length))];a.push("📈 "+l+" just climbed the Leaderboard — competition is heating up!")}}catch(e){}try{(await r.collection("irl_events").where("date",">=",(new Date).toISOString()).orderBy("date","asc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🤝 Upcoming meetup: "'+(t.title||"Bitcoin Meetup").substring(0,35)+'" — RSVP in IRL Sync!')})}catch(e){}}catch(e){console.log("Ticker live data skipped:",e)}for(var d=a.length-1;d>0;d--){var u=Math.floor(Math.random()*(d+1)),p=a[d];a[d]=a[u],a[u]=p}n.style.display="flex";var m=0;g(),setInterval(g,12e3)}function g(){i.style.animation="none",i.offsetHeight,i.textContent=a[m],i.style.animation="tickerScroll 12s linear infinite",m=(m+1)%a.length}}const o=document.createElement("style");o.textContent="\n #ticker-content { \n white-space: nowrap !important;\n overflow: visible !important;\n text-overflow: clip !important;\n display: inline-block !important;\n width: auto !important;\n padding-right: 50px;\n }\n @keyframes tickerScroll {\n 0% { transform: translateX(100%); }\n 100% { transform: translateX(-100%); }\n }\n ",document.head.appendChild(o),window.rateChannel=async function(e,t){const o=document.getElementById("sentiment-"+e);if(o){o.innerHTML='
    Thank you! 🦌
    Nacho will use this to organize better content.
    ';try{const o=firebase.firestore();await o.collection("channel_feedback").add({channelId:e,rating:t,uid:firebase.auth().currentUser?firebase.auth().currentUser.uid:"anon",createdAt:firebase.firestore.FieldValue.serverTimestamp()}),"function"==typeof awardPoints&&awardPoints(5,"Feedback bonus")}catch(e){console.log("Feedback save skipped:",e)}}},window.checkNewsletterPrompt=function(){localStorage.getItem("btc_newsletter_prompt_shown")||safeJSON("btc_visited_channels",[]).length>=10&&(function(){const e=document.createElement("div");e.id="newsletterModal",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);z-index:10000;display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(5px);",e.innerHTML='
    📡

    Stay Orange-Pilled

    You\'ve explored 10+ channels! Stay connected with Bitcoin updates and community news.

    📱 Join Telegram Updates📧 Subscribe on Substack
    ',document.body.appendChild(e)}(),localStorage.setItem("btc_newsletter_prompt_shown","true"))},window.optInNewsletter=async function(){const e=document.getElementById("newsletterModal"),t=firebase.auth().currentUser;if(!t||t.isAnonymous)return showToast("Please sign in with email to join the newsletter!"),"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void(e&&e.remove());try{const e=firebase.firestore();await e.collection("users").doc(t.uid).update({newsletterOptIn:!0,newsletterOptInDate:firebase.firestore.FieldValue.serverTimestamp()}),showToast("🎉 Welcome to the Orange Pill newsletter!")}catch(e){console.log("Newsletter opt-in failed:",e)}e&&e.remove()},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){t(),checkNewsletterPrompt()}):(t(),checkNewsletterPrompt())}(),window.showNachoStory=function(e){var t=[{title:"Chapter 1: The Genesis Block",text:"In the beginning, there was nothing but fiat. Nacho was just a young buck growing up in the White Mountains of New Hampshire — the Live Free or Die state. He spent his fawn days splashing in the Pemigewasset River, racing chipmunks through birch groves, and nibbling on leaves of debt from the forest of traditional finance. His mama always said the acorns were getting smaller every year, but nobody could explain why. One cold January day in 2009, a mysterious message appeared carved into a sugar maple: 'Chancellor on brink of second bailout for banks.' Nacho didn't understand it yet, but something had changed forever. A new kind of money had been born — one that no government could print, no bank could freeze, and no deer could counterfeit. It was called Bitcoin."},{title:"Chapter 2: The Pizza That Changed Everything",text:"Nacho heard a rumor from a blue jay passing through Franconia Notch: someone had traded 10,000 bitcoins for two pizzas. 'That's crazy!' he thought, nearly choking on a wild blueberry. But was it? Those pizzas proved Bitcoin had real value — people would actually exchange goods for it. Nacho realized this wasn't just internet magic beans. It was the beginning of price discovery. He thought about all the acorns he'd traded with the squirrels over the years — weren't those his first 'transactions' too? Every great journey starts with a single trade, and Bitcoin's started with pepperoni and cheese."},{title:"Chapter 3: Down the Rabbit Hole",text:"Nacho found a weathered copy of the whitepaper pinned to a bulletin board at a general store in Lincoln, New Hampshire. Only 9 pages, but each one hit different. Peer-to-peer. No trusted third party. Proof of work. 21 million cap. He read it by the light of a campfire near the Kancamagus Highway, the stars of the Granite State blazing overhead. The deeper he went, the more he understood: Bitcoin wasn't just new money. It was a paradigm shift. Sound money that couldn't be debased. A monetary network with no CEO, no headquarters, no off switch. Nacho's antlers tingled — literally. His first set was coming in. He was growing up, and he was becoming a Bitcoiner."},{title:"Chapter 4: HODL Through the Storm",text:"A nor'easter hit New Hampshire that winter, and the price of Bitcoin crashed right along with the temperature. Then crashed again. Nacho watched his sats lose 80% of their dollar value from a snow-covered ridge overlooking the Presidential Range. His forest friends laughed. 'Told you it was a scam!' chirped a skeptical chickadee. But Nacho had done his homework. He understood the halving cycles. He knew that every 210,000 blocks, the new supply gets cut in half. Scarcity + time = value. So Nacho did what legends do: he stood firm in the blizzard and held. Not because he was reckless, but because he understood what he held. The storms always pass. The mountains remain."},{title:"Chapter 5: Not Your Keys, Not Your Cheese",text:"One crisp autumn morning, as the New Hampshire maples blazed orange and gold, Nacho woke up to terrible news. An exchange had been hacked. Billions gone. Friends who kept their bitcoin on the exchange lost everything. A young doe from Vermont had her entire savings wiped out. Nacho felt sick — but also relieved. He'd moved his sats to a hardware wallet weeks ago, buried it in a waterproof case near his favorite granite boulder in the White Mountains. Cold storage. Air-gapped. His keys, his bitcoin. From that day forward, Nacho's motto was clear: 'Not your keys, not your cheese.' 🧀🔑 He even carved it into a birch tree so no deer would forget."},{title:"Chapter 6: The Halving",text:"Every four years, something magical happens — and Nacho had the perfect view from Mount Washington's summit. The block reward — the number of new bitcoins created with each block — gets cut in half. He watched the countdown with a group of bitcoiners who'd hiked up for the occasion, huddled together at 6,288 feet with thermoses of coffee and Lightning-powered phones. From 6.25 BTC to 3.125 BTC per block. Less new supply entering the market. Same or growing demand. The wind howled, but nobody cared. It's not magic; it's math. And it's the most predictable monetary policy in the history of money. Nacho shed a single tear — which immediately froze to his fur."},{title:"Chapter 7: Nacho's Mission",text:"Nacho looked out from his favorite overlook in the White Mountains — the same spot where he'd first read the whitepaper by campfire light. He'd grown from a gangly fawn into a strong buck with a magnificent rack of antlers (seven points, if you're counting). But so many deer — so many people — still didn't understand Bitcoin. They heard 'crypto' and thought of scams, memecoins, and celebrity tokens. But Bitcoin is different. It's the signal in the noise. So Nacho decided to dedicate his life to education, right here from the Live Free or Die state. Not shilling. Not pumping. Teaching. Because the best way to orange-pill someone isn't to tell them to buy — it's to help them understand WHY. And that's why you're here. Welcome to the Archive. 🦌🟠"}],o=(new Date).toISOString().split("T")[0],n=safeJSON("btc_nacho_story_days",[]);(0===n.length||-1===n.indexOf(o))&&(n.push(o),localStorage.setItem("btc_nacho_story_days",JSON.stringify(n)));var i,a=Math.min(n.length,t.length);if(void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryProgress:a,nachoStoryDate:o,nachoStoryDays:n}).catch(function(){})}catch(e){}localStorage.setItem("btc_nacho_story_highest",a.toString()),localStorage.setItem("btc_nacho_story_date",o),"number"==typeof e?(i=Math.min(e,a-1))<0&&(i=0):(i=a-1)<0&&(i=0);var r=t[i],s=document.createElement("div");s.id="nachoStoryOverlay",s.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",s.onclick=function(e){e.target===s&&s.remove()};for(var c='
    ',l=0;l'+(l+1)+"":''}c+="
    ";var u,p=i>0?"':"";u=i+1Next →':i>=t.length-1?'✅ Story Complete!':'🔒 Come back tomorrow!';var m=document.createElement("div");m.style.cssText="background:#1a1a2e;border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:500px;width:100%;margin:40px auto;color:#e2e8f0;font-family:inherit;",m.innerHTML='
    🦌📖
    '+c+'

    '+r.title+'

    '+r.text+'

    📖 Chapter '+(i+1)+" of "+t.length+" · "+a+" unlocked ("+(t.length-a)+' remaining)
    '+p+u+'
    ',s.appendChild(m),document.body.appendChild(s);var g=safeJSON("btc_nacho_story_awarded",[]);if("function"==typeof awardPoints&&-1===g.indexOf(i)){g.push(i),localStorage.setItem("btc_nacho_story_awarded",JSON.stringify(g));var h=i===t.length-1?50:15;awardPoints(h,"📖 Completed Chapter "+(i+1)),"function"==typeof showToast&&showToast("📖 +"+h+" XP — Chapter "+(i+1)+" complete!"),g.length===t.length&&setTimeout(function(){if(awardPoints(100,"📖🎉 Completed Nacho's Story!"),"function"==typeof awardOrangeTickets)awardOrangeTickets(25,"📖 Nacho's Story Complete!");else{var e=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(e+25).toString())}"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound();var t=document.createElement("div");if(t.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",t.onclick=function(){t.style.opacity="0",t.style.transition="opacity 0.4s",setTimeout(function(){t.remove()},400)},t.innerHTML='
    🦌📖🎉
    STORY COMPLETE!
    You\'ve followed Nacho\'s entire Bitcoin journey from the Genesis Block to his mission of education. You\'re officially a Story Master! 🏆
    +100
    BONUS PTS
    +25
    🎟️ TICKETS
    ',document.body.appendChild(t),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryComplete:!0,nachoStoryCompletedAt:(new Date).toISOString()}).catch(function(){})}catch(e){}},800)}},window.showPricePrediction=function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0;if(!e&&"undefined"!=typeof _lastWsPrice&&_lastWsPrice&&(e=_lastWsPrice,localStorage.setItem("btc_last_price",e.toString())),!e&&"undefined"!=typeof _dashData&&_dashData&&_dashData.price&&(e=_dashData.price,localStorage.setItem("btc_last_price",e.toString())),!e)return"function"==typeof showToast&&showToast("⏳ Fetching price..."),void fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd?(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),showPricePrediction()):"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")}).catch(function(){"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")});var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&t.remove()};var o=safeJSON("btc_price_prediction",null),n=document.createElement("div");if(n.style.cssText="background:var(--card-bg,#1a1a2e);border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:420px;width:100%;color:var(--text,#e2e8f0);font-family:inherit;text-align:center;",o&&Date.now()-o.time<864e5){var i=Date.now()-o.time;if(!(i>=864e5)){var a=Math.ceil((864e5-i)/36e5);return n.innerHTML='

    Prediction Locked In!

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+'

    ⏳ Results in ~'+a+" hour"+(1!==a?"s":"")+'
    Come back after 24 hours to see if you were right!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},500),t.appendChild(n),void document.body.appendChild(t)}var r=e-o.price,s=(r/o.price*100).toFixed(2),c="up"===o.direction&&r>0||"down"===o.direction&&r<0;o._notified||("function"==typeof notifyPredictionResult&¬ifyPredictionResult(c,o.direction),o._notified=!0,localStorage.setItem("btc_price_prediction",JSON.stringify(o)));var l=parseInt(localStorage.getItem("btc_predict_streak")||"0");n.innerHTML=''+(c?"🎉":"😅")+'

    Your Prediction

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+" ("+(r>=0?"+":"")+s+'%)

    '+(c?"✅ You were RIGHT! +25 XP":"❌ Not this time!")+"

    "+(c&&l>=2?'

    🔥 '+l+" correct in a row!

    ":"")+'
    Come back tomorrow for a new prediction!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},100)}else n.innerHTML='📈📉

    Predict Bitcoin\'s Price

    Current BTC Price:

    $'+Math.round(e).toLocaleString()+'

    Will Bitcoin go UP or DOWN in the next 24 hours?

    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStats");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 Be the first to predict!"})},100);t.appendChild(n),document.body.appendChild(t)},window._savePrediction=function(e){var t={direction:e,price:parseFloat(localStorage.getItem("btc_last_price"))||0,time:Date.now(),resolved:!1};localStorage.setItem("btc_price_prediction",JSON.stringify(t)),"function"==typeof showToast&&showToast("🎯 Prediction saved! Check back tomorrow to see if you were right."),"function"==typeof awardPoints&&awardPoints(5,"📈 Price prediction made"),_syncPredictionToFirestore(t)},window.checkPredictionResult=function(){var e=safeJSON("btc_price_prediction",null);if(e&&!e.resolved&&!(Date.now()-e.time<864e5)){var t=parseFloat(localStorage.getItem("btc_last_price"))||0;if(t&&e.price){var o=t-e.price,n=(o/e.price*100).toFixed(2),i="up"===e.direction&&o>0||"down"===e.direction&&o<0;e.resolved=!0,e.result=i?"correct":"wrong",e.finalPrice=t,localStorage.setItem("btc_price_prediction",JSON.stringify(e)),_updatePredictionStats(i);try{void 0!==auth&&auth.currentUser&&void 0!==db&&db.collection("active_predictions").doc(auth.currentUser.uid).delete().catch(function(){})}catch(e){}if(i){"function"==typeof awardPoints&&awardPoints(25,"🎯 Correct price prediction!");var a=parseInt(localStorage.getItem("btc_predict_streak")||"0")+1;localStorage.setItem("btc_predict_streak",a.toString()),setTimeout(function(){"function"==typeof showToast&&showToast("🎉 Your prediction was RIGHT! Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"% — +25 XP!"+(a>=3?" 🔥 "+a+" correct in a row!":""))},2e3)}else localStorage.setItem("btc_predict_streak","0"),setTimeout(function(){"function"==typeof showToast&&showToast("📉 Your prediction was wrong — Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"%. Try again tomorrow!")},2e3)}}};var _globalPredCache=null,_globalPredCacheTs=0;window.getGlobalPredictionStats=function(e){if(_globalPredCache&&Date.now()-_globalPredCacheTs<12e4)e(_globalPredCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{db.collection("stats").doc("predictions").get().then(function(t){t.exists?(_globalPredCache=t.data(),_globalPredCacheTs=Date.now(),e(_globalPredCache)):e(null)}).catch(function(){e(null)})}catch(t){e(null)}else e(null)},window.getPredictionStats=function(e){var t=e&&e.predictions?e.predictions:null;if(!t||!t.total)return null;var o=t.total>0?Math.round(t.correct/t.total*100):0;return{total:t.total||0,correct:t.correct||0,percentage:o,streak:t.streak||0,bestStreak:t.bestStreak||0}};var _communityStatsCache=null,_communityStatsCacheTs=0,_communityStatsUnsub=null;function _renderCommunityStats(e,t,o){var n=[];o.channelVisits&&n.push("📖 "+_fmtNum(o.channelVisits)+" channel reads"),o.questsCompleted&&n.push("⚡ "+_fmtNum(o.questsCompleted)+" quests completed"),o.chatMessages&&n.push("💬 "+_fmtNum(o.chatMessages)+" chat messages"),o.spins&&n.push("🎡 "+_fmtNum(o.spins)+" daily spins"),o.pvpMatches&&n.push("⚔️ "+_fmtNum(o.pvpMatches)+" PVP battles");var i=document.getElementById("visitCount");if(i&&"—"!==i.textContent&&n.push("👥 "+i.textContent+" total visits"),o.userCount&&n.push("🧑‍🤝‍🧑 "+_fmtNum(o.userCount)+" registered users"),o.watchTimeMinutes){var a=Math.floor(o.watchTimeMinutes/60);n.push("📺 "+(a>0?_fmtNum(a)+" hours":o.watchTimeMinutes+" min")+" Timechain TV watched")}if(0!==n.length){e.innerHTML=n.join("  ·  ");var r=function(e,t){var o=document.getElementById(e);o&&t&&(o.textContent=t.toLocaleString())};if(r("csChannelReads",o.channelVisits),r("csQuests",o.questsCompleted),r("csChatMsgs",o.chatMessages),r("csSpins",o.spins),r("csPvp",o.pvpMatches),r("csUsers",o.userCount),o.watchTimeMinutes){var s=Math.floor(o.watchTimeMinutes/60);r("csWatchTime",s>0?s:o.watchTimeMinutes)}}else e.innerHTML="No stats yet"}function _fmtNum(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function renderExplorationMap(){var e=document.getElementById("explorationMap");if(e&&void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]);void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>t.length&&(t=currentUser.readChannels);var o=Object.keys(CHANNELS),n=o.length,i=t.length,a=Math.round(i/n*100),r="";o.forEach(function(e){var o=-1!==t.indexOf(e),n=CHANNELS[e].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}|\u{2700}-\u{27BF}|\u{FE00}-\u{FEFF}|\u{1F900}-\u{1F9FF}|\u{1FA00}-\u{1FA6F}|\u{1FA70}-\u{1FAFF}|\u{200D}|\u{FE0F}]+)/u),i=n?n[1]:"📄";r+="
    '+(o?i:"?")+"
    "});var s="true"===localStorage.getItem("btc_explore_map_open");e.innerHTML="
    "+(s?"▾":"▸")+'🗺️ Exploration Map
    '+i+"/"+n+" ("+a+'%)
    '+r+"
    "}}window.loadCommunityStats=function(){var e=document.getElementById("communityStatsInner");if(e){var t=e.parentElement;if(_communityStatsUnsub&&_communityStatsCache)_renderCommunityStats(e,t,_communityStatsCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{_communityStatsUnsub=db.collection("stats").doc("global").onSnapshot(function(e){var t=e.exists?e.data():{};_communityStatsCache=t,_communityStatsCacheTs=Date.now();var o=document.getElementById("communityStatsInner");o&&_renderCommunityStats(o,o.parentElement,t)})}catch(e){}}},setTimeout(function(){"function"==typeof loadCommunityStats&&loadCommunityStats()},5e3),window.updatePredictionLabel=function(){var e=document.getElementById("predAccuracyLabel");return!!e&&void 0!==db&&"undefined"!=typeof firebase&&"function"==typeof getGlobalPredictionStats&&(getGlobalPredictionStats(function(t){var o=[];if(t&&t.total){var n=Math.round(t.correct/t.total*100);o.push("🌍 "+n+"% community accuracy")}if(void 0!==currentUser&¤tUser&¤tUser.predictions&¤tUser.predictions.total){var i=Math.round(currentUser.predictions.correct/currentUser.predictions.total*100);o.push("👤 "+i+"% you")}e.innerHTML=o.join("
    ")}),!0)},function(){var e=0,t=setInterval(function(){e++,(window.updatePredictionLabel&&window.updatePredictionLabel()||e>60)&&clearInterval(t)},1e3)}(),function e(){if("function"==typeof window.goHome){if(!window.goHome.__predHooked){var t=window.goHome;window.goHome=function(){var e=t.apply(this,arguments);return setTimeout(function(){window.updatePredictionLabel&&window.updatePredictionLabel()},400),e},window.goHome.__predHooked=!0}}else var o=setInterval(function(){"function"==typeof window.goHome&&(clearInterval(o),e())},500)}(),window.renderExplorationMap=renderExplorationMap;var BITCOIN_QUOTES=[{text:"If you don't believe it or don't get it, I don't have the time to try to convince you, sorry.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"The root problem with conventional currency is all the trust that's required to make it work.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"It might make sense just to get some in case it catches on.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"Running bitcoin.",author:"Hal Finney",channel:"history"},{text:"Bitcoin is a remarkable cryptographic achievement and the ability to create something that is not duplicable in the digital world has enormous value.",author:"Eric Schmidt",channel:"dominant"},{text:"Bitcoin is a technological tour de force.",author:"Bill Gates",channel:"one-stop-shop"},{text:"I think the internet is going to be one of the major forces for reducing the role of government. The one thing that's missing, but that will soon be developed, is a reliable e-cash.",author:"Milton Friedman (1999)",channel:"videos"},{text:"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.",author:"Bitcoin Genesis Block",channel:"history"},{text:"Not your keys, not your coins.",author:"Bitcoin Proverb",channel:"self-custody"},{text:"Stay humble, stack sats.",author:"Bitcoin Community",channel:"investment-strategy"},{text:"In the long run, hard money is superior to soft money.",author:"Gigi, 21 Lessons",channel:"articles-threads"},{text:"Bitcoin is the first truly digital solution to the problem of money.",author:"Saifedean Ammous",channel:"books"},{text:"Fix the money, fix the world.",author:"Bitcoin Mantra",channel:"problems-of-money"},{text:"The supply of Bitcoin is limited. Period. No central bank is going to come along and print more.",author:"Andreas Antonopoulos",channel:"scarce"},{text:"Everyone is a scammer until proven otherwise. Don't trust, verify.",author:"Bitcoin Culture",channel:"secure"},{text:"Bitcoin makes money great again. It lets you transact freely, save freely, and live freely.",author:"Michael Saylor",channel:"giga-chad"},{text:"There is no second best.",author:"Michael Saylor",channel:"maximalism"},{text:"I don't think there's anything more important in my lifetime to work on.",author:"Jack Dorsey",channel:"giga-chad"},{text:"Bitcoin is the most important invention in the history of the world since the internet.",author:"Roger Ver (before he fell off)",channel:"history"},{text:"The computer can be used as a tool to liberate and protect people, rather than to control them.",author:"Hal Finney",channel:"cryptography"},{text:"One of the greatest things that Satoshi did was disappear.",author:"Gigi, 21 Lessons",channel:"satoshi-nakamoto"},{text:"Bitcoin has no CEO, no marketing department, no headquarters. It has math.",author:"Bitcoin Education Archive",channel:"decentralized"},{text:"We are all Satoshi.",author:"Bitcoin Community",channel:"satoshi-nakamoto"},{text:"Cypherpunks write code.",author:"Eric Hughes",channel:"cryptography"},{text:"Privacy is necessary for an open society in the electronic age.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Money is a tool for trading human time.",author:"Robert Breedlove",channel:"articles-threads"},{text:"Bitcoin is Time.",author:"Gigi",channel:"time"},{text:"The root cause of the housing crisis, student debt crisis, and healthcare crisis is the money crisis.",author:"Saifedean Ammous",channel:"problems-of-money"},{text:"Tick tock, next block.",author:"Bitcoin Community",channel:"blockchain-timechain"},{text:"The difficulty adjustment is the most elegant feature of Bitcoin.",author:"Bitcoin Educators",channel:"difficulty-adjustment"},{text:"Every informed person needs to know about Bitcoin because it might be one of the world's most important developments.",author:"Leon Luow",channel:"one-stop-shop"},{text:"Bitcoin is the only commodity in the world that the more demand there is, the more supply does NOT increase.",author:"Parker Lewis",channel:"scarce"},{text:"Gradually, then suddenly.",author:"Parker Lewis / Ernest Hemingway",channel:"articles-threads"},{text:"You can't stop an idea whose time has come.",author:"Victor Hugo (on Bitcoin)",channel:"organic"},{text:"Bitcoin is a hedge against the entire system.",author:"Lyn Alden",channel:"investment-strategy"},{text:"The question isn't what Bitcoin's price will be. The question is what the dollar's price will be.",author:"Bitcoiners",channel:"problems-of-money"},{text:"I was once told that nobody ever lost money saving in Bitcoin for 4+ years. I checked. It's true.",author:"Anonymous Bitcoiner",channel:"investment-strategy"},{text:"Bitcoin is the exit.",author:"Bitcoin Maximalists",channel:"maximalism"},{text:"Don't trust, verify.",author:"Bitcoin Ethos",channel:"nodes"},{text:"Number go up technology.",author:"Bitcoin Twitter",channel:"fun-facts"},{text:"Energy is the universal currency. Bitcoin makes that literal.",author:"Bitcoin Mining Community",channel:"energy"},{text:"Bitcoin is not an investment — it is a savings technology.",author:"Bitcoin Educators",channel:"money"},{text:"Fiat currency always returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Give me control of a nation's money supply, and I care not who makes its laws.",author:"Mayer Amschel Rothschild",channel:"problems-of-money"},{text:"Inflation is taxation without legislation.",author:"Milton Friedman",channel:"problems-of-money"},{text:"Bitcoin is for enemies. That's the whole point.",author:"Bitcoin Community",channel:"game_theory"},{text:"When you understand Bitcoin, you understand everything else differently.",author:"Many Bitcoiners",channel:"philosophy"},{text:"Bitcoin doesn't care about your feelings.",author:"Bitcoin Proverb",channel:"fun-facts"},{text:"Stack sats and stay humble.",author:"Matt Odell",channel:"investment-strategy"},{text:"Number go up because money printer go brr.",author:"Bitcoin Memes",channel:"memes-funny"},{text:"Those who would give up essential liberty, to purchase a little temporary safety, deserve neither liberty nor safety.",author:"Benjamin Franklin",channel:"human_rights__social_justice_and_freedo"},{text:"Freedom is never more than one generation away from extinction.",author:"Ronald Reagan",channel:"human_rights__social_justice_and_freedo"},{text:"The only way to deal with an unfree world is to become so absolutely free that your very existence is an act of rebellion.",author:"Albert Camus",channel:"philosophy"},{text:"If the American people ever allow private banks to control the issue of their currency, first by inflation, then by deflation, the banks and corporations that will grow up around them will deprive the people of all property.",author:"Thomas Jefferson",channel:"problems-of-money"},{text:"It is well enough that people of the nation do not understand our banking and monetary system, for if they did, I believe there would be a revolution before tomorrow morning.",author:"Henry Ford",channel:"problems-of-money"},{text:"The most dangerous man to any government is the man who is able to think things out for himself.",author:"H.L. Mencken",channel:"philosophy"},{text:"In a time of deceit, telling the truth is a revolutionary act.",author:"George Orwell",channel:"philosophy"},{text:"The urge to save humanity is almost always a false front for the urge to rule it.",author:"H.L. Mencken",channel:"philosophy"},{text:"A society that puts equality before freedom will get neither. A society that puts freedom before equality will get a high degree of both.",author:"Milton Friedman",channel:"philosophy"},{text:"The state is that great fiction by which everyone tries to live at the expense of everyone else.",author:"Frédéric Bastiat",channel:"austrian_school_of_economics"},{text:"There is no means of avoiding the final collapse of a boom brought about by credit expansion.",author:"Ludwig von Mises",channel:"austrian_school_of_economics"},{text:"The first panacea for a mismanaged nation is inflation of the currency; the second is war. Both bring a temporary prosperity; both bring a permanent ruin.",author:"Ernest Hemingway",channel:"problems-of-money"},{text:"Gold is money. Everything else is credit.",author:"J.P. Morgan",channel:"money"},{text:"We don't have a trillion-dollar debt because we haven't taxed enough; we have a trillion-dollar debt because we spend too much.",author:"Ronald Reagan",channel:"problems-of-money"},{text:"Government is the only institution that can take a valuable commodity like paper, and make it worthless by applying ink.",author:"Ludwig von Mises",channel:"problems-of-money"},{text:"Whenever destroyers appear among men, they start by destroying money.",author:"Ayn Rand",channel:"problems-of-money"},{text:"The way to crush the bourgeoisie is to grind them between the millstones of taxation and inflation.",author:"Vladimir Lenin",channel:"problems-of-money"},{text:"Savings represent goods produced but not yet consumed. That's what real wealth is — not digits in a bank database.",author:"Saifedean Ammous",channel:"money"},{text:"Civilization is in a race between education and catastrophe. Let us learn the truth and spread it as far and wide as our circumstances allow.",author:"H.G. Wells",channel:"one-stop-shop"},{text:"Paper money eventually returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Bitcoin is the separation of money and state.",author:"Bitcoin Community",channel:"maximalism"},{text:"Bitcoin is the first money in the history of the world where the supply is entirely unaffected by an increase in demand.",author:"Jeff Booth",channel:"scarce"},{text:"In a world where everything is printed, scarcity is the ultimate feature.",author:"Bitcoin Educators",channel:"scarce"},{text:"Bitcoin is hope for humanity.",author:"Jack Mallers",channel:"one-stop-shop"},{text:"The cost of Bitcoin is measured in electricity. The cost of fiat is measured in human freedom.",author:"Bitcoin Community",channel:"energy"},{text:"Your savings should not be someone else's liability.",author:"Bitcoin Educators",channel:"self-custody"},{text:"Bitcoin is the peaceful protest that cannot be silenced.",author:"Alex Gladstein",channel:"human_rights__social_justice_and_freedo"},{text:"Bitcoin gives us the ability to opt out of a system that was designed to extract value from us.",author:"Many Bitcoiners",channel:"problems-of-money"},{text:"Proof of work means proof of energy. Energy is the one thing that cannot be faked.",author:"Bitcoin Mining Community",channel:"mining"},{text:"The Bitcoin network processes more value per year than Visa. Without a CEO.",author:"Bitcoin Stats",channel:"decentralized"},{text:"If Bitcoin is a bubble, it's the only bubble that reflated itself five times in a row.",author:"Bitcoin Community",channel:"fun-facts"},{text:"Bitcoin has died 474 times according to the media. It's still here.",author:"Bitcoin Obituaries",channel:"misconceptions-fud"},{text:"Your grandchildren will ask you why you didn't buy Bitcoin when it was under six figures.",author:"Bitcoin Twitter",channel:"predictions"},{text:"The next 4 years are going to be very exciting for Bitcoin.",author:"Every Bitcoiner, Every Year",channel:"fun-facts"},{text:"Bitcoin isn't getting more expensive. Your dollars are getting cheaper.",author:"Bitcoin Community",channel:"problems-of-money"},{text:"If you can't hold it, you don't own it. If you didn't earn it, you'll lose it.",author:"Bitcoin Wisdom",channel:"self-custody"},{text:"Think in sats, not dollars.",author:"Bitcoin Community",channel:"sats__or__bits"},{text:"The best time to buy Bitcoin was 10 years ago. The second best time is now.",author:"Bitcoin Proverb",channel:"investment-strategy"},{text:"Work is the transfer of energy over time. Money should measure exactly that.",author:"Jason Lowery",channel:"energy"},{text:"Bitcoin is not anti-government. Bitcoin is anti-fraud.",author:"Bitcoin Educators",channel:"regulation"},{text:"We must defend our own privacy if we expect to have any.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Cryptography is the ultimate form of non-violent direct action.",author:"Julian Assange",channel:"cryptography"},{text:"Strong cryptography can resist an unlimited application of violence.",author:"Jacob Appelbaum",channel:"cryptography"},{text:"The Net interprets censorship as damage and routes around it.",author:"John Gilmore",channel:"privacy-nonkyc"},{text:"Bitcoin is a weapon of peace.",author:"Jason Lowery, Softwar",channel:"geopolitics___macroeconomics"},{text:"Running a node means nobody can change the rules on you.",author:"Bitcoin Node Runners",channel:"nodes"},{text:"Hashrate is the heartbeat of Bitcoin. As long as miners mine, Bitcoin lives.",author:"Bitcoin Mining Community",channel:"mining"},{text:"Lightning is what makes Bitcoin usable for 8 billion people.",author:"Lightning Network Community",channel:"layer-2-lightning"},{text:"2,099,999,997,690,000 satoshis. That's all there will ever be.",author:"The Bitcoin Protocol",channel:"scarce"},{text:"Code is speech. Math is law. Cryptography is defense.",author:"Cypherpunks",channel:"cryptography"},{text:"I predict the Internet will go spectacularly supernova and in 1996 catastrophically collapse.",author:"Robert Metcalfe (1995) — They said this about Bitcoin too",channel:"misconceptions-fud"},{text:"Every generation needs a new revolution.",author:"Thomas Jefferson",channel:"philosophy"},{text:"First they ignore you, then they laugh at you, then they fight you, then you win.",author:"Often attributed to Gandhi",channel:"organic"},{text:"I do not think there is any other quality so essential to success of any kind as the quality of perseverance.",author:"John D. Rockefeller",channel:"philosophy"},{text:"The world is a dangerous place, not because of those who do evil, but because of those who look on and do nothing.",author:"Albert Einstein",channel:"philosophy"},{text:"Hard times create strong men. Strong men create good times. Good times create weak men. Weak men create hard times.",author:"G. Michael Hopf",channel:"time_preference"},{text:"An investment in knowledge pays the best interest.",author:"Benjamin Franklin",channel:"one-stop-shop"}];window.renderDailyQuote=function(){var e=document.getElementById("quoteOfDay");if(e){var t=new Date,o=Math.floor((t-new Date(t.getFullYear(),0,0))/864e5),n=BITCOIN_QUOTES[o%BITCOIN_QUOTES.length];n&&(e.innerHTML="
    💬 Quote of the Day
    "'+n.text+'"
    — '+n.author+"
    ")}},window.renderReadNext=function(e){if(void 0===CHANNELS)return"";var t=CHANNELS[e];if(!t)return"";var o=Object.entries(CHANNELS).filter(function(o){return o[1].cat===t.cat&&o[0]!==e});if(0===o.length)return"";var n=o.sort(function(){return Math.random()-.5}).slice(0,3),i='
    📖 Read Next
    ';return n.forEach(function(e){var t=e[1].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}]+)/u),o=t?t[1]:"📄";i+=""}),i+="
    "},window.getNachoStoryProgress=function(){return parseInt(localStorage.getItem("btc_nacho_story_highest")||"0")},window.checkHiddenBadges=function(){if(void 0!==HIDDEN_BADGES&&window._hiddenBadgesReady){var e=safeJSON("btc_hidden_badges",[]),t=!1;HIDDEN_BADGES.forEach(function(o){if(-1===e.indexOf(o.id))try{if(o.check&&o.check()&&(e.push(o.id),t=!0,"function"==typeof showToast&&showToast(o.emoji+" Secret Badge: "+(o.revealName||o.name)+"! +"+o.pts+" XP"),"function"==typeof awardPoints&&awardPoints(o.pts,"Hidden Badge: "+(o.revealName||o.name)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:e})}catch(e){}}catch(e){}}),t&&localStorage.setItem("btc_hidden_badges",JSON.stringify(e))}},setInterval(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},3e4),setTimeout(function(){window._hiddenBadgesReady||(window._hiddenBadgesReady=!0)},2e4),window.awardHiddenBadge=function(e,t){var o=safeJSON("btc_hidden_badges",[]);if(-1===o.indexOf(e)&&(o.push(e),localStorage.setItem("btc_hidden_badges",JSON.stringify(o)),t&&"function"==typeof showToast&&showToast("🏅 "+t),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:o})}catch(e){}},window.awardOrangeTickets=function(e,t){void 0!==currentUser&¤tUser&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,currentUser._isLocal||"function"!=typeof awardPoints||awardPoints(0,"🎟️ "+(t||"Orange Tickets"),null,e));var o=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(o+e).toString()),"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Ticket"+(e>1?"s":"")+(t?" — "+t:""))},window.setFloatingElementsVisible=function(e){["floatingRandomBtn","lbFloatBtn","mobileSearchBtn","backToTop","scrollToBottom","chatOverlayBtn","aiToolsBtn","dashboardFloatBtn"].forEach(function(t){var o=document.getElementById(t);o&&(o.style.display=e?"":"none")})},window.showCelebration=function(e){var t=e.emoji||"🎉",o=e.title||"Achievement Unlocked!",n=e.message||"",i=e.rewards||[],a=e.btnText||"Amazing! 🎉",r=document.createElement("div");r.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",r.onclick=function(e){e.target===r&&(r.style.opacity="0",r.style.transition="opacity 0.4s",setTimeout(function(){r.remove()},400))};var s="";i.length>0&&(s='
    ',i.forEach(function(e){s+='
    +'+e.label+'
    '+e.sub+"
    "}),s+="
    "),r.innerHTML='
    '+t+'
    '+o+'
    '+n+"
    "+s+'
    ",document.body.appendChild(r),"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound(),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200)},setInterval(function(){["prop","tech"].forEach(function(e){var t="btc_scholar_"+e+"_passed",o="btc_scholar_"+e+"_celebrated";if("true"===localStorage.getItem(t)&&"true"!==localStorage.getItem(o)){localStorage.setItem(o,"true");var n="tech"===e;setTimeout(function(){showCelebration({emoji:n?"🛠️🎓🏆":"📖🎓🎉",title:n?"PROTOCOL EXPERT!":"BITCOIN SCHOLAR!",message:n?"You passed the Technical Protocol Expert Certification! You understand Bitcoin at the deepest level. True cypherpunk material! 🔐":"You passed the Bitcoin Scholar Certification! You have a thorough understanding of Bitcoin's properties and economics! 🧡",rewards:[{label:"2,100",sub:"PTS",color:"#22c55e"},{label:n?"🛠️":"🎓",sub:"BADGE",color:"#f7931a"}],btnText:n?"Protocol Expert! 🛠️":"Scholar! 🎓"})},500)}})},3e3),function(){var e=[{pct:25,key:"explore_25",emoji:"🗺️🌱",title:"25% EXPLORED!",msg:"A quarter of the archive explored! You're building a solid Bitcoin foundation.",pts:50,tickets:10},{pct:50,key:"explore_50",emoji:"🗺️🔥",title:"50% EXPLORED!",msg:"Halfway through the entire archive! You know more about Bitcoin than most people on Earth.",pts:100,tickets:25},{pct:75,key:"explore_75",emoji:"🗺️⚡",title:"75% EXPLORED!",msg:"Three quarters done! You're in the top tier of Bitcoin knowledge seekers.",pts:200,tickets:50},{pct:100,key:"explore_100",emoji:"🗺️👑🏆",title:"ARCHIVE COMPLETE!",msg:"You've explored EVERY SINGLE channel in the archive. You are a true Bitcoin scholar. Satoshi would be proud! 🧡",pts:500,tickets:100}];window._checkExplorationMilestones=function(){if(void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]),o=Object.keys(CHANNELS).length,n=Math.round(t.length/o*100);e.forEach(function(e){if(n>=e.pct&&"true"!==localStorage.getItem("btc_"+e.key+"_celebrated")){if(localStorage.setItem("btc_"+e.key+"_celebrated","true"),"function"==typeof awardPoints&&awardPoints(e.pts,"🗺️ "+e.pct+"% Explored"),"function"==typeof awardOrangeTickets)awardOrangeTickets(e.tickets,"🗺️ "+e.pct+"% Explored");else{var t=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(t+e.tickets).toString())}if(setTimeout(function(){showCelebration({emoji:e.emoji,title:e.title,message:e.msg,rewards:[{label:e.pts.toString(),sub:"PTS",color:"#22c55e"},{label:e.tickets.toString(),sub:"🎟️ TICKETS",color:"#f7931a"}]})},800),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o={};o["explorationMilestone_"+e.pct]=!0;try{db.collection("users").doc(auth.currentUser.uid).update(o).catch(function(){})}catch(e){}}}})}};var t=window.renderExplorationMap;window.renderExplorationMap=function(){t(),window._checkExplorationMilestones()}}(),function(){var e=window.showQuestFinalResults;e&&(window.showQuestFinalResults=function(){e.apply(this,arguments);var t=window._questScore||0;5===t?("function"==typeof showToast&&showToast("🏆 PERFECT SCORE! You nailed every question!"),"function"==typeof launchConfetti&&setTimeout(launchConfetti,300)):t>=3&&"function"==typeof showToast&&showToast("⚡ Quest passed! +"+(window._questPts||0)+" XP earned!")});var t=window.nachoQuizAnswer;t&&(window.nachoQuizAnswer=function(e,o){t.apply(this,arguments),o&&"function"==typeof haptic&&haptic("success")});var o=window.convoQuizAnswer;o&&(window.convoQuizAnswer=function(e,t){o.apply(this,arguments),t&&"function"==typeof haptic&&haptic("light")})}(),function(){window._scrollPositions={};var e=window.go;e&&(window.go=async function(t,o,n){var i=document.getElementById("main"),a=location.hash.slice(1);a&&i&&(window._scrollPositions[a]=i.scrollTop),await e(t,o,n),window._scrollPositions[t]&&i&&setTimeout(function(){i.scrollTop=window._scrollPositions[t]},100)}),window.haptic=function(e){if("visible"===document.visibilityState&&"false"!==localStorage.getItem("btc_haptic")&&navigator.vibrate)switch(e){case"light":navigator.vibrate(10);break;case"medium":navigator.vibrate(25);break;case"heavy":navigator.vibrate([30,50,30]);break;case"success":navigator.vibrate([15,30,15,30,15]);break;case"error":navigator.vibrate([50,30,50]);break;default:navigator.vibrate(15)}};var t=window.awardPoints;t&&(window.awardPoints=function(){return haptic("success"),t.apply(this,arguments)});var o=window.showLevelUpCelebration;o&&(window.showLevelUpCelebration=function(){return haptic("heavy"),o.apply(this,arguments)}),function(){var e=document.createElement("style");e.textContent="@keyframes slideInRight{from{transform:translateX(30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInLeft{from{transform:translateX(-30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInUp{from{transform:translateY(20px);opacity:0}to{transform:translateY(0);opacity:1}}.page-transition-right{animation:slideInRight 0.25s ease-out;}.page-transition-left{animation:slideInLeft 0.25s ease-out;}.page-transition-up{animation:slideInUp 0.2s ease-out;}",document.head.appendChild(e);var t=document.getElementById("main");t&&new MutationObserver(function(){var e=document.getElementById("hero");e&&e.innerHTML&&(e.classList.remove("page-transition-right"),e.offsetWidth,e.classList.add("page-transition-right"))}).observe(document.getElementById("hero")||t,{childList:!0})}();var n=0;document.addEventListener("touchend",function(e){var t=Date.now();if(t-n<300){var o=e.target.closest&&e.target.closest('[onclick*="forumViewPost"]');if(o){var i=o.querySelector('[onclick*="forumVotePost"]');i&&(i.click(),haptic("medium")),e.preventDefault()}}n=t},{passive:!1});var i=(new Date).toISOString().split("T")[0];function a(e){return localStorage.getItem(e+"_"+i)||null}function r(e,t){localStorage.setItem(e+"_"+i,t)}function s(e){return parseInt(a(e)||"0",10)}function c(e){var t=s(e)+1;return r(e,String(t)),t}var l,d=[{id:"read",text:"📖 Read a new channel",check:function(){return"true"===a("btc_new_channel_read")}},{id:"nacho",text:"🦌 Ask Nacho a question",check:function(){return s("btc_nacho_asked")>0}},{id:"quiz",text:"🎮 Complete a quiz question",check:function(){return"true"===a("btc_quiz_done")}},{id:"explore",text:"🗺️ Visit 3 different channels",check:function(){return s("btc_channels_today")>=3}},{id:"forum",text:"🗣️ Visit the PlebTalk",check:function(){return"true"===a("btc_forum_visited")}},{id:"streak",text:"🔥 Log in to keep your streak",check:function(){return!0}},{id:"favorite",text:"⭐ Save a channel to favorites",check:function(){return"true"===a("btc_fav_added")}},{id:"tctv_10m",text:"📺 Watch 10 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=10}},{id:"tctv_visit",text:"📺 Tune in to Timechain TV",check:function(){return"true"===a("btc_tctv_visited")}},{id:"tctv_3ch",text:"📺 Watch 3 different TCTV stations",check:function(){try{var e=a("btc_tctv_stations_visited");return!!e&&JSON.parse(e).length>=3}catch(e){return!1}}},{id:"tctv_30m",text:"📺 Watch 30 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=30}},{id:"tip_send",text:"⚡ Send a Lightning tip to someone",check:function(){return"true"===a("btc_tip_sent")}},{id:"tip_3",text:"⚡ Send 3 Lightning tips today",check:function(){return s("btc_tips_sent_count")>=3}},{id:"ln_setup",text:"⚡ Set up your Lightning wallet",check:function(){return!!(localStorage.getItem("btc_nwc_url")||localStorage.getItem("btc_ln_address")||void 0!==currentUser&¤tUser&¤tUser.lightningAddress)}},{id:"chat_msg",text:"🌍 Send a message in Global Chat",check:function(){return"true"===a("btc_chat_sent")}},{id:"pvp_battle",text:"⚔️ Complete a PVP trivia battle",check:function(){return"true"===a("btc_pvp_done")}},{id:"beats_listen",text:"🎸 Listen to a track on Bitcoin Beats",check:function(){return"true"===a("btc_beats_played")}},{id:"explore_5",text:"🗺️ Explore 5 different channels today",check:function(){return s("btc_channels_today")>=5}},{id:"nacho_3",text:"🦌 Ask Nacho 3 questions",check:function(){return s("btc_nacho_asked")>=3}}];function u(){var e=(new Date).toISOString().split("T")[0],t=Math.floor(new Date(e).getTime()/864e5);return d[t%d.length]}function p(){var e=u(),t=(new Date).toISOString().split("T")[0],o=localStorage.getItem("btc_challenge_done")===t,n=document.getElementById("dailyChallengeCard");n&&(o?(n.style.borderColor="#22c55e",n.style.background="rgba(34,197,94,0.05)",n.innerHTML='
    Today\'s Challenge ✔️
    '+e.text+" — Done! +100 XP 🎉
    "):(n.style.borderColor="var(--border)",n.style.background="var(--card-bg)",n.innerHTML='
    🎯
    Today\'s Challenge
    '+e.text+"
    "))}if(window.checkDailyChallenge=function(){var e=(new Date).toISOString().split("T")[0];if(localStorage.getItem("btc_challenge_done")!==e&&u().check()){localStorage.setItem("btc_challenge_done",e),"function"==typeof awardPoints&&awardPoints(100,"🎯 Daily challenge!"),"function"==typeof awardOrangeTickets&&awardOrangeTickets(5,"🎯 Daily challenge!"),"function"==typeof showToast&&showToast("🎯 Daily challenge complete! +100 XP + 🎟️ 5 tickets!"),haptic("success"),p();var t=document.getElementById("dailyChallengeCard");t&&(t.style.transition="transform 0.3s, box-shadow 0.3s",t.style.transform="scale(1.03)",t.style.boxShadow="0 0 20px rgba(34,197,94,0.4)",setTimeout(function(){t.style.transform="",t.style.boxShadow=""},1500))}},setInterval(window.checkDailyChallenge,3e3),window._raidHomeUnsub=null,window._raidHomeTimer=null,window.renderRaidBossHome=function(){var e=document.getElementById("raidBossHomeCard");e&&("undefined"!=typeof firebase&&void 0!==db?(window._raidHomeUnsub&&(window._raidHomeUnsub(),window._raidHomeUnsub=null),window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),window._raidHomeUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.style.display="none";else{var o=Date.now(),n=null,i=null,a=null;t.forEach(function(e){var t=e.data();t.id=e.id;var r=t.startTime&&t.startTime.toDate?t.startTime.toDate().getTime():0,s=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime&&i.startTime.toDate?i.startTime.toDate().getTime():0))&&(i=t):t.defeated&&(a||(a=t))}),function(e,t,o,n){if(window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),t||o||n){e.style.display="";var i="if(typeof showQuestHub==='function'){showQuestHub();setTimeout(function(){if(typeof window._questHubTab!=='undefined'){window._questHubTab='raid';if(typeof _renderQuestHubTab==='function')_renderQuestHubTab();}},300)}",a="";if(t){var r=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0,s=t.target>0?Math.min(100,Math.round((t.current||0)/t.target*100)):0,c=Math.max(0,(t.target||0)-(t.current||0)),l=Math.max(0,100-s),d=l<=25?"#ef4444":l<=50?"#f59e0b":"#22c55e",u=t.image||"";if(!u){var p={"Channel-Crawler":"channel-crawler","Quiz-Crusader":"quiz-crusader","TV-Titan":"tv-titan","Beats-Baron":"beats-baron","Flash-Flash":"flash-flash","XP-Hoarder":"xp-hoarder","Poll-Patroller":"poll-patroller","Chat-Charger":"chat-charger","Badge-Builder":"badge-builder","Streak-Sage":"streak-sage","Topic-Explorer":"topic-explorer","Lightning-Lancer":"lightning-lancer","Forum-Forge":"forum-forge","Trivia-Tactician":"trivia-tactician","Content-Conqueror":"content-conqueror"};p[t.name]&&(u="images/raid-bosses/"+p[t.name]+".png")}a+='
    '+(u?'':'⚔️')+'
    ⚔️ CURRENT RAID BOSS
    '+(t.name||"Raid Boss")+'
    ❤️ '+c+"/"+t.target+' HP⏱ '+h(r)+'
    ',window._raidActiveEndMs=r}if(o){var m=o.startTime&&o.startTime.toDate?o.startTime.toDate().getTime():0,g=new Date(m).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"});a+='
    ⚔️
    NEXT BOSS
    '+(o.name||"TBD")+" — "+g+'
    Starts in '+h(m)+'
    ',window._raidUpcomingStartMs=m}n&&!t&&(a='
    💀
    🎉 BOSS DEFEATED!
    '+("function"==typeof escapeHtml?escapeHtml(n.name||"Raid Boss"):n.name||"Raid Boss")+' has fallen!
    🏆 Orange ticket drawing this Friday!
    '+a),e.innerHTML=a,window._raidHomeTimer=setInterval(function(){var e=document.getElementById("raidHomeCountdown");e&&window._raidActiveEndMs&&(e.textContent="⏱ "+h(window._raidActiveEndMs));var t=document.getElementById("raidHomeUpcomingCountdown");t&&window._raidUpcomingStartMs&&(t.textContent="Starts in "+h(window._raidUpcomingStartMs)),e||t||(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null)},1e3)}else e.style.display="none";function h(e){var t=Math.max(0,e-Date.now());if(t<=0)return"⏳ Any moment now...";var o=Math.floor(t/864e5),n=Math.floor(t%864e5/36e5),i=Math.floor(t%36e5/6e4),a=Math.floor(t%6e4/1e3);return o>0?o+"d "+n+"h "+i+"m":n>0?n+"h "+i+"m "+a+"s":i+"m "+a+"s"}}(e,n,i,a)}},function(){e.style.display="none"})):e.style.display="none")},l="",window._trackChallengeNav=function(e){e&&e!==l&&(l=e,"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e||r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},500))},window.go){var m=window.go;window.go=async function(e){var t=!1;e&&"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e&&(t=-1===safeJSON("btc_visited_channels",[]).indexOf(e));var o=await m.apply(this,arguments);return"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e),e&&"forum"!==e&&(c("btc_channels_today"),t&&r("btc_new_channel_read","true")),"forum"===e&&r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},300),o}}var g=window.nachoUnifiedAnswer;g&&(window.nachoUnifiedAnswer=function(e,t){return c("btc_nacho_asked"),g.apply(this,arguments)}),window.addEventListener("hashchange",function(){var e=location.hash.slice(1);e&&"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e)}),window.renderProgressRings=function(){var e=document.getElementById("progressRings");if(e){var t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=0;void 0!==currentUser&¤tUser&&(currentUser.readChannels&¤tUser.readChannels.length?o=currentUser.readChannels.length:currentUser.channelsVisited&&(o=currentUser.channelsVisited)),0===o&&(o=safeJSON("btc_visited_channels",[]).length);var n=void 0!==currentUser&¤tUser&¤tUser.streak||0,i=void 0!==currentUser&¤tUser&¤tUser.points||0,a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.innerHTML='
    '+r(Math.min(100,o/t*100),"#f7931a","Channels",o+"/"+t)+r(Math.min(100,5*n),"#22c55e","Streak","🔥"+n)+r(Math.min(100,i/21e3*100),"#8B5CF6","XP",i>999?Math.floor(i/1e3)+"k":i)+r(Math.min(100,2*a),"#3B82F6","Nacho",a)+"
    "}function r(e,t,o,n){var i=2*Math.PI*32;return'
    '+n+'
    '+o+"
    "}};var h=null;function f(){console.log("[MobileUX] Initializing..."),function(){var e=document.createElement("div");e.id="bottomNav",e.className="mobile-nav",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:200000;background:rgba(10,10,10,0.95);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border-top:1px solid rgba(255,255,255,0.1);padding:10px 0 env(safe-area-inset-bottom,10px) 0;padding-bottom:max(env(safe-area-inset-bottom,10px),10px);display:none;transition:transform 0.25s ease;-webkit-transform:translateZ(0);transform:translateZ(0);",e.innerHTML='
    ';var t=document.createElement("style");t.textContent=".bnav-btn{background:none;border:none;color:var(--text-dim,#666);font-size:0.6rem;cursor:pointer;font-family:inherit;padding:6px 0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;touch-action:manipulation;-webkit-tap-highlight-color:transparent;transition:0.2s;flex:1;min-width:0;}.bnav-icon{font-size:1.3rem;line-height:1;display:block;transition:transform 0.2s;}.bnav-label{font-size:0.55rem;line-height:1;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;}.bnav-btn:active .bnav-icon{transform:scale(1.2);}.bnav-btn.active{color:var(--accent);}@media(min-width:901px){#bottomNav{display:none!important;}}@media(max-width:900px){#bottomNav{display:block!important;visibility:visible!important;opacity:1!important;}.messages{padding-bottom:140px!important;}.home-page{padding-bottom:100px!important;}}",document.head.appendChild(t),document.body.appendChild(e)}(),function(){var e=document.getElementById("main");if(e){var t=0,o=document.getElementById("bottomNav");o&&e.addEventListener("scroll",function(){if(!(window.innerWidth>900)){var n=e.scrollTop,i=n-t;i>10&&n>200?o.classList.add("nav-hidden"):(i<-5||n<=10)&&o.classList.remove("nav-hidden"),t=n}},{passive:!0})}}(),setTimeout(function(){!function(){var e=0;if(void 0!==currentUser&¤tUser&&(e=currentUser.streak||0),!(e<2||document.getElementById("streakBanner"))){var t=document.createElement("div");t.id="streakBanner",t.style.cssText="position:fixed;top:32px;left:0;right:0;z-index:300;background:linear-gradient(135deg,#f7931a,#ea580c);color:#fff;padding:10px 16px;text-align:center;font-size:0.85rem;font-weight:700;cursor:pointer;animation:slideInUp 0.3s;",t.innerHTML="🔥 Day "+e+' streak! Keep it alive! tap to dismiss',t.onclick=function(){t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.remove()},300)},document.body.appendChild(t),setTimeout(function(){t.parentNode&&(t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.parentNode&&t.remove()},300))},5e3)}}(),function(){if("function"==typeof forceShowBubble&&!sessionStorage.getItem("btc_welcomed_back")){sessionStorage.setItem("btc_welcomed_back","true");var e="";void 0!==currentUser&¤tUser&¤tUser.username&&(e=currentUser.username);var t,o=void 0!==currentUser&¤tUser&¤tUser.streak||0,n=(new Date).getHours(),i=n<12?"Morning":n<17?"Afternoon":"Evening",a=u();t=e&&o>=2?"Good "+i.toLowerCase()+", "+e+"! ☀️ Day "+o+" streak — you're on fire! 🔥 Today's challenge: "+a.text:e?"Hey "+e+"! 🦌 Welcome back! Today's challenge: "+a.text:"Welcome back! 🦌 Today's challenge: "+a.text,setTimeout(function(){forceShowBubble(t)},3e3)}}(),p(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof renderProgressRings&&renderProgressRings()},2500)}window.addEventListener("beforeinstallprompt",function(e){if(e.preventDefault(),h=e,!window.matchMedia("(display-mode: standalone)").matches){var t=localStorage.getItem("btc_pwa_dismissed");if(t&&Date.now()-parseInt(t)<6048e5)return;window._pwaLoadTime=Date.now(),window._pwaCheckInterval=setInterval(function(){if(!(Date.now()-(window._pwaLoadTime||Date.now())<9e4)){var e=[];try{e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}e.length>=3&&(clearInterval(window._pwaCheckInterval),function(){if(!document.getElementById("pwaInstallBanner")){var e=document.createElement("div");if(e.id="pwaInstallBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Install Bitcoin Education
    Add to home screen for the best experience — works offline!
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}}())}},1e4)}}),window.installPWA=function(){h&&(h.prompt(),h.userChoice.then(function(e){"accepted"===e.outcome&&"function"==typeof showToast&&showToast("🦌 Welcome aboard! App installed!"),h=null})),dismissPWABanner()},window.dismissPWABanner=function(){var e=document.getElementById("pwaInstallBanner");e&&e.remove(),localStorage.setItem("btc_pwa_dismissed",Date.now().toString())},function(){var e=/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,t=/Safari/.test(navigator.userAgent)&&!/CriOS|FxiOS|Chrome/.test(navigator.userAgent),o=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(e&&t&&!o){var n=localStorage.getItem("btc_ios_a2hs_dismissed");n&&Date.now()-parseInt(n)<2592e6||setTimeout(function(){if(!document.getElementById("iosA2HSBanner")){var e=document.createElement("div");if(e.id="iosA2HSBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Add to Home Screen
    For the best experience, add this app to your home screen:
    1. Tap the Share button ⬆️ at the bottom
    2. Scroll down and tap Add to Home Screen
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}},12e4)}}(),window.dismissIOSA2HS=function(){var e=document.getElementById("iosA2HSBanner");e&&e.remove(),localStorage.setItem("btc_ios_a2hs_dismissed",Date.now().toString())},window.toggleMobileLearnMenu=function(){var e=document.getElementById("mobileLearnMenu");if(e)e.remove();else{var t=document.getElementById("appsMenu");t&&t.remove();var o=document.createElement("div");o.id="mobileLearnMenu",o.style.cssText="position:fixed;bottom:70px;left:8px;right:8px;z-index:250;max-width:400px;margin:0 auto;background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:18px;box-shadow:0 -8px 40px rgba(0,0,0,0.6);animation:fadeSlideIn 0.25s ease-out;",o.innerHTML='

    🎓 Learn

    ',document.body.appendChild(o),setTimeout(function(){document.addEventListener("click",function e(t){var o=document.getElementById("mobileLearnMenu");!o||o.contains(t.target)||t.target.closest("#bnavLearn")||(o.remove(),document.removeEventListener("click",e))})},100)}},window.toggleMobileFlashcards=function(){var e=document.getElementById("mLearnFlashGrid"),t=document.getElementById("mLearnFlashBtn");e&&("none"===e.style.display?(e.style.display="flex",t&&(t.textContent="📚 Flashcards ▼")):(e.style.display="none",t&&(t.textContent="📚 Flashcards ▶")))},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",f):f()}(),function(){"use strict";var e=null,t=null,o=null,n=null;function i(){if(!(e&&e.readyState<=1))try{(e=new WebSocket("wss://ws.coincap.io/prices?assets=bitcoin")).onopen=function(){console.log("[Dashboard] Price WebSocket connected (CoinCap)"),window._wsDataTimer=setTimeout(function(){t||(console.warn("[Dashboard] WS connected but no data — falling back"),r())},1e4)},e.onmessage=function(e){try{window._wsDataTimer&&(clearTimeout(window._wsDataTimer),window._wsDataTimer=null);var i=JSON.parse(e.data);if(!i.bitcoin)return;var a=parseFloat(i.bitcoin);!n&&t&&(n=t),t=a,n&&(o=(t-n)/n*100),n=parseFloat(i.o);var r=document.getElementById("dashLivePrice");r&&(r.textContent="$"+p(t,2));var s=document.getElementById("dashLiveChange");if(s){var c=o>=0?"#22c55e":"#ef4444",l=o>=0?"▲":"▼";s.innerHTML=''+l+" "+Math.abs(o).toFixed(2)+"% (24h)"}var d=document.getElementById("dashBtnPrice");if(d){var u=o>=0?"#22c55e":"#ef4444",m=o>=0?"▲":"▼";d.innerHTML="$"+p(t,0)+' '+m+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}catch(e){}},e.onclose=function(){console.log("[Dashboard] WS closed, reconnecting..."),e=null,setTimeout(i,5e3)},e.onerror=function(t){console.warn("[Dashboard] WS error, falling back to polling");try{e.close()}catch(e){}e=null,r()}}catch(e){r()}}var a=null;function r(){function e(){fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true").then(function(e){return e.json()}).then(function(e){if(e&&e.bitcoin){t=e.bitcoin.usd,o=e.bitcoin.usd_24h_change||0;var n=document.getElementById("dashLivePrice");n&&(n.textContent="$"+p(t,2));var i=document.getElementById("dashLiveChange");if(i){var a=o>=0?"#22c55e":"#ef4444",r=o>=0?"▲":"▼";i.innerHTML=''+r+" "+Math.abs(o).toFixed(2)+"% (24h)"}var s=document.getElementById("dashBtnPrice");if(s){var c=o>=0?"#22c55e":"#ef4444",l=o>=0?"▲":"▼";s.innerHTML="$"+p(t,0)+' '+l+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}}).catch(function(){})}a||(console.log("[Dashboard] Starting price polling fallback (CoinGecko)"),e(),a=setInterval(e,3e4))}var s="btc_dashboard_cache",c=12e4,l=null,d=!1,u=null;function p(e,t){return null==e?"—":"number"==typeof t?Number(e).toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t}):Number(e).toLocaleString()}function m(e){return null==e?"—":e>=1e12?"$"+(e/1e12).toFixed(1)+"T":e>=1e9?"$"+(e/1e9).toFixed(1)+"B":e>=1e6?"$"+(e/1e6).toFixed(1)+"M":e>=1e3?"$"+(e/1e3).toFixed(0)+"K":"$"+Math.round(e)}function g(e){return null==e?"—":e>=1e12?(e/1e12).toFixed(2)+" T":e>=1e9?(e/1e9).toFixed(2)+" B":p(e)}async function h(){if(d)return await new Promise(function(e){var t=setInterval(function(){d||(clearInterval(t),e())},200);setTimeout(function(){clearInterval(t),d=!1,e()},1e4)}),l||{};d=!0;var e=null;try{var i=JSON.parse(localStorage.getItem(s));if(i&&i.data&&(e=i.data,Date.now()-i.tse.text()).then(e=>{a.blockHeight=parseInt(e);try{localStorage.setItem("btc_last_height",a.blockHeight.toString())}catch(e){}var t=document.getElementById("btcDashCard");t&&!a.price&&a.blockHeight&&(t.innerHTML=f(a))}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/fees/recommended").then(e=>e.json()).then(e=>{a.feeFast=e.fastestFee,a.feeHalf=e.halfHourFee,a.feeHour=e.hourFee,a.feeEcon=e.economyFee,a.feeMin=e.minimumFee}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/mining/hashrate/1m").then(e=>e.json()).then(e=>{if(e.currentHashrate&&(a.hashrate=e.currentHashrate),e.currentDifficulty&&(a.difficulty=e.currentDifficulty),e.hashrates&&e.hashrates.length>=6){var t=e.hashrates.length,o=(e.hashrates[t-1].avgHashrate+e.hashrates[t-2].avgHashrate+e.hashrates[t-3].avgHashrate)/3,n=(e.hashrates[t-4].avgHashrate+e.hashrates[t-5].avgHashrate+e.hashrates[t-6].avgHashrate)/3;n>0&&(a.hashrateChange24h=(o-n)/n*100)}}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/difficulty-adjustment").then(e=>e.json()).then(e=>{a.diffChange=e.difficultyChange,a.diffEstDate=e.estimatedRetargetDate,a.diffRemaining=e.remainingBlocks,a.diffProgress=e.progressPercent}).catch(()=>{})),r.push(fetch("https://mempool.space/api/mempool").then(e=>e.json()).then(e=>{a.mempoolTxs=e.count,a.mempoolSize=e.vsize}).catch(()=>{})),r.push(fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true&include_24hr_vol=true&include_market_cap=true").then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{if(e.bitcoin){a.price=e.bitcoin.usd;try{localStorage.setItem("btc_last_price",e.bitcoin.usd.toString())}catch(e){}a.change24h=e.bitcoin.usd_24h_change,a.volume24h=e.bitcoin.usd_24h_vol,a.marketCap=e.bitcoin.usd_market_cap,!n&&a.price&&a.change24h&&(n=a.price/(1+a.change24h/100),o=a.change24h)}var t=document.getElementById("btcDashCard");return t&&a.price&&(t.innerHTML=f(a)),new Promise(function(e){setTimeout(e,1500)})}).then(function(){return fetch("https://api.coingecko.com/api/v3/coins/bitcoin?localization=false&tickers=false&community_data=false&developer_data=false")}).then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{e.market_data&&(a.supply=e.market_data.circulating_supply,a.ath=e.market_data.ath?e.market_data.ath.usd:null,a.athDate=e.market_data.ath_date?e.market_data.ath_date.usd:null,a.athChange=e.market_data.ath_change_percentage?e.market_data.ath_change_percentage.usd:null,a.high24h=e.market_data.high_24h?e.market_data.high_24h.usd:null,a.low24h=e.market_data.low_24h?e.market_data.low_24h.usd:null,a.mktCapChange24h=e.market_data.market_cap_change_percentage_24h||null)}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/lightning/statistics/latest").then(e=>e.json()).then(e=>{e&&(a.lnCapacity=e.latest?e.latest.total_capacity:e.total_capacity,a.lnNodes=e.latest?e.latest.node_count:e.node_count,a.lnChannels=e.latest?e.latest.channel_count:e.channel_count)}).catch(()=>{})),r.push(fetch("https://api.alternative.me/fng/?limit=1").then(e=>e.json()).then(e=>{e.data&&e.data[0]&&(a.fearGreed=parseInt(e.data[0].value),a.fearGreedLabel=e.data[0].value_classification)}).catch(()=>{})),await Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,12e3))]),!a.price&&t&&(a.price=t);for(var u=[s,"btc_dash_backup"],p=0;p'+(r<=2?"Live metrics · Updates every 2 min":"📦 Data from "+(r<60?r+"m":Math.round(r/60)+"h")+" ago · Refreshing...")+"",a+='',a+="";var s=t||n.price,c=null!==o?o:n.change24h||0,l=c>=0?"#22c55e":"#ef4444",d=c>=0?"▲":"▼";if(a+='
    ',a+='
    $'+p(s,2)+"
    ",a+='
    '+d+" "+Math.abs(c).toFixed(2)+"%
    ",a+='
    🔴 Live — updates automatically · All % changes are 24h
    ',a+='
    ',a+='24h High: $'+p(n.high24h,0)+"",a+='24h Low: $'+p(n.low24h,0)+"",a+="
    ",a+="
    ",void 0!==n.halvingDays){var u=n.halving?((21e4-n.halving)/21e4*100).toFixed(1):0,m=n.halvingEta?n.halvingEta.toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"}):"—";a+='
    ',a+='
    ⏳ Next Halving — Block #'+p(n.halvingBlock)+'
    ',window._halvingTargetMs=Date.now()+10*n.halving*60*1e3,a+='
    ',a+='
    '+(n.halvingDays||0)+'
    Days
    ',a+='
    :
    ',a+='
    '+(n.halvingHours||0)+'
    Hours
    ',a+='
    :
    ',a+='
    '+(n.halvingMins||0)+'
    Mins
    ',a+='
    :
    ',a+='
    00
    Secs
    ',a+="
    ",a+='
    Est. '+m+" · "+p(n.halving)+" blocks remaining
    ",a+='
    ',a+='
    ',a+="
    ",a+='
    '+u+"% through epoch · Subsidy drops "+n.subsidy+" → "+(n.nextSubsidy||"?")+" BTC
    ",a+="
    "}a+='
    ',a+=y("⚡","Sats per Dollar",p(n.satsPerDollar),"Moscow Time","How many satoshis (sats) you get for $1 USD. A satoshi is the smallest unit of Bitcoin (0.00000001 BTC). Also called Moscow Time — the number on the clock is how many sats per dollar."),a+=y("⛓️","Block Height",p(n.blockHeight),"","The total number of blocks mined since Bitcoin's Genesis Block on Jan 3, 2009. A new block is added roughly every 10 minutes. This number only goes up — never down."),a+=y("🪙","Block Subsidy",n.subsidy+" BTC",p(n.halving)+" blocks to halving","The reward miners receive for finding each new block. Started at 50 BTC in 2009 and halves every 210,000 blocks (~4 years). Currently 3.125 BTC per block.");var h,f="";if(null!=n.hashrateChange24h){var v=n.hashrateChange24h;f=''+(v>=0?"▲":"▼")+" "+Math.abs(v).toFixed(1)+"%"}a+=y("⛏️","Hashrate",null==(h=n.hashrate)?"—":h>=1e18?(h/1e18).toFixed(2)+" EH/s":h>=1e15?(h/1e15).toFixed(2)+" PH/s":h>=1e12?(h/1e12).toFixed(2)+" TH/s":h>=1e9?(h/1e9).toFixed(2)+" GH/s":h>=1e6?(h/1e6).toFixed(2)+" M":h>=1e3?(h/1e3).toFixed(1)+"K":p(h),f,"The total computing power securing the Bitcoin network, measured in hashes per second. Higher hashrate = more secure network. EH/s = quintillion hashes per second."),a+=y("🎯","Difficulty",g(n.difficulty),"","How hard it is to mine a new block. Adjusts every 2,016 blocks (~2 weeks) to keep block times at ~10 minutes. If miners join, difficulty goes up. If miners leave, it goes down."),a+=y("🔄","Next Adjustment",(n.diffChange>=0?"+":"")+(n.diffChange||0).toFixed(2)+"%",i+" · "+p(n.diffRemaining)+" blocks","The estimated change in mining difficulty at the next adjustment. Positive means blocks are being found faster than 10 min (more miners joined). Negative means slower (miners left)."),a+=y("💸","Fast Fee",(n.feeFast||"—")+" sat/vB","Half-hour: "+(n.feeHalf||"—")+" · Economy: "+(n.feeEcon||"—"),"The recommended transaction fee in satoshis per virtual byte (sat/vB). Fast = next block (~10 min). Half-hour = 1-3 blocks. Economy = lowest priority. Higher fees = faster confirmation."),a+=y("📋","Mempool",p(n.mempoolTxs)+" txs",n.mempoolSize?(n.mempoolSize/1e6).toFixed(1)+" MvB":"","The waiting room for unconfirmed Bitcoin transactions. Shows how many transactions are waiting to be included in a block and their total size. A full mempool means higher fees."),a+=y("💰","Circulating Supply",function(e){return e?(e/1e6).toFixed(2)+"M / 21M":"—"}(n.supply),function(e){return e?(e/21e6*100).toFixed(2)+"%":"—"}(n.supply)+" mined","How many of the 21 million total Bitcoin have been mined so far. No more than 21 million will ever exist — this is enforced by code and consensus. The last Bitcoin will be mined around the year 2140.");var b="";if(null!=n.mktCapChange24h){var w=n.mktCapChange24h;b=''+(w>=0?"▲":"▼")+" "+Math.abs(w).toFixed(1)+"%"}a+=y("📊","Market Cap","$"+g(n.marketCap),b,"Total value of all Bitcoin in circulation (price × circulating supply). Puts Bitcoin's size in perspective compared to gold (~$16T), the S&P 500, or global real estate.");var x="";n.volume24h&&n.marketCap&&(x="Vol/MCap: "+(n.volume24h/n.marketCap*100).toFixed(2)+"%"),a+=y("📈","24h Volume","$"+g(n.volume24h),x,"Total USD value of Bitcoin traded across all exchanges in the last 24 hours. High volume often signals strong market interest or significant price moves.");var k=n.lnCapacity?(n.lnCapacity/1e8).toFixed(0):"—",B=n.lnCapacity&&n.price?"$"+g(n.lnCapacity/1e8*n.price):"",E=(n.lnNodes?p(n.lnNodes)+" nodes · ":"")+(n.lnChannels?p(n.lnChannels)+" channels":"")+(B?"
    "+B:"");a+=y("⚡","Lightning Capacity",p(k)+" BTC",E,"Total Bitcoin locked in Lightning Network payment channels. Lightning enables instant, near-free Bitcoin payments. More capacity = more liquidity for fast payments. Nodes route payments; channels connect them."),n.ath&&(a+='
    ',a+='🏔️',a+='
    All-Time High
    ',a+='
    $'+p(n.ath,0)+"
    ",a+='
    '+(n.athChange||0).toFixed(1)+"%
    ",n.athDate&&(a+='
    '+new Date(n.athDate).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})+"
    "),a+="
    "),a+="
    ";var A=n.marketCap?n.marketCap/1e12:0;return a+='
    ',a+='
    ⚖️ Bitcoin vs Gold
    ',a+='
    ',a+='
    ₿ Bitcoin$'+A.toFixed(2)+"T
    ",a+='
    ',a+='
    🥇 GoldLoading...
    ',a+='
    Fetching live gold price...
    ',a+="
    ",setTimeout(function(){!function(e,t){if(!T)try{var o=JSON.parse(localStorage.getItem("btc_gold_cache"));o&&o.p&&(T=o.p,S=o.t||0)}catch(e){}T&&Date.now()-S<18e5?_(T,e,t):(T&&_(T,e,t),fetch("https://api.coingecko.com/api/v3/simple/price?ids=tether-gold&vs_currencies=usd").then(function(e){return e.json()}).then(function(o){var n=o["tether-gold"]?o["tether-gold"].usd:null;if(n){T=n,S=Date.now();try{localStorage.setItem("btc_gold_cache",JSON.stringify({p:n,t:Date.now()}))}catch(e){}_(n,e,t)}}).catch(function(){T||_(3200,e,t)}))}(A,n.supply||0)},150),a+='
    ',a+='
    🏛️ Bitcoin Treasuries ⓘ tap for top holders
    ',a+='
    Loading live treasury data...
    ',a+="
    ",setTimeout(function(){!function(e){var t=document.getElementById("treasuryData");if(t){if(!I)try{var o=JSON.parse(localStorage.getItem("btc_treasury_cache"));o&&o.d&&(I=o.d,C=o.t||0)}catch(e){}I&&Date.now()-C<18e5?M(t,I,e):(I&&M(t,I,e),fetch("https://api.coingecko.com/api/v3/companies/public_treasury/bitcoin").then(function(e){return e.json()}).then(function(o){I=o,C=Date.now();try{localStorage.setItem("btc_treasury_cache",JSON.stringify({d:o,t:Date.now()}))}catch(e){}M(t,o,e)}).catch(function(){I||(t.innerHTML='
    Could not load treasury data
    ')}))}}(n.price||0)},200),a+='
    ',a+='
    🏦 Bitcoin ETFs top 5 by BTC in custody
    ',a+='
    Loading ETF holdings...
    ',a+="
    ",setTimeout(function(){!function(e,t){var o=document.getElementById("etfHoldingsData");if(o){var n=e||parseFloat(localStorage.getItem("btc_last_price"))||83e3,i=t||1984e4,a=null;try{a=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"))}catch(e){}a&&a.holdings&&P(o,a.holdings,a.totalBtc,n,i,a.updated),fetch("data/etf-holdings.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.holdings&&e.holdings.length){try{localStorage.setItem("btc_etf_holdings_cache",JSON.stringify(e))}catch(e){}P(o,e.holdings,e.totalBtc,n,i,e.updated)}}).catch(function(){a||P(o,z,L,n,i,null)})}}(n.price||0,n.supply||0)},250),a+='
    ',a+='',a+='
    ",a+='
    ',a+="Data Sources: ",a+='mempool.space (blocks, fees, hashrate, difficulty, mempool) · ',a+='CoinGecko (price, market cap, supply, volume) · ',a+='Alternative.me (Fear & Greed Index) · ',a+='BitcoinTreasuries.net (company & government holdings)',a+='
    Last updated: '+new Date(n.ts||Date.now()).toLocaleTimeString()+"
    ",a+="
    ",setTimeout(function(){window._halvingTargetMs&&document.getElementById("halvSecs")&&"function"==typeof window._startHalvingTicker&&window._startHalvingTicker(),"function"==typeof window._attachTipListeners&&window._attachTipListeners()},100),a}function y(e,t,o,n,i){return"
    '+e+" "+t+(i?' ':"")+'
    '+(o||"—")+"
    "+(n?'
    '+n+"
    ":"")+""}setInterval(function(){d&&(console.warn("[Dashboard] Force-clearing stuck loading flag"),d=!1)},15e3);var v="ontouchstart"in window||navigator.maxTouchPoints>0;function b(){injectDashboardButton(),injectHomeDashboardButton(),i()}window.showDashTip=function(e,t){var o=document.getElementById("dashTipPopup");o&&o.remove();var n=document.createElement("div");n.id="dashTipPopup",n.style.cssText="position:absolute;left:50%;transform:translateX(-50%);bottom:calc(100% + 8px);z-index:10;background:var(--bg-side,#1a1a2e);border:1px solid var(--accent);border-radius:10px;padding:10px 14px;max-width:320px;width:max-content;box-shadow:0 8px 24px rgba(0,0,0,0.5);animation:fadeSlideIn 0.2s ease-out;pointer-events:auto;",n.innerHTML='
    '+t.replace(/\\n/g,"
    ").replace(/\n/g,"
    ")+'
    ',e.style.position="relative",e.appendChild(n),setTimeout(function(){document.addEventListener("click",function e(t){n.parentNode&&n.remove(),document.removeEventListener("click",e)},{once:!0})},50)},window.hideDashTip=function(e){var t=e?e.querySelector("#dashTipPopup"):document.getElementById("dashTipPopup");t&&t.remove()},window._attachTipListeners=function(){document.querySelectorAll("[data-dash-tip]:not([data-tip-bound])").forEach(function(e){e.setAttribute("data-tip-bound","1");var t=e.getAttribute("data-dash-tip");t&&(v?e.addEventListener("click",function(o){o.stopPropagation();var n=e.querySelector("#dashTipPopup");n?n.remove():showDashTip(e,t)}):(e.addEventListener("mouseenter",function(){showDashTip(e,t)}),e.addEventListener("mouseleave",function(){hideDashTip(e)})))})},window.injectDashboardButton=function(){},window.injectHomeDashboardButton=function(){},window.toggleDashboard=async function(){var e=document.getElementById("btcDashOverlay");if(e)return e.remove(),clearInterval(u),void(u=null);var t=document.createElement("div");t.id="btcDashOverlay",t.style.cssText="position:fixed;inset:0;z-index:10002;background:rgba(0,0,0,0.88);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&closeDashboard()};var o=document.createElement("div");o.id="btcDashCard",o.style.cssText="background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:24px;max-width:500px;width:100%;margin:40px auto;box-shadow:0 20px 60px rgba(0,0,0,0.5);animation:fadeSlideIn 0.3s ease-out;",t.appendChild(o),document.body.appendChild(t),i();var n=!1;try{var a=JSON.parse(localStorage.getItem(s));a&&a.data&&(a.data.price||a.data.blockHeight)&&(o.innerHTML=f(a.data),n=!0)}catch(e){}if(!n){var r={};if("undefined"!=typeof nachoLiveData&&(nachoLiveData.price&&(r.price=nachoLiveData.price),nachoLiveData.blockHeight&&(r.blockHeight=nachoLiveData.blockHeight)),!r.price)try{r.price=parseFloat(localStorage.getItem("btc_last_price"))||0}catch(e){}if(!r.blockHeight)try{r.blockHeight=parseInt(localStorage.getItem("btc_last_height"))||0}catch(e){}r.price||r.blockHeight?(o.innerHTML=f(r),n=!0):o.innerHTML='
    Loading Bitcoin metrics...
    '}h().then(function(e){var t=document.getElementById("btcDashCard");if(t){var o=document.getElementById("topIndicatorsPanel"),i=o&&"none"!==o.style.display;if(e&&(e.price||e.blockHeight)?t.innerHTML=f(e):n||(t.innerHTML='
    📊
    Unable to load fresh metrics.
    Showing last known data. Try again later.
    '),i){var a=document.getElementById("topIndicatorsPanel"),r=document.getElementById("topIndArrow");a&&(a.style.display="block",w=!1,k()),r&&(r.textContent="▲")}}}),u=setInterval(async function(){if(document.getElementById("btcDashOverlay")){var e=document.getElementById("topIndicatorsPanel"),t=e&&"none"!==e.style.display;localStorage.removeItem(s);var o=await h(),n=document.getElementById("btcDashCard");if(n&&(n.innerHTML=f(o),t)){var i=document.getElementById("topIndicatorsPanel"),a=document.getElementById("topIndArrow");i&&(i.style.display="block",w=!1,k()),a&&(a.textContent="▲")}}else clearInterval(u)},c)},window.closeDashboard=function(){var e=document.getElementById("btcDashOverlay");e&&e.remove(),u&&(clearInterval(u),u=null)},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(b,2e3)}):setTimeout(b,2e3),window.toggleTopIndicators=function(){var e=document.getElementById("topIndicatorsPanel"),t=document.getElementById("topIndArrow");e&&("none"===e.style.display?(e.style.display="block",t.textContent="▲",k()):(e.style.display="none",t.textContent="▼"))};var w=!1,x="btc_top_indicators_cache";function k(){if(!w){w=!0;var e=document.getElementById("topIndContent");if(e){try{var t=JSON.parse(localStorage.getItem(x));if(t&&t.html){var o=Math.round((Date.now()-t.ts)/6e4),n=o>5?'
    📦 Cached '+(o<60?o+"m":Math.round(o/60)+"h")+" ago · refreshing...
    ":"";e.innerHTML=n+t.html}}catch(e){}var i=l||{},a=i.price||0,r=i.blockHeight||0,s=i.supply||0,c=i.fearGreed||0,d=i.fearGreedLabel||"—",u=[];if(r){var m=Math.floor(r/21e4),g=50/Math.pow(2,m)*6*24*365,h=g>0?(s||198e5)/g:0,f=Math.pow(10,3.31954*Math.log10(h)-1.32093),y=a>0?(a/f).toFixed(2):"—";u.push({emoji:"📈",name:"Stock-to-Flow",value:h.toFixed(1),sub:"Model: $"+p(Math.round(f))+" · Ratio: "+y+"x",tip:"Stock-to-Flow measures scarcity. Higher S2F = scarcer asset. Bitcoin's S2F increases with each halving. Gold is ~62, Silver ~22. A ratio below 1x suggests undervalued vs the model."})}if(c){var v=c<=25?"#ef4444":c<=45?"#f97316":c<=55?"#eab308":c<=75?"#84cc16":"#22c55e";u.push({emoji:"😱",name:"Fear & Greed",value:c,color:v,sub:d,tip:"Crypto Fear & Greed Index. 0 = Extreme Fear (potential buy), 100 = Extreme Greed (potential sell). Aggregates volatility, momentum, social media, and surveys."})}if(u.push({emoji:"📐",name:"Mayer Multiple",value:"...",sub:"Loading...",tip:"Price divided by 200-day moving average. Below 1.0 = historically cheap. Above 2.4 = overheated. Named after Trace Mayer.",id:"mayerMultiple"}),r){var b=r%21e4,k=(b/21e4*100).toFixed(1),T=Math.round(10*b/1440),S=T>=365&&T<=730;u.push({emoji:"🔄",name:"Halving Cycle",value:k+"%",sub:"Day "+T+"/~1460"+(S?" · 🔥 Peak Window":""),color:S?"#f97316":null,tip:"Position in the current 4-year halving cycle (210,000 blocks). Historically, price peaks occur 12-24 months after a halving (Day 365-730). We are at day "+T+"."})}if(i.ath&&i.athDate){var B=new Date(i.athDate),_=Math.floor((Date.now()-B.getTime())/864e5),I=i.athChange?Math.abs(i.athChange).toFixed(1):"—";u.push({emoji:"🏔️",name:"ATH Drawdown",value:"-"+I+"%",sub:_+" days since ATH ($"+p(Math.round(i.ath))+")",tip:"Current drawdown from the all-time high. In previous cycles, bear markets saw -70% to -85% drawdowns. Recovery to new ATH has always followed."})}if(a&&s&&r){m=Math.floor(r/21e4);for(var C=0,E=r,A=0;A<=m&&E>0;A++){var M=Math.min(E,21e4);C+=M*(50/Math.pow(2,A)),E-=M}var z=3e4*C,P=z>0?(a*s/z).toFixed(1):"—";u.push({emoji:"🌡️",name:"Thermo Multiple",value:P+"x",sub:"Market Cap / Thermocap",tip:'Thermocap Multiple compares market cap to total miner revenue (a proxy for "energy spent"). Values >5x historically signal overheating (cycle tops hit 4-8x). <10x = accumulation zone.'})}if(a&&s&&i.volume24h){var U=a*s,N=i.volume24h>0?(U/i.volume24h).toFixed(1):"—",H=N<30?"#22c55e":N>150?"#ef4444":"var(--heading)";u.push({emoji:"📡",name:"NVT Ratio",value:N,color:H,sub:N<30?"Undervalued zone":N>150?"Overvalued zone":"Normal range",tip:"Network Value to Transactions ratio. Compares market cap to annualized transaction volume. Below 30 = undervalued relative to usage. Above 150 = potentially overvalued. Think of it like P/E ratio for Bitcoin."})}if(i.marketCap){var q=i.marketCap/.62;(i.marketCap/q*100).toFixed(1),u.push({emoji:"👑",name:"BTC Dominance",value:"~62%",sub:"Market cap share vs all crypto",tip:"Bitcoin's share of the total cryptocurrency market cap. Higher dominance = Bitcoin is outperforming alts. During alt seasons, dominance drops below 40%. During Bitcoin seasons (now), it rises above 55-65%. Historically, increasing dominance signals strength.",id:"btcDominance"})}if(u.push({emoji:"💎",name:"MVRV Z-Score",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Market Value to Realized Value ratio. Compares market cap to realized cap (sum of each coin valued at its last move price). Above 3.0 historically marks cycle tops. Below 1.0 marks bottoms. Data from CBBI open-source API. Top threshold: normalized ≥ 0.7 (≈ MVRV 3+).",id:"mvrvScore"}),a){var D=new Date("2009-01-03T00:00:00Z"),O=Math.floor((Date.now()-D.getTime())/864e5),j=5.82*Math.log10(O)-17.01,R=Math.pow(10,j),F=((a-R)/R*100).toFixed(0),W=parseFloat(F),V=W>200?"#ef4444":W>100?"#f97316":W<-30?"#22c55e":"var(--heading)",G=W>200,Q=W>200?"Far above — extreme ⚠️":W>100?"Above trend — elevated":W>0?"Above fair value":W>-30?"Near fair value":"Below trend — deep value 🟢";u.push({emoji:"📏",name:"Power Law",value:(W>=0?"+":"")+F+"%",color:V,sub:"Fair value: ~$"+p(Math.round(R))+" · "+Q,tip:"Bitcoin Power Law model tracks the long-term price trend using a log-log regression since genesis (Jan 3, 2009). Parameters: P = 10^(5.82 × log₁₀(days) - 17.01). Above +200% = historically extreme (cycle top zone). Below -30% = deep value accumulation. Current: "+O+" days since genesis.",flashing:G})}if(u.push({emoji:"🔵",name:"Pi Cycle Top",value:"...",sub:"Loading...",tip:"When the 111-day MA crosses above the 350-day MA × 2, it has historically signaled the exact top of every Bitcoin cycle. Flashes when the gap narrows to <5%.",id:"piCycleTop",flashing:!1}),r&&a){var Y=(144*(i.subsidy?parseFloat(i.subsidy):3.125)*a/27e6).toFixed(2),J=parseFloat(Y);u.push({emoji:"⛏️",name:"Puell Multiple",value:Y,color:J>2.2?"#ef4444":J<.5?"#22c55e":"var(--heading)",sub:J>2.2?"Miners overleveraged ⚠️":J<.5?"Miner capitulation zone 🟢":"Normal range",tip:"Ratio of daily miner revenue to its 365-day moving average. Above 2.2 = miners are earning far more than usual (historically a sell signal). Below 0.5 = miner capitulation (buy signal). Top threshold: ≥ 2.2.",flashing:J>=2.2})}if(a){for(var X=new Date("2010-07-18"),K=Math.floor((Date.now()-X.getTime())/864e5),$=Math.log(K+1400),Z=[2.775,2.788,2.801,2.815,2.8295,2.8445,2.859,2.872,2.886,2.9],ee=10,te=0;te=9})}if(a){for(var ae=new Date("2009-01-03T00:00:00Z"),re=Math.floor((Date.now()-ae.getTime())/864e5),se=0,ce=0;ce<1460;ce++){var le=re-ce;le>365&&(se+=Math.pow(10,5.82*Math.log10(le)-17.01))}var de=se/1460,ue=de>0?(a/de).toFixed(2):"—",pe=parseFloat(ue);u.push({emoji:"📊",name:"4-Year MA Multiple",value:ue+"x",color:pe>=3.5?"#ef4444":pe<1?"#22c55e":"var(--heading)",sub:"Est. 4Y MA: ~$"+p(Math.round(de))+(pe>=3.5?" · Top zone ⚠️":""),tip:"Price divided by the 4-year (1460-day) moving average. Historically, when price exceeds 3.5× the 4-year MA, it signals a cycle top. Below 1× = accumulation zone. Top threshold: ≥ 3.5.",flashing:pe>=3.5})}if(u.push({emoji:"💰",name:"NUPL",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Net Unrealized Profit/Loss. Shows aggregate profit/loss of all Bitcoin holders. Above 75% = euphoria (top zone). Below 0% = capitulation (bottom zone). Data from CBBI open-source API. Top threshold: normalized ≥ 0.75.",id:"nuplScore"}),a&&r){var me=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),ge=Math.pow(10,5.82*Math.log10(me)-17.01),he=ge>0?(a/ge).toFixed(2):"—",fe=parseFloat(he);u.push({emoji:"🔢",name:"AHR999",value:he,color:fe>1.2?"#ef4444":fe<.45?"#22c55e":"var(--heading)",sub:fe>1.2?"Overvalued — stop DCA ⚠️":fe<.45?"Deep value — DCA zone 🟢":fe<1?"Below model — DCA":"Near model",tip:"AHR999 compares current price to its long-term model value. Below 0.45 = extreme buy (accumulate aggressively). Above 1.2 = stop DCA, consider selling. Used by cost-averaging investors to time entries. Top threshold: ≥ 1.2.",flashing:fe>=1.2})}if(a){for(var ye=new Date("2009-01-03T00:00:00Z"),ve=Math.floor((Date.now()-ye.getTime())/864e5),be=0,we=0;we<730;we++){var xe=ve-we;xe>365&&(be+=Math.pow(10,5.82*Math.log10(xe)-17.01))}var ke=be/730,Te=5*ke,Se=a>Te;u.push({emoji:"📉",name:"2-Year MA ×5",value:(a/ke).toFixed(2)+"x",color:Se?"#ef4444":a365&&(Ie+=Math.pow(10,5.82*Math.log10(Ee)-17.01))}var Ae=Ie/350,Me=Ae>0?(a/Ae).toFixed(2):"—",ze=parseFloat(Me),Le=ze>=8?"Above ×8 — max top ⚠️":ze>=5?"Above ×5 — overheated":ze>=3?"Above ×3 — elevated":ze>=1.6?"Above ×1.6 — bullish":"Below ×1.6";u.push({emoji:"🔱",name:"Golden Ratio",value:Me+"x",color:ze>=5?"#ef4444":ze>=3?"#f97316":"var(--heading)",sub:"350d MA: $"+p(Math.round(Ae))+" · "+Le,tip:"Price relative to the 350-day MA using Fibonacci golden ratio multiples (1.6, 2, 3, 5, 8, 13, 21). Each cycle top has touched a lower multiple. Top threshold: ≥ 5×.",flashing:ze>=5})}if(r&&s&&a){for(var Pe=0,Ue=r,Ne=0;Ne<=Math.floor(r/21e4)&&Ue>0;Ne++){var He=Math.min(Ue,21e4);Pe+=He*(50/Math.pow(2,Ne)),Ue-=He}var qe=21*(s>0?3e4*Pe/s:0),De=qe>0?(a/qe*100).toFixed(0):"—";u.push({emoji:"🎯",name:"Terminal Price",value:"$"+p(Math.round(qe)),color:a>=qe?"#ef4444":"var(--heading)",sub:"Current: "+De+"% of terminal · "+(a>=qe?"ABOVE — extreme ⚠️":"Below terminal"),tip:"Terminal Price = Transferred Price × 21. Represents a theoretical maximum based on cumulative miner revenue and coin movement. Every cycle top has approached or exceeded this level. Top threshold: price ≥ Terminal Price.",flashing:a>=qe})}if(a){var Oe=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),je=Math.pow(10,5.82*Math.log10(Oe)-17.01),Re=(je>0?(Math.log10(a)-Math.log10(je))/.3:0).toFixed(1),Fe=parseFloat(Re);u.push({emoji:"🫧",name:"Bubble Index",value:Re+"σ",color:Fe>=2?"#ef4444":Fe>=1?"#f97316":Fe<-1?"#22c55e":"var(--heading)",sub:Fe>=2?"Extreme bubble ⚠️":Fe>=1?"Elevated":Fe<-1?"Deep discount 🟢":"Normal",tip:"How many standard deviations Bitcoin's price is above its long-term log trend. Above +2σ = extreme bubble territory (historical tops). Below -1σ = deep value. Top threshold: ≥ 2σ.",flashing:Fe>=2})}if(a){var We=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),Ve=Math.pow(10,5.82*Math.log10(We-90)-17.01),Ge=(Ve>0?100*(Math.pow(a/Ve,4)-1):0).toFixed(0),Qe=parseFloat(Ge);u.push({emoji:"🚀",name:"3M Annualized",value:(Qe>=0?"+":"")+Ge+"%",color:Qe>200?"#ef4444":Qe>100?"#f97316":"var(--heading)",sub:Qe>200?"Unsustainable — top risk ⚠️":Qe>100?"Very high":"Normal",tip:"3-month return annualized. When Bitcoin is gaining over 200% annualized, it historically signals the late stages of a bull run. Top threshold: > 200%.",flashing:Qe>200,id:"ann3m"})}if(a){var Ye=75694,Je=762099,Xe=((a-Ye)/Ye*100).toFixed(1);u.push({emoji:"🏢",name:"MSTR Avg Cost",value:"$"+p(Ye),sub:p(Je)+" BTC · P&L: "+(Xe>=0?"+":"")+Xe+"%",tip:"MicroStrategy (MSTR) average Bitcoin acquisition cost. When price is far above MSTR's cost basis, it indicates broader market euphoria. MSTR holds "+p(Je)+" BTC. Informational — no top threshold.",flashing:!1,noFlashLogic:!0})}if(u.push({emoji:"🎯",name:"CBBI Index",value:"...",color:"var(--heading)",sub:"Loading CBBI data...",tip:"Colin Talks Crypto Bitcoin Bull Run Index. Combines 9 on-chain metrics into a single 0-100 confidence score. Above 80 = approaching cycle top. Below 20 = approaching bottom. Open source. Top threshold: ≥ 80.",id:"cbbiScore"}),u.push({emoji:"💎",name:"RHODL Ratio",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Realized HODL Ratio. Compares 1-week realized value to 1-2 year realized value, adjusted by market age. High values = speculative activity dominating (top signal). Low values = long-term holders dominating. Top threshold: normalized ≥ 0.85.",id:"rhodlRatio"}),u.push({emoji:"📊",name:"Macro Oscillator",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Bitcoin Macro Oscillator (Woobull). Composite z-score of MVRV, VWAP, CVDD, and Sharpe ratios. Above 0.7 = euphoria zone. Below 0.2 = accumulation zone. Top threshold: normalized ≥ 0.7.",id:"macroOsc"}),a){var Ke=23e4,$e=(a/Ke*100).toFixed(1);u.push({emoji:"🔮",name:"Smithson's Forecast",value:$e+"%",color:parseFloat($e)>=90?"#ef4444":"var(--heading)",sub:"Target: $"+p(175e3)+"-$"+p(Ke)+" · Current: $"+p(Math.round(a)),tip:"Sminston With quantile regression model (99th percentile). Forecasts cycle top at $175K-$230K. Progress shows how close current price is to the upper target. Top threshold: ≥ 90% of target.",flashing:parseFloat($e)>=90})}u.push({emoji:"⏳",name:"LTH/STH Ratio",value:"...",color:"var(--heading)",sub:"Estimated from CBBI data...",tip:"Long-Term Holder to Short-Term Holder supply ratio (estimated). When LTH supply drops sharply (distributing to STH), it signals late-cycle selling. When LTH supply grows, holders are accumulating. Derived from CBBI on-chain metrics. Top threshold: CBBI MVRV + Puell both > 0.7.",id:"lthSthRatio"}),u.push({emoji:"📉",name:"RSI-22 Day",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Relative Strength Index over 22 days. Above 80 = overbought (potential top signal). Below 30 = oversold (potential bottom). 22-day RSI smooths out short-term noise. Top threshold: ≥ 80.",id:"rsi22d"}),u.push({emoji:"🚨",name:"AHR999x",value:"...",color:"var(--heading)",sub:"Loading 200d MA...",tip:"AHR999x Escape Top indicator. Calculated as (price / 200-day MA)². When above 8, signals extreme overvaluation. Above 3.5 = elevated. A complement to the AHR999 DCA indicator. Top threshold: ≥ 8.",id:"ahr999x"}),u.push({emoji:"🏦",name:"ETF/BTC Ratio",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Bitcoin spot ETF total AUM divided by BTC market cap. Shows how much of Bitcoin's value is held in ETFs. High ratios (>8%) could indicate institutional overexposure. Low ratios = room to grow. Top threshold: ≥ 8%.",id:"etfBtcRatio"}),u.push({emoji:"📊",name:"ETF Net Flow",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Daily Bitcoin spot ETF net inflows/outflows. Sustained outflows (7+ days) can signal institutional selling. Sustained inflows signal demand. Data from Bitbo/BitcoinTreasuries. Top threshold: 7+ consecutive outflow days.",flashing:!1,id:"etfNetFlow"}),u.push({emoji:"📈",name:"ETF 5-Day Flow",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Sum of last 5 trading days of ETF flows. Large negative = sustained selling pressure. Large positive = accumulation. Top threshold: 5-day sum below -$500M.",flashing:!1,id:"etf5dFlow"}),u.forEach(function(e){if(!e.noFlashLogic&&void 0===e.flashing){var t=e.name;e.flashing="Stock-to-Flow"===t?a>0&&f>0&&a>1.5*f:"Fear & Greed"===t?c>=75:"Mayer Multiple"!==t&&("Halving Cycle"===t?e.sub&&-1!==e.sub.indexOf("Peak Window"):"ATH Drawdown"===t?parseFloat(e.value)>-5:"Thermo Multiple"===t?parseFloat(e.value)>5:"NVT Ratio"===t&&parseFloat(e.value)>150)}});var Ze=u.filter(function(e){return e.flashing}).length,et=u.filter(function(e){return!e.noFlashLogic}).length,tt="",ot=et>0?Math.round(Ze/et*100):0,nt=0===Ze?"#22c55e":ot<15?"#eab308":ot<40?"#f97316":"#ef4444";tt+='
    ',tt+='
    '+Ze+" / "+et+"
    ",tt+='
    '+(0===Ze?"No top signals — Accumulate 🟢":ot<15?"Few signals — Monitor 🟡":ot<40?"Multiple signals — Caution 🟠":"Many signals — Extreme caution 🔴")+"
    ",tt+='
    Top indicators flashing 🔴 = potential cycle top signal
    ',tt+="
    ",u.forEach(function(e){var t=e.flashing?"rgba(239,68,68,0.5)":"var(--border)",o=e.flashing?"background:rgba(239,68,68,0.04);":"";tt+="",e.noFlashLogic||(e.flashing?tt+='
    🔴 TOP
    ':tt+='
    🟢 OK
    '),tt+='
    '+e.emoji+" "+e.name+(e.tip?' ':"")+"
    ",tt+='
    '+(e.value||"—")+"
    ",e.sub&&(tt+='
    '+e.sub+"
    "),tt+=""}),tt+='',e.innerHTML=tt,setTimeout(function(){"function"==typeof window._attachTipListeners&&window._attachTipListeners()},50);try{localStorage.setItem(x,JSON.stringify({html:tt,ts:Date.now()}))}catch(e){}fetch("https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=365&interval=daily").then(function(e){return e.json()}).then(function(e){if(e&&e.prices&&e.prices.length>=200){for(var t=e.prices,o=t.length,n=0,i=Math.max(0,o-200);i2.4?"#ef4444":"var(--heading)";c.style.color=l,c.textContent=s+"x";var d=c.nextElementSibling;d&&(d.textContent="200d MA: $"+p(Math.round(a))+(s<1?" · Below MA ✅":s>2.4?" · Overheated ⚠️":""));var u=c.closest('div[style*="border-radius:12px"]');if(u&&s>2.4){u.style.borderColor="rgba(239,68,68,0.5)",u.style.background="rgba(239,68,68,0.04)";var m=u.querySelector('div[style*="OK"]');m&&(m.innerHTML="🔴 TOP",m.style.color="#ef4444",m.style.background="rgba(239,68,68,0.15)",m.style.borderColor="rgba(239,68,68,0.4)")}}if(o>=111){for(var g=0,h=o-111;h0?((f-w)/w*100).toFixed(1):0,k=parseFloat(x),T=document.getElementById("piCycleTop");if(T){var S=k>=0;T.textContent=(k>=0?"+":"")+x+"%",T.style.color=S?"#ef4444":k>-5?"#f97316":"var(--heading)";var B=T.nextElementSibling;B&&(B.textContent="111d: $"+p(Math.round(f))+" vs 350d×2: $"+p(Math.round(w))+(S?" · CROSSED ⚠️":k>-5?" · Narrowing!":""));var _=T.closest('div[style*="border-radius:12px"]');if(_&&S){_.style.borderColor="rgba(239,68,68,0.5)",_.style.background="rgba(239,68,68,0.04)";var I=_.querySelector('div[style*="OK"]');I&&(I.innerHTML="🔴 TOP",I.style.color="#ef4444",I.style.background="rgba(239,68,68,0.15)",I.style.borderColor="rgba(239,68,68,0.4)")}}}if(o>=23){for(var C=0,E=0,A=o-22;A0?C+=M:E-=M}var z=E/22,L=0===z?100:100-100/(1+C/22/z),P=L.toFixed(1),U=document.getElementById("rsi22d");if(U){var N=L>=80;U.textContent=P,U.style.color=L>=80?"#ef4444":L<=30?"#22c55e":"var(--heading)";var H=U.nextElementSibling;if(H&&(H.textContent=L>=80?"Overbought ⚠️":L<=30?"Oversold ✅":L>=60?"Bullish":L<=40?"Bearish":"Neutral"),N){var q=U.closest('div[style*="border-radius:12px"]');if(q){q.style.borderColor="rgba(239,68,68,0.5)",q.style.background="rgba(239,68,68,0.04)";var D=q.querySelector('div[style*="OK"]');D&&(D.innerHTML="🔴 TOP",D.style.color="#ef4444",D.style.background="rgba(239,68,68,0.15)",D.style.borderColor="rgba(239,68,68,0.4)")}}}}var O=Math.pow(r/a,2).toFixed(2),j=document.getElementById("ahr999x");if(j){var R=parseFloat(O),F=R>=8;j.textContent=O,j.style.color=R>=8?"#ef4444":R>=3.5?"#f97316":"var(--heading)";var W=j.nextElementSibling;if(W&&(W.textContent="200d MA: $"+p(Math.round(a))+(R>=8?" · Extreme top ⚠️":R>=3.5?" · Elevated":R<1?" · Below MA":" · Normal")),F){var V=j.closest('div[style*="border-radius:12px"]');if(V){V.style.borderColor="rgba(239,68,68,0.5)",V.style.background="rgba(239,68,68,0.04)";var G=V.querySelector('div[style*="OK"]');G&&(G.innerHTML="🔴 TOP",G.style.color="#ef4444",G.style.background="rgba(239,68,68,0.15)",G.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("mayerMultiple");e&&(e.textContent="N/A")}),fetch("https://api.coingecko.com/api/v3/global").then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.market_cap_percentage&&e.data.market_cap_percentage.btc){var t=e.data.market_cap_percentage.btc.toFixed(1),o=document.getElementById("btcDominance");if(o){o.textContent=t+"%";var n=t>55?"#22c55e":t<40?"#ef4444":"var(--heading)";o.style.color=n;var i=o.nextElementSibling;i&&(i.textContent=t>55?"Bitcoin season 👑":t<40?"Alt season ⚠️":"Neutral")}}}).catch(function(){}),fetch("https://colintalkscrypto.com/cbbi/data/latest.json").then(function(e){return e.json()}).then(function(e){if(e&&e.Confidence){var t=Object.keys(e.Confidence).sort(),o=t[t.length-1],n=(100*e.Confidence[o]).toFixed(0),i=parseInt(n),a=document.getElementById("cbbiScore");if(a){a.textContent=n+"%",a.style.color=i>=80?"#ef4444":i<=20?"#22c55e":"var(--heading)";var r=a.nextElementSibling;if(r&&(r.textContent=i>=80?"Approaching top ⚠️":i<=20?"Approaching bottom 🟢":i>=50?"Mid-cycle bullish":"Early cycle"),i>=80){var s=a.closest('div[style*="border-radius:12px"]');if(s){s.style.borderColor="rgba(239,68,68,0.5)",s.style.background="rgba(239,68,68,0.04)";var c=s.querySelector('div[style*="OK"]');c&&(c.innerHTML="🔴 TOP",c.style.color="#ef4444",c.style.background="rgba(239,68,68,0.15)",c.style.borderColor="rgba(239,68,68,0.4)")}}}var l=Object.keys(e.RHODL).sort(),d=e.RHODL[l[l.length-1]],u=document.getElementById("rhodlRatio");if(u){u.textContent=(100*d).toFixed(0)+"%",u.style.color=d>=.85?"#ef4444":d<=.2?"#22c55e":"var(--heading)";var p=u.nextElementSibling;if(p&&(p.textContent=d>=.85?"Speculative frenzy ⚠️":d<=.2?"Accumulation zone 🟢":"Normalized: "+(100*d).toFixed(0)+"%"),d>=.85){var m=u.closest('div[style*="border-radius:12px"]');if(m){m.style.borderColor="rgba(239,68,68,0.5)",m.style.background="rgba(239,68,68,0.04)";var g=m.querySelector('div[style*="OK"]');g&&(g.innerHTML="🔴 TOP",g.style.color="#ef4444",g.style.background="rgba(239,68,68,0.15)",g.style.borderColor="rgba(239,68,68,0.4)")}}}var h=Object.keys(e.Woobull).sort(),f=e.Woobull[h[h.length-1]],y=document.getElementById("macroOsc");if(y){y.textContent=(100*f).toFixed(0)+"%",y.style.color=f>=.7?"#ef4444":f<=.2?"#22c55e":"var(--heading)";var v=y.nextElementSibling;if(v&&(v.textContent=f>=.7?"Euphoria zone ⚠️":f<=.2?"Accumulation 🟢":"Normalized: "+(100*f).toFixed(0)+"%"),f>=.7){var b=y.closest('div[style*="border-radius:12px"]');if(b){b.style.borderColor="rgba(239,68,68,0.5)",b.style.background="rgba(239,68,68,0.04)";var w=b.querySelector('div[style*="OK"]');w&&(w.innerHTML="🔴 TOP",w.style.color="#ef4444",w.style.background="rgba(239,68,68,0.15)",w.style.borderColor="rgba(239,68,68,0.4)")}}}var x=Object.keys(e.MVRV).sort(),k=Object.keys(e.Puell).sort(),T=e.MVRV[x[x.length-1]],S=e.Puell[k[k.length-1]],B=document.getElementById("lthSthRatio");if(B){var _=((T+S)/2*100).toFixed(0),I=parseInt(_);B.textContent=I+"%",B.style.color=I>=70?"#ef4444":I<=25?"#22c55e":"var(--heading)";var C=B.nextElementSibling;if(C&&(C.textContent=I>=70?"LTH distributing ⚠️":I<=25?"LTH accumulating 🟢":"Distribution score: "+I+"%"),I>=70){var E=B.closest('div[style*="border-radius:12px"]');if(E){E.style.borderColor="rgba(239,68,68,0.5)",E.style.background="rgba(239,68,68,0.04)";var A=E.querySelector('div[style*="OK"]');A&&(A.innerHTML="🔴 TOP",A.style.color="#ef4444",A.style.background="rgba(239,68,68,0.15)",A.style.borderColor="rgba(239,68,68,0.4)")}}}var M=document.getElementById("mvrvScore");if(M){var z=(100*T).toFixed(0);M.textContent=z+"%",M.style.color=T>=.7?"#ef4444":T<=.2?"#22c55e":"var(--heading)";var L=M.nextElementSibling;if(L&&(L.textContent=T>=.7?"Overvalued — top zone ⚠️":T<=.2?"Undervalued — accumulate 🟢":"Normalized: "+z+"%"),T>=.7){var P=M.closest('div[style*="border-radius:12px"]');if(P){P.style.borderColor="rgba(239,68,68,0.5)",P.style.background="rgba(239,68,68,0.04)";var U=P.querySelector('div[style*="OK"]');U&&(U.innerHTML="🔴 TOP",U.style.color="#ef4444",U.style.background="rgba(239,68,68,0.15)",U.style.borderColor="rgba(239,68,68,0.4)")}}}var N=Object.keys(e.RUPL).sort(),H=e.RUPL[N[N.length-1]],q=document.getElementById("nuplScore");if(q){var D=(100*H).toFixed(0);q.textContent=D+"%",q.style.color=H>=.75?"#ef4444":H<=.2?"#22c55e":"var(--heading)";var O=q.nextElementSibling;if(O&&(O.textContent=H>=.75?"Euphoria ⚠️":H<=.2?"Capitulation zone 🟢":"Normalized: "+D+"%"),H>=.75){var j=q.closest('div[style*="border-radius:12px"]');if(j){j.style.borderColor="rgba(239,68,68,0.5)",j.style.background="rgba(239,68,68,0.04)";var R=j.querySelector('div[style*="OK"]');R&&(R.innerHTML="🔴 TOP",R.style.color="#ef4444",R.style.background="rgba(239,68,68,0.15)",R.style.borderColor="rgba(239,68,68,0.4)")}}}var F=Object.keys(e.ReserveRisk).sort();e.ReserveRisk[F[F.length-1]];try{localStorage.setItem("cbbi_cache",JSON.stringify({ts:Date.now(),confidence:n,rhodl:d,woobull:f,mvrv:T,puell:S}))}catch(e){}}}).catch(function(){try{var e=JSON.parse(localStorage.getItem("cbbi_cache"));if(e&&Date.now()-e.ts<864e5){var t=document.getElementById("cbbiScore");t&&(t.textContent=e.confidence+"%")}}catch(e){}}),fetch("data/etf-flows.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.latestFlow){var t=document.getElementById("etfNetFlow");if(t){var o=e.latestFlow,n=(o>=0?"+":"")+o.toFixed(1)+"M";t.textContent=n,t.style.color=o>0?"#22c55e":o<-100?"#ef4444":o<0?"#f97316":"var(--heading)";var i=t.nextElementSibling;if(i&&(i.textContent=e.latestDate+" · "+e.outflowDays+"/"+e.totalDays+" outflow days"+(e.outflowDays>=7?" ⚠️":"")),e.outflowDays>=7){var a=t.closest('div[style*="border-radius:12px"]');if(a){a.style.borderColor="rgba(239,68,68,0.5)",a.style.background="rgba(239,68,68,0.04)";var r=a.querySelector('div[style*="OK"]');r&&(r.innerHTML="🔴 TOP",r.style.color="#ef4444",r.style.background="rgba(239,68,68,0.15)",r.style.borderColor="rgba(239,68,68,0.4)")}}}var s=document.getElementById("etf5dFlow");if(s){var c=e.sum5d;s.textContent=(c>=0?"+":"")+c.toFixed(1)+"M",s.style.color=c>100?"#22c55e":c<-500?"#ef4444":c<0?"#f97316":"var(--heading)";var l=s.nextElementSibling;if(l&&(l.textContent="5-day total"+(c<-500?" · Heavy selling ⚠️":c>500?" · Strong inflows 🟢":"")),c<-500){var d=s.closest('div[style*="border-radius:12px"]');if(d){d.style.borderColor="rgba(239,68,68,0.5)",d.style.background="rgba(239,68,68,0.04)";var u=d.querySelector('div[style*="OK"]');u&&(u.innerHTML="🔴 TOP",u.style.color="#ef4444",u.style.background="rgba(239,68,68,0.15)",u.style.borderColor="rgba(239,68,68,0.4)")}}}var p=L;try{var m=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"));m&&m.totalBtc&&(p=m.totalBtc)}catch(e){}var g=parseFloat(localStorage.getItem("btc_last_price"))||83e3,h=p*g,f=1984e4*g,y=f>0?(h/f*100).toFixed(1):"—",v=document.getElementById("etfBtcRatio");if(v){var b=parseFloat(y);v.textContent=y+"%",v.style.color=b>=8?"#ef4444":"var(--heading)";var w=v.nextElementSibling;if(w&&(w.textContent="ETF AUM: ~$"+(h/1e9).toFixed(0)+"B / Mkt Cap: ~$"+(f/1e12).toFixed(2)+"T"+(b>=8?" · High exposure ⚠️":"")),b>=8){var x=v.closest('div[style*="border-radius:12px"]');if(x){x.style.borderColor="rgba(239,68,68,0.5)",x.style.background="rgba(239,68,68,0.04)";var k=x.querySelector('div[style*="OK"]');k&&(k.innerHTML="🔴 TOP",k.style.color="#ef4444",k.style.background="rgba(239,68,68,0.15)",k.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("etfNetFlow");e&&(e.textContent="N/A")})}}}var T=null,S=0,B=212582*32150.7;function _(e,t,o){var n=e*B/1e12,i=t>0?(t/n*100).toFixed(1):"—",a=o>0?Math.round(1e12*n/o):"—",r=document.getElementById("goldMktCapLabel");r&&(r.textContent="$"+n.toFixed(1)+"T");var s=document.getElementById("goldBar");s&&(s.style.width=Math.min(parseFloat(i)||0,100)+"%");var c=document.getElementById("goldPctArea");c&&(c.innerHTML='
    '+i+'% of Gold Market Cap
    BTC needs ~$'+("number"==typeof a?p(a):a)+'/coin to match Gold
    Gold: $'+p(Math.round(e))+"/oz · Live via CoinGecko
    ");var l=document.getElementById("goldCompareCard");if(l){var d="Gold has been humanitys store of value for 5,000+ years. Bitcoin is digital gold — scarce, durable, portable, divisible, and verifiable. Gold price: $"+p(Math.round(e))+"/oz. Total above-ground gold: ~212,582 tonnes (~6.83B troy oz). Gold market cap: ~$"+n.toFixed(1)+"T. The flippening = Bitcoin absorbs golds entire monetary premium.";l.setAttribute("data-dash-tip",d),"function"==typeof window._attachTipListeners&&window._attachTipListeners()}}var I=null,C=0,E=[{name:"🇺🇸 United States",btc:325293},{name:"🇨🇳 China",btc:19e4},{name:"🇬🇧 United Kingdom",btc:61245},{name:"🇧🇹 Bhutan",btc:10635},{name:"🇸🇻 El Salvador",btc:6135}],A=649864;function M(e,t,o){var n=(t.companies||[]).slice(0,5),i=Math.round(t.total_holdings||0),a=t.total_value_usd||0,r=o||(i>0?a/i:0),s=n.map(function(e){return'
    '+(e.name||"?")+''+p(e.total_holdings)+" BTC
    "}).join(""),c=E.map(function(e){return'
    '+e.name+''+p(e.btc)+" BTC
    "}).join(""),l=i+A;e.innerHTML='
    🏢 Public Companies
    '+p(i)+'
    BTC · ~'+m(a||i*r)+'
    🏛️ Governments
    '+p(A)+'
    BTC · ~'+m(A*r)+'
    Total: '+p(l)+" BTC ("+(l/21e6*100).toFixed(1)+'% of supply)
    TOP 5 COMPANIES
    '+s+'
    TOP 5 GOVERNMENTS
    '+c+'
    Companies: live via CoinGecko · Governments: bitcointreasuries.net
    ';var d=document.getElementById("treasuryCard");d&&d.removeAttribute("onclick")}var z=[{ticker:"IBIT",name:"BlackRock",btc:787044,color:"#6366f1"},{ticker:"FBTC",name:"Fidelity",btc:213399,color:"#22c55e"},{ticker:"GBTC",name:"Grayscale",btc:180584,color:"#eab308"},{ticker:"ARKB",name:"ARK 21Shares",btc:63920,color:"#f97316"},{ticker:"BITB",name:"Bitwise",btc:53930,color:"#06b6d4"}],L=1367239;function P(e,t,o,n,i,a){var r=o*n,s=(o/i*100).toFixed(1),c=t[0].btc,l=t.map(function(e){var t=Math.max(4,e.btc/c*100).toFixed(0),o=m(e.btc*n);return'
    '+e.ticker+' '+e.name+''+p(e.btc)+' BTC
    '+o+"
    "}).join(""),d="";if(a){var u=Math.round((Date.now()-new Date(a).getTime())/36e5);d=u<1?"Updated just now":u<24?"Updated "+u+"h ago":"Updated "+Math.round(u/24)+"d ago"}e.innerHTML='
    '+p(o)+' BTC
    ~'+m(r)+" AUM · "+s+'% of supply held in ETFs
    '+l+'
    Data: SEC filings + CoinGlass'+(d?" · "+d:"")+"
    "}var U=null;window._startHalvingTicker=function(){U&&clearInterval(U),U=setInterval(function(){if(window._halvingTargetMs){var e=document.getElementById("halvSecs");if(!e)return clearInterval(U),void(U=null);var t=Math.max(0,window._halvingTargetMs-Date.now()),o=Math.floor(t/1e3),n=Math.floor(o/86400),i=Math.floor(o%86400/3600),a=Math.floor(o%3600/60),r=o%60,s=document.getElementById("halvDays"),c=document.getElementById("halvHours"),l=document.getElementById("halvMins");s&&(s.textContent=n),c&&(c.textContent=i),l&&(l.textContent=a),e.textContent=r<10?"0"+r:r}},1e3)}}(),function(){if(window._sessionStart=window._sessionStart||Date.now(),window._cleanUrl=function(e){if(!e)return"/";var t=window.location.pathname;return t==="/"+e||t==="/app/"+e?t:"#"+e},window._parseCleanUrl=function(){var e,t=window.location.pathname;return(e=t.match(/^\/channels\/(.+)$/))||(e=t.match(/^\/app\/(.+)$/))?e[1]:"/timechain-tv"===t||"/tv"===t?"timechain-tv":"/meetup-builder"===t?"meetup-builder":"/irl-sync"===t||"/meet"===t?"irl-sync":"/forum"===t?"forum":"/marketplace"===t?"marketplace":"/bitcoin-beats"===t||"/beats"===t?"bitcoin-beats":"/chat"===t?"chat":"/pvp"===t?"pvp":window.location.hash.replace("#","")||null},!document.getElementById("lb")){var e=document.createElement("div");e.id="lb",e.onclick=function(){document.getElementById("lb").classList.remove("open")},e.innerHTML='',document.body.appendChild(e)}function t(e){document.getElementById("lb-img").src=e,document.getElementById("lb").classList.add("open")}function o(){return window.innerWidth<=900}function n(){const e="light"!==document.body.getAttribute("data-theme");document.body.setAttribute("data-theme",e?"light":"dark"),localStorage.setItem("theme",e?"light":"dark");const t=document.getElementById("themeBtn");t&&(t.textContent=e?"☀️":"🌙");const o=document.getElementById("mobileThemeBtn");o&&(o.textContent=e?"☀️":"🌙")}function i(){var e=document.getElementById("sidebar");e&&(e.classList.toggle("open"),"function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!e.classList.contains("open")))}function a(){var e=document.getElementById("sidebar");if(e){var t=e.classList.toggle("sidebar-collapsed");try{localStorage.setItem("sidebar-collapsed",t?"1":"0")}catch(e){}}}function r(e){var t=e.nextElementSibling;if(t){var o=e.querySelector(".cat-arrow");"true"===e.getAttribute("data-expanded")?(t.style.display="none",e.setAttribute("data-expanded","false"),o&&(o.textContent="▶")):(t.style.display="",e.setAttribute("data-expanded","true"),o&&(o.textContent="▼"))}}function s(e){if(e){var t=e.closest(".cat-group");if(t&&"none"===t.style.display){var o=t.previousElementSibling;if(o&&o.classList.contains("cat-toggle")){t.style.display="",o.setAttribute("data-expanded","true");var n=o.querySelector(".cat-arrow");n&&(n.textContent="▼")}}}}function c(){return safeJSON("btc_favs",[])}function l(){var e=document.getElementById("favsList"),t=document.getElementById("favsSection");if(e){var o=c(),n=safeJSON("btc_bookmarks",[]);if(!(o.length>0||n.length>0))return e.innerHTML="",(i=document.getElementById("bookmarksList"))&&(i.innerHTML=""),void(t&&(t.style.display="none"));t&&(t.style.display="block");var i,a="";if(o.forEach(function(e){var t=void 0!==CHANNELS?CHANNELS[e]:null,o=t?(t.emoji||"")+" "+(t.name||e):e;a+="
    "+o+"
    "}),e.innerHTML=a,i=document.getElementById("bookmarksList"))if(0===n.length)i.innerHTML="";else{var r='
    🔖 Bookmarked Messages
    ';n.slice(0,15).forEach(function(e){var t=void 0!==CHANNELS&&CHANNELS[e.channel]?CHANNELS[e.channel]:null,o=t?(t.emoji||"")+" "+(t.name||e.channel):e.channel;r+="
    🔖 "+o+"
    "}),i.innerHTML=r}}}function d(e,t){let o=c();if(o.includes(e))o=o.filter(t=>t!==e),t&&(t.innerHTML="☆ Save");else{o.push(e),t&&(t.innerHTML="⭐ Saved");try{var n=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_fav_added_"+n,"true")}catch(e){}}var i;i=o,localStorage.setItem("btc_favs",JSON.stringify(i)),l(),"function"==typeof syncFavsToFirebase&&syncFavsToFirebase()}!function(){try{if(window.innerWidth>900&&"1"===localStorage.getItem("sidebar-collapsed")){var e=document.getElementById("sidebar");e&&e.classList.add("sidebar-collapsed")}}catch(e){}}();let u=!1,p=null,m=null;function g(e){u=!u;const t=document.getElementById("galleryBtn");t&&(t.classList.toggle("active",u),t.textContent=u?"📄 List View":"🖼️ Gallery View"),h(e)}function h(e){const t=p;if(!t)return;const n=document.getElementById("msgs");if(u){let e=[];t.msgs.forEach(t=>{t.imgs&&t.imgs.forEach(t=>e.push(t))});let i='",e.length>a&&(window._galleryImgs=e,window._galleryOffset=a,i+='"),n.innerHTML=i}else{const i=o()?20:50,a=t.msgs;let r=function(){const t=a.slice(0,0+i);let n="";{const t=void 0!==CHANNELS?CHANNELS[e]:null;t&&t.desc&&(n+='
    🦌
    Nacho\'s Summary
    '+t.desc+"
    ")}return t.forEach((t,i)=>{if(n+='
    ',t.text){let e=t.text,i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"});let a=[];e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){const t=e.startsWith("http")?e:"https://"+e;return a.push(t),"%%TW"+(a.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){const n=a[parseInt(t)],i="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),c=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+c+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),n+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?n+='':n+=''});var a=0+i,r=safeJSON("btc_bookmarks",[]).some(function(t){return t.channel===e&&t.idx===a});n+="',n+="
    "}),n}();a.length>i&&(r+='"),n.innerHTML=r,window._currentMsgs=a,window._currentOffset=i}window._sidebarOrder||(window._sidebarOrder=[...document.querySelectorAll(".ch-btn")].map(e=>{const t=e.getAttribute("onclick").match(/go\('([^']+)'/);return t?t[1]:null}).filter(Boolean));const i=window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),a=i.indexOf(e),r=a0?i[a-1]:i[i.length-1]);CHANNELS[s]&&CHANNELS[s].title;let c='
    ';c+="',c+='',c+='',c+='',c+='',c+="',c+="
    ",c+='
    ',c+='',c+="
    ","function"==typeof renderReadNext&&(c+=renderReadNext(e)),c+='
    Disclaimer
    This Bitcoin education is presented authentically and from a first-principles standpoint that maximizes truth. However, this is not financial, investment, legal, or tax advice and anyone reading this material should still verify its validity by doing their own research. Bitcoin is volatile and you can lose money. Bitcoin Education Archive, its operators, and contributors make no warranty regarding the accuracy, completeness, or timeliness of any educational content and accept no liability for decisions made based on it. Always consult a licensed professional before making financial decisions. Terms · Privacy
    ',n.innerHTML+=c,n.classList.add("fade-in")}let f=!1;function y(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML='
    Loading tweet...
    ',f)v(e,t);else{const o=document.createElement("script");o.src="https://platform.twitter.com/widgets.js",o.async=!0,o.onload=function(){f=!0,v(e,t)},document.head.appendChild(o)}}function v(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML="",window.twttr&&window.twttr.widgets){const e=t.match(/status\/(\d+)/);if(e){const n=document.createElement("div");o.appendChild(n),twttr.widgets.createTweet(e[1],n,{theme:"light"===document.body.getAttribute("data-theme")?"light":"dark",align:"center",conversation:"none",width:500}).then(function(e){e||(o.innerHTML='')})}}else o.innerHTML=''}async function b(){window._keepFloatingBtn=!0;const e=Object.keys(CHANNELS);window._randomChannelHistory||(window._randomChannelHistory=[]);var t=e.filter(function(e){return-1===window._randomChannelHistory.indexOf(e)});0===t.length&&(window._randomChannelHistory.length=0,t=e);const o=t[Math.floor(Math.random()*t.length)];window._randomChannelHistory.push(o),window._randomChannelHistory.length>Math.floor(.3*e.length)&&window._randomChannelHistory.shift(),await go(o),window._keepFloatingBtn=!1,S("__random__","🎲","Next Random Channel")}async function w(e,t,o){window._keepFloatingBtn=!0;const n=CHANNELS[e];if(!n)return void(window._keepFloatingBtn=!1);let i;if(G[e])i=G[e];else try{const t=await fetch(n.file);i=await t.json(),G[e]=i}catch(e){return}const a=i.msgs.length>1?i.msgs.slice(1):i.msgs,r=[];if(a.forEach((e,t)=>{e.imgs&&e.imgs.length>0&&r.push(t)}),0!==r.length){window._randomHistory||(window._randomHistory={}),window._randomHistory[e]||(window._randomHistory[e]=[]);var s=window._randomHistory[e],c=Math.min(Math.floor(.2*r.length),50),l=r.filter(function(e){return-1===s.indexOf(e)});0===l.length&&(s.length=0,l=r);var d=l[Math.floor(Math.random()*l.length)];s.push(d),s.length>c&&s.shift();var u=a[d];if(u&&u.imgs&&u.imgs.forEach(function(e){(new Image).src=e}),await go(e),d>=50){const e=document.getElementById("loadMoreBtn");for(var p=0;window._currentOffset<=d&&e&&document.contains(e)&&p<50;)window.loadMoreMsgs(),p++}setTimeout(function(){const n=document.getElementById("msg-"+d);n&&(n.querySelectorAll('img[loading="lazy"]').forEach(function(e){e.loading="eager"}),n.scrollIntoView({behavior:"smooth",block:"center"}),n.style.transition="box-shadow 0.3s, border-color 0.3s",n.style.boxShadow="0 0 20px rgba(247,147,26,0.4)",n.style.borderColor="#f7931a",setTimeout(function(){n.style.boxShadow="",n.style.borderColor=""},2e3),window._keepFloatingBtn=!1,S(e,t,o))},300)}}function x(){return w("memes-funny","😂","Next Random Meme")}function k(){return w("art-inspiration","🎨","Next Random Art")}function T(){return w("graphics","📊","Next Random Graphic")}function S(e,t,o){var n=document.getElementById("floatingRandomBtn");n||((n=document.createElement("button")).id="floatingRandomBtn",n.style.cssText="position:fixed;bottom:140px;right:180px;z-index:150;padding:12px 20px;background:var(--accent);color:#fff;border:none;border-radius:12px;font-size:0.9rem;font-weight:700;cursor:pointer;font-family:inherit;box-shadow:0 4px 20px rgba(0,0,0,0.3);transition:0.2s;display:flex;align-items:center;gap:6px;",document.body.appendChild(n)),n.innerHTML=t+" "+o,n.onclick="__random__"===e?function(){b()}:function(){w(e,t,o)},n.style.display="flex",window.addEventListener("popstate",function e(){n.style.display="none",window.removeEventListener("popstate",e)},{once:!0})}function B(e,t){const o=e+"\n\n"+t;navigator.clipboard.writeText(o).then(()=>{showToast("📋 Note copied! Paste it in Primal to post.")}).catch(()=>{}),window.open("https://primal.net/home","_blank")}window.goRandomMeme=x,window.goRandomArt=k,window.goRandomGraphic=T,window.toggleBookmark=function(e,t,o){var n=safeJSON("btc_bookmarks",[]),i=n.findIndex(function(o){return o.channel===e&&o.idx===t});-1!==i?(n.splice(i,1),o&&(o.style.opacity="0.3",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Bookmark removed")):(n.push({channel:e,idx:t,ts:Date.now()}),o&&(o.style.opacity="1",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Saved to sidebar")),localStorage.setItem("btc_bookmarks",JSON.stringify(n)),l(),"function"==typeof syncBookmarksToFirebase&&syncBookmarksToFirebase()},window.loadMoreGallery=function(){const e=window._galleryImgs,o=window._galleryOffset,n=document.querySelector(".gallery-grid"),i=document.getElementById("loadMoreGallery");e.slice(o,o+100).forEach(e=>{const o=document.createElement("img");o.src=e,o.loading="lazy",o.onclick=function(){t(this.src)},n.appendChild(o)}),window._galleryOffset=o+100,window._galleryOffset>=e.length?i.remove():i.textContent="Load more ("+(e.length-window._galleryOffset)+" remaining)"},window.showSpinWheel=function(){var e=localStorage.getItem("btc_last_spin_date"),t=(new Date).toDateString();if(e!==t){var o=document.getElementById("spinModal");o&&o.remove();var n=document.createElement("div");n.id="spinModal",n.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.85);-webkit-overflow-scrolling:touch;overflow-y:auto;padding:20px;";var i=[{label:"🎟️ 1 Ticket",value:"ticket_1",weight:25,color:"#f7931a"},{label:"🎟️ 2 Tickets",value:"ticket_2",weight:22,color:"#ea580c"},{label:"⭐ 25 XP",value:"points_25",weight:18,color:"#22c55e"},{label:"🎟️ 3 Tickets",value:"ticket_3",weight:12,color:"#fbbf24"},{label:"⭐ 50 XP",value:"points_50",weight:8,color:"#3b82f6"},{label:"👔 Closet!",value:"closet_item",weight:5,color:"#ec4899"},{label:"🧊 Freeze!",value:"freeze",weight:4,color:"#06b6d4"},{label:"⭐ 100 XP",value:"points_100",weight:3,color:"#8b5cf6"},{label:"🎟️ 5 Tickets",value:"ticket_5",weight:1.5,color:"#a855f7"},{label:"💎 RARE!",value:"rare_drop",weight:1.5,color:"#ef4444"}],a=[{label:"🎟️ 10 Tickets",value:"ticket_10",weight:1e3},{label:"🎟️ 25 Tickets",value:"ticket_25",weight:500},{label:"🎟️ 50 Tickets",value:"ticket_50",weight:100},{label:"🎟️ 100 Tickets!",value:"ticket_100",weight:50},{label:"🎟️ 500 Tickets!!",value:"ticket_500",weight:10},{label:"🎟️💎 1,000 Tickets!!!",value:"ticket_1000",weight:3},{label:"🎟️👑 10,000 TICKETS!!!!",value:"ticket_10000",weight:1}];n.innerHTML='
    🎡
    Daily Spin

    Spin for Orange Tickets, XP, Nacho Closet items, and rare Freeze Tickets!

    ',document.body.appendChild(n);var r=document.getElementById("spinCanvas").getContext("2d"),s=125,c=125,l=2*Math.PI/i.length;i.forEach(function(e,t){r.beginPath(),r.moveTo(s,c),r.arc(s,c,120,t*l,(t+1)*l),r.fillStyle=e.color,r.fill(),r.strokeStyle="#fff",r.lineWidth=2,r.stroke(),r.save(),r.translate(s,c),r.rotate(t*l+l/2),r.textAlign="right",r.fillStyle="#fff",r.font="bold 12px sans-serif",r.fillText(e.label,105,4),r.restore()});var d=!1,u=document.getElementById("spinBtn"),p=document.getElementById("spinResult");u.addEventListener("click",function(){if(!d){d=!0,u.disabled=!0,u.style.opacity="0.5";for(var e=i.reduce(function(e,t){return e+t.weight},0),o=Math.random()*e,n=0,m=0,g=0;gMath.floor(30*(d-.01))&&"function"==typeof playSpinTick&&playSpinTick(),requestAnimationFrame(e);else{"function"==typeof playSpinWin&&playSpinWin();var g="",f=h.value.split("_")[0],y=parseInt(h.value.split("_")[1])||1;if("rare_drop"===h.value){for(var v=a.reduce(function(e,t){return e+t.weight},0),w=Math.random()*v,x=a[0],T=0,S=0;S.01&&(B=100,x={label:"🎟️ 100 Tickets!",value:"ticket_100"}),g="💎 RARE DROP! "+x.label,"function"==typeof awardOrangeTickets)awardOrangeTickets(B,"Rare Spin Drop");else{var _=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",_+B)}B>=100&&("function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound())}else if("closet"===f){var I=safeJSON("btc_spin_closet_items",[]),C=["orange_scarf","sunglasses","bowtie","mining_helmet","lightning_chain","party_hat","hodl_hoodie","crown","steak","diamond_hooves"].filter(function(e){return-1===I.indexOf(e)});if(C.length>0){var E=C[Math.floor(Math.random()*C.length)];if(I.push(E),localStorage.setItem("btc_spin_closet_items",JSON.stringify(I)),void 0!==currentUser&¤tUser&&!currentUser._isLocal)try{db.collection("users").doc(auth.currentUser.uid).update({spinClosetItems:firebase.firestore.FieldValue.arrayUnion(E)}).catch(function(){})}catch(e){}g="👔 CLOSET ITEM! You unlocked: "+({orange_scarf:"Bitcoin Scarf 🧣",sunglasses:"Cool Shades 🕶️",bowtie:"Fancy Bowtie 🎀",mining_helmet:"Mining Helmet ⛑️",lightning_chain:"Lightning Chain ⚡",party_hat:"Party Hat 🎉",hodl_hoodie:"HODL Hoodie 🧥",crown:"Royal Crown 👑",steak:"Proof of Steak 🥩",diamond_hooves:"Diamond Hooves 💎"}[E]||E)+"! Equip it in Nacho's Closet!"}else g="👔 You already own all spin closet items! +25 bonus XP instead!","function"==typeof awardPoints&&awardPoints(25,"Closet bonus")}else if("freeze"===f){g="🧊 STREAK FREEZE TICKET! Your streak is protected for 1 missed day!";var A=parseInt(localStorage.getItem("btc_streak_freezes")||"0");localStorage.setItem("btc_streak_freezes",A+1),"function"==typeof awardPoints&&awardPoints(0,"🧊 Streak Freeze",null,0,1),void 0!==currentUser&¤tUser&&(currentUser.streakFreezes=(currentUser.streakFreezes||0)+1)}else if("ticket"===f)if(g="🎟️ You won "+y+" Orange Ticket"+(y>1?"s":"")+"!","function"==typeof awardOrangeTickets)awardOrangeTickets(y,"Daily Spin");else{var M=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",M+y)}else if("points"===f)if(g="⭐ You won "+y+" XP!","function"==typeof awardPoints)awardPoints(y,"Daily Spin");else{var z=parseInt(localStorage.getItem("btc_points")||"0");localStorage.setItem("btc_points",z+y)}p.innerHTML='
    '+h.label.split(" ")[0]+'
    '+g+'
    ',"function"==typeof notifySelfSpin&¬ifySelfSpin(g);var L=parseInt(localStorage.getItem("btc_spin_count")||"0");localStorage.setItem("btc_spin_count",String(L+1));var P=localStorage.getItem("btc_spin_last_day")||"";if(P===new Date(Date.now()-864e5).toISOString().slice(0,10)){var U=parseInt(localStorage.getItem("btc_spin_streak")||"0");localStorage.setItem("btc_spin_streak",String(U+1))}else P!==t&&localStorage.setItem("btc_spin_streak","1");localStorage.setItem("btc_spin_last_day",t),"rare_drop"===h.value&&localStorage.setItem("btc_spin_hit_rare","true"),localStorage.setItem("btc_last_spin_date",t),"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("dailySpin")({}).catch(function(e){console.log("[SPIN] Server validation:",e.message||"ok")}),void 0!==currentUser&¤tUser&¤tUser._isLocal}})}}),n.addEventListener("click",function(e){e.target===n&&n.remove()})}else showToast("🎡 You already spun today! Come back tomorrow!")};var _=null;function I(e,t,o,n,i){var a="dc_"+Math.random().toString(36).substr(2,6),r=n?'Open ↗':"";return'
    '+e+"
    "+(i?'
    '+e+' QR
    ':"")+(t?'
    "+o+'
    "+r+"
    ":"")+"
    "}function C(e,t){navigator.clipboard.writeText(e).then(()=>{t.classList.add("copied"),t.textContent="✅ Copied!",setTimeout(()=>{t.classList.remove("copied"),t.innerHTML="🔗 Copy Link"},2e3)})}setTimeout(function(){var e=new Image;e.crossOrigin="anonymous",e.src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:spontaneousleopard54@zeuspay.com",e.onload=function(){try{var t=document.createElement("canvas");t.width=e.width,t.height=e.height,t.getContext("2d").drawImage(e,0,0),_=t.toDataURL("image/png")}catch(t){_=e.src}}},3e3),window.showDonateModal=function(){var e=document.getElementById("donateModal");e&&e.remove();var t=document.createElement("div");t.id="donateModal",t.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:flex-start;justify-content:center;background:rgba(2,6,23,0.9);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;";var o="spontaneousleopard54@zeuspay.com",n=_||"https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:"+o;t.innerHTML='
    🧡
    Support the Archive

    Your sats help keep this archive free and open for the next billion Bitcoiners! 🦌⚡

    Lightning QR Code
    '+o+"

    ⚠️ Donations are non-refundable

    "+I("💵 Cash App","$NEEDcreations","$NEEDcreations","https://cash.app/$NEEDcreations","images/donate/cashapp-qr.jpg")+I("💜 Venmo","@Phil2140","@Phil2140","https://venmo.com/code?user_id=1358236213051392692&created=1773155307","images/donate/venmo-qr.jpg")+I("💙 PayPal","paypal.me/PhilipFazioli","paypal.me/PhilipFazioli","https://paypal.me/PhilipFazioli","images/donate/paypal-qr.jpg")+I("💚 Zelle",null,null,null,"images/donate/zelle-qr.jpg")+I("₿ On-Chain Bitcoin","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf",null,"images/donate/onchain-qr.jpg")+I("🔒 BIP47 Payment Code","PM8TJWpq8HqPeBEuz3dAoB3uyZADVxQjWekQJCJYddpWPce9nDaeK6XjYnifBUnjjKcWF8Y98EkfPZYaftC7uDJkiFqBTBYrd8TJhRg5qQwXtfnTTg89","PM8TJWpq8Hq...Tg89",null,"images/donate/bip47-qr.jpg")+"
    ",document.body.appendChild(t);var i=document.getElementById("donateCopyBtn");i&&i.addEventListener("click",function(e){e.stopPropagation();var t=this;if(navigator.clipboard)navigator.clipboard.writeText(o).then(function(){t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)});else{var n=document.createElement("textarea");n.value=o,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)}}),t.addEventListener("click",function(e){e.target===t&&t.remove()})};let E=!1;function A(){const e=document.getElementById("supportBtn");E?(navigator.clipboard.writeText("info.603btc@gmail.com").then(function(){e.innerHTML="✅ Copied!",e.style.color="#22c55e",setTimeout(function(){e.innerHTML='info.603btc@gmail.com tap to copy',e.style.color="var(--text)"},1500)}).catch(function(){}),window.location.href="mailto:info.603btc@gmail.com?subject=Support%20-%20Bitcoin%20Education%20Archive"):(E=!0,e.style.transition="0.3s",e.style.background="var(--accent)",e.style.color="#fff",e.style.borderColor="var(--accent)",e.innerHTML='info.603btc@gmail.com tap to copy',setTimeout(function(){e.style.background="var(--card-bg)",e.style.color="var(--text)",e.style.borderColor="var(--border)"},400))}function M(e){if(!e)return"";var t=new Date(e),o=t.getHours(),n=t.getMinutes(),i=o>=12?"PM":"AM";return 0==(o%=12)&&(o=12),o+":"+(n<10?"0":"")+n+" "+i}window._nachoMode=!1,window._nachoModeEarnings={points:0,badges:[],interactions:0},window.enterNachoMode=function(e){if(window._nachoMode=!0,window._nachoBusy=!0,window._nachoModeEarnings={points:0,badges:[],interactions:0},window._nachoModeStartTime=Date.now(),window._nachoModeTopics=[],window._nachoConvoQuizOffered=!1,!window._nachoPointsHooked){window._nachoPointsHooked=!0;var t=window.awardPoints;t&&(window.awardPoints=function(e,o){return window._nachoMode&&window._nachoModeEarnings&&(window._nachoModeEarnings.points+=e),t.apply(this,arguments)});var o=window.showToast;o&&(window.showToast=function(e){return window._nachoMode&&window._nachoModeEarnings&&"string"==typeof e&&(-1!==e.indexOf("badge")||-1!==e.indexOf("Badge")||-1!==e.indexOf("🏅"))&&window._nachoModeEarnings.badges.push(e),o.apply(this,arguments)})}e||history.pushState({nachoMode:!0},"","/app/nacho"),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="none")});var n=document.querySelector(".mobile-bar");n&&(n.style.display="none");var i=document.getElementById("main");i.scrollTop=0,"undefined"!=typeof NACHO_SVG&&NACHO_SVG,void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var a=!(!window.SpeechRecognition&&!window.webkitSpeechRecognition),r=a?'':"";window._nachoChatHistory=safeJSON("btc_nacho_chat",[]),window._nachoSentHistory=safeJSON("btc_nacho_sent",[]),window._nachoSentIdx=-1;var s=document.createElement("div");s.id="nachoModeScreen",s.style.cssText="display:flex;flex-direction:column;height:calc(100vh - 32px);margin-top:32px;animation:fadeSlideIn 0.4s ease-out;position:relative;z-index:9999;",s.innerHTML='
    Nacho
    '+("function"==typeof nachoNickname?nachoNickname():"Nacho").toUpperCase()+' MODE
    Home
    '+r+'
    ',i.appendChild(s),N(),setTimeout(function(){var e=document.getElementById("nachoModeChat");e&&(e.scrollTop=e.scrollHeight)},100),j();var c=document.getElementById("nachoEli5Btn");c&&(c.style.opacity=window._nachoEli5?"1":"0.5"),function(){var e=document.getElementById("nachoModeOverlay");if(e&&(e.innerHTML="","function"==typeof getEquippedItem)){var t=getEquippedItem();if(t){var o=t.hidden?t.revealEmoji:t.emoji,n=document.createElement("span");n.textContent=t.overlay&&t.overlay.custom?t.overlay.custom:o,n.style.cssText="position:absolute;font-size:2.5rem;pointer-events:none;",t.overlay&&(t.overlay.top&&(n.style.top=t.overlay.top),t.overlay.left&&(n.style.left=t.overlay.left),t.overlay.right&&(n.style.right=t.overlay.right),t.overlay.bottom&&(n.style.bottom=t.overlay.bottom),t.overlay.transform&&(n.style.transform=t.overlay.transform)),e.appendChild(n)}}}(),setTimeout(function(){var e=document.getElementById("nachoModeInput");e&&e.focus()},300)},window.nachoModeKeydown=function(e){if("Enter"!==e.key){var t=document.getElementById("nachoModeInput");if(t){var o=window._nachoSentHistory||[];if("ArrowUp"===e.key){if(0===o.length)return;-1===window._nachoSentIdx&&(window._nachoSentDraft=t.value),window._nachoSentIdx=Math.min(window._nachoSentIdx+1,o.length-1),t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault(),setTimeout(function(){t.setSelectionRange(t.value.length,t.value.length)},0)}else if("ArrowDown"===e.key){if(window._nachoSentIdx<=0)return window._nachoSentIdx=-1,void(t.value=window._nachoSentDraft||"");window._nachoSentIdx--,t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault()}}}else nachoModeSend()};var z=["There will only ever be 21 million Bitcoin. No government, company, or person can change this. 🔒","The Bitcoin network has been running non-stop since January 3, 2009 — over 99.98% uptime. No bank can say that! 🏦","The first Bitcoin transaction was 10,000 BTC for two pizzas. Today that's worth hundreds of millions! 🍕","Bitcoin processes over $10 billion in transactions daily — more than most countries' payment systems. 💸","Bitcoin mining now uses more renewable energy than almost any other industry — over 50%! ⚡","Satoshi Nakamoto's true identity remains unknown. They hold about 1 million BTC and have never spent any. 🕵️","A 'satoshi' (sat) is the smallest unit of Bitcoin: 0.00000001 BTC. You don't need to buy a whole coin! 🪙","The Bitcoin Lightning Network can process millions of transactions per second — faster than Visa! ⚡","El Salvador became the first country to adopt Bitcoin as legal tender in September 2021. 🇸🇻","Bitcoin's code is completely open source — anyone can read, verify, and contribute to it. 📖","Every 4 years, Bitcoin's new supply gets cut in half. This is called the 'halving.' The next one is in 2028! 📉","There are more Bitcoin wallets than bank accounts in most countries. Over 100 million and growing! 📈","Bitcoin can be sent anywhere in the world in minutes, 24/7, with no middleman. Try that on a Sunday with a bank! 🌍","The Genesis Block contains a hidden message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰","About 20% of all Bitcoin is estimated to be permanently lost — mostly from early users who lost their keys. 🔑","Bitcoin's difficulty adjustment is like a thermostat — it automatically adapts every 2 weeks to keep blocks at ~10 minutes. ⚙️","Running a Bitcoin node means YOU verify every transaction yourself. No trust required. Don't trust, verify! ✅","The Lightning Network lets you send payments as small as 1 sat (~$0.0003). Try doing that with a credit card! 💳","Bitcoin has survived 400+ declared 'deaths' by media. It keeps coming back stronger every time. 💪","Over 50 publicly traded companies now hold Bitcoin on their balance sheets, led by MicroStrategy. 🏢","Bitcoin transactions are pseudonymous, not anonymous. Every transaction is recorded on the public blockchain forever. 🔍","The Bitcoin network is protected by more computing power than all the world's supercomputers combined. 🖥️","You can run a full Bitcoin node on a Raspberry Pi — a $50 computer can verify the entire monetary system. 🥧","Bitcoin's inflation rate is currently lower than gold's. After the 2028 halving, it'll be even lower. 🥇","Multisig wallets require multiple keys to spend Bitcoin — like a safety deposit box that needs 2 of 3 keys. 🗝️","Bitcoin doesn't care about borders, politics, or holidays. It works the same everywhere, always. 🌐","The last Bitcoin won't be mined until approximately the year 2140. We're still very early! ⏰","Jack Dorsey, Elon Musk, and many tech leaders have publicly supported Bitcoin's vision. 🚀","A Bitcoin block is mined roughly every 10 minutes. That's about 144 blocks per day, every day, forever. ⛏️","Nostr is a decentralized social protocol that many Bitcoiners are building on — social media you can't be censored from. 📡"];window.nachoModeChip=function(e){var t=document.getElementById("nachoModeInput");t&&(t.value=e,nachoModeSend())},window._nachoEli5="true"===localStorage.getItem("btc_nacho_eli5"),window.toggleNachoEli5=function(){window._nachoEli5=!window._nachoEli5,localStorage.setItem("btc_nacho_eli5",window._nachoEli5?"true":"false");var e=document.getElementById("nachoEli5Btn");e&&(e.style.opacity=window._nachoEli5?"1":"0.5",e.title=window._nachoEli5?"ELI5 Mode ON — Simple language":"Explain Like I'm 5"),"function"==typeof showToast&&showToast(window._nachoEli5?"🧒 ELI5 Mode ON — Nacho will use simple language!":"🧒 ELI5 Mode OFF — Back to normal")},window.showEli5Prompt=function(){var e=window._nachoEli5,t='
    🧒
    ELI5 Mode
    Explain Like I\'m 5

    When turned on, Nacho will answer your questions using super simple language — like explaining Bitcoin to a 5-year-old! 🦌

    Perfect for beginners or anyone who wants the basics without the jargon.
    Currently: '+(e?"ON ✅":"OFF")+'
    ',o=document.createElement("div");o.innerHTML=t,document.body.appendChild(o.firstChild)},window.nachoShareAnswer=function(e){var t="🦌 I learned this from Nacho at bitcoineducation.quest:\n\n"+e.replace(/<[^>]+>/g,"").replace(/🦌\s*/g,"").substring(0,280);if(navigator.share)navigator.share({title:"Bitcoin Fact from Nacho 🦌",text:t,url:"https://bitcoineducation.quest"}).catch(function(){});else{var o=document.createElement("textarea");o.value=t,document.body.appendChild(o),o.select();try{document.execCommand("copy")}catch(e){}document.body.removeChild(o),"function"==typeof showToast&&showToast("📋 Copied to clipboard!")}};var L=!1,P=[{step:1,emoji:"📘",title:"What is Bitcoin?",q:"What is Bitcoin and how does it work?"},{step:2,emoji:"💡",title:"Why Bitcoin Matters",q:"Why is Bitcoin important? Why should I care?"},{step:3,emoji:"📈",title:"Bitcoin vs Money",q:"How is Bitcoin different from regular money and gold?"},{step:4,emoji:"🛒",title:"Buying Your First Bitcoin",q:"How do I buy my first Bitcoin? Where do I start?"},{step:5,emoji:"💼",title:"Wallets & Storage",q:"What Bitcoin wallet should I use? What are the types?"},{step:6,emoji:"🔑",title:"Seed Phrases & Security",q:"What is a seed phrase and how do I keep my Bitcoin safe?"},{step:7,emoji:"⚡",title:"Lightning Network",q:"What is the Lightning Network and why does it matter?"},{step:8,emoji:"⛏️",title:"Mining & Proof of Work",q:"How does Bitcoin mining work? What is proof of work?"},{step:9,emoji:"🏃",title:"Running a Node",q:"What is a Bitcoin node and should I run one?"},{step:10,emoji:"🔒",title:"Privacy & KYC",q:"How private is Bitcoin? What is KYC and why does it matter?"}];window.nachoLearningPath=function(){var e=parseInt(localStorage.getItem("btc_nacho_path_step")||"0");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth&&auth?auth.currentUser:null;if(document.getElementById("nachoModeChat")){var o='
    🗺️ Your Bitcoin Journey
    '+Math.round(e/P.length*100)+"% concepts mastered
    ";o+='
    ✅ All Features Unlocked

    Every app and feature is available to you. Explore freely! 🦌

    🗣️ Pleb Talk
    🤝 IRL Sync
    ⚡ Lightning Mart
    🔹 Sign Up: 🏁 Profile & Persistence
    ',o+='
    ';for(var n=0;n'+(a?"✅":i.emoji)+'
    Level '+i.step+": "+i.title+"
    "+(r?'NEXT →':"")+""}e>=P.length&&(o+='
    🎓🦌🎉
    Journey Complete!
    You\'ve covered all the Bitcoin basics. You\'re officially not a normie anymore!
    '),q("nacho","",o)}},window.nachoPathStep=function(e){var t=P[e];t&&(e>=parseInt(localStorage.getItem("btc_nacho_path_step")||"0")&&localStorage.setItem("btc_nacho_path_step",(e+1).toString()),nachoModeChip(t.q))};const U=[{q:"What is the primary benefit of running a Bitcoin full node?",a:"You can independently verify the consensus rules and your own transactions.",w:["It earns you a small percentage of every transaction fee on the network.","It automatically mines new Bitcoins using your computer's idle CPU.","It hides your IP address from everyone else using the network.","It increases the speed of your internet connection by 21%."]},{q:"What does 'Satoshi' represent in the context of Bitcoin?",a:"The smallest unit of Bitcoin, equal to 0.00000001 BTC.",w:["A type of advanced encryption used for private messages.","The official name for a Bitcoin wallet's public address.","A digital certificate of ownership for a single Bitcoin.","The name of the first computer used to mine block zero."]},{q:"Why is Bitcoin's difficulty adjustment important?",a:"It ensures blocks are produced roughly every 10 minutes regardless of total hash rate.",w:["It prevents the price of Bitcoin from dropping below its mining cost.","It automatically updates the Bitcoin Core software for all users.","It calculates the total number of users active on the network daily.","It decides which transactions are most important for the miners."]},{q:"What happens if you lose your 12 or 24-word seed phrase?",a:"You lose access to your funds forever, as there is no central 'reset' authority.",w:["You can call Bitcoin's customer support to verify your identity and reset it.","The government can recover your coins using your social security number.","Your hardware wallet will automatically generate a new phrase after 24 hours.","Your Bitcoin is donated to a pool for new developers to use for testing."]},{q:"What is the primary function of the Lightning Network?",a:"To enable instant, near-free Bitcoin payments by moving them off-chain.",w:["To increase the total number of Bitcoins that will ever exist to 42 million.","To allow Bitcoin to be mined using only mobile phones and tablets.","To encrypt the entire blockchain so it cannot be read by anyone.","To create a secondary blockchain that is faster but less secure than Bitcoin."]}];function N(){var e=document.getElementById("nachoModeChat");if(e){var t=window._nachoChatHistory||[];if(0!==t.length){for(var o,n="",i="",a=0;a'+s+"",i=s),"user"===r.role?n+='
    '+escapeHtml(r.text)+'
    '+M(r.ts)+"
    ":n+='
    🦌 '+escapeHtml("function"==typeof nachoNickname?nachoNickname():"Nacho")+": "+r.html+'
    '+M(r.ts)+"
    "}e.innerHTML=n,e.scrollTop=e.scrollHeight}else{var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"";e.innerHTML='
    Nacho
    🦌 NACHO MODE
    '+(c?"Hey "+escapeHtml(c)+"! Let's talk Bitcoin.":"Hey! Let's talk Bitcoin.")+'
    💡 DID YOU KNOW?
    '+(o=Math.floor((Date.now()-new Date((new Date).getFullYear(),0,0))/864e5),z[o%z.length]+'
    Tap a topic or ask me anything:
    ')+function(){for(var e=[{emoji:"📘",label:"What is Bitcoin?",q:"What is Bitcoin and what problem does it solve?"},{emoji:"💰",label:"Why Bitcoin?",q:"Why is Bitcoin better than regular money and why should I care?"},{emoji:"🔒",label:"21 Million",q:"Why is the 21 million cap important and why can't it be changed?"},{emoji:"🛒",label:"How to Buy",q:"How do I buy my first Bitcoin and start stacking sats?"},{emoji:"🔑",label:"Self-Custody",q:"What is self-custody and why is it the most important thing in Bitcoin?"},{emoji:"⚡",label:"Lightning",q:"What is the Lightning Network and how does it make Bitcoin faster?"},{emoji:"🪙",label:"Why Not Altcoins?",q:"Why do Bitcoiners only focus on Bitcoin and not other cryptocurrencies?"},{emoji:"🌍",label:"Fix the World",q:"How is Bitcoin actually changing the world for the better?"}],t='
    ',o=0;o"+e[o].emoji+" "+e[o].label+"";return t+"
    "}()+'
    '}}}function H(e,t,o){var n={role:e,text:t||"",html:o||escapeHtml(t||""),ts:Date.now()};return window._nachoChatHistory.push(n),nachoChatSave(),n}function q(e,t,o){var n=document.getElementById("nachoModeChat");if(n){window._nachoChatHistory.length<=1&&n.querySelector("#nachoModeAvatar")&&(n.innerHTML="");var i=M(Date.now()),a=document.createElement("div");if(a.className="nm-msg "+("user"===e?"nm-user":"nm-nacho"),"user"===e)a.innerHTML=""+escapeHtml(t)+'
    '+i+"
    ";else{var r="function"==typeof nachoNickname?nachoNickname():"Nacho";a.innerHTML='🦌 '+escapeHtml(r)+": "+o+'
    '+i+"
    "}n.appendChild(a),"user"===e?n.scrollTop=n.scrollHeight:a.scrollIntoView({behavior:"smooth",block:"start"})}}function D(){if(window._nachoMode){var e=document.getElementById("nachoModeInput");if(e&&e===document.activeElement)setTimeout(D,3e4);else if(document.querySelector(".nm-nacho .thinking, .nm-thinking"))setTimeout(D,1e4);else{var t=window._nachoModeTopics||[];if(!(t.length<3)){var o=[],n=[],i=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;if(i&&"object"==typeof i&&Object.keys(i).forEach(function(e){var t=i[e];Array.isArray(t)&&t.forEach(function(t){n.push({question:t.q,options:[t.a].concat(t.wrong||[]),answer:t.a,category:e})})}),n.length>0){for(var a=0;a3&&-1!==l.indexOf(r[d])){o.push(c);break}}for(;o.length<3&&n.length>0;){var u=n[Math.floor(Math.random()*n.length)];-1===o.indexOf(u)&&o.push(u)}}0!==o.length&&(q("nacho","",'
    🎯
    Conversation Quest!
    You\'ve been learning a lot! Let\'s see how much you remember from our chat.
    '),window._convoQuizQuestions=o)}}}}function O(){var e,t,o,n,i=window._convoQuizQuestions||[],a=window._convoQuizIdx||0;if(a>=window._convoQuizTotal||a>=i.length)e=window._convoQuizScore||0,t=window._convoQuizTotal||3,q("nacho","",'
    '+(o>=80?"🏆":o>=60?"⭐":o>=40?"💪":"📚")+'
    Conversation Quest Complete!
    '+e+"/"+t+' correct
    '+(o>=80?"Outstanding! You really paid attention!":o>=60?"Great job! You learned a lot from our chat!":o>=40?"Not bad! Keep learning and you'll get there!":"Keep going! Every question is a learning opportunity!")+"
    "+((n=5*e)>0?'
    +'+n+" XP earned! 🎉
    ":"")+"
    "),n>0&&("function"==typeof awardPoints&&awardPoints(n,"🎯 Conversation Quest!"),"function"==typeof showToast&&showToast("🎯 +"+n+" XP — Conversation Quest!"));else{for(var r=i[a],s='
    Question '+(a+1)+" of "+window._convoQuizTotal+'
    '+escapeHtml(r.question)+"
    ",c=r.options||[],l=0;l'+escapeHtml(c[l])+""}q("nacho","",s+="
    ")}}function j(){var e=document.getElementById("nachoModeFriendship");if(e){var t="function"==typeof getNachoFriendship?getNachoFriendship():{emoji:"🦌",name:"Unknown",level:0},o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.textContent=t.emoji+" Friendship: "+t.name+" · "+o+" interactions"}}function R(){const e=document.getElementById("continueReading");if(!e)return;const t=localStorage.getItem("btc_last_channel");if(t&&CHANNELS[t]){const o=CHANNELS[t];e.style.display="block",e.innerHTML='
    📖 Continue Reading
    "+o.title+'
    '+o.cat+"
    "}else e.style.display="none"}window.nachoQuizMe=function(e){if(!window._nachoMode)return void("function"==typeof enterNachoMode&&(enterNachoMode(),setTimeout(function(){nachoQuizMe(e)},500)));let t=[];var o=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;o&&"object"==typeof o&&Object.keys(o).length>0&&Object.keys(o).forEach(e=>{var n=o[e];Array.isArray(n)&&n.forEach(o=>{t.push({question:o.q,options:fisherYates([o.a,...o.wrong||o.w||[]]),answer:o.a,category:e})})}),U.forEach(e=>{t.push({question:e.q,options:fisherYates([e.a,...e.w]),answer:e.a,category:"generic"})});var n=e?t.filter(function(t){return t.category&&-1!==t.category.toLowerCase().indexOf(e.toLowerCase())}):t;0===n.length&&(n=t);for(var i=n[Math.floor(Math.random()*n.length)],a='
    🎮 Quiz Time!
    '+(e?"Topic: "+e:"Nacho Challenge")+'
    '+escapeHtml(i.question)+"
    ",r=i.options||[],s=0;s'+escapeHtml(r[s])+""}a+="
    ",e||(a+='
    🦌 Pro Tip: Chat with me first! Future quizzes will be based on the questions you ask me.
    '),q("nacho","",a+="')},window.nachoQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n,i=e.parentElement.querySelectorAll("button");i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.7"}),t?(e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1","function"==typeof awardPoints&&awardPoints(10,"🎮 Quiz correct!"),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(34,197,94,0.1);border:1px solid #22c55e;border-radius:8px;color:#22c55e;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="✅ Correct! +10 XP",e.parentElement.appendChild(n)):(e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.borderColor="#22c55e",t.style.color="#22c55e",t.style.opacity="1")}),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(239,68,68,0.1);border:1px solid #ef4444;border-radius:8px;color:#ef4444;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="❌ Incorrect. Try another!",e.parentElement.appendChild(n))},window.nachoChatSave=function(){var e=window._nachoChatHistory||[];e.length>100&&(e=e.slice(e.length-100)),window._nachoChatHistory=e;try{localStorage.setItem("btc_nacho_chat",JSON.stringify(e))}catch(e){}},window.startConversationQuiz=function(){var e=window._convoQuizQuestions||[];0!==e.length&&(window._convoQuizIdx=0,window._convoQuizScore=0,window._convoQuizTotal=Math.min(e.length,5),O())},window.convoQuizAnswer=function(e,t){var o=e.parentElement,n=o.querySelectorAll("button");if(n.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1",window._convoQuizScore=(window._convoQuizScore||0)+1;var i=document.createElement("div");i.style.cssText="margin-top:6px;color:#22c55e;font-size:0.8rem;font-weight:700;",i.textContent="✅ Correct!",o.appendChild(i)}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",n.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var a=document.createElement("div");a.style.cssText="margin-top:6px;color:#ef4444;font-size:0.8rem;font-weight:700;",a.textContent="❌ Not quite!",o.appendChild(a)}window._convoQuizIdx=(window._convoQuizIdx||0)+1,setTimeout(O,1500)},window.nachoChatExport=function(){var e=window._nachoChatHistory||[];if(0!==e.length){for(var t=["=== Nacho Mode Chat Export ===","Exported: "+(new Date).toLocaleString(),""],o=0;o]+>/g,"");t.push("["+i+"] "+a+": "+r)}t.push("","--- bitcoineducation.quest ---");var s=new Blob([t.join("\n")],{type:"text/plain"}),c=document.createElement("a");c.href=URL.createObjectURL(s),c.download="nacho-chat-"+(new Date).toISOString().slice(0,10)+".txt",c.click(),URL.revokeObjectURL(c.href),"function"==typeof showToast&&showToast("💾 Chat saved!")}else"function"==typeof showToast&&showToast("No chat to save!")},window.nachoChatClear=function(){confirm("Clear all chat history with Nacho?")&&(window._nachoChatHistory=[],localStorage.removeItem("btc_nacho_chat"),N(),"function"==typeof showToast&&showToast("🗑️ Chat cleared"))},window.nachoModeSend=function(){var e=document.getElementById("nachoModeInput");if(e){var t=e.value.trim();if(t){e.value="",window._nachoSentIdx=-1,window._nachoSentDraft="",window._nachoAskedQuestions||(window._nachoAskedQuestions=[]),window._nachoAskedQuestions.push(t.toLowerCase()),window._nachoAskedQuestions.length>30&&(window._nachoAskedQuestions=window._nachoAskedQuestions.slice(-20)),window._nachoSentHistory.push(t),window._nachoSentHistory.length>50&&window._nachoSentHistory.shift();try{localStorage.setItem("btc_nacho_sent",JSON.stringify(window._nachoSentHistory))}catch(e){}var o;(o=document.getElementById("nachoHeroAvatar"))&&o.classList.add("talking"),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,window._nachoModeTopics&&t.length>10&&window._nachoModeTopics.push(t),!window._nachoConvoQuizOffered&&window._nachoModeStartTime&&window._nachoModeTopics&&(Date.now()-window._nachoModeStartTime)/6e4>=15&&window._nachoModeTopics.length>=5&&(window._nachoConvoQuizOffered=!0,setTimeout(function(){D()},8e3)),H("user",t),q("user",t),function(){var e=document.getElementById("nachoModeChat");if(e){e.querySelector("#nachoModeAvatar")&&(e.innerHTML="");var t=document.createElement("div");t.id="nmThinking",t.className="nm-msg nm-nacho",t.innerHTML='🦌 Thinking',e.appendChild(t),e.scrollTop=e.scrollHeight;var o=t.querySelector(".nacho-dots"),n=0;window._nmDotsTimer=setInterval(function(){n=(n+1)%4,o&&(o.textContent=".".repeat(n))},400)}}();var n="nm_"+Date.now()+"_"+Math.random().toString(36).substr(2,4),i=!1,a=setTimeout(function(){i||(i=!0,console.warn("[Nacho] Master timer fired — pipeline took >15s for:",t),s("That's a great question! I'm having a little trouble with my brain right now 🦌 Try asking me again in a moment, or explore the channels on the left to learn about Bitcoin!","fallback"))},15e3);if("function"!=typeof nachoUnifiedAnswer){if(!document.querySelector("script[data-nacho-retry]")){var r=document.createElement("script");r.src="nacho-qa.js?v="+Date.now(),r.setAttribute("data-nacho-retry","1"),document.head.appendChild(r)}setTimeout(function(){if("function"==typeof nachoUnifiedAnswer)try{nachoUnifiedAnswer(t,c)}catch(e){console.warn("Nacho pipeline retry error:",e),c({type:"fallback",answer:"I'm still loading up my Bitcoin knowledge! Try again in a moment 🦌"})}else!function(e,t){if("function"==typeof checkOffTopic){var o=checkOffTopic(e);if(o)return void t("function"==typeof personalize?personalize(o):o,"offtopic")}var n=e.toLowerCase().trim();if(/^(hey|hi|hello|yo|sup|howdy|hola|what'?s up|how are you|how'?s it going|good morning|good evening|good afternoon|gm|greetings)$/i.test(n)||/^(hey|hi|hello|yo) (nacho|there|buddy|friend|deer)/i.test(n)){var i=["Hey there! 🦌 Doing great — just hanging out waiting for someone to ask me about Bitcoin! What's on your mind?","Hey hey! 🧡 Welcome! I'm Nacho, your Bitcoin buddy. What would you like to learn about today?","Well hello! 🦌 Nice to see you. Ask me anything about Bitcoin — I've got 146 channels of knowledge in these antlers!","Hey! 👋 I'm good, thanks for asking! Ready to talk Bitcoin whenever you are. What's on your mind?"];t(i[Math.floor(Math.random()*i.length)],"offtopic")}else"function"==typeof nachoTrackMiss&&nachoTrackMiss(e),t("Give me just a moment — I'm loading up my Bitcoin knowledge! Try again in a few seconds. 🦌","fallback")}(t,s)},2e3)}else try{console.log("[Nacho] Calling nachoUnifiedAnswer for:",t),nachoUnifiedAnswer(t,function(e){console.log("[Nacho] Pipeline returned:",e?e.type:"null"),c(e)})}catch(e){console.error("[Nacho] Pipeline CRASH:",e),c({type:"fallback",answer:"Oops, my brain hit a bump! 🦌 Try asking again — I know a LOT about Bitcoin!"})}}}function s(e,o){!function(){window._nmDotsTimer&&(clearInterval(window._nmDotsTimer),window._nmDotsTimer=null);var e=document.getElementById("nmThinking");e&&e.remove()}(),function(){var e=document.getElementById("nachoHeroAvatar");e&&e.classList.remove("talking")}();var i="";if(o&&"safety"!==o){window._nachoAnswerData||(window._nachoAnswerData={}),window._nachoAnswerData[n]=e;var a="background:none;border:1px solid var(--border);border-radius:16px;cursor:pointer;font-size:0.75rem;padding:4px 10px;transition:0.2s;color:var(--text-muted);display:inline-flex;align-items:center;gap:3px;touch-action:manipulation;",r='
    ';"function"==typeof nachoRatingHtml&&(r+='",r+='"),r+="',i+=r+="
    ",i+=function(e){if(!e||0===e.length)return"";for(var t='
    ',o=0;o💬 "+e[o]+"";return t+"
    "}("function"==typeof nachoFollowUps?nachoFollowUps((t||"")+" "+(e||"")):[])}H("nacho","",e+i),q("nacho","",e+i),j(),"function"==typeof nachoTrackTopic&&nachoTrackTopic(t,o||"unknown");var s=function(){if(L)return null;for(var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[10,25,50,100,200,500],o=safeJSON("btc_nacho_q_milestones",[]),n=null,i=0;i=a&&-1===o.indexOf(r)&&-1===o.indexOf(a)&&(o.push(r),n=a)}return null===n?null:(localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(o)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({nachoMilestones:o}).catch(function(){}),L=!0,{10:"🎉 10 questions! You're officially a Bitcoin Beginner! Keep going — there's so much to learn! 🦌",25:"🎉 25 questions! You've leveled up to Bitcoin Explorer! You're asking the right questions! 💪",50:"🎉 50 questions! Bitcoin Apprentice unlocked! You know more than most people already! 🧠",100:"🏆 100 questions! You're a Bitcoin Scholar now! Satoshi would be proud! 🎓",200:"🔥 200 questions! Bitcoin Expert status! You could probably teach ME a thing or two! 🦌💡",500:"👑 500 QUESTIONS! You are a Bitcoin LEGEND! There's nothing Nacho can't discuss with you now! 🦌🏆🔥"}[n]||null)}();s&&setTimeout(function(){H("nacho","",s),q("nacho","",s)},1500)}function c(e){if(!i){i=!0,clearTimeout(a);var t="";e&&e.siteAction?t='

    ":e&&e.channel&&(t='

    📖 Read more: '+(e.channelName||e.channel)+" →"),s((e&&e.answer?e.answer:"Hmm, let me think about that... Try asking another way! 🦌")+t,e&&e.type||"fallback")}}},window.nachoModeAvatarTap=function(){var e=document.getElementById("nachoModeAvatar");e&&(e.style.transform="scale(1.1) rotate("+(Math.random()>.5?"5":"-5")+"deg)",setTimeout(function(){e.style.transform=""},300),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,j())},window._nachoModeRecognition=null,window._nachoModeListening=!1,window.nachoModeVoice=function(){var e=window.SpeechRecognition||window.webkitSpeechRecognition;if(e){var t=document.getElementById("nachoModeInput"),o=document.getElementById("nachoModeMic");if(t&&o)if(window._nachoModeListening&&window._nachoModeRecognition)window._nachoModeRecognition.stop();else{var n=new e;window._nachoModeRecognition=n,n.lang="en-US",n.interimResults=!0,n.maxAlternatives=1,n.continuous=!0,o.style.opacity="1",o.innerHTML="🛑",t.placeholder="Nacho is listening... (Tap 🛑 to finish)",t.style.borderColor="#f7931a",window._nachoModeListening=!0;var i="";n.onresult=function(e){for(var o="",n=e.resultIndex;n0&&nachoModeSend()},n.onerror=function(){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6",t.style.borderColor="var(--border,#333)",t.placeholder="Voice error — try typing"};try{n.start()}catch(e){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6"}}}},window.exitNachoMode=function(e){window._nachoMode=!1,window._nachoBusy=!1,window._btcPriceTimer&&(clearInterval(window._btcPriceTimer),window._btcPriceTimer=null);var t=document.getElementById("nachoModeScreen");t&&t.remove(),document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="")});var o=document.querySelector(".mobile-bar");if(o&&window.innerWidth<=900&&(o.style.display="flex"),!e){var n=window._nachoModeEarnings,i=window._nachoModeStartTime||Date.now(),a=Math.round((Date.now()-i)/6e4);if("function"==typeof showToast){var r=[];a>0&&r.push("⏱️ "+a+" min"),n&&n.interactions>0&&r.push("🦌 "+n.interactions+" interactions"),n&&n.points>0&&r.push("+"+n.points+" XP");var s=n?Array.isArray(n.badges)?n.badges.length:n.badges||0:0;s>0&&r.push("🏅 "+s+" badge"+(s>1?"s":"")),r.length>0?showToast(r.join(" · ")):showToast("🦌 Thanks for hanging out with "+("function"==typeof nachoNickname?nachoNickname():"Nacho")+"!")}goHome()}},window.goHome=function(e){if(document.activeElement&&document.activeElement.blur&&document.activeElement.blur(),"function"==typeof hideUsernamePrompt){var t=document.getElementById("usernameModal");t&&t.classList.contains("open")&&hideUsernamePrompt()}"function"==typeof _tctvStopTracker&&_tctvStopTracker();var n=document.getElementById("bottomNav");n&&n.classList.remove("nav-hidden"),"function"==typeof _updateSEO&&_updateSEO("home","Learn Bitcoin","A curated Bitcoin education archive with 146 topics, 8800+ messages, and community tools.");var i=document.getElementById("floatingRandomBtn");i&&(i.style.display="none");var a=document.getElementById("lbFloatBtn");a&&a.classList.remove("chat-shifted"),(l=document.getElementById("forumContainer"))&&(l.style.display="none"),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes();var r=document.getElementById("msgs");r&&(r.style.display="none");var s=document.getElementById("hero");s&&(s.style.display="none");var c=void 0!==auth&&auth?auth.currentUser:null;c&&c.email,void 0!==currentUser&¤tUser&¤tUser.totalVisits;try{safeJSON("btc_visited_channels",[]).length}catch(e){}var l,d=document.querySelector('[onclick*="showSpinWheel"]'),u=(document.querySelector('[onclick*="showPricePrediction"]'),document.querySelector('[onclick*="showNachoStory"]'),document.getElementById("dailyChallengeCard")),p=document.querySelector("[onclick*=\"go('bitcoin-beats'\"]"),m=document.querySelector("[onclick*=\"go('forum'\"]"),g=document.querySelector("[onclick*=\"go('marketplace'\"]"),h=document.querySelector('[onclick*="enterNachoMode"]');d&&(d.parentElement.style.display="grid"),u&&(u.style.display=""),m&&(m.style.display=""),p&&(p.style.display=""),g&&(g.style.display=""),h&&(h.style.display=""),(l=document.getElementById("forumContainer"))&&(l.style.display="none",l.innerHTML="");var f=document.getElementById("hero");f&&(f.style.display="none",f.innerHTML="");var y=document.getElementById("msgs");if(y&&(y.style.display="none",y.innerHTML=""),document.getElementById("home").classList.remove("hidden"),document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),document.getElementById("main").scrollTop=0,e||history.pushState({channel:null},"","/"),"function"==typeof window._renderSatoshiFavorHome&&window._renderSatoshiFavorHome(),o()){document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0);var v=document.querySelector(".mobile-bar");v&&(v.style.display="flex"),"function"==typeof updateRankUI&&updateRankUI()}R(),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof loadCommunityStats&&loadCommunityStats(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof window._renderCharityHome&&window._renderCharityHome(),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn()},document.addEventListener("keydown",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.isContentEditable){var t=e.key.toLowerCase();if(!e.ctrlKey&&!e.metaKey)if("h"!==t)if("/"!==t)if("c"!==t)if("r"!==t)if("m"!==t)if("a"!==t)if("t"!==t)if("s"!==t)if("l"!==t)if("q"!==t)if("f"!==t)if("n"!==t)if("d"!==t)if("v"!==t)if("g"!==t)if("p"!==t)if("x"!==t)if("j"!==t)if("k"!==t){if(" "===t)return e.preventDefault(),void document.getElementById("main").scrollBy({top:.8*window.innerHeight,behavior:"smooth"});if("?"===t||e.shiftKey&&"/"===t)!function(){var e=document.getElementById("kbHelpModal");if(e)e.remove();else{var t=document.createElement("div");t.id="kbHelpModal",t.style.cssText="position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.7);",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

    ⌨️ Keyboard Shortcuts

    Press ? to toggle this menu
    Navigation
    '+V("H","Go home")+V("/","Search")+V("C","Random topic")+V("M","Random Meme")+V("R","Random Art")+V("G","Random Graphic")+V("B","Back to last channel")+V("T","PlebTalk (Forum)")+V("S","Lightning Mart")+'
    Actions
    '+V("F","Favorite channel")+V("A","Ask Nacho")+V("N","Nacho Mode")+V("D","Dark / Light mode")+V("L","Leaderboard")+V("Q","Start quest")+V("V","Gallery view")+V("X","PVP Battle")+V("P","Donate")+V("I","Settings")+'
    Scrolling
    '+V("J","Scroll down")+V("K","Scroll up")+V("Space","Page down")+V("Esc","Close modals")+'
    Mobile Gestures
    '+V("2-finger","Nacho Mode")+V("3-finger","Settings")+V("Long-press","Explore Apps (on logo)")+"
    ",document.body.appendChild(t)}}();else if("i"!==t)if("b"!==t)if("2"!==t)if("3"!==t)if("1"!==t){if("0"===t)return W("Don't trust. Verify."),void("function"==typeof earnSticker&&earnSticker("cool"));if("9"===t)return W("Number go up!"),void("function"==typeof nachoFly&&nachoFly());if("2"!==window._eggBuffer||"1"!==t)if("w"!==t){if(window._eggBuffer=(window._eggBuffer||"")+t,window._eggBuffer.length>10&&(window._eggBuffer=window._eggBuffer.slice(-10)),-1!==window._eggBuffer.indexOf("btc")&&(window._eggBuffer="",localStorage.setItem("btc_bitcoin_eyes_unlocked","true"),"function"==typeof showToast&&showToast("₿₿ Secret unlocked: Bitcoin Eyes! Check Nacho's Closet!"),"function"==typeof haptic&&haptic("success")),"escape"===t){e.preventDefault();var i=document.getElementById("lb");if(i&&i.classList.contains("open"))return void i.classList.remove("open");var a=document.getElementById("usernameModal");if(a&&a.classList.contains("open"))return void("function"==typeof hideUsernamePrompt&&hideUsernamePrompt());var r=document.getElementById("questModal");if(r&&r.classList.contains("open"))return void r.classList.remove("open");var s=document.getElementById("searchOverlay");if(s&&"none"!==s.style.display)return void(s.style.display="none");var c=document.getElementById("nachoStoryOverlay");if(c)return void c.remove();var l=document.getElementById("spinModal");if(l)return void l.remove();var d=document.getElementById("donateModal");if(d)return void d.remove();var u=document.getElementById("kbHelpModal");if(u)return void u.remove();if(document.getElementById("pvpOverlay"))return void("function"==typeof exitPVPMode&&exitPVPMode());var p=document.getElementById("appsMenu");if(p&&"block"===p.style.display)return void(p.style.display="none");if(o()){var m=document.getElementById("sidebar");if(m&&m.classList.contains("open"))return m.classList.remove("open"),void("function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!0))}if(window._nachoMode&&"function"==typeof exitNachoMode)return void exitNachoMode()}}else W("Stay humble. Stack sats.");else W("Twenty-one million. Final and absolute.")}else W("One more block.");else W("Three point one two five. The current block reward.");else W("There is no second best.");else{var g=localStorage.getItem("btc_last_channel");g&&go(g)}else"function"==typeof showSettingsPage&&showSettingsPage("account")}else document.getElementById("main").scrollBy({top:-300,behavior:"smooth"});else document.getElementById("main").scrollBy({top:300,behavior:"smooth"});else"function"==typeof enterPVPMode&&enterPVPMode();else showDonateModal();else T();else{var h=document.getElementById("galleryBtn");h&&h.click()}else n();else"function"==typeof enterNachoMode&&enterNachoMode();else{var f=document.getElementById("favBtn");f&&f.click()}else{var y=document.getElementById("questBtn");y&&y.click()}else"function"==typeof toggleLeaderboard&&toggleLeaderboard();else go("marketplace");else go("forum");else"function"==typeof showNachoInput&&showNachoInput();else x();else k();else b();else{e.preventDefault();var v=document.getElementById("searchInput");v&&(v.focus(),o()&&document.getElementById("sidebar").classList.add("open"))}else goHome()}});var F=0;function W(e){var t=Date.now();if(!(t-F<3e3)){F=t,"function"==typeof showToast&&showToast("🟠 "+e);try{var o=new SpeechSynthesisUtterance(e);o.rate=.9,o.pitch=.85,o.volume=.8;var n=speechSynthesis.getVoices().find(function(e){return-1!==e.name.indexOf("Daniel")||-1!==e.name.indexOf("Google UK English Male")||-1!==e.name.indexOf("Male")});n&&(o.voice=n),speechSynthesis.cancel(),speechSynthesis.speak(o)}catch(e){}}}function V(e,t){return'
    '+e+'
    '+t+"
    "}"undefined"!=typeof speechSynthesis&&speechSynthesis.getVoices(),function(){if("ontouchstart"in window){var e=0,t=0;window.addEventListener("devicemotion",function(o){var n=o.acceleration&&null!==o.acceleration.x?o.acceleration:null;if(n&&Math.abs(n.x)+Math.abs(n.y)+Math.abs(n.z)>25){if(e++,clearTimeout(window._shakeResetTimer),window._shakeResetTimer=setTimeout(function(){e=0},1e3),e<3)return;e=0;var i=Date.now();if(i-t<1e4)return;t=i;var a=["There is no second best.","One more block.","Don't trust. Verify.","Number go up!","Stay humble. Stack sats.","Not your keys, not your coins.","Bitcoin fixes this.","Tick tock, next block."];W(a[Math.floor(Math.random()*a.length)]),Math.random()<.3&&"function"==typeof nachoFly&&nachoFly()}});var o=0,n=0,i=0,a=document.getElementById("main");a.addEventListener("touchstart",function(e){"INPUT"===e.target.tagName||"TEXTAREA"===e.target.tagName||e.target.closest(".no-swipe")||(o=e.touches[0].clientX,n=e.touches[0].clientY,i=Date.now())},{passive:!0}),a.addEventListener("touchend",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.closest(".no-swipe")){var t=e.changedTouches[0].clientX-o,a=e.changedTouches[0].clientY-n,r=Date.now()-i,s=Math.abs(t),c=Math.abs(a);r>600||s>150&&s>2.5*c&&(t>0?(goPrev(),"function"==typeof haptic&&haptic("light")):(goNext(),"function"==typeof haptic&&haptic("light")))}},{passive:!0});var r=0,s=0;document.getElementById("main").addEventListener("touchstart",function(e){2===e.touches.length&&(s=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(s&&0===e.touches.length&&e.changedTouches.length>=1){var t=Date.now()-s;if(s=0,t>400)return;var o=Date.now();if(o-r<3e3)return;r=o,"function"==typeof enterNachoMode&&enterNachoMode()}},{passive:!0}),document.querySelectorAll(".home-logos img, .channel-logos .channel-logo-img").forEach(d),new MutationObserver(function(){document.querySelectorAll(".channel-logos .channel-logo-img").forEach(d)}).observe(document.getElementById("main"),{childList:!0,subtree:!0});var c=0,l=0;document.getElementById("main").addEventListener("touchstart",function(e){3===e.touches.length&&(l=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(l&&0===e.touches.length){var t=Date.now()-l;if(l=0,t>400)return;var o=Date.now();if(o-c<3e3)return;c=o,"function"==typeof showSettings&&showSettings()}},{passive:!0})}function d(e){var t;e._logoLongPress||(e._logoLongPress=!0,e.addEventListener("touchstart",function(e){t=setTimeout(function(){"function"==typeof toggleAppsMenu&&toggleAppsMenu(),"function"==typeof haptic&&haptic("medium")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t)}),e.addEventListener("touchmove",function(){clearTimeout(t)}))}}();const G={};function Q(){const e=safeJSON("btc_visited_channels",[]).length;void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth?auth:null,o=t&&t.currentUser;o&&o.email;var n="function"==typeof getOnboardingProfile?getOnboardingProfile():null;n&&("advanced"===n.level||n.level);const i=document.querySelectorAll(".cat-label.cat-toggle"),a=document.querySelectorAll(".quest-start-btn, .home-cta, #beatsBtnHome, [onclick*=\"go('forum'\"], [onclick*=\"go('marketplace'\"]");function r(e){return function(){var t=e.match(/^go\(['"]([^'"]+)['"]/);if(t)go(t[1]);else{var o=e.match(/^(?:if\(typeof\s+(\w+)==='function'\))?\s*(\w+)\(\)/);if(o){var n=o[2]||o[1];if("function"==typeof window[n])return void window[n]()}var i=e.match(/renderChatHub\(['"](\w+)['"]\)/);if(i&&"function"==typeof window.renderChatHub)window.renderChatHub(i[1]);else{var a=e.match(/showSettingsPage\(['"](\w+)['"]\)/);a&&"function"==typeof window.showSettingsPage?window.showSettingsPage(a[1]):console.warn("[SECURITY] Unrecognized action pattern:",e)}}}}i.forEach(function(e){var t=e.nextElementSibling;t&&t.classList.contains("cat-group")&&(e.style.display="",t.style.display="true"===e.getAttribute("data-expanded")?"":"none")}),a.forEach(e=>{if(e.closest("#appsMenu")||e.closest("#guideOverlay")||e.closest("#questHubOverlay"))return;const t=e.getAttribute("data-name")||e.textContent.replace("🔒 ","").trim();e.getAttribute("data-name")||e.setAttribute("data-name",t);const o=e.getAttribute("data-onclick")||e.getAttribute("onclick");e.getAttribute("data-onclick")||e.setAttribute("data-onclick",o),e.innerHTML=t,e.style.opacity="1",e.style.filter="none",e.style.cursor="pointer",e.title="";var n=e.getAttribute("data-onclick");n&&(e.onclick=r(n))}),document.querySelectorAll("[data-tier]").forEach(t=>{const o=t.getAttribute("data-tier"),n=t.getAttribute("data-unlock-name")||t.textContent.trim(),i=t.getAttribute("data-onclick")||t.getAttribute("onclick");!t.getAttribute("data-onclick")&&i&&t.setAttribute("data-onclick","string"==typeof i?i:i.toString()),!t.getAttribute("data-orig-tooltip")&&t.getAttribute("data-tooltip")&&t.setAttribute("data-orig-tooltip",t.getAttribute("data-tooltip"));let a=!1,s="";if("explorer"===o?(a=true,s="🔒 Visit "+Math.max(0,3-e)+" more channel"+(3-e==1?"":"s")+" to unlock "+n+"!"):"community"===o?(a=true,s="🔒 Explore "+Math.max(0,5-e)+" more channel"+(5-e==1?"":"s")+" to unlock "+n+"!"):"full"===o&&(a=true,s="🔒 Explore "+Math.max(0,10-e)+" more channel"+(10-e==1?"":"s")+" or sign in to unlock "+n+"!"),a){t.innerHTML=n,t.style.opacity="1",t.style.filter="none";var c=t.getAttribute("data-orig-tooltip")||t.getAttribute("data-tooltip");c?(t.title=c,t.setAttribute("data-tooltip",c)):t.title=n,t.style.cursor="pointer",t.title="";var l=t.getAttribute("data-onclick");l&&(t.onclick=r(l))}else t.innerHTML="🔒 "+n,t.style.opacity="0.45",t.style.filter="grayscale(0.8)",t.style.cursor="help",t.title=s,t.setAttribute("data-tooltip",s),t.onclick=function(e){e.preventDefault(),e.stopPropagation(),"function"==typeof showToast&&showToast(s)}});var s=localStorage.getItem("btc_unlocked_tier")||"none",c=["none","explorer","community","full"],l="full",d=c.indexOf(s);if(c.indexOf(l)>d){localStorage.setItem("btc_unlocked_tier",l);var u=document.getElementById("appsMenu");u&&u.remove(),"function"==typeof showToast&&showToast("🚀 ⚡ Lightning Mart unlocked! You have full access!")}var p=document.getElementById("sidebarMilestone");p&&p.remove()}function Y(){window.audioEnabled=!window.audioEnabled,localStorage.setItem("btc_audio",window.audioEnabled.toString()),X(),"function"==typeof showToast&&showToast(window.audioEnabled?"🔊 Sound on":"🔇 Sound off")}function J(e){window.audioVolume=parseFloat(e),localStorage.setItem("btc_volume",window.audioVolume.toString()),window.audioVolume<=0?(window.audioEnabled=!1,localStorage.setItem("btc_audio","false")):window.audioEnabled||(window.audioEnabled=!0,localStorage.setItem("btc_audio","true")),window._beatsAudio&&(window._beatsAudio.volume=window.audioVolume),window._djAudio&&(window._djAudio.volume=window.audioVolume);var t=document.getElementById("beatsVolume");t&&(t.value=Math.round(100*window.audioVolume));var o=document.getElementById("djVolume");o&&(o.value=Math.round(100*window.audioVolume)),X()}function X(){const e=document.getElementById("audioBtn");e&&(e.textContent=window.audioEnabled&&window.audioVolume>0?window.audioVolume>.5?"🔊":"🔉":"🔇");const t=document.getElementById("volumeSlider");t&&(t.value=window.audioEnabled?window.audioVolume:0),document.querySelectorAll('button[onclick*="toggleAudio"]').forEach(function(e){"ON"!==e.textContent&&"OFF"!==e.textContent||(e.textContent=window.audioEnabled?"ON":"OFF",e.style.background=window.audioEnabled?"#22c55e":"var(--bg-side)",e.style.color=window.audioEnabled?"#fff":"var(--text-muted)")})}Q(),window._sidebarTierInterval=setInterval(Q,5e3),window.audioEnabled="false"!==localStorage.getItem("btc_audio"),window.audioVolume=parseFloat(localStorage.getItem("btc_volume")||"0.5"),window.canPlaySound=function(){return window.audioEnabled&&window.audioVolume>0&&"visible"===document.visibilityState},window.goNext=function(){if(void 0===CHANNELS)return;const e=window._sidebarOrder&&window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(m);if(-1===t)return void go(e[0]);const o=t0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(m);if(-1===t)return void go(e[e.length-1]);const o=t>0?e[t-1]:e[e.length-1];go(o)},window.go=async function(e,t,n){"function"==typeof _tctvStopTracker&&_tctvStopTracker();var i=document.getElementById("bottomNav");i&&i.classList.remove("nav-hidden"),window._nachoMode&&!n&&("function"==typeof nachoChatSave&&nachoChatSave(),window._nachoReturnPending=!0);var a=document.getElementById("msgs"),r=document.getElementById("hero");const l=CHANNELS[e];let d="";l&&(d='"),a.innerHTML=d+'
    \x3c!-- Nacho Summary skeleton --\x3e
    \x3c!-- Message skeletons --\x3e
    \x3c!-- Image skeleton --\x3e
    ',a.style.display="",document.getElementById("home").classList.add("hidden"),r.style.display="none",o()&&document.getElementById("sidebar").classList.remove("open");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var g,f=void 0!==auth&&auth?auth.currentUser:null;if(f&&f.email,"forum"===e||"marketplace"===e||"bitcoin-beats"===e||"irl-sync"===e||"dms"===e||"lightning"===e||"chat"===e||"first-purchase"===e||"timechain-tv"===e||"trails"===e)return window._nachoMode&&exitNachoMode(!0),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.getElementById("msgs").style.display="none",document.getElementById("hero").style.display="none",(g=document.getElementById("forumContainer"))&&(g.style.display="block"),n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&document.getElementById("sidebar").classList.remove("open"),function e(t,o){if(o=o||0,"first-purchase"===t&&"function"==typeof renderFirstPurchase)renderFirstPurchase(),document.getElementById("main").scrollTop=0;else if("timechain-tv"===t&&"function"==typeof renderTimechainTV)renderTimechainTV(),document.getElementById("main").scrollTop=0,"function"==typeof _tctvStartTracker&&_tctvStartTracker();else if("marketplace"===t&&"function"==typeof renderMarketplace)renderMarketplace();else if("bitcoin-beats"===t&&"function"==typeof renderBitcoinBeats)renderBitcoinBeats();else if("irl-sync"===t&&"function"==typeof renderIRLSync)renderIRLSync();else if("dms"===t&&"function"==typeof showInbox)showInbox();else if("lightning"===t&&"function"==typeof renderLightning)renderLightning();else if("chat"===t&&"function"==typeof renderChatHub)renderChatHub("global");else if("trails"===t&&"function"==typeof renderModules)renderModules();else if("forum"===t&&"function"==typeof renderForum)renderForum();else if(o<20){if(setTimeout(function(){e(t,o+1)},250),0===o){var n=document.getElementById("forumContainer");n&&(n.innerHTML='
    Loading...
    ')}}else if("forum"===t&&"function"==typeof renderForum)renderForum();else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
    ⚠️
    Still loading...
    This feature is taking longer than expected.
    ')}}(e),document.getElementById("main").scrollTop=0,g&&(g.scrollTop=0),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0,setTimeout(function(){document.getElementById("main").scrollTop=0,document.getElementById("forumContainer")&&(document.getElementById("forumContainer").scrollTop=0),window.scrollTo(0,0)},50),setFloatingElementsVisible(!0),void("function"==typeof nachoOnPage&&nachoOnPage(e));if(!l)return;if(window._nachoMode&&exitNachoMode(!0),(g=document.getElementById("forumContainer"))&&(g.style.display="none",g.innerHTML=""),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes(),document.getElementById("hero").style.display="",document.getElementById("msgs").style.display="",!window._keepFloatingBtn){var y=document.getElementById("floatingRandomBtn");y&&"none"!==y.style.display&&"memes-funny"!==e&&"art-inspiration"!==e&&"graphics"!==e&&(y.style.display="none")}localStorage.setItem("btc_last_channel",e),function(){if(window.canPlaySound())try{const e=new(window.AudioContext||window.webkitAudioContext),t=window.audioVolume,o=e.createOscillator(),n=e.createGain();o.connect(n),n.connect(e.destination),o.frequency.value=880,o.type="sine",n.gain.setValueAtTime(.08*t,e.currentTime),n.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15),o.start(e.currentTime),o.stop(e.currentTime+.15);const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=1318.5,i.type="sine",a.gain.setValueAtTime(.05*t,e.currentTime+.05),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.25),i.start(e.currentTime+.05),i.stop(e.currentTime+.25)}catch(e){}}(),document.getElementById("home").classList.add("hidden"),(a=document.getElementById("msgs")).innerHTML=d+'
    ',document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),t?(t.classList.add("active"),s(t)):document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("'"+e+"'")&&(t.classList.add("active"),s(t))});const v=["graphics","memes-funny","art-inspiration","charts","swag-merch","fun-facts"].includes(e),b="https://bitcoineducation.quest/#"+e,w=l.title+" — Bitcoin Education Archive";let x;if(document.getElementById("hero").innerHTML='
    Home
    '+l.cat+"

    "+l.title+'

    "+(v?'":""),document.getElementById("hero").classList.remove("fade-in"),document.getElementById("msgs").innerHTML='
    Loading channel...
    ',document.getElementById("main").scrollTop=0,n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&(document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0)),G[e])x=G[e];else try{const t=await fetch(l.file);x=await t.json(),G[e]=x}catch(e){return void(document.getElementById("msgs").innerHTML='
    Error loading channel data
    ')}if(p=x,m=e,window.currentChannelId=e,u=!1,"function"==typeof window._raidOnChannelVisit&&window._raidOnChannelVisit(e),"function"==typeof _updateSEO&&void 0!==CHANNELS&&CHANNELS[e]){var k=CHANNELS[e];_updateSEO(e,k.title||k.name,k.desc||"")}if(h(e),window._searchScrollTarget&&window._searchScrollTarget.channel===e){var T=0;setTimeout(function e(){T++,window._searchScrollTarget&&(document.getElementById("msg-"+window._searchScrollTarget.msgIdx)||T>=3?"function"==typeof window._tryScrollToSearchResult&&window._tryScrollToSearchResult():setTimeout(e,400*T))},200)}document.getElementById("hero").classList.add("fade-in"),document.getElementById("msgs").classList.add("fade-in"),window._currentMsgs=x.msgs,window._currentOffset=o()?20:50,window._currentLoadChannel=e,window.loadMoreMsgs=function(){if(window._currentLoadChannel!==m)return;const e=window._currentOffset,t=window._currentMsgs,n=document.getElementById("loadMoreBtn");if(!n)return;const i=t.slice(e,e+50);let a="";i.forEach((t,n)=>{if(a+='
    ',t.text){let e=t.text,n=[],i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){var t=e.startsWith("http")?e:"https://"+e;return i.push(t),"%%TW"+(i.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){var n=i[parseInt(t)],a="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),c=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+c+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),a+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?a+='':a+=''}),a+="
    "}),n.insertAdjacentHTML("beforebegin",a),window._currentOffset=e+50,window._currentOffset>=t.length?(n.remove(),window._scrollObserver&&window._scrollObserver.disconnect()):n.textContent="Load more ("+(t.length-window._currentOffset)+" remaining)"},function(){if(window._scrollObserver&&(window._scrollObserver.disconnect(),window._scrollObserver=null),document.getElementById("loadMoreBtn")){window._scrollObserver=new IntersectionObserver(function(e){e[0].isIntersecting&&"function"==typeof window.loadMoreMsgs&&window.loadMoreMsgs()},{root:null,rootMargin:"300px",threshold:0});var e=document.getElementById("loadMoreBtn");e&&window._scrollObserver.observe(e)}}(),document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")});let S=safeJSON("btc_visited_channels",[]);S.includes(e)||(S.push(e),localStorage.setItem("btc_visited_channels",JSON.stringify(S)),Q());try{void 0!==db&&"undefined"!=typeof firebase&&db.collection("stats").doc("global").set({channelVisits:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}if("function"==typeof window._raidContribute&&window._raidContribute("channelVisit",1,e),x.msgs&&x.msgs.length>0){const t='
    Did this help you learn something?
    Your feedback helps Nacho improve the archive!
    ';a.insertAdjacentHTML("beforeend",t)}window._lastChannelOpenTime=Date.now(),"function"==typeof onChannelOpen&&onChannelOpen(e)};let K=!1,$={},Z=null;const ee=[{id:"_irl",title:"🤝 IRL Sync",desc:"Find and create local Bitcoin meetups and events",keywords:"irl meetup events sync meeting community local map gather conference meetup event rsvp",action:"go('irl-sync')"},{id:"_beats",title:"🎸 Bitcoin Beats",desc:"Community music — discover, upload, and listen to Bitcoin tracks. Upload entire albums and EPs.",keywords:"beats music livestream live video radio stream audio upload song track listen discover artist genre community album ep discography bulk batch dj broadcast",action:"go('bitcoin-beats')"},{id:"_nacho",title:"🦌 Nacho Mode",desc:"Interactive AI-powered Bitcoin tutor",keywords:"nacho mode ai chat ask question tutor learn mascot deer",action:"enterNachoMode()"},{id:"_forum",title:"🗣️ PlebTalk",desc:"Discuss Bitcoin with the community",keywords:"forum community chat discuss talk conversation post plebtalk reply thread threaded replies nested conversation",action:"go('forum')"},{id:"_articles",title:"📝 Articles",desc:"Read and write long-form Bitcoin articles",keywords:"article write publish essay blog read long form content author",action:"forumTab='articles';go('forum')"},{id:"_market",title:"⚡ LightningMart",desc:"Buy and sell with Bitcoin",keywords:"marketplace market buy sell trade shop store bitcoin sats lightning wallet hardware merch",action:"go('marketplace')"},{id:"_settings",title:"⚙️ Settings",desc:"Profile, rank, tickets, referral link, theme",keywords:"settings profile account rank level points tickets referral theme dark light audio sound notifications push",action:"showSettings()"},{id:"_spin",title:"🎡 Daily Spin",desc:"Spin the wheel for free Orange Tickets",keywords:"spin wheel daily reward ticket prize free",action:"showSpinWheel()"},{id:"_quest",title:"⚔️ Quest Hub",desc:"Quiz, Trivia, and Poll quests — earn XP!",keywords:"quest mission journey learn guided start challenge quiz trivia poll hub",action:"showQuestHub()"},{id:"_scholar",title:"🎓 Scholar Certification",desc:"Bitcoin Scholar & Protocol Expert Certifications",keywords:"scholar certification exam test certificate diploma bitcoin technical protocol",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_signal",title:"📡 The Signal",desc:"Weekly curated Bitcoin insights newsletter",keywords:"signal newsletter weekly email updates curated insights",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_flashcards",title:"📚 Flashcards",desc:"Study Bitcoin topics with interactive flashcards",keywords:"flashcard study cards learn review quiz prep memorize practice drill test",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_leaderboard",title:"🏆 Leaderboard",desc:"See top ranked Bitcoiners",keywords:"leaderboard ranking top leaders scoreboard competition",action:"toggleLeaderboard()"},{id:"_tickets",title:"🎟️ Orange Tickets",desc:"Earn tickets for giveaways and rewards",keywords:"tickets orange giveaway raffle prize sats reward earn",action:"showSettings()"},{id:"_referral",title:"🔗 Referral Program",desc:"Invite friends and earn 50 tickets each",keywords:"referral invite share link friend earn bonus",action:"showSettings()"},{id:"_closet",title:"🎽 Nacho's Closet",desc:"Dress up Nacho with items you unlock",keywords:"closet outfit clothes dress costume item equip nacho customize color hat scarf sunglasses crown hoodie accessories wardrobe",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_badges",title:"🏅 Badges",desc:"View your earned badges and goals — chat, DJ, discovery, knowledge",keywords:"badges achievement trophy unlock goal progress medal chat dj streak listener",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_story",title:"📖 Nacho's Story",desc:"Read Nacho's Bitcoin adventure — one chapter per day",keywords:"story chapter read book adventure nacho tale",action:"showNachoStory()"},{id:"_predict",title:"📈 Price Prediction",desc:"Predict if Bitcoin goes up or down in 24 hours",keywords:"predict prediction price bitcoin up down forecast",action:"showPricePrediction()"},{id:"_random",title:"🎲 Random Channel",desc:"Jump to a random Bitcoin channel",keywords:"random channel surprise discover explore dice",action:"goRandom()"},{id:"_meme",title:"😂 Random Meme",desc:"See a random Bitcoin meme",keywords:"meme funny joke random humor laugh memes",action:"goRandomMeme()"},{id:"_art",title:"🎨 Random Art",desc:"See random Bitcoin art and inspiration",keywords:"art random artwork creative inspiration gallery",action:"goRandomArt()"},{id:"_graphic",title:"📊 Random Graphic",desc:"See a random Bitcoin graphic or chart",keywords:"graphic chart data visual infographic random graphics",action:"goRandomGraphic()"},{id:"_quiz",title:"🎮 Quiz Me",desc:"Test your Bitcoin knowledge with Nacho",keywords:"quiz question test knowledge trivia game answer",action:"nachoQuizMe()"},{id:"_pvp",title:"⚔️ PVP Battle",desc:"Real-time Bitcoin trivia battles against other players",keywords:"pvp battle fight 1v1 versus trivia quiz compete multiplayer arena duel challenge opponent leaderboard wins losses",action:"enterPVPMode()"},{id:"_donate",title:"💛 Donate",desc:"Support Bitcoin Education Archive with sats",keywords:"donate support tip sats lightning contribute funding",action:"showDonateModal()"},{id:"_theme",title:"🌙 Toggle Theme",desc:"Switch between dark and light mode",keywords:"theme dark light mode toggle switch appearance color night day",action:'document.getElementById("themeToggle").click()'},{id:"_audio",title:"🔊 Toggle Audio",desc:"Turn sound effects on or off",keywords:"audio sound music mute volume effects toggle",action:"toggleAudio()"},{id:"_keyboard",title:"⌨️ Keyboard Shortcuts",desc:"View all keyboard shortcuts",keywords:"keyboard shortcut hotkey key binding keys shortcuts help",action:"showKeyboardHelp()"},{id:"_explore",title:"🗺️ Exploration Map",desc:"See which topics you have visited",keywords:"exploration map progress visited topics grid complete coverage",action:"goHome()"},{id:"_globalchat",title:"🌍 Global Chat",desc:"Live global chat room — talk with the community in real time",keywords:"global chat room live talk community message send public chatroom online users presence dm reaction gif emoji sticker emoji picker smiley face emoticon",action:"if(typeof renderChatHub==='function')renderChatHub('global');else if(typeof toggleChatOverlay==='function')toggleChatOverlay()"},{id:"_timechaintv",title:"📺 Timechain TV",desc:"Live Bitcoin television — 8 channels of curated Bitcoin videos playing 24/7",keywords:"tv television video watch live stream channel timechain tube youtube documentary tutorial mining sync broadcast cinema epg guide schedule remote couch nacho",action:"go('timechain-tv')"},{id:"_djmode",title:"🎧 DJ Mode",desc:"Go live as a DJ — broadcast music, use sound effects, crossfade, and play Bitcoin quotes",keywords:"dj mode broadcast live music stream turntable crossfade sound effects horn airhorn scratch mixer controls",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('livestream')},300)"},{id:"_upload_album",title:"📀 Upload Album/EP",desc:"Upload up to 20 songs at once — group as Album or EP with cover art",keywords:"upload album ep discography batch bulk multiple songs tracks artist release collection",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('upload')},300)"},{id:"_messages",title:"💬 Messages / DMs",desc:"Direct messages — chat privately with other users",keywords:"messages dm direct message inbox chat private conversation contact send receive talk",action:"showInbox()"},{id:"_signin",title:"🔐 Sign In",desc:"Sign in or create an account",keywords:"sign in login register create account google twitter github facebook email",action:"showUsernamePrompt()"},{id:"_home",title:"🏠 Home",desc:"Return to the homepage",keywords:"home main start beginning",action:"goHome()"},{id:"_firstpurchase",title:"🛒 Your First Bitcoin Purchase",desc:"Step-by-step guide to buying your first Bitcoin — apps for 11 regions",keywords:"buy purchase first bitcoin exchange app strike river cash coinbase amber wallet region country how to start beginner dca",action:"go('first-purchase')"},{id:"_trails",title:"🦌 Nacho's Trails",desc:"Guided learning paths through Bitcoin education — Meadow, Mountain & Summit",keywords:"trails nacho guided path learning course module meadow mountain summit exam test progress curriculum education beginner intermediate advanced",action:"go('trails')"},{id:"_dashboard",title:"📊 Top Indicators",desc:"Live Bitcoin cycle top indicators — Pi Cycle, NUPL, Puell, Power Law & more",keywords:"dashboard indicators top cycle signal pi cycle nupl puell mayer multiple rsi ahr999 mstr etf power law rainbow reserve risk bitcoin metrics data analytics chart",action:"if(typeof toggleDashboard==='function')toggleDashboard()"},{id:"_meetupbox",title:"📦 Meetup-in-a-Box",desc:"Ready-made meetup templates with agendas and host tips",keywords:"meetup box template agenda host tips lightning workshop self custody mining event organize plan download",action:"go('irl-sync')"},{id:"_buddy",title:"🤝 Bitcoin Buddy",desc:"Find a learning partner — teachers matched with learners",keywords:"buddy partner match learn teach mentor mentee pair connect chat find friend study accountability group",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_certs",title:"📜 Shareable Certificates",desc:"Share your Scholar Certification with a verifiable public link",keywords:"certificate share verify link public proof scholar achievement social media url",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_satsvbits",title:"⚡ Sats vs Bits",desc:"Live community vote — sats or bits for the Bitcoin denomination?",keywords:"sats bits vote poll denomination unit satoshi community debate live",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_newbie",title:"🟢 Brand New to Bitcoin?",desc:"Quick introduction for absolute beginners",keywords:"new beginner brand new start zero nothing know nothing introduction first time newbie noob",action:"go('one-stop-shop')"},{id:"_meetupbuilder",title:"🔨 Meetup Builder",desc:"Plan, share, and discover Bitcoin meetups — resources, venues & guides",keywords:"meetup builder create plan share venue platform resource guide community",action:"go('meetup-builder')"},{id:"_sats",title:"⚡ Claim Sats",desc:"Convert your earned points into real Bitcoin sats via Lightning",keywords:"sats claim withdraw cashout bitcoin lightning faucet earn XP convert redeem payout real btc satoshi",action:"showSettings();setTimeout(function(){showSettingsPage('sats')},100)"},{id:"_tips",title:"⚡ Lightning Tips",desc:"Tip other users with Lightning sats",keywords:"tip tips lightning send sats zap reward give appreciation",action:"if(typeof showTipOverlay==='function')showTipOverlay()"},{id:"_network",title:"📡 Bitcoin Network",desc:"Live mempool, hashrate, difficulty, fees, and block explorer",keywords:"network mempool hashrate difficulty fees block explorer transaction confirmations bitcoin network stats",action:"go('bitcoin-dashboard')"},{id:"_notifications",title:"🔔 Notifications",desc:"Enable push notifications for updates and alerts",keywords:"notifications push alerts notify bell updates permission enable disable",action:"if(typeof requestNotificationPermission==='function')requestNotificationPermission();else showSettings()"},{id:"_streakfreeze",title:"🧊 Streak Freeze",desc:"Protect your visit streak with freeze tickets",keywords:"streak freeze ticket protect miss save guard insurance ice",action:"showSettings();setTimeout(function(){showSettingsPage('data')},100)"},{id:"_cotd",title:"📅 Channel of the Day",desc:"Today's featured Bitcoin education channel",keywords:"channel of the day daily featured recommendation today pick spotlight",action:"goHome()"},{id:"_nostr",title:"🟣 Nostr Login",desc:"Sign in with Nostr — extension, nsec, or npub",keywords:"nostr login sign in nip npub nsec extension relay decentralized identity",action:"showUsernamePrompt()"},{id:"_buddyfind",title:"🤝 Find a Bitcoin Buddy",desc:"Get matched with a learning partner — teachers meet learners",keywords:"buddy partner match learn teach mentor mentee pair connect study group accountability partner friend",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_favor",title:"✨⛏️ Satoshi's Favor",desc:"Community mining game — earn points, activate mining, hash for 21,000 sats",keywords:"satoshi favor mining hash mine community points activate 21 sats game block nonce difficulty target hashing brute force proof of work",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='favor';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_raid",title:"⚔️ Raid Boss",desc:"Monthly community challenge — deal damage by earning badges and completing activities",keywords:"raid boss challenge monthly community damage badge activity quest defeat winner prize leaderboard attack",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='raid';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_charity",title:"❤️ Donate XP for Charity",desc:"Donate your XP points for charity — 1,000 XP = 1,000 sats pledged. 10× more impact than redeeming for yourself.",keywords:"charity donate donation xp points sats bitcoin giving community philanthropy pledge faction badger hornet",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='charity';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_pow",title:"🚶 Proof of Walk",desc:"Connect Strava and earn XP for walking — proof of work with your feet",keywords:"proof of walk strava walking steps exercise fitness health outdoor move earn xp activity sync connect",action:"go('explore');setTimeout(function(){if(typeof renderProofOfWalk==='function')renderProofOfWalk()},300)"},{id:"_pop",title:"🕹️ Proof of Play",desc:"Bitcoin gaming hub — Timechain Arcade games + PVP trivia battles",keywords:"proof of play arcade games pvp battle timechain bitcoin gaming 1v1 trivia lightning to the moon node runner nakamoto knights block hunt",action:'if(typeof enterProofOfPlay==="function")enterProofOfPlay()'}];function te(e){const t=document.getElementById("searchResults"),o=document.getElementById("channelList");if(["searchInput","searchOverlayInput"].forEach(t=>{const o=document.getElementById(t);o&&o.value!==e&&(o.value=e)}),e&&"satoshi"===e.toLowerCase()&&("function"==typeof awardHiddenBadge&&awardHiddenBadge("discovery_satoshi","Found Satoshi! 🦢"),W("I am Satoshi. We are all Satoshi.")),e&&"deer"===e.toLowerCase()&&("function"==typeof setPose&&setPose("celebrate"),W("Fawntastic! You found the secret buck."),"function"==typeof nachoFly&&setTimeout(nachoFly,1e3)),!e||e.length<2){var n=safeJSON("btc_recent_searches",[]);if(n.length>0&&t){var i='
    🕐 Recent Searches
    ';n.forEach(function(e){i+=""}),i+="
    ",t.innerHTML=i,t.classList.add("active")}else t.classList.remove("active"),t.innerHTML="";return void(o&&(o.style.display=""))}e=e.toLowerCase(),o.style.display="none",t.classList.add("active");let a=[];for(const t of ee)(t.title.toLowerCase().includes(e)||t.keywords.includes(e)||t.desc.toLowerCase().includes(e))&&a.push({key:t.id,title:t.title,cat:"⚡ App",match:t.desc,action:t.action});let r=[];for(const[t,o]of Object.entries(CHANNELS))(o.title.toLowerCase().includes(e)||o.desc.toLowerCase().includes(e))&&r.push({key:t,title:o.title,cat:o.cat,match:"Channel match"});ie([...a,...r],t),clearTimeout(Z),Z=setTimeout(async()=>{await async function(){if(K)return;const e=Object.entries(CHANNELS).map(async([e,t])=>{if(G[e])$[e]=G[e];else try{const o=await fetch(t.file),n=await o.json();G[e]=n,$[e]=n}catch(e){}});await Promise.all(e),K=!0}();let o=[];for(const[t,n]of Object.entries($)){const i=CHANNELS[t];if(!i)continue;if(r.some(e=>e.key===t))continue;const a=n.msgs||[];for(let n=0;n0?"...":"")+r.text.substring(s,a+e.length+30).replace(/<[^>]+>/g,"")+"...";o.push({key:t,title:i.title,cat:i.cat,match:c,msgIdx:n});break}}}ie([...a,...r,...o],t)},500)}const oe=[{q:"What is Bitcoin?",icon:"💰",reason:"Most asked"},{q:"Lightning Network",icon:"⚡",reason:"Trending"},{q:"How to buy Bitcoin",icon:"🛒",reason:"Popular"},{q:"Self-custody wallets",icon:"🔐",reason:"Essential"},{q:"Bitcoin vs Ethereum",icon:"🆚",reason:"Hot topic"},{q:"Why 21 million?",icon:"🔢",reason:"Fundamental"},{q:"Mining explained",icon:"⛏️",reason:"Technical"},{q:"Bitcoin security",icon:"🛡️",reason:"Important"}];function ne(){var e=document.getElementById("searchResults");if(e){var t='
    🔥 Trending Topics
    ';oe.forEach(function(e){t+=""}),t+="
    ",e.innerHTML=t,e.classList.add("active")}}function ie(e,t){0!==e.length?t.innerHTML=e.slice(0,30).map(e=>{const t=e.key&&e.key.startsWith("_");return'
    "+e.cat+"
    "+e.title+'
    '+e.match+"
    "}).join(""):t.innerHTML='
    No results found
    Try: "Lightning Network" or "What is Bitcoin?"
    '}function ae(e,t){var o=document.getElementById("searchOverlayInput"),n=document.getElementById("searchInput"),i=o&&o.value||n&&n.value||"";!function(e){if(e&&!(e.length<2)){var t=safeJSON("btc_recent_searches",[]);(t=t.filter(function(t){return t.toLowerCase()!==e.toLowerCase()})).unshift(e.length>40?e.substring(0,40):e),t.length>10&&(t=t.slice(0,10)),localStorage.setItem("btc_recent_searches",JSON.stringify(t))}}(i),n&&(n.value=""),o&&(o.value=""),document.getElementById("searchOverlay").style.display="none",te(""),"number"==typeof t&&t>=0&&(window._searchScrollTarget={channel:e,msgIdx:t,query:i}),go(e)}window._tryScrollToSearchResult=function(){var e=window._searchScrollTarget;if(e){var t=e.msgIdx;if(e.query,window._searchScrollTarget=null,t>=(o()?20:50)&&"function"==typeof window.loadMoreMsgs)for(var n=0;!document.getElementById("msg-"+t)&&document.getElementById("loadMoreBtn")&&n<50;)window.loadMoreMsgs(),n++;var i=document.getElementById("msg-"+t);i&&setTimeout(function(){i.scrollIntoView({behavior:"smooth",block:"center"}),i.style.transition="background 0.3s, box-shadow 0.3s",i.style.background="rgba(249,115,22,0.12)",i.style.boxShadow="inset 3px 0 0 #f97316",i.style.borderRadius="8px",setTimeout(function(){i.style.background="",i.style.boxShadow="",i.style.borderRadius=""},3e3)},300)}},function(){const e=document.getElementById("visitCount");setTimeout(function(){if("undefined"==typeof firebase||!firebase.firestore)return;const t=firebase.firestore(),o=(new Date).toISOString().split("T")[0];for(var n=[screen.width,screen.height,screen.colorDepth,Intl.DateTimeFormat().resolvedOptions().timeZone,navigator.language,navigator.hardwareConcurrency||0,navigator.platform].join("|"),i=0,a=0;a{a.textContent="Submit Suggestion",a.disabled=!1},3e3)}catch(e){i.innerHTML='Error submitting. Please try again.',a.textContent="Submit Suggestion",a.disabled=!1}}else i.innerHTML='Please enter a suggestion!'},function(){const e=Object.keys(CHANNELS),t=new Date,o=e[Math.floor((t-new Date(t.getFullYear(),0,0))/864e5)%e.length],n=CHANNELS[o];if(n){const e=document.getElementById("dailyChannel");e.innerHTML='
    📅 Channel of the Day
    '+n.title+'
    '+n.desc+"
    ",e.onclick=()=>go(o)}}(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof renderExplorationMap&&renderExplorationMap(),window.innerWidth>900&&document.getElementById("main").addEventListener("scroll",function(){const e=this;document.getElementById("backToTop").classList.toggle("visible",e.scrollTop>400);var t=e.scrollTop+e.clientHeight>=e.scrollHeight-200;document.getElementById("scrollToBottom").classList.toggle("visible",!t)}),window._launchPVP=function(){if("function"==typeof enterPVPMode)enterPVPMode();else{"function"==typeof window._loadDeferred&&window._loadDeferred(),"function"==typeof showToast&&showToast("⚔️ Loading PVP arena...");var e=0,t=setInterval(function(){e++,"function"==typeof enterPVPMode?(clearInterval(t),enterPVPMode()):e>15&&(clearInterval(t),"function"==typeof showToast&&showToast("⚠️ PVP failed to load — try refreshing the page"))},200)}},window.toggleAppsMenu=function(e){e&&e.stopPropagation();var t=document.getElementById("appsMenu");if(t&&"block"===t.style.display)t.style.display="none";else{t&&t.remove();var o=safeJSON("btc_visited_channels",[]).length,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i=void 0!==auth?auth:null,a=i&&i.currentUser,r=a&&-1!==["needcreations@gmail.com","info.603btc@gmail.com"].indexOf(a.email||""),s="function"==typeof getOnboardingProfile?getOnboardingProfile():null,c=s&&("advanced"===s.level||"full"===s.level)||r||a&&!a.isAnonymous||n>=10||o>=10,l=c||n>=5||o>=5,d="padding:15px;background:var(--card-bg);border:1px solid var(--border);border-radius:16px;color:var(--text);font-size:0.85rem;font-weight:700;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:8px;transition:0.2s;",u=d+"opacity:0.45;filter:grayscale(0.8);cursor:help;",p={"Nacho Mode":"Chat with our AI Bitcoin tutor","Proof of Play":"Bitcoin gaming hub — Arcade + PVP","Pleb Talk":"Community discussion board for Bitcoin topics","Lightning Mart":"Buy and sell with Lightning sats","IRL Sync":"Find or host local Bitcoin meetups","Bitcoin Beats":"Community music player","Timechain TV":"21 channels of Bitcoin video content","Proof of Walk":"Earn XP by walking — connect Strava","Proof of Play":"Bitcoin gaming hub — Arcade + PVP"},m=!(l||n>=3||o>=3),g=!l,h=!c,f="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Bitcoin Beats!",y="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Pleb Talk!",v="🔒 Explore "+Math.max(0,5-o)+" more topics to unlock IRL Sync!",b="🔒 Explore "+Math.max(0,10-o)+" more topics or sign in to unlock Lightning Mart!",w='";document.body.insertAdjacentHTML("beforeend",w);var x=document.getElementById("appsMenu");document.addEventListener("click",function(e){"block"!==x.style.display||x.contains(e.target)||(x.style.display="none")}),x.style.display="block","function"==typeof playSound&&playSound("pop")}function k(e,t,o,n,i){var a=p[t]||t;return n?"":""}},window.showProofOfWalk=function(){var e=document.getElementById("appsMenu");e&&(e.style.display="none");var t=document.getElementById("main");t&&(t.innerHTML='
    ',window.renderProofOfWalk&&window.renderProofOfWalk())},window.toggleSidebarMenu=function(e){var t=document.getElementById(e);t&&("flex"===t.style.display||"grid"===t.style.display||"block"===t.style.display?t.style.display="none":(e.includes("Flash")?t.style.display="flex":e.includes("homeAppsMenu")?t.style.display="grid":(t.style.display="flex",t.style.flexDirection="column"),"function"==typeof playSound&&playSound("pop")))},window.onload=()=>{"true"!==localStorage.getItem("btc_nacho_mode_default")||window.location.hash||setTimeout(function(){"function"==typeof enterNachoMode&&enterNachoMode()},1500),safeJSON("btc_visited_channels",[]).forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})}),l(),R(),"function"==typeof checkPredictionResult&&setTimeout(checkPredictionResult,4e3);var e=window.location.hash||"";history.state||(history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname+e)),window.addEventListener("popstate",function(e){var t=e.state||{},o=location.hash.slice(1);if(o||"function"!=typeof _parseCleanUrl||(o=_parseCleanUrl()||""),!e.state||t.guard)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);if(!e.state&&!o)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);var n=document.getElementById("notifPanel");if(n&&"translateY(0px)"===n.style.transform)"function"==typeof toggleNotifOverlay&&toggleNotifOverlay();else if(window._chatOverlayOpen)"function"==typeof toggleChatOverlay&&toggleChatOverlay();else{var i=document.getElementById("usernameModal");if(i&&i.classList.contains("open"))return i.classList.remove("open"),void("function"==typeof window._restoreSignUpForm&&window._restoreSignUpForm());var a=document.getElementById("mobileLearnMenu");if(a)a.remove();else{var r=document.getElementById("appsMenu");if(r&&"block"===r.style.display)r.style.display="none";else{var s=document.getElementById("questModal");if(s&&s.classList.contains("open"))s.classList.remove("open");else if(t.returnToGuide)"function"==typeof showGuide&&(showGuide(),setTimeout(function(){var e=document.getElementById("guideOverlay");if(e&&window._guideScrollTop){var t=e.querySelector('div[style*="border-radius:24px"]');t&&(t.scrollTop=window._guideScrollTop)}},500));else{for(var c=["guideOverlay","onboardingOverlay","pvpNameOverlay","pvpOverlay","tipOverlay","donateModal","lnAuthModal","nostrAuthOverlay","spinModal","hostEventModal","eventDetailOverlay","editEventOverlay","nachoColorPicker","articleLinkDialog","articleImageDialog","eli5Prompt","kbHelpModal","forumRulesOverlay","chatRulesOverlay","marketRulesOverlay","irlRulesOverlay"],l=0;l30&&clearInterval(o)},300)},1500)},function(){function e(){var e=window.location.hash.replace("#","");if(e||"function"!=typeof _parseCleanUrl||(e=_parseCleanUrl()||""),e){console.log("[ROUTE] Routing to:",e);var t=0;setTimeout(function o(){if(t>8e3)console.warn("[HASH] Gave up routing to:",e);else{if(!document.getElementById("msgs")||!document.getElementById("home"))return t+=200,void setTimeout(o,200);switch(e){case"nacho":if("function"==typeof enterNachoMode)return void enterNachoMode();break;case"pvp":if("function"==typeof enterPVPMode)return void enterPVPMode();break;case"forum":if("function"==typeof go)return void go("forum");break;case"marketplace":if("function"==typeof go)return void go("marketplace");break;case"first-purchase":case"buy":if("function"==typeof go)return void go("first-purchase");break;case"trails":case"learn":case"modules":if("function"==typeof go)return void go("trails");break;case"meetup-builder":if(window._mbRouted)return;if("function"==typeof go){window._mbRouted=!0,window._skipIRLRules=!0,localStorage.setItem("btc_irl_rules_accepted","true"),go("irl-sync"),setTimeout(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove()},100),history.replaceState({channel:"meetup-builder"},"","#meetup-builder");var n=0,i=setInterval(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove();var t=document.getElementById("meetupBuilderSection");t&&(clearInterval(i),t.scrollIntoView({behavior:"smooth",block:"start"})),++n>30&&clearInterval(i)},300);return}break;case"irl-sync":case"meet":if("function"==typeof go)return void go("irl-sync");break;case"bitcoin-beats":if("function"==typeof go)return void go("bitcoin-beats");break;case"chat":if("function"==typeof renderChatHub)return void renderChatHub("global");break;case"dms":if("function"==typeof renderChatHub)return void renderChatHub("dms");if("function"==typeof openDMInbox)return void openDMInbox();if("function"==typeof showInbox)return void showInbox();break;case"lightning":if("function"==typeof go)return void go("lightning");break;case"timechain-tv":case"tv":if("function"==typeof go)return void go("timechain-tv");break;case"pow-support":if("function"==typeof renderPOWSupport)return void renderPOWSupport();break;case"quests":if("function"==typeof showQuestHub)return void showQuestHub();break;case"dashboard":case"bitcoin-dashboard":case"metrics":case"network":if("function"==typeof toggleDashboard)return history.replaceState({home:!0},"",window.location.pathname),void toggleDashboard();break;default:if(0===e.indexOf("beats/")&&"function"==typeof go&&!window._beatsRouted){if(0===e.indexOf("beats/playlist/")){var a=e.replace("beats/playlist/","").split("/");2===a.length&&(window._beatsDeepLink={type:"playlist",ownerUid:a[0],playlistId:a[1]})}else{var r=e.replace("beats/","");r&&-1===r.indexOf("/")&&(window._beatsDeepLink={type:"track",trackId:r})}return window._beatsRouted=!0,void go("bitcoin-beats")}if(0===e.indexOf("beats/")&&window._beatsRouted)return;if(0===e.indexOf("cert/")&&"function"==typeof go)return void go(e);if("function"==typeof go&&void 0!==CHANNELS&&CHANNELS[e])return void go(e)}t+=200,setTimeout(o,200)}},500)}}e(),window.addEventListener("load",function(){setTimeout(function(){var t=window.location.hash.replace("#","");t&&document.getElementById("home")&&!document.getElementById("home").classList.contains("hidden")&&(console.log("[HASH] Post-load fallback routing to:",t),e())},800)}),window.addEventListener("hashchange",e)}(),void 0!==r&&(window.toggleCat=r),void 0!==n&&(window.toggleTheme=n),void 0!==Y&&(window.toggleAudio=Y),void 0!==J&&(window.setVolume=J),void 0!==A&&(window.handleSupportClick=A),"undefined"!=typeof showDonateModal&&(window.showDonateModal=showDonateModal),"undefined"!=typeof enterNachoMode&&(window.enterNachoMode=enterNachoMode),"undefined"!=typeof goHome&&(window.goHome=goHome),void 0!==b&&(window.goRandom=b),void 0!==k&&(window.goRandomArt=k),void 0!==x&&(window.goRandomMeme=x),void 0!==T&&(window.goRandomGraphic=T),void 0!==te&&(window.doSearch=te),void 0!==ne&&(window.showTrendingTopics=ne),void 0!==ae&&(window.selectResult=ae),void 0!==i&&(window.toggleMenu=i),void 0!==a&&(window.toggleSidebarCollapse=a),void 0!==t&&(window.openImg=t),void 0!==d&&(window.toggleFav=d),void 0!==B&&(window.shareNostr=B),void 0!==C&&(window.copyLink=C),void 0!==g&&(window.toggleGallery=g),void 0!==h&&(window.renderContent=h),"undefined"!=typeof showBeginnerGuide&&(window.showBeginnerGuide=showBeginnerGuide),void 0!==y&&(window.loadTweetEmbed=y)}(),window._spinSoundCtx=null,window.playSpinTick=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx,t=e.createOscillator(),o=e.createGain();t.connect(o),o.connect(e.destination),t.frequency.value=800+400*Math.random(),t.type="triangle",o.gain.value=.08,o.gain.exponentialRampToValueAtTime(.001,e.currentTime+.08),t.start(e.currentTime),t.stop(e.currentTime+.08)}catch(e){}},window._tctvTimer=null,window._tctvMinutesSession=0,window._tctvStartTracker=function(){if(!window._tctvTimer){window._tctvMinutesSession=0;try{var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_tctv_visited_"+e,"true")}catch(e){}console.log("[TCTV] Watch tracker started."),window._tctvTimer=setInterval(function(){if("timechain-tv"===(window.currentChannelId||"")){if(!document.hidden){var e=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")+1;localStorage.setItem("btc_tctv_watch_time",e.toString()),window._tctvMinutesSession++;try{var t=(new Date).toISOString().split("T")[0],o=parseInt(localStorage.getItem("btc_tctv_minutes_"+t)||"0")+1;localStorage.setItem("btc_tctv_minutes_"+t,String(o))}catch(e){}console.log("[TCTV] Watch time:",e,"min (Session:",window._tctvMinutesSession,"min)");try{void 0!==db&&"undefined"!=typeof firebase&&void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("stats").doc("global").set({watchTimeMinutes:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}e%10==0?("function"==typeof awardPoints&&awardPoints(10,"tctv_watch_10m"),"function"==typeof checkBadges&&checkBadges(),"function"==typeof showToast&&showToast("👁️ +10 Points — Thanks for watching Timechain TV!")):1===e&&"function"==typeof showToast&&showToast("📺 Watching Timechain TV — Points awarded every 10 min!")}}else window._tctvStopTracker()},6e4)}},window._tctvStopTracker=function(){window._tctvTimer&&(clearInterval(window._tctvTimer),window._tctvTimer=null,console.log("[TCTV] Watch tracker stopped. Total minutes watched:",window._tctvMinutesSession))},window._updateSEO=function(e,t,o){if(e){document.title=(t?t+" | ":"")+"Bitcoin Education Archive";var n=document.querySelector('link[rel="canonical"]');if(n){var i="home"===e||"/"===e?"":"/app/"+e;n.setAttribute("href","https://bitcoineducation.quest"+i)}var a=document.querySelector('meta[name="description"]');a&&o&&a.setAttribute("content",o.substring(0,160));var r=window._cleanUrl(e);window.location.href.includes(r)||history.replaceState({channel:e},"",r)}},window.playSpinWin=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx;[523,659,784,1047].forEach(function(t,o){var n=e.createOscillator(),i=e.createGain();n.connect(i),i.connect(e.destination),n.frequency.value=t,n.type="sine",i.gain.value=.1,i.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15*(o+1)+.3),n.start(e.currentTime+.15*o),n.stop(e.currentTime+.15*(o+1)+.3)})}catch(e){}},window._aiToolsOpen=!1,window.toggleAITools=function(){var e=document.getElementById("aiToolsPanel");if(!e){(e=document.createElement("div")).id="aiToolsPanel",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:250000;background:var(--bg,#0a0a0f);border-top:2px solid var(--accent,#f7931a);border-radius:16px 16px 0 0;transform:translateY(100%);transition:transform 0.3s ease;box-shadow:0 -10px 40px rgba(0,0,0,0.6);",e.innerHTML='
    🤖AI Toolspowered by PPQ
    ',document.body.appendChild(e);var t=document.createElement("style");t.id="aiToolsPanelCSS",t.textContent="@media(min-width:901px){#aiToolsPanel{max-width:480px;right:16px;left:auto;border-radius:16px 16px 0 0;}}@media(max-width:900px){#aiToolsPanel iframe{height:calc(70vh - 56px);}}",document.head.appendChild(t)}window._aiToolsOpen=!window._aiToolsOpen,e.style.transform=window._aiToolsOpen?"translateY(0)":"translateY(100%)";var o=document.getElementById("aiToolsBtn");if(o&&(o.style.background=window._aiToolsOpen?"var(--card-bg)":"linear-gradient(135deg,#6366f1,#8b5cf6)",o.style.borderColor=window._aiToolsOpen?"var(--accent)":"transparent"),window._aiToolsOpen&&void 0!==db&&db)try{var n=auth&&auth.currentUser?auth.currentUser.uid:"anon_"+(localStorage.getItem("visitorId")||"unknown");db.collection("ai_tools_opens").add({uid:n,openedAt:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){console.warn("[AI Tools] tracking error",e)}},function(){function e(){if(!document.getElementById("aiToolsBtn")){var e=document.createElement("button");e.id="aiToolsBtn",e.onclick=toggleAITools,e.title="AI Tools",e.setAttribute("aria-label","Open AI Tools"),e.style.cssText="position:fixed;bottom:10px;right:132px;z-index:200001;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;border:2px solid transparent;border-radius:50%;width:48px;height:48px;font-size:1.4rem;cursor:pointer;font-family:inherit;box-shadow:0 4px 20px rgba(99,102,241,0.4);display:flex;align-items:center;justify-content:center;transition:0.2s;-webkit-transform:translateZ(0);transform:translateZ(0);",e.innerHTML="🤖",document.body.appendChild(e);var t=document.getElementById("aiToolsBtnCSS");t||((t=document.createElement("style")).id="aiToolsBtnCSS",t.textContent="@media(max-width:900px){#aiToolsBtn{bottom:70px!important;right:128px!important;}}",document.head.appendChild(t))}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}(),function(){var e=window.renderBitcoinBeats;e&&(window.renderBitcoinBeats=function(){e(),setTimeout(function(){document.getElementById("beatsLoader");var e=document.getElementById("beatsEmbedArea");if(e){var t=e.querySelector("iframe"),o=e.querySelector(".twitter-tweet-rendered, twitter-widget");t||o||(e.innerHTML='
    🎸
    Stream Unavailable
    The live stream couldn\'t be loaded. Check out these great Bitcoin audio sources instead:
    ')}},8e3)})}(),void 0===window.contactSeller&&(window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to contact sellers!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==db&&db.collection("marketplace").doc(e).get().then(function(e){if(e.exists){var t=e.data(),o=t.sellerUid;o!==auth.currentUser.uid?("function"==typeof openDM?openDM(o,t.sellerName||"Seller"):"function"==typeof showInbox&&(showInbox(),setTimeout(function(){"function"==typeof startNewDM&&startNewDM(o,t.sellerName||"Seller")},500)),void 0!==db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1),"function"==typeof showToast&&showToast("💬 Opening chat with "+(t.sellerName||"seller")+"...")):"function"==typeof showToast&&showToast("That's your own listing!")}})}),window.handleMktImageUploadV2=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var o=document.getElementById("mktImagePreview"),n=document.getElementById("mktImagePreviewImg");if(o&&(o.style.display="block",n&&(n.src=""),o.innerHTML='
    📤 Uploading...
    '),"undefined"!=typeof firebase&&firebase.storage){var i=firebase.storage().ref(),a="marketplace/"+auth.currentUser.uid+"/"+Date.now()+"_"+t.name.replace(/[^a-zA-Z0-9.]/g,"_"),r=i.child(a).put(t,{contentType:t.type});r.on("state_changed",function(e){var t=Math.round(e.bytesTransferred/e.totalBytes*100);o&&(o.innerHTML='
    📤 Uploading... '+t+"%
    ")},function(t){"function"==typeof showToast&&showToast("Upload failed: "+t.message),o&&(o.style.display="none"),handleMktImageUpload(e)},function(){r.snapshot.ref.getDownloadURL().then(function(e){window._mktUploadedImage=e,o&&n&&(o.innerHTML=''),"function"==typeof showToast&&showToast("✅ Image uploaded!")})})}else"function"==typeof handleMktImageUpload&&handleMktImageUpload(e)}else"function"==typeof showToast&&showToast("Sign in to upload images")},function(){var e=[{type:"youtube",id:"UvSnC7P-m-U",title:"What is Bitcoin? — Andreas Antonopoulos",desc:"The best intro talk ever given"},{type:"youtube",id:"l1si5ZWLgy0",title:"Bitcoin for Beginners — BTC Sessions",desc:"Step-by-step Bitcoin guide"},{type:"youtube",id:"ZKwqNgG-Sv4",title:"The Bitcoin Standard — Saifedean Ammous",desc:"Author presentation on sound money"},{type:"youtube",id:"2pDlaOGA2ac",title:"How Bitcoin Works Under the Hood",desc:"Technical deep-dive"},{type:"youtube",id:"bBC-nXj3Ng4",title:"But How Does Bitcoin Actually Work?",desc:"3Blue1Brown explains"},{type:"youtube",id:"Gc2en3nHxA4",title:"Michael Saylor on Why Bitcoin",desc:"The macro case for Bitcoin"},{type:"youtube",id:"xLYhx1z7gC4",title:"This Machine Greens — Bitcoin & Energy",desc:"Bitcoin mining documentary"},{type:"youtube",id:"HCLWDGYnAzk",title:"Running a Bitcoin Node — Ministry of Nodes",desc:"How to verify for yourself"}];window.beatsPlaylistIndex=parseInt(localStorage.getItem("btc_beats_idx")||"0")%e.length,window.renderBeatsPlaylist=function(t){if(t){var o=e[window.beatsPlaylistIndex],n=e.length,i=window.beatsPlaylistIndex,a='
    ';a+='
    ',a+='
    '+o.title+'
    '+o.desc+" • "+(i+1)+"/"+n+'
    ',t.innerHTML=a}},window.beatsNav=function(t){window.beatsPlaylistIndex=(window.beatsPlaylistIndex+t+e.length)%e.length,localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var o=document.getElementById("beatsEmbedArea");o&&renderBeatsPlaylist(o)},window.beatsNavRandom=function(){window.beatsPlaylistIndex=Math.floor(Math.random()*e.length),localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var t=document.getElementById("beatsEmbedArea");t&&renderBeatsPlaylist(t)};var t=8e3,o=setInterval(function(){var e=document.getElementById("beatsEmbedArea");e&&(document.getElementById("beatsLoader")?(t-=500)<=0&&(clearInterval(o),renderBeatsPlaylist(e)):clearInterval(o))},500)}(),window.fuzzyMatch=function(e,t){if(!t||!e)return!0;var o=e.toLowerCase();return t.toLowerCase().split(/\s+/).every(function(e){return-1!==o.indexOf(e)})},function(){function e(){return!(!auth||!auth.currentUser)&&"needcreations@gmail.com"===(auth.currentUser.email||"")}window.forumEditPost=function(t){auth&&auth.currentUser&&void 0!==db&&db.collection("forum_posts").doc(t).get().then(function(o){if(o.exists){var n=o.data();if(n.authorId===auth.currentUser.uid||e()){var i=n.createdAt?n.createdAt.toDate():new Date;if(Date.now()-i.getTime()>9e5&&!e())"function"==typeof showToast&&showToast("Posts can only be edited within 15 minutes of creation");else{var a='
    ✏️ Edit Post
    Edited posts will show an "edited" indicator
    ',r=document.createElement("div");r.innerHTML=a,document.body.appendChild(r.firstChild)}}else"function"==typeof showToast&&showToast("You can only edit your own posts")}})},window.forumSaveEdit=function(e){var t=(document.getElementById("editPostTitle").value||"").trim(),o=(document.getElementById("editPostBody").value||"").trim();!t||t.length<5?"function"==typeof showToast&&showToast("Title must be at least 5 characters"):"function"!=typeof isCleanText||isCleanText(t+" "+o)?db.collection("forum_posts").doc(e).update({title:t.substring(0,120),body:o.substring(0,2e3),editedAt:firebase.firestore.FieldValue.serverTimestamp(),edited:!0}).then(function(){var t=document.getElementById("forumEditOverlay");t&&t.remove(),"function"==typeof showToast&&showToast("✅ Post updated!"),"function"==typeof forumViewPost&&forumViewPost(e,!0)}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))}):"function"==typeof showToast&&showToast("Post contains inappropriate language")}}(),function(){var e=[{level:1,name:"Just Met",emoji:"🦌",threshold:1},{level:2,name:"Getting Acquainted",emoji:"👋",threshold:10},{level:3,name:"Good Friends",emoji:"😊",threshold:100},{level:4,name:"Close Friends",emoji:"🧡",threshold:350},{level:5,name:"Best Buds",emoji:"💛",threshold:750}],t=window.trackNachoInteraction;t&&(window.trackNachoInteraction=function(){for(var o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),n=0,i=e.length-1;i>=0;i--)if(o>=e[i].threshold){n=e[i].level;break}t();for(var a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r=0,s=null,c=e.length-1;c>=0;c--)if(a>=e[c].threshold){r=e[c].level,s=e[c];break}if(r>n&&s){var l=JSON.parse(localStorage.getItem("btc_nacho_level_celebrated")||"[]");-1===l.indexOf(s.level)&&(l.push(s.level),localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(l)),"function"==typeof syncCelebratedState&&syncCelebratedState(),setTimeout(function(){var e="function"==typeof nachoUserName?nachoUserName():"",t=s.emoji+" "+(e?e+", w":"W")+"e just became "+s.name+"! "+(s.level>=3?"New closet items are now available! Check the Closet! 👔✨":"Keep chatting with me to unlock more! 🦌");"function"==typeof forceShowBubble?(forceShowBubble(t),s.level>=3&&setTimeout(function(){var e=document.getElementById("nacho-bubble");e&&(e.style.cursor="pointer",e.onclick=function(){e.classList.remove("show"),window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},300)})},100)):"function"==typeof showToast&&showToast("🦌 Friendship Level Up: "+s.emoji+" "+s.name+"!")},1e3))}})}(),function(){var e=[],t=!1,o=0;function n(){if(!t&&0!==e.length){var i=Date.now();if(i-o<3e4)setTimeout(n,3e4-(i-o)+100);else{t=!0;var a=e.shift();o=i;try{a.show()}catch(e){console.log("Notification error:",e)}setTimeout(function(){t=!1,n()},5e3)}}}window.queueNotification=function(t,o){e.push({type:t,show:o,queued:Date.now()}),n()};var i=window.showToast;i&&(window.showToastQueued=function(e){queueNotification("toast",function(){i(e)})})}(),window.initMiniPlayer=function(){if(!document.getElementById("miniPlayer")){var e=document.createElement("div");e.id="miniPlayer",e.style.cssText="position:fixed;bottom:60px;left:0;right:0;z-index:180;background:rgba(10,10,10,0.95);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-top:1px solid rgba(247,147,26,0.3);padding:8px 16px;display:none;align-items:center;gap:12px;",e.innerHTML='
    Not playing
    Bitcoin Beats
    ',document.body.appendChild(e)}},window._miniPlayerAudio=null,window.playInMiniPlayer=function(e,t,o){initMiniPlayer();var n=document.getElementById("miniPlayer");n&&(window._miniPlayerAudio&&window._miniPlayerAudio.pause(),window._miniPlayerAudio=new Audio(e),window._miniPlayerAudio.play().catch(function(){}),document.getElementById("mpTitle").textContent=t||"Playing...",document.getElementById("mpArtist").textContent=o||"Bitcoin Beats",document.getElementById("mpPlayPause").textContent="⏸",n.style.display="flex")},window.toggleMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.paused?(window._miniPlayerAudio.play(),document.getElementById("mpPlayPause").textContent="⏸"):(window._miniPlayerAudio.pause(),document.getElementById("mpPlayPause").textContent="▶"))},window.closeMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.pause(),window._miniPlayerAudio=null);var e=document.getElementById("miniPlayer");e&&(e.style.display="none")},function(){var e=2592e6;window.isListingExpired=function(t){if(!t||!t.createdAt)return!1;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt);return Date.now()-o.getTime()>e},window.renewListing=function(e){auth&&auth.currentUser&&void 0!==db&&db.collection("marketplace").doc(e).update({createdAt:firebase.firestore.FieldValue.serverTimestamp(),renewed:!0,renewedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){"function"==typeof showToast&&showToast("✅ Listing renewed for 30 more days!"),"function"==typeof renderMarketplace&&renderMarketplace({listingId:e})}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))})},window.getExpiryStatus=function(t){if(!t||!t.createdAt)return null;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt),n=Date.now()-o.getTime(),i=Math.max(0,Math.ceil((e-n)/864e5));return i<=0?{status:"expired",text:"This listing has expired",color:"#ef4444"}:i<=5?{status:"expiring",text:"Expires in "+i+" day"+(1!==i?"s":""),color:"#eab308"}:null}}(),window.renderSellerReputation=function(e,t){e&&t&&void 0!==db&&db.collection("users").doc(e).get().then(function(e){if(e.exists){var o=e.data(),n=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):null,i=n?n.toLocaleDateString("en-US",{month:"short",year:"numeric"}):"Unknown",a="function"==typeof getLevel?getLevel(o.points||0):{emoji:"🟢",name:"Normie"},r='
    '+a.emoji+" "+a.name+'📅 Member since '+i+""+(o.forumPosts?'💬 '+o.forumPosts+" posts":"")+(o.marketListings?'🛒 '+o.marketListings+" listings":"")+"
    ";t.innerHTML+=r}}).catch(function(){})},function(){var e="btc_forum_draft",t="btc_forum_reply_",o=null;window.saveForumDraft=function(){var t=document.getElementById("forumNewTitle"),o=document.getElementById("forumNewBody"),n=document.getElementById("forumNewCategory");if(t||o){var i={title:t?t.value:"",body:o?o.value:"",category:n?n.value:"general",savedAt:Date.now()};localStorage.setItem(e,JSON.stringify(i))}},window.restoreForumDraft=function(){try{var t=JSON.parse(localStorage.getItem(e));return!t||Date.now()-t.savedAt>864e5?null:t}catch(e){return null}},window.clearForumDraft=function(){localStorage.removeItem(e)},window.saveReplyDraft=function(e){var o=document.getElementById("forumReplyInput");o&&o.value.trim()?localStorage.setItem(t+e,o.value):localStorage.removeItem(t+e)},window.restoreReplyDraft=function(e){return localStorage.getItem(t+e)||""},window.clearReplyDraft=function(e){localStorage.removeItem(t+e)};var n=new MutationObserver(function(){var e=document.getElementById("forumNewTitle"),t=document.getElementById("forumNewBody");if(e&&!e._draftBound){e._draftBound=!0,e.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)});var n=restoreForumDraft();n&&(n.title||n.body)&&(e.value=n.title||"",t&&(t.value=n.body||""),"function"==typeof showToast&&showToast("📝 Draft restored"))}t&&!t._draftBound&&(t._draftBound=!0,t.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)}));var i=document.getElementById("forumReplyInput");if(i&&!i._draftBound&&"undefined"!=typeof forumCurrentPost&&forumCurrentPost){i._draftBound=!0;var a=forumCurrentPost.id,r=restoreReplyDraft(a);r&&(i.value=r),i.addEventListener("input",function(){clearTimeout(o),o=setTimeout(function(){saveReplyDraft(a)},3e3)})}});document.body?n.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",function(){n.observe(document.body,{childList:!0,subtree:!0})})}(),window.isCleanTextV2=function(e){if(!e)return!0;for(var t=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","faggot","retard","nazi","hitler","kkk","porn","hentai","rape","pedo","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","jap","paki","wop","slut","whore","cum","dildo","tits","nude","naked","milf","molest","suicide","terrorist","jihad","genocide","lynch","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","supremacy","acab","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","erection","ejaculat","deepthroat","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes"],o=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g,"").split(/\s+/),n=0;n=4&&-1!==o[n].indexOf(t[i]))return!1}return!0},void 0!==window.isCleanText&&(window._origIsCleanText=window.isCleanText,window.isCleanText=window.isCleanTextV2),function(){var e=document.createElement("style");e.id="ux-patch-styles",e.textContent="\n /* Modal overlay */\n .modal-overlay {\n position: fixed; inset: 0;\n background: rgba(0,0,0,0.7);\n backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);\n z-index: 9999;\n display: flex; align-items: center; justify-content: center;\n padding: 16px;\n }\n /* Modal card */\n .modal-card {\n background: var(--bg-side, #1a1a2e);\n border: 1px solid rgba(255,255,255,0.1);\n border-radius: 24px;\n padding: 24px;\n max-width: 480px; width: 100%;\n max-height: 85vh; overflow-y: auto;\n box-shadow: 0 20px 60px rgba(0,0,0,0.5);\n animation: fadeSlideIn 0.3s;\n -webkit-overflow-scrolling: touch;\n }\n /* Pill button */\n .pill-btn {\n padding: 6px 14px;\n border-radius: 20px;\n border: 1px solid var(--border);\n background: var(--card-bg);\n color: var(--text-muted);\n font-size: 0.75rem;\n cursor: pointer;\n font-family: inherit;\n white-space: nowrap;\n font-weight: 600;\n transition: 0.2s;\n }\n .pill-btn.active {\n border-color: var(--accent);\n background: var(--accent);\n color: #fff;\n }\n /* scroll-top-btn removed — using #backToTop in index.html */\n /* Badge progress bar */\n .badge-progress {\n width: 100%; height: 4px;\n background: rgba(255,255,255,0.1);\n border-radius: 2px;\n margin-top: 4px;\n overflow: hidden;\n }\n .badge-progress-fill {\n height: 100%;\n background: var(--accent);\n border-radius: 2px;\n transition: width 0.5s ease;\n }\n ",document.head.appendChild(e)}(),window.renderQuestDashboard=function(){if(void 0===QUESTION_BANK)return"";var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=parseInt(localStorage.getItem("btc_quests_completed")||"0"),o=Object.keys(QUESTION_BANK).filter(function(t){return-1!==e.indexOf(t)}),n=Object.keys(QUESTION_BANK).length;return'
    ⚔️
    Quest Progress
    '+t+' quests completed
    Channels with questions unlocked'+o.length+"/"+n+'
    Visit more topics to unlock new quests! Each topic you read adds its questions to your quest pool.
    '},window.renderBadgeWithProgress=function(e,t){var o="";if(!t&&e.progress&&"function"==typeof e.progress){var n=e.progress(),i=n.match(/(\d+)\/(\d+)/);if(i){var a=parseInt(i[1]),r=parseInt(i[2]);o='
    '+n+"
    "}}return'
    '+e.emoji+'
    '+e.name+'
    '+e.desc+"
    "+(t?'
    ✅ Earned!
    ':"")+o+"
    "},function(){function e(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;for(var o=[],n=0;n<=t.length;n++)o[n]=[n];for(var i=0;i<=e.length;i++)o[0][i]=i;for(n=1;n<=t.length;n++)for(i=1;i<=e.length;i++)t.charAt(n-1)===e.charAt(i-1)?o[n][i]=o[n-1][i-1]:o[n][i]=Math.min(o[n-1][i-1]+1,o[n][i-1]+1,o[n-1][i]+1);return o[t.length][e.length]}window.fuzzyChannelSearch=function(t,o){if(!t||!o)return[];var n=t.toLowerCase().trim().split(/\s+/),i=[];for(var a in o){var r=o[a],s=(r.name||r.title||a).toLowerCase(),c=(r.desc||"").toLowerCase(),l=s+" "+c+" "+a.replace(/-/g," "),d=0,u=0;n.forEach(function(t){if(-1!==s.indexOf(t))d+=10,u++;else if(-1!==l.indexOf(t))d+=5,u++;else if(t.length>3)for(var o=l.split(/\s+/),n=0;n0&&i.push({id:a,channel:r,score:d})}return i.sort(function(e,t){return t.score-e.score}),i}}(),console.log("✅ UX Patches loaded — 24 tasks from the UX Review Report"),new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e].concat(Array.from(e.querySelectorAll('.msg-text, .msg-body, [class*="msg"]'))):[e]).forEach(function(e){e.innerHTML&&-1!==e.innerHTML.indexOf("this Discord")&&(e.innerHTML=e.innerHTML.replace(/this Discord/g,"this App"))})})})}).observe(document.body,{childList:!0,subtree:!0}),function(){var e=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e,...e.querySelectorAll("img.msg-img")]:[e]).forEach(function(e){"IMG"===e.tagName&&e.classList.contains("msg-img")&&!e.dataset.blurUp&&(e.dataset.blurUp="1",e.style.filter="blur(8px)",e.style.transition="filter 0.4s ease",e.complete&&e.naturalWidth>0?e.style.filter="none":(e.addEventListener("load",function(){e.style.filter="none"},{once:!0}),e.addEventListener("error",function(){e.style.filter="none"},{once:!0})))})})})});document.getElementById("main")&&e.observe(document.getElementById("main"),{childList:!0,subtree:!0})}(),function(){var e="btc_nacho_convo_persist",t=window.nachoRemember;"function"==typeof t&&(window.nachoRemember=function(o,n){t(o,n);try{var i=JSON.parse(localStorage.getItem(e)||"[]");i.push({q:o,a:(n||"").substring(0,200),t:Date.now()}),i.length>20&&(i=i.slice(-20)),localStorage.setItem(e,JSON.stringify(i))}catch(e){}}),setTimeout(function(){if(void 0!==window._nachoConvoHistory&&0===window._nachoConvoHistory.length)try{var t=JSON.parse(localStorage.getItem(e)||"[]");if(t.length>0)for(var o=Math.max(0,t.length-5);ot.clientHeight?Math.round(t.scrollTop/(t.scrollHeight-t.clientHeight)*100):100;try{var n=JSON.parse(localStorage.getItem(e)||"{}");o>(n[window.currentChannelId]||0)&&(n[window.currentChannelId]=o,localStorage.setItem(e,JSON.stringify(n)))}catch(e){}},500))},{passive:!0}),window.getChannelProgress=function(t){try{return JSON.parse(localStorage.getItem(e)||"{}")[t]||0}catch(e){return 0}}}}(),function(){var e=0,t=!1;window.addEventListener("unhandledrejection",function(o){if(!(++e>10)){var n=o.reason&&o.reason.message?o.reason.message:"",i=o.reason&&o.reason.code?o.reason.code:"";console.error("[Error Boundary] Unhandled promise rejection:",n||o.reason),/permission.denied|Missing or insufficient|requires an index|PERMISSION_DENIED/i.test(n+i)||!t&&/network|fetch|Failed to fetch|UNAVAILABLE|unavailable/i.test(n+i)&&(t=!0,"function"==typeof showToast&&showToast("⚠️ Connection issue — some features may not work. Try refreshing."))}}),window.addEventListener("error",function(t){++e>5||console.error("[Error Boundary]",t.message,t.filename,t.lineno)})}(),function(){var e="btc_offline_channels";"function"!=typeof window.go||window._offlineCacheHooked||(window._offlineCacheHooked=!0,setInterval(function(){if(window.currentChannelId&&void 0!==CHANNELS){var t=CHANNELS[window.currentChannelId];if(t&&t.file)try{var o=JSON.parse(localStorage.getItem(e)||"{}");if(o[window.currentChannelId]&&Date.now()-o[window.currentChannelId].ts<864e5)return;"caches"in window&&caches.open("btc-offline-channels").then(function(e){e.add(t.file).catch(function(){})}),o[window.currentChannelId]={ts:Date.now()};var n=Object.keys(o);if(n.length>10){n.sort(function(e,t){return o[e].ts-o[t].ts});for(var i=0;iwindow.innerWidth-8&&(n=window.innerWidth-240-8),t.style.left=n+"px",t.style.width="240px",window.innerWidth>900?(t.style.top=o.top-8+"px",t.style.transform="translateY(-100%)"):(t.style.top=o.bottom+8+"px",t.style.transform="none")}}document.addEventListener("mouseover",function(t){var o=t.target.closest(".badge-item");o&&e(o)}),document.addEventListener("click",function(t){var o=t.target.closest(".badge-item");o&&e(o)})}(),function(){"use strict";function e(){var e=function(){if(void 0===window.NACHO_TRAILS)return null;var e=[];try{e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]")}catch(e){}var t={};try{t=JSON.parse(localStorage.getItem("btc_trail_progress")||"{}")}catch(e){}for(var o=0;o0){var r=document.createElement("div");if(r.className="ch-progress",r.style.cssText="position:absolute;bottom:0;left:0;height:2px;background:"+(i>=100?"#22c55e":"var(--accent,#f7931a)")+";width:"+Math.min(i,100)+"%;border-radius:0 1px 0 0;transition:width 0.3s;opacity:0.7;",t.style.position="relative",t.style.overflow="hidden",t.appendChild(r),i>=100&&!t.querySelector(".ch-done")){var s=document.createElement("span");s.className="ch-done",s.style.cssText="position:absolute;right:6px;top:50%;transform:translateY(-50%);font-size:0.6rem;opacity:0.5;",s.textContent="✓",t.appendChild(s)}}}})}catch(e){}}setTimeout(e,2e3);var t=window.goHome;t&&(window.goHome=function(){var o=t.apply(this,arguments);return setTimeout(e,500),o});var o=window.go;o&&(window.go=function(){var t=o.apply(this,arguments);return setTimeout(e,1e3),t}),window.updateSidebarProgress=e}(); \ No newline at end of file diff --git a/bundle.src.js b/bundle.src.js index 6680903ec..3b66fffc8 100644 --- a/bundle.src.js +++ b/bundle.src.js @@ -168,12 +168,13 @@ var PREMIUM_CONFIG = { // ============================================= const FIREBASE_CONFIG = { - apiKey: "AIzaSyDLwucmRxjoJp2KMBTi2ujf0mlVkgLHyKk", - authDomain: "bitcoin-education-archive.firebaseapp.com", - projectId: "bitcoin-education-archive", - storageBucket: "bitcoin-education-archive.firebasestorage.app", - messagingSenderId: "1055248200518", - appId: "1:1055248200518:web:6c6d64a5ee78e19bfbeb47" + apiKey: "AIzaSyCkUGX2KWaVGmSQXpYJhWDxF_BSiHRX6SM", + authDomain: "btc-archive-test.firebaseapp.com", + projectId: "btc-archive-test", + storageBucket: "btc-archive-test.firebasestorage.app", + messagingSenderId: "60810625669", + appId: "1:60810625669:web:ea4dacd55333e41429dfec", + measurementId: "G-7C2FKDJ8E4" }; // Levels @@ -29919,71 +29920,10 @@ console.log('✅ UX Patches loaded — 24 tasks from the UX Review Report'); // ---- PVP Answer: Server-Side Validation Override ---- // Routes pvpAnswer through Cloud Function instead of direct Firestore write +// REMOVED: Cloud function not used in current project (function() { 'use strict'; - var _origPvpAnswer = null; - function patchPvpAnswer() { - if (typeof window.pvpAnswer !== 'function') return; - if (window._pvpAnswerPatched) return; - window._pvpAnswerPatched = true; - _origPvpAnswer = window.pvpAnswer; - - window.pvpAnswer = function(questionIdx, answerIdx, btnEl) { - // Still do the UI updates from original (disable buttons, show colors) - var t = window._pvpState || {}; - if (t.answered) return; - t.answered = true; - if (t._questionTimeout) { clearTimeout(t._questionTimeout); t._questionTimeout = null; } - - // UI feedback - var questions = t.questions || []; - var q = questions[questionIdx]; - if (q && btnEl) { - var opts = btnEl.parentElement; - if (opts) { - var btns = opts.querySelectorAll('button'); - for (var i = 0; i < btns.length; i++) { - btns[i].disabled = true; - btns[i].style.cursor = 'default'; - btns[i].style.opacity = '0.7'; - } - if (btns[q.correct]) { - btns[q.correct].style.borderColor = '#22c55e'; - btns[q.correct].style.background = 'rgba(34,197,94,0.15)'; - btns[q.correct].style.opacity = '1'; - } - if (answerIdx >= 0 && answerIdx !== q.correct && btns[answerIdx]) { - btns[answerIdx].style.borderColor = '#ef4444'; - btns[answerIdx].style.background = 'rgba(239,68,68,0.15)'; - } - } - if (opts) opts.insertAdjacentHTML('afterend', '
    ' + (answerIdx === q.correct ? '✅ Correct! Waiting...' : answerIdx < 0 ? '⏰ Time\'s up!' : '❌ Wrong! Waiting...') + '
    '); - } - - // Submit via Cloud Function - if (typeof firebase !== 'undefined' && firebase.functions && t.matchId) { - firebase.functions().httpsCallable('pvpSubmitAnswer')({ - matchId: t.matchId, - questionIndex: questionIdx, - answerIndex: answerIdx - }).then(function(result) { - if (result.data && result.data.alreadyAnswered) { - console.log('[PVP] Already answered, idempotent'); - } - }).catch(function(err) { - console.error('[PVP] Server answer submission failed:', err); - if (typeof showToast === 'function') showToast('⚠️ Answer submit failed — check connection'); - }); - } - }; - } - // Patch after PVP loads - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', function() { setTimeout(patchPvpAnswer, 3000); }); - } else { - setTimeout(patchPvpAnswer, 3000); - } // Also re-patch on enterPVPMode — retry until pvp.js loads var _origEnterPVP = null; var _pvpPatchAttempts = 0; @@ -29994,7 +29934,6 @@ console.log('✅ UX Patches loaded — 24 tasks from the UX Review Report'); _origEnterPVP = window.enterPVPMode; window.enterPVPMode = function() { _origEnterPVP.apply(this, arguments); - setTimeout(patchPvpAnswer, 500); // Announce PVP lobby entry in Global Chat var _pvpName = (typeof currentUser !== 'undefined' && currentUser && currentUser.username) ? currentUser.username : null; if (_pvpName && typeof window.nachoGlobalAnnounce === 'function') { diff --git a/firebase-messaging-sw.js b/firebase-messaging-sw.js index bed587c19..ab769c40e 100644 --- a/firebase-messaging-sw.js +++ b/firebase-messaging-sw.js @@ -2,12 +2,13 @@ importScripts('https://www.gstatic.com/firebasejs/9.23.0/firebase-app-compat.js' importScripts('https://www.gstatic.com/firebasejs/9.23.0/firebase-messaging-compat.js'); firebase.initializeApp({ - apiKey: "AIzaSyDLwucmRxjoJp2KMBTi2ujf0mlVkgLHyKk", - authDomain: "bitcoin-education-archive.firebaseapp.com", - projectId: "bitcoin-education-archive", - storageBucket: "bitcoin-education-archive.firebasestorage.app", - messagingSenderId: "1055248200518", - appId: "1:1055248200518:web:6c6d64a5ee78e19bfbeb47" + apiKey: "AIzaSyCkUGX2KWaVGmSQXpYJhWDxF_BSiHRX6SM", + authDomain: "btc-archive-test.firebaseapp.com", + projectId: "btc-archive-test", + storageBucket: "btc-archive-test.firebasestorage.app", + messagingSenderId: "60810625669", + appId: "1:60810625669:web:ea4dacd55333e41429dfec", + measurementId: "G-7C2FKDJ8E4" }); const messaging = firebase.messaging(); diff --git a/index.html b/index.html index 33f94ae22..e4f8cc0a0 100644 --- a/index.html +++ b/index.html @@ -3,6 +3,8 @@ + + - + + + + - + + diff --git a/pvp-enhance.js b/pvp-enhance.js index c993525c9..78b1ba9d0 100644 --- a/pvp-enhance.js +++ b/pvp-enhance.js @@ -2,351 +2,477 @@ // ⚔️ PVP Enhancements — Bolt-on features // Sudden Death, Speed Bonus, Taunts, Match History // ============================================= -!function() { -'use strict'; - -// ---- 1. SUDDEN DEATH ---- -// Override reroll text to show "SUDDEN DEATH" instead of "Both wrong!" -var _origResultShown = false; -var _sdObserver = new MutationObserver(function(mutations) { - mutations.forEach(function(m) { - m.addedNodes.forEach(function(node) { - if (node.nodeType === 1 && node.textContent) { - // Detect reroll result screen - if (node.textContent.indexOf('Both wrong!') !== -1) { - var rerollDiv = node.querySelector ? node.querySelector('div[style*="font-size:3rem"]') : null; - if (rerollDiv) { - rerollDiv.textContent = '⚡'; - } - var textDiv = node.querySelector ? node.querySelector('div[style*="font-weight:800"]') : null; - if (textDiv && textDiv.textContent.indexOf('Both wrong') !== -1) { - textDiv.textContent = '⚡ SUDDEN DEATH!'; - textDiv.style.color = '#f7931a'; - textDiv.style.letterSpacing = '2px'; - } - var subText = node.querySelector ? node.querySelector('div[style*="text-faint"]') : null; - if (subText && subText.textContent.indexOf('Next question') !== -1) { - subText.textContent = 'Neither got it — next question decides!'; - } - } +!(function () { + "use strict"; + + // ---- 1. SUDDEN DEATH ---- + // Override reroll text to show "SUDDEN DEATH" instead of "Both wrong!" + var _origResultShown = false; + var _sdObserver = new MutationObserver(function (mutations) { + mutations.forEach(function (m) { + m.addedNodes.forEach(function (node) { + if (node.nodeType === 1 && node.textContent) { + // Detect reroll result screen + if (node.textContent.indexOf("Both wrong!") !== -1) { + var rerollDiv = node.querySelector + ? node.querySelector('div[style*="font-size:3rem"]') + : null; + if (rerollDiv) { + rerollDiv.textContent = "⚡"; } - }); - }); -}); - -// ---- 2. SPEED BONUS VISUAL ---- -// Show "⚡ LIGHTNING FAST!" when answering in under 3 seconds -var _questionShownAt = 0; -var _speedObserver = new MutationObserver(function(mutations) { - mutations.forEach(function(m) { - m.addedNodes.forEach(function(node) { - if (node.nodeType !== 1) return; - // Detect question appearing (has pvpQuestion id) - if (node.id === 'pvpOverlay' || (node.querySelector && node.querySelector('#pvpQuestion'))) { - _questionShownAt = Date.now(); + var textDiv = node.querySelector + ? node.querySelector('div[style*="font-weight:800"]') + : null; + if (textDiv && textDiv.textContent.indexOf("Both wrong") !== -1) { + textDiv.textContent = "⚡ SUDDEN DEATH!"; + textDiv.style.color = "#f7931a"; + textDiv.style.letterSpacing = "2px"; } - // Detect "Correct! Waiting for opponent" or "Wrong!" - if (node.textContent && (node.textContent.indexOf('Correct! Waiting') !== -1 || node.textContent.indexOf('Wrong!') !== -1 || node.textContent.indexOf("Time's up") !== -1)) { - var elapsed = Date.now() - _questionShownAt; - if (elapsed < 3000 && elapsed > 0 && node.textContent.indexOf('Correct') !== -1) { - var speedBadge = document.createElement('div'); - speedBadge.style.cssText = 'text-align:center;margin-top:8px;font-size:0.85rem;font-weight:800;color:#f7931a;animation:pvpSlideIn 0.3s ease;'; - speedBadge.textContent = '⚡ LIGHTNING FAST! (' + (elapsed / 1000).toFixed(1) + 's)'; - node.parentElement.insertBefore(speedBadge, node.nextSibling); - if (typeof haptic === 'function') haptic('medium'); - } + var subText = node.querySelector + ? node.querySelector('div[style*="text-faint"]') + : null; + if ( + subText && + subText.textContent.indexOf("Next question") !== -1 + ) { + subText.textContent = "Neither got it — next question decides!"; } - }); + } + } + }); + }); + }); + + // ---- 2. SPEED BONUS VISUAL ---- + // Show "⚡ LIGHTNING FAST!" when answering in under 3 seconds + var _questionShownAt = 0; + var _speedObserver = new MutationObserver(function (mutations) { + mutations.forEach(function (m) { + m.addedNodes.forEach(function (node) { + if (node.nodeType !== 1) return; + // Detect question appearing (has pvpQuestion id) + if ( + node.id === "pvpOverlay" || + (node.querySelector && node.querySelector("#pvpQuestion")) + ) { + _questionShownAt = Date.now(); + } + // Detect "Correct! Waiting for opponent" or "Wrong!" + if ( + node.textContent && + (node.textContent.indexOf("Correct! Waiting") !== -1 || + node.textContent.indexOf("Wrong!") !== -1 || + node.textContent.indexOf("Time's up") !== -1) + ) { + var elapsed = Date.now() - _questionShownAt; + if ( + elapsed < 3000 && + elapsed > 0 && + node.textContent.indexOf("Correct") !== -1 + ) { + var speedBadge = document.createElement("div"); + speedBadge.style.cssText = + "text-align:center;margin-top:8px;font-size:0.85rem;font-weight:800;color:#f7931a;animation:pvpSlideIn 0.3s ease;"; + speedBadge.textContent = + "⚡ LIGHTNING FAST! (" + (elapsed / 1000).toFixed(1) + "s)"; + node.parentElement.insertBefore(speedBadge, node.nextSibling); + if (typeof haptic === "function") haptic("medium"); + } + } + }); }); -}); + }); -// ---- 3. TAUNT EMOJIS ---- -// Add taunt buttons when waiting for opponent's answer -var TAUNTS = ['😂', '🔥', '💀', '😎', '🤔', '⚡']; -var _lastTauntTime = 0; + // ---- 3. TAUNT EMOJIS ---- + // Add taunt buttons when waiting for opponent's answer + var TAUNTS = ["😂", "🔥", "💀", "😎", "🤔", "⚡"]; + var _lastTauntTime = 0; -window._pvpSendTaunt = function(emoji) { + window._pvpSendTaunt = function (emoji) { if (Date.now() - _lastTauntTime < 3000) return; // 3s cooldown _lastTauntTime = Date.now(); - - if (typeof db === 'undefined' || !db || typeof auth === 'undefined' || !auth || !auth.currentUser) return; - + + if ( + typeof db === "undefined" || + !db || + typeof auth === "undefined" || + !auth || + !auth.currentUser + ) + return; + // Show locally _showTauntBubble(emoji, true); - + // Write to match doc so opponent sees it via their existing real-time listener try { - // Find match ID from the PVP overlay's current state - // The match doc is already being listened to — we just add a taunt field - var uid = auth.currentUser.uid; - // Search for the match ID in pvp_matches where this user is a player - // Actually, the match ID is stored on the global pvp state. Let's access it. - if (window._pvpEnhanceMatchId) { - db.collection('pvp_matches').doc(window._pvpEnhanceMatchId).update({ - lastTaunt: { uid: uid, emoji: emoji, ts: Date.now() } - }).catch(function() {}); - } - } catch(e) {} -}; - -function _showTauntBubble(emoji, isMine) { - var bubble = document.createElement('div'); - bubble.style.cssText = 'position:fixed;' + (isMine ? 'bottom:180px;right:20px;' : 'bottom:180px;left:20px;') + - 'z-index:100010;font-size:3.5rem;pointer-events:none;' + - 'animation:pvpTauntFloat 2s ease forwards;' + - 'text-shadow:0 0 20px rgba(0,0,0,0.5);'; + // Find match ID from the PVP overlay's current state + // The match doc is already being listened to — we just add a taunt field + var uid = auth.currentUser.uid; + // Search for the match ID in pvp_matches where this user is a player + // Actually, the match ID is stored on the global pvp state. Let's access it. + if (window._pvpEnhanceMatchId) { + db.collection("pvp_matches") + .doc(window._pvpEnhanceMatchId) + .update({ + lastTaunt: { uid: uid, emoji: emoji, ts: Date.now() }, + }) + .catch(function () {}); + } + } catch (e) {} + }; + + function _showTauntBubble(emoji, isMine) { + var bubble = document.createElement("div"); + bubble.style.cssText = + "position:fixed;" + + (isMine ? "bottom:180px;right:20px;" : "bottom:180px;left:20px;") + + "z-index:100010;font-size:3.5rem;pointer-events:none;" + + "animation:pvpTauntFloat 2s ease forwards;" + + "text-shadow:0 0 20px rgba(0,0,0,0.5);"; bubble.textContent = emoji; document.body.appendChild(bubble); - + // Play a subtle sound for received taunts - if (!isMine && typeof window.canPlaySound === 'function' && window.canPlaySound()) { - try { - var ctx = new (window.AudioContext || window.webkitAudioContext)(); - var osc = ctx.createOscillator(); - var gain = ctx.createGain(); - osc.connect(gain); gain.connect(ctx.destination); - osc.frequency.value = 600; - osc.type = 'sine'; - gain.gain.setValueAtTime(0.1, ctx.currentTime); - gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.2); - osc.start(ctx.currentTime); - osc.stop(ctx.currentTime + 0.2); - } catch(e) {} + if ( + !isMine && + typeof window.canPlaySound === "function" && + window.canPlaySound() + ) { + try { + var ctx = new (window.AudioContext || window.webkitAudioContext)(); + var osc = ctx.createOscillator(); + var gain = ctx.createGain(); + osc.connect(gain); + gain.connect(ctx.destination); + osc.frequency.value = 600; + osc.type = "sine"; + gain.gain.setValueAtTime(0.1, ctx.currentTime); + gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.2); + osc.start(ctx.currentTime); + osc.stop(ctx.currentTime + 0.2); + } catch (e) {} } - - setTimeout(function() { bubble.remove(); }, 2000); -} - -// Inject taunt bar into the waiting-for-opponent screen -var _tauntObserver = new MutationObserver(function(mutations) { - mutations.forEach(function(m) { - m.addedNodes.forEach(function(node) { - if (node.nodeType !== 1) return; - // Detect "Waiting for opponent" text - if (node.textContent && node.textContent.indexOf('Waiting for opponent') !== -1 && !document.getElementById('pvpTauntBar')) { - var bar = document.createElement('div'); - bar.id = 'pvpTauntBar'; - bar.style.cssText = 'display:flex;justify-content:center;gap:8px;margin-top:12px;animation:pvpSlideIn 0.3s ease;'; - TAUNTS.forEach(function(t) { - var btn = document.createElement('button'); - btn.textContent = t; - btn.style.cssText = 'font-size:1.5rem;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:50%;width:44px;height:44px;cursor:pointer;transition:0.2s;touch-action:manipulation;display:flex;align-items:center;justify-content:center;'; - btn.onclick = function() { - _pvpSendTaunt(t); - btn.style.transform = 'scale(1.3)'; - btn.style.opacity = '0.5'; - setTimeout(function() { btn.style.transform = ''; btn.style.opacity = '1'; }, 300); - }; - bar.appendChild(btn); - }); - node.parentElement.appendChild(bar); - } - }); + + setTimeout(function () { + bubble.remove(); + }, 2000); + } + + // Inject taunt bar into the waiting-for-opponent screen + var _tauntObserver = new MutationObserver(function (mutations) { + mutations.forEach(function (m) { + m.addedNodes.forEach(function (node) { + if (node.nodeType !== 1) return; + // Detect "Waiting for opponent" text + if ( + node.textContent && + node.textContent.indexOf("Waiting for opponent") !== -1 && + !document.getElementById("pvpTauntBar") + ) { + var bar = document.createElement("div"); + bar.id = "pvpTauntBar"; + bar.style.cssText = + "display:flex;justify-content:center;gap:8px;margin-top:12px;animation:pvpSlideIn 0.3s ease;"; + TAUNTS.forEach(function (t) { + var btn = document.createElement("button"); + btn.textContent = t; + btn.style.cssText = + "font-size:1.5rem;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:50%;width:44px;height:44px;cursor:pointer;transition:0.2s;touch-action:manipulation;display:flex;align-items:center;justify-content:center;"; + btn.onclick = function () { + _pvpSendTaunt(t); + btn.style.transform = "scale(1.3)"; + btn.style.opacity = "0.5"; + setTimeout(function () { + btn.style.transform = ""; + btn.style.opacity = "1"; + }, 300); + }; + bar.appendChild(btn); + }); + node.parentElement.appendChild(bar); + } + }); }); -}); + }); -// ---- 4. MATCH HISTORY ---- -// Save match results to localStorage and show on lobby -window._pvpSaveMatchHistory = function(opponentName, myScore, oppScore, won) { + // ---- 4. MATCH HISTORY ---- + // Save match results to localStorage and show on lobby + window._pvpSaveMatchHistory = function ( + opponentName, + myScore, + oppScore, + won, + ) { try { - var history = JSON.parse(localStorage.getItem('btc_pvp_history') || '[]'); - history.unshift({ - opponent: opponentName, - myScore: myScore, - oppScore: oppScore, - won: won, - date: Date.now() - }); - if (history.length > 10) history = history.slice(0, 10); - localStorage.setItem('btc_pvp_history', JSON.stringify(history)); - } catch(e) {} -}; - -// Hook into match result to save history -var _historyObserver = new MutationObserver(function(mutations) { - mutations.forEach(function(m) { - m.addedNodes.forEach(function(node) { - if (node.nodeType !== 1) return; - // Detect VICTORY/DEFEAT screen - if (node.textContent && (node.textContent.indexOf('VICTORY!') !== -1 || node.textContent.indexOf('DEFEAT') !== -1)) { - var isWin = node.textContent.indexOf('VICTORY!') !== -1; - // Extract scores from the result screen - var scoreEls = node.querySelectorAll ? node.querySelectorAll('div[style*="font-size:2rem"][style*="font-weight:900"]') : []; - var myScore = 0, oppScore = 0; - if (scoreEls.length >= 2) { - myScore = parseInt(scoreEls[0].textContent) || 0; - oppScore = parseInt(scoreEls[1].textContent) || 0; - } - // Get opponent name - var oppNameEls = node.querySelectorAll ? node.querySelectorAll('div[style*="font-weight:700"][style*="font-size:0.85rem"]') : []; - var oppName = oppNameEls.length >= 2 ? oppNameEls[1].textContent : 'Unknown'; - - _pvpSaveMatchHistory(oppName, myScore, oppScore, isWin); - - // Increment global PVP match counter (only count once per match — winner side) - if (isWin) { - try { - if (typeof firebase !== 'undefined' && firebase.firestore) { - firebase.firestore().collection('stats').doc('global').set({ - pvpMatches: firebase.firestore.FieldValue.increment(1) - }, { merge: true }).catch(function() {}); - } - } catch(e) {} - } - } - }); + var history = JSON.parse(localStorage.getItem("btc_pvp_history") || "[]"); + history.unshift({ + opponent: opponentName, + myScore: myScore, + oppScore: oppScore, + won: won, + date: Date.now(), + }); + if (history.length > 10) history = history.slice(0, 10); + localStorage.setItem("btc_pvp_history", JSON.stringify(history)); + } catch (e) {} + }; + + // Hook into match result to save history + var _historyObserver = new MutationObserver(function (mutations) { + mutations.forEach(function (m) { + m.addedNodes.forEach(function (node) { + if (node.nodeType !== 1) return; + // Detect VICTORY/DEFEAT screen + if ( + node.textContent && + (node.textContent.indexOf("VICTORY!") !== -1 || + node.textContent.indexOf("DEFEAT") !== -1) + ) { + var isWin = node.textContent.indexOf("VICTORY!") !== -1; + // Extract scores from the result screen + var scoreEls = node.querySelectorAll + ? node.querySelectorAll( + 'div[style*="font-size:2rem"][style*="font-weight:900"]', + ) + : []; + var myScore = 0, + oppScore = 0; + if (scoreEls.length >= 2) { + myScore = parseInt(scoreEls[0].textContent) || 0; + oppScore = parseInt(scoreEls[1].textContent) || 0; + } + // Get opponent name + var oppNameEls = node.querySelectorAll + ? node.querySelectorAll( + 'div[style*="font-weight:700"][style*="font-size:0.85rem"]', + ) + : []; + var oppName = + oppNameEls.length >= 2 ? oppNameEls[1].textContent : "Unknown"; + + _pvpSaveMatchHistory(oppName, myScore, oppScore, isWin); + + // Increment global PVP match counter (only count once per match — winner side) + if (isWin) { + try { + if (typeof firebase !== "undefined" && firebase.firestore) { + firebase + .firestore() + .collection("stats") + .doc("global") + .set( + { + pvpMatches: firebase.firestore.FieldValue.increment(1), + }, + { merge: true }, + ) + .catch(function () {}); + } + } catch (e) {} + } + } + }); }); -}); + }); + + // Inject match history into lobby + function _injectMatchHistory() { + var lobby = document.getElementById("pvpLobbyStatus"); + if (!lobby || document.getElementById("pvpMatchHistory")) return; -// Inject match history into lobby -function _injectMatchHistory() { - var lobby = document.getElementById('pvpLobbyStatus'); - if (!lobby || document.getElementById('pvpMatchHistory')) return; - var history; - try { history = JSON.parse(localStorage.getItem('btc_pvp_history') || '[]'); } catch(e) { return; } + try { + history = JSON.parse(localStorage.getItem("btc_pvp_history") || "[]"); + } catch (e) { + return; + } if (history.length === 0) return; - - var html = '
    ' + - '
    📜 Recent Battles
    '; - - history.slice(0, 5).forEach(function(match) { - var ago = _timeAgo(match.date); - var icon = match.won ? '🏆' : '💀'; - var color = match.won ? '#22c55e' : '#ef4444'; - html += '
    ' + - '' + icon + '' + - '
    ' + - '
    vs ' + _escHtml(match.opponent) + '
    ' + - '
    ' + ago + '
    ' + - '
    ' + - '
    ' + match.myScore + '-' + match.oppScore + '
    ' + - '
    '; + + var html = + '
    ' + + '
    📜 Recent Battles
    '; + + history.slice(0, 5).forEach(function (match) { + var ago = _timeAgo(match.date); + var icon = match.won ? "🏆" : "💀"; + var color = match.won ? "#22c55e" : "#ef4444"; + html += + '
    ' + + '' + + icon + + "" + + '
    ' + + '
    vs ' + + _escHtml(match.opponent) + + "
    " + + '
    ' + + ago + + "
    " + + "
    " + + '
    ' + + match.myScore + + "-" + + match.oppScore + + "
    " + + "
    "; }); - - html += '
    '; - + + html += "
    "; + // Insert after the lobby status - lobby.insertAdjacentHTML('afterend', html); -} + lobby.insertAdjacentHTML("afterend", html); + } -function _timeAgo(ts) { + function _timeAgo(ts) { var diff = Math.floor((Date.now() - ts) / 1000); - if (diff < 60) return 'just now'; - if (diff < 3600) return Math.floor(diff / 60) + 'm ago'; - if (diff < 86400) return Math.floor(diff / 3600) + 'h ago'; - return Math.floor(diff / 86400) + 'd ago'; -} - -function _escHtml(s) { - return s ? s.replace(/&/g, '&').replace(//g, '>') : ''; -} - -// ---- Add CSS for taunt animation ---- -var style = document.createElement('style'); -style.textContent = '@keyframes pvpTauntFloat { 0% { opacity:1; transform:translateY(0) scale(1); } 50% { opacity:1; transform:translateY(-40px) scale(1.3); } 100% { opacity:0; transform:translateY(-80px) scale(0.8); } }'; -document.head.appendChild(style); - -// ---- Taunt listener — watch match doc for opponent taunts ---- -var _tauntUnsub = null; -var _lastSeenTauntTs = 0; - -function _startTauntListener(matchId) { + if (diff < 60) return "just now"; + if (diff < 3600) return Math.floor(diff / 60) + "m ago"; + if (diff < 86400) return Math.floor(diff / 3600) + "h ago"; + return Math.floor(diff / 86400) + "d ago"; + } + + function _escHtml(s) { + return s + ? s.replace(/&/g, "&").replace(//g, ">") + : ""; + } + + // ---- Add CSS for taunt animation ---- + var style = document.createElement("style"); + style.textContent = + "@keyframes pvpTauntFloat { 0% { opacity:1; transform:translateY(0) scale(1); } 50% { opacity:1; transform:translateY(-40px) scale(1.3); } 100% { opacity:0; transform:translateY(-80px) scale(0.8); } }"; + document.head.appendChild(style); + + // ---- Taunt listener — watch match doc for opponent taunts ---- + var _tauntUnsub = null; + var _lastSeenTauntTs = 0; + + function _startTauntListener(matchId) { if (_tauntUnsub) _tauntUnsub(); window._pvpEnhanceMatchId = matchId; _lastSeenTauntTs = Date.now(); - - _tauntUnsub = db.collection('pvp_matches').doc(matchId).onSnapshot(function(snap) { - if (!snap.exists) return; - var data = snap.data(); - if (data.lastTaunt && data.lastTaunt.ts > _lastSeenTauntTs) { + + _tauntUnsub = db + .collection("pvp_matches") + .doc(matchId) + .onSnapshot( + function (snap) { + if (!snap.exists) return; + var data = snap.data(); + if (data.lastTaunt && data.lastTaunt.ts > _lastSeenTauntTs) { _lastSeenTauntTs = data.lastTaunt.ts; // Only show if it's from the opponent - if (auth.currentUser && data.lastTaunt.uid !== auth.currentUser.uid) { - _showTauntBubble(data.lastTaunt.emoji, false); - if (typeof haptic === 'function') haptic('light'); + if ( + auth.currentUser && + data.lastTaunt.uid !== auth.currentUser.uid + ) { + _showTauntBubble(data.lastTaunt.emoji, false); + if (typeof haptic === "function") haptic("light"); } - } - }, function() {}); -} + } + }, + function () {}, + ); + } -function _stopTauntListener() { - if (_tauntUnsub) { _tauntUnsub(); _tauntUnsub = null; } + function _stopTauntListener() { + if (_tauntUnsub) { + _tauntUnsub(); + _tauntUnsub = null; + } window._pvpEnhanceMatchId = null; -} + } -// ---- Detect match start by watching for the VS screen / question screen ---- -function _detectMatchId() { + // ---- Detect match start by watching for the VS screen / question screen ---- + function _detectMatchId() { // Poll for the match ID from Firestore — find active match for this user - if (typeof db === 'undefined' || !db || typeof auth === 'undefined' || !auth || !auth.currentUser) return; + if ( + typeof db === "undefined" || + !db || + typeof auth === "undefined" || + !auth || + !auth.currentUser + ) + return; var uid = auth.currentUser.uid; - + // Check both player positions — simple query without composite index - db.collection('pvp_matches') - .where('player1.uid', '==', uid) - .orderBy('createdAt', 'desc') - .limit(1).get().then(function(snap) { - if (!snap.empty) { - var d = snap.docs[0].data(); - if (d.status !== 'finished' && d.status !== 'forfeit') { - _startTauntListener(snap.docs[0].id); - return; - } - } - db.collection('pvp_matches') - .where('player2.uid', '==', uid) - .orderBy('createdAt', 'desc') - .limit(1).get().then(function(snap2) { - if (!snap2.empty) { - var d2 = snap2.docs[0].data(); - if (d2.status !== 'finished' && d2.status !== 'forfeit') { - _startTauntListener(snap2.docs[0].id); - } - } - }).catch(function() {}); - }).catch(function() {}); -} - -// ---- Start observers when PVP overlay opens ---- -var _pvpMainObserver = new MutationObserver(function(mutations) { - mutations.forEach(function(m) { - m.addedNodes.forEach(function(node) { - if (node.nodeType === 1 && node.id === 'pvpOverlay') { - // PVP overlay appeared — start all observers - _sdObserver.observe(node, { childList: true, subtree: true }); - _speedObserver.observe(node, { childList: true, subtree: true }); - _tauntObserver.observe(node, { childList: true, subtree: true }); - _historyObserver.observe(node, { childList: true, subtree: true }); - - // Inject match history into lobby - setTimeout(_injectMatchHistory, 500); - - // Detect match for taunts (check after countdown) - setTimeout(_detectMatchId, 5000); - setTimeout(_detectMatchId, 10000); - } - }); - m.removedNodes.forEach(function(node) { - if (node.nodeType === 1 && node.id === 'pvpOverlay') { - // Cleanup - _sdObserver.disconnect(); - _speedObserver.disconnect(); - _tauntObserver.disconnect(); - _historyObserver.disconnect(); - _stopTauntListener(); + db.collection("pvp_matches") + .where("player1.uid", "==", uid) + .orderBy("createdAt", "desc") + .limit(1) + .get() + .then(function (snap) { + if (!snap.empty) { + var d = snap.docs[0].data(); + if (d.status !== "finished" && d.status !== "forfeit") { + _startTauntListener(snap.docs[0].id); + return; + } + } + db.collection("pvp_matches") + .where("player2.uid", "==", uid) + .orderBy("createdAt", "desc") + .limit(1) + .get() + .then(function (snap2) { + if (!snap2.empty) { + var d2 = snap2.docs[0].data(); + if (d2.status !== "finished" && d2.status !== "forfeit") { + _startTauntListener(snap2.docs[0].id); + } } - }); + }) + .catch(function () {}); + }) + .catch(function () {}); + } + + // ---- Start observers when PVP overlay opens ---- + var _pvpMainObserver = new MutationObserver(function (mutations) { + mutations.forEach(function (m) { + m.addedNodes.forEach(function (node) { + if (node.nodeType === 1 && node.id === "pvpOverlay") { + // PVP overlay appeared — start all observers + _sdObserver.observe(node, { childList: true, subtree: true }); + _speedObserver.observe(node, { childList: true, subtree: true }); + _tauntObserver.observe(node, { childList: true, subtree: true }); + _historyObserver.observe(node, { childList: true, subtree: true }); + + // Inject match history into lobby + setTimeout(_injectMatchHistory, 500); + + // Detect match for taunts (check after countdown) + setTimeout(_detectMatchId, 5000); + setTimeout(_detectMatchId, 10000); + } + }); + m.removedNodes.forEach(function (node) { + if (node.nodeType === 1 && node.id === "pvpOverlay") { + // Cleanup + _sdObserver.disconnect(); + _speedObserver.disconnect(); + _tauntObserver.disconnect(); + _historyObserver.disconnect(); + _stopTauntListener(); + } + }); }); -}); + }); -// Watch document.body for PVP overlay -if (document.body) { + // Watch document.body for PVP overlay + if (document.body) { _pvpMainObserver.observe(document.body, { childList: true }); -} else { - document.addEventListener('DOMContentLoaded', function() { - _pvpMainObserver.observe(document.body, { childList: true }); + } else { + document.addEventListener("DOMContentLoaded", function () { + _pvpMainObserver.observe(document.body, { childList: true }); }); -} + } -console.log('[PVP] Enhancements loaded — Sudden Death, Speed Bonus, Taunts, Match History'); -}(); + console.log( + "[PVP] Enhancements loaded — Sudden Death, Speed Bonus, Taunts, Match History", + ); +})(); diff --git a/pvp.js b/pvp.js index 8c0fc7a84..b8a37cf82 100644 --- a/pvp.js +++ b/pvp.js @@ -1 +1 @@ -!function(){"use strict";const e=[{id:"pvp_1",name:"First Blood",emoji:"⚔️",desc:"Won your first PVP match",threshold:1,pts:25},{id:"pvp_5",name:"Contender",emoji:"🥊",desc:"Won 5 PVP matches",threshold:5,pts:50},{id:"pvp_25",name:"Gladiator",emoji:"🏟️",desc:"Won 25 PVP matches",threshold:25,pts:100},{id:"pvp_50",name:"Champion",emoji:"🏆",desc:"Won 50 PVP matches",threshold:50,pts:200},{id:"pvp_100",name:"PVP Legend",emoji:"👑",desc:"Won 100 PVP matches",threshold:100,pts:500}];"undefined"!=typeof BADGE_DEFS&&e.forEach(function(e){BADGE_DEFS.some(function(t){return t.id===e.id})||BADGE_DEFS.push({id:e.id,name:e.name,emoji:e.emoji,desc:e.desc,pts:e.pts,check:function(){return parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=e.threshold}})});var t={active:!1,inLobby:!1,inMatch:!1,matchId:null,lobbyDocId:null,opponentName:"",opponentUid:"",questions:[],currentQ:0,myScore:0,opponentScore:0,myCorrect:0,opponentCorrect:0,streak:0,roundWins:0,opponentRoundWins:0,answered:!1,listenerUnsub:null,lobbyUnsub:null,tickerUnsub:null,isPlayer1:!1,_countdownDone:!1,practicing:!1,practiceQ:null,practiceAnswered:!1,practiceCorrect:0,practiceCount:0,_practicePromptTimer:null};function n(e){for(var t=function(){if("undefined"==typeof QUESTION_BANK)return[];for(var e=[],t=Object.keys(QUESTION_BANK),n=0;n0;n--){var r=Math.floor(Math.random()*(n+1)),o=t[n];t[n]=t[r],t[r]=o}return t.slice(0,e)}function r(e){var t=e.wrong.slice(),n=Math.floor(Math.random()*(t.length+1));return t.splice(n,0,e.a),{q:e.q,options:t,correct:n}}function o(){return"undefined"!=typeof firebase&&firebase.firestore?firebase.firestore():null}function i(){return"undefined"!=typeof firebase&&firebase.auth?firebase.auth():null}function a(){var e=i();return e&&e.currentUser?e.currentUser.uid:null}function s(){var e=localStorage.getItem("btc_username");if(e)return e;var t=i();return t&&t.currentUser&&t.currentUser.displayName?t.currentUser.displayName:"Anonymous Pleb"}function c(){return"undefined"!=typeof currentUser&¤tUser&¤tUser.profilePic?currentUser.profilePic:""}function l(){var e=o();e&&(t.tickerUnsub&&t.tickerUnsub(),t.tickerUnsub=e.collection("pvp_lobby").where("status","==","waiting").onSnapshot(function(e){var n=a(),r=[];e.forEach(function(e){var t=e.data();t.uid!==n&&(z(t)?r.push(t):e.ref.delete().catch(function(){}))}),r.length>0&&!t.active?(d(!0),function(){if(t.active||t.inLobby||t.inMatch)return;var e=Date.now();if(e-u0&&t.inLobby&&t.practicing?function(){t.practicing=!1;var e=document.getElementById("pvpPracticeArea");e&&e.remove();var n=document.getElementById("pvpPracticePrompt");n&&n.remove();var r=document.getElementById("pvpLobbyStatus");if(!r)return;r.insertAdjacentHTML("afterend",'
    ⚔️
    OPPONENT FOUND!
    Someone just entered the PVP lobby.
    Ready to battle for real?
    '),"function"==typeof haptic&&haptic("medium")}():d(!1)},function(e){console.log("PVP lobby ticker listener error:",e)}))}var p=!1;function d(e){if(e&&!p){if(p=!0,"undefined"!=typeof TICKER_ITEMS){for(var t=TICKER_ITEMS.length-1;t>=0;t--)-1!==TICKER_ITEMS[t].indexOf("PVP MODE")&&TICKER_ITEMS.splice(t,1);TICKER_ITEMS.unshift("ANOTHER PLAYER IS WAITING FOR YOU IN PVP MODE. ⚔️")}}else if(!e&&p&&(p=!1,"undefined"!=typeof TICKER_ITEMS))for(t=TICKER_ITEMS.length-1;t>=0;t--)-1!==TICKER_ITEMS[t].indexOf("PVP MODE")&&TICKER_ITEMS.splice(t,1)}var u=0,f=9e5;var v=10;function m(){var e=new Date;return"btc_pvp_practice_"+e.getFullYear()+"-"+String(e.getMonth()+1).padStart(2,"0")+"-"+String(e.getDate()).padStart(2,"0")}function g(){return parseInt(localStorage.getItem(m())||"0")}function b(){t._practicePromptTimer&&clearTimeout(t._practicePromptTimer),t._practicePromptTimer=setTimeout(function(){t._practicePromptTimer=null,!t.inLobby||t.inMatch||t.practicing||function(){var e=document.getElementById("pvpLobbyStatus");if(!e)return;var t=g();if(t>=v)return void e.insertAdjacentHTML("afterend",'
    📚
    Daily Practice Complete!
    You\'ve finished your 10 practice questions for today.
    Come back tomorrow for more! 🔥
    ');var n=v-t;e.insertAdjacentHTML("afterend",'
    🧠
    Warm Up While You Wait?
    Practice Bitcoin trivia and earn 10 pts per correct answer!
    '+n+" practice question"+(1!==n?"s":"")+' left today
    ')}()},1e4)}function y(){if(t.practicing&&t.inLobby){var e=g();if(e>=v)h();else{var r=n(1);if(0!==r.length){var o=r[0],i=o.wrong.slice(),a=Math.floor(Math.random()*(i.length+1));i.splice(a,0,o.a),t.practiceQ={q:o.q,options:i,correct:a},t.practiceAnswered=!1;var s=v-e,c=document.getElementById("pvpPracticeArea");c&&c.remove();var l=document.getElementById("pvpLobbyStatus");if(l){var p='
    🧠 Practice Mode
    '+s+" left today · "+t.practiceCorrect+' correct
    '+N(t.practiceQ.q)+'
    '+i.map(function(e,t){return'"}).join("")+"
    ";l.insertAdjacentHTML("afterend",p)}}}}}function h(){t.practicing=!1;var e=document.getElementById("pvpPracticeArea");e&&e.remove();var n=document.getElementById("pvpLobbyStatus");n&&n.insertAdjacentHTML("afterend",'
    🏁
    Practice Complete!
    '+t.practiceCorrect+"/"+t.practiceCount+' correct this session
    You\'ve used all '+"10 practice questions for today.
    Come back tomorrow for more! 🔥
    ")}window.pvpDismissPractice=function(){var e=document.getElementById("pvpPracticePrompt");e&&e.remove()},window.pvpStartPractice=function(){var e=document.getElementById("pvpPracticePrompt");e&&e.remove(),g()>=v?"function"==typeof showToast&&showToast("📚 You've used all 10 practice questions today!"):(t.practicing=!0,t.practiceCorrect=0,t.practiceCount=0,y())},window.pvpPracticeAnswer=function(e,n){if(!t.practiceAnswered&&t.practiceQ){t.practiceAnswered=!0;var r=t.practiceQ,o=e===r.correct,i=document.getElementById("pvpPracticeOptions");if(i){for(var a=i.querySelectorAll("button"),s=0;s'+(o?"✅ Correct! +10 pts":"❌ Wrong — the answer was "+String.fromCharCode(65+r.correct))+"";d+=p>=v?'':'',d+="",i&&i.insertAdjacentHTML("afterend",d)}},window.showNextPracticeQuestion=function(){y()},window.showPracticeDailyLimit=function(){h()},window.pvpAcceptMatch=function(){var e=document.getElementById("pvpPracticeArea");e&&e.remove();var t=document.getElementById("pvpLobbyStatus");if(t){var n=t.querySelector('div[style*="font-weight:700"]');n&&(n.textContent="Connecting to opponent...")}},window.pvpDeclineMatchContinuePractice=function(){var e=document.getElementById("pvpPracticeArea");e&&e.remove(),g()>=v?h():(t.practicing=!0,y())};var x=null;window._pvpQuickName=function(){var e=document.createElement("div");e.id="pvpNameOverlay",e.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;",e.onclick=function(t){t.target===e&&e.remove()},history.pushState({overlay:"pvpName"},"","#pvp"),window.addEventListener("popstate",function e(t){var n=document.getElementById("pvpNameOverlay");n&&n.remove(),window.removeEventListener("popstate",e)},{once:!0}),e.innerHTML='
    ⚔️

    Enter the Arena

    Choose a battle name to play PVP trivia!

    Want to save your wins and get on the leaderboard permanently?
    ',document.body.appendChild(e),setTimeout(function(){var e=document.getElementById("pvpQuickNameInput");e&&e.focus()},100)},window.pvpQuickNameSubmit=async function(){var e=document.getElementById("pvpQuickNameInput"),t=e?e.value.trim():"";if(!t||t.length<2)"function"==typeof showToast&&showToast("Name must be at least 2 characters");else{t.length>20&&(t=t.substring(0,20));try{var n=i();if(!n.currentUser||void 0===n.currentUser.isAnonymous){await n.signInAnonymously();n.currentUser||await new Promise(function(e){var t=n.onAuthStateChanged(function(n){n&&(t(),e())});setTimeout(e,3e3)})}if(!n.currentUser)throw new Error("Sign-in failed. Please try again.");var r=n.currentUser.uid;await db.collection("users").doc(r).set({username:t,points:0,channelsVisited:0,totalVisits:1,streak:0,pvpWins:0,pvpLosses:0,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0}),"function"==typeof loadUser?await loadUser(r):("undefined"!=typeof currentUser&¤tUser||(window.currentUser={}),currentUser.username=t,currentUser.uid=r);var o=document.getElementById("pvpNameOverlay");o&&o.remove(),enterPVPMode()}catch(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Try again"))}}},window.enterPVPMode=function(){var n=i();if(n&&n.currentUser){if(n.currentUser.isAnonymous)if(!("undefined"!=typeof currentUser&¤tUser&¤tUser.username&&"Anon"!==currentUser.username))return void _pvpQuickName();t.active=!0,t.inLobby=!0,t.inMatch=!1,"#pvp"!==window.location.hash&&history.pushState({channel:"pvp"},"","#pvp");var r=document.getElementById("nacho-bubble");r&&(r.classList.remove("show"),r.removeAttribute("data-interactive"));var s=document.getElementById("appsMenu");s&&(s.style.display="none"),function(){var t=document.getElementById("pvpOverlay");t&&t.remove();!function(){if(P)return;P=!0,fetch("data/R_fun-facts.json?v="+Date.now()).then(function(e){return e.json()}).then(function(e){if(e&&e.msgs)for(var t=(w=e.msgs.map(function(e){var t=(e.text||"").replace(/https?:\/\/\S+/g,"").replace(/\n+/g," ").trim();if("-"===t.charAt(0)&&(t=t.substring(1).trim()),t.length>280){var n=t.lastIndexOf(".",280);t=t.substring(0,n>100?n+1:280)+"…"}return t}).filter(function(e){return e.length>20})).length-1;t>0;t--){var n=Math.floor(Math.random()*(t+1)),r=w[t];w[t]=w[n],w[n]=r}}).catch(function(){})}();var n=document.createElement("div");n.id="pvpOverlay",n.style.cssText="position:fixed;inset:0;z-index:100002;background:var(--bg,#0a0a1a);display:flex;flex-direction:column;overflow-y:auto;";var r=parseInt(localStorage.getItem("btc_pvp_wins")||"0"),o=parseInt(localStorage.getItem("btc_pvp_losses")||"0"),i=S();n.innerHTML='
    Home
    '+i.price+'|⛏️'+i.height+'
    ⚔️

    PVP MODE

    Bitcoin Trivia Battles — 1v1
    '+r+'
    Wins
    '+o+'
    Losses
    How It Works
    5 questions per round · First correct answer wins · Streaks = bonus pts · Win 3 of 5 for victory!
    🔍
    Searching for opponent...
    First come, first served matchmaking
    🔗⚔️
    Send this link to a friend right now to battle them in PVP Bitcoin trivia!
    https://bitcoineducation.quest/#pvp
    '+(navigator.share?"":"")+'
    🎉Did You Know?
    Loading fun facts...
    PVP Badges
    '+e.map(function(e){var t=parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=e.threshold;return'
    '+e.emoji+" "+e.name+" ("+e.threshold+"W)
    "}).join("")+'
    ',document.body.appendChild(n),function(){_&&clearInterval(_);T(),_=setInterval(T,12e3)}(),x&&clearInterval(x),x=setInterval(function(){var e=S(),t=document.getElementById("pvpTickerPrice"),n=document.getElementById("pvpTickerHeight");t&&(t.textContent=e.price),n&&(n.textContent=e.height)},3e4)}(),function(){var e=o(),t=a();if(!e||!t)return;e.collection("pvp_lobby").where("status","==","waiting").limit(10).get().then(function(e){var n=!1;e.forEach(function(e){if(!n){var r=e.data();r.uid!==t&&z(r)?(n=!0,M(e.id,r)):e.ref.delete().catch(function(){})}}),n||E(t)}).catch(function(e){console.error("PVP lobby query error:",e),E(t)})}()}else _pvpQuickName()},window.exitPVPMode=function(e){var n=t.inMatch,r=t.inLobby,i=t.matchId;t.isPlayer1,t.isPlayer1;if(n&&i&&!e){var s=o();if(s){var c={status:"forfeit"};c.forfeitedBy=a(),c.forfeitReason="manual_leave",s.collection("pvp_matches").doc(i).update(c).catch(function(){});var l=parseInt(localStorage.getItem("btc_pvp_losses")||"0")+1;localStorage.setItem("btc_pvp_losses",l.toString()),U(parseInt(localStorage.getItem("btc_pvp_wins")||"0"),l),"function"==typeof showToast&&showToast("💀 You forfeited — counted as a loss")}}else r&&!n?"function"==typeof showToast&&showToast("⚔️ Left PVP lobby"):n||r||"function"==typeof showToast&&showToast("⚔️ Left PVP Battle");!function(){t._matchPoll&&(clearInterval(t._matchPoll),t._matchPoll=null);t._heartbeat&&(clearInterval(t._heartbeat),t._heartbeat=null);t._lobbyHeartbeat&&(clearInterval(t._lobbyHeartbeat),t._lobbyHeartbeat=null);t._forceResultTimer&&(clearTimeout(t._forceResultTimer),t._forceResultTimer=null);t._oppTimeoutTimer&&(clearTimeout(t._oppTimeoutTimer),t._oppTimeoutTimer=null);t._p1AdvanceTimer&&(clearTimeout(t._p1AdvanceTimer),t._p1AdvanceTimer=null);(function(){t.practicing=!1,t.practiceQ=null,t.practiceAnswered=!1,t._practicePromptTimer&&(clearTimeout(t._practicePromptTimer),t._practicePromptTimer=null);var e=document.getElementById("pvpPracticeArea");e&&e.remove();var n=document.getElementById("pvpPracticePrompt");n&&n.remove()})(),void(_&&(clearInterval(_),_=null)),void(x&&(clearInterval(x),x=null)),t._resultShown=!1,t._matchResultShown=!1,t._countdownDone=!1,t._pendingQuestionData=null,t.listenerUnsub&&(t.listenerUnsub(),t.listenerUnsub=null);t.lobbyUnsub&&(t.lobbyUnsub(),t.lobbyUnsub=null);var e=o();e&&t.lobbyDocId&&(e.collection("pvp_lobby").doc(t.lobbyDocId).delete().catch(function(){}),t.lobbyDocId=null);t.matchId=null,t.currentQ=0,t.myScore=0,t.opponentScore=0,t.myCorrect=0,t.opponentCorrect=0,t.streak=0,t.roundWins=0,t.opponentRoundWins=0,t.answered=!1,t.questions=[]}(),t.active=!1,t.inLobby=!1,t.inMatch=!1;var p=document.getElementById("pvpOverlay");p&&p.remove(),"#pvp"===window.location.hash&&history.pushState({home:!0},"",window.location.pathname)};var w=[],P=!1;var I=0,_=null;function T(){var e=document.getElementById("pvpFunFact");if(e){var t=function(){if(0===w.length)return"Bitcoin has been running non-stop since January 3, 2009 — over 99.98% uptime!";var e=w[I%w.length];return I++,e}();e.style.opacity="0",setTimeout(function(){e.textContent=t,e.style.opacity="1"},300)}}function S(){var e="--",t="--";if("function"==typeof getNachoLiveData){var n=getNachoLiveData();n.price&&(e="$"+Math.round(n.price).toLocaleString()),n.blockHeight&&(t=n.blockHeight.toLocaleString())}if("--"===e){var r=localStorage.getItem("btc_last_price");r&&(e="$"+Math.round(parseFloat(r)).toLocaleString())}if("--"===t){var o=localStorage.getItem("btc_last_height");o&&(t=parseInt(o).toLocaleString())}return{price:e,height:t}}var k=3e4;function z(e){return!!e.lastSeen&&Date.now()-e.lastSeen=100?o="👑":a>=50?o="🏆":a>=25?o="🏟️":a>=5?o="🥊":a>=1&&(o="⚔️")}return{emoji:n,name:r,pvpBadge:o}}(0,a()),i=c(),l=t.opponentProfilePic||"",p=i?'':o.emoji,d=i?"width:70px;height:70px;border-radius:50%;border:3px solid #f7931a;margin:0 auto 8px;box-shadow:0 0 20px rgba(247,147,26,0.4);overflow:hidden;":"width:70px;height:70px;border-radius:50%;background:linear-gradient(135deg,#f7931a,#e8720c);display:flex;align-items:center;justify-content:center;font-size:1.8rem;margin:0 auto 8px;box-shadow:0 0 20px rgba(247,147,26,0.4);",u=l?'':"🟣",f=l?"width:70px;height:70px;border-radius:50%;border:3px solid #6366f1;margin:0 auto 8px;box-shadow:0 0 20px rgba(99,102,241,0.4);overflow:hidden;":"width:70px;height:70px;border-radius:50%;background:linear-gradient(135deg,#6366f1,#4f46e5);display:flex;align-items:center;justify-content:center;font-size:1.8rem;margin:0 auto 8px;box-shadow:0 0 20px rgba(99,102,241,0.4);";e.innerHTML='
    MATCH FOUND
    Prepare for battle!
    '+p+'
    '+N(n)+'
    '+o.name+(o.pvpBadge?" "+o.pvpBadge:"")+'
    VS
    '+u+'
    '+N(r)+'
    Challenger
    Get ready...
    ',"function"==typeof haptic&&haptic("medium"),setTimeout(function(){var e=document.getElementById("pvpOverlay");e&&(e.style.animation="pvpShake 0.3s ease 2"),"function"==typeof haptic&&haptic("heavy")},1800),setTimeout(function(){var e=document.getElementById("pvpCountdown"),n=document.getElementById("pvpCountdownLabel");if(e){e.style.opacity="1",n&&(n.style.opacity="1"),e.textContent="3",e.style.animation="pvpCountdown 0.5s ease";var r=[2,1,"BATTLE!"],o=0,i=setInterval(function(){if(o>=r.length)return clearInterval(i),e&&(e.textContent="⚔️ BATTLE! ⚔️",e.style.color="#f7931a",e.style.fontSize="3rem",e.style.animation="none",e.offsetHeight,e.style.animation="pvpCountdown 0.5s ease"),"function"==typeof haptic&&haptic("heavy"),void setTimeout(function(){if(t._countdownDone=!0,t.isPlayer1){if(t._pendingQuestionData){var e=t._pendingQuestionData;t._pendingQuestionData=null,t.currentQ=e.currentQ,t.answered=!1,t._resultShown=!1,L(e)}}else A()},1e3);e&&(e.textContent=r[o],e.style.animation="none",e.offsetHeight,e.style.animation="pvpCountdown 0.5s ease",1===r[o]?e.style.color="#ef4444":2===r[o]&&(e.style.color="#fbbf24")),"function"==typeof haptic&&haptic("light"),o++},1e3)}},2500)}}function B(n){var r=o();if(r){t.listenerUnsub&&t.listenerUnsub(),t._heartbeat&&clearInterval(t._heartbeat);var i=t.isPlayer1?"player1LastSeen":"player2LastSeen";t._heartbeat=setInterval(function(){if(t.inMatch&&t.matchId){var e={};e[i]=Date.now(),r.collection("pvp_matches").doc(n).update(e).catch(function(){})}else clearInterval(t._heartbeat)},5e3);var c={};c[i]=Date.now(),r.collection("pvp_matches").doc(n).update(c).catch(function(){}),t.listenerUnsub=r.collection("pvp_matches").doc(n).onSnapshot(function(i){if(i.exists){var c=i.data();t.questions=c.questions||[];var l=t.isPlayer1?"player1":"player2",p=t.isPlayer1?"player2":"player1";t.myScore=c[l].score,t.opponentScore=c[p].score,t.myCorrect=c[l].correct,t.opponentCorrect=c[p].correct;var d=c[l].answers||[],u=c[p].answers||[];t.roundWins=0,t.opponentRoundWins=0;for(var f=0;fc.currentQ&&m.length<=c.currentQ&&(t._oppTimeoutTimer||(t._oppTimeoutTimer=setTimeout(function(){t._oppTimeoutTimer=null;var e=r.collection("pvp_matches").doc(n);r.runTransaction(function(t){return t.get(e).then(function(n){if(n.exists){var r=n.data();if("active"===r.status){var o=r.currentQ,i=r[p].answers||[];if(!(i.length>o)){var a={selected:-1,correct:!1,answeredAt:(new Date).toISOString(),won:!1},s=i.slice();s.push(a);var c=r[l].answers||[],d={};d[p+".answers"]=s,C(d,r,c.slice(),s,o,l,p,r[l],r[p],c[o].correct),t.update(e,d)}}}})}).catch(function(e){console.error("Opp timeout tx error:",e)})},18e3)))}if("question_result"===c.status&&(t._resultShown||(t._resultShown=!0,function(e){var n=document.getElementById("pvpOverlay");if(!n)return;var r=e.currentQ,o=e.questionWinner,i=t.isPlayer1?"player1":"player2",a=o===i,s="reroll"===o,c=s?"🔄":a?"✅":"❌",l=s?"Both wrong! New question incoming...":a?"You won this round!":N(t.opponentName)+" got it first!",p=s?"#eab308":a?"#22c55e":"#ef4444";a?t.streak++:t.streak=0;n.innerHTML='
    '+c+'
    '+l+"
    "+(t.streak>1?'
    🔥 '+t.streak+" streak! Bonus points!
    ":"")+'
    You
    '+e[i].score+'
    '+N(t.opponentName)+'
    '+e[t.isPlayer1?"player2":"player1"].score+'
    Next question in 3s...
    ';var d=s?2:3,u=setInterval(function(){d--;var e=document.getElementById("pvpNextTimer");e&&(e.textContent=d),d<=0&&(clearInterval(u),(s||(t.currentQ=r+1),t._p1AdvanceTimer&&(clearTimeout(t._p1AdvanceTimer),t._p1AdvanceTimer=null),t.isPlayer1?t._p1AdvanceTimer=setTimeout(function(){t._p1AdvanceTimer=null,t.inMatch&&A()},500):A()))},1e3)}(c))),"finished"===c.status&&(t._matchResultShown||(t._matchResultShown=!0,function(n){var r=document.getElementById("pvpOverlay");if(!r)return;for(var i=t.isPlayer1?"player1":"player2",a=t.isPlayer1?"player2":"player1",c=n[i],l=n[a],p=0,d=0,u=c.answers||[],f=l.answers||[],v=0;vd,g=p===d,b="btc_pvp_anon_win_"+(new Date).toISOString().split("T")[0],y=parseInt(localStorage.getItem(b)||"0"),h="btc_pvp_newacct_win_"+(new Date).toISOString().split("T")[0],x=parseInt(localStorage.getItem(h)||"0");function w(t,n){if(m)if(m&&(t&&y>=1||n&&x>=1))"function"==typeof awardPoints&&awardPoints(Math.floor(c.score/2),"⚔️ PVP Win (unranked vs guest)"),"function"==typeof showToast&&showToast("⚔️ Win! Stats not recorded — max 1 ranked win vs guests per day.");else{var r=parseInt(localStorage.getItem("btc_pvp_wins")||"0")+1;localStorage.setItem("btc_pvp_wins",r.toString()),"function"==typeof awardPoints&&awardPoints(c.score,"⚔️ PVP Victory!"),function(t){e.forEach(function(e){if(t>=e.threshold){var n="undefined"!=typeof earnedBadges?earnedBadges:new Set;n.has(e.id)||(n.add(e.id),localStorage.setItem("btc_badges",JSON.stringify([...n])),"function"==typeof showToast&&showToast(e.emoji+" Badge Earned: "+e.name+"! +"+e.pts+" pts"),"function"==typeof awardPoints&&awardPoints(e.pts,e.emoji+" "+e.name),"function"==typeof showBadgeToast&&showBadgeToast(e))}})}(r),U(r,parseInt(localStorage.getItem("btc_pvp_losses")||"0")),t&&localStorage.setItem(b,(y+1).toString()),n&&localStorage.setItem(h,(x+1).toString())}else if(g)"function"==typeof awardPoints&&awardPoints(5,"⚔️ PVP Draw");else{var o=parseInt(localStorage.getItem("btc_pvp_losses")||"0")+1;localStorage.setItem("btc_pvp_losses",o.toString()),"function"==typeof awardPoints&&c.score>0&&awardPoints(Math.floor(c.score/2),"⚔️ PVP Consolation"),U(parseInt(localStorage.getItem("btc_pvp_wins")||"0"),o)}}t.opponentUid&&S?S.collection("users").doc(t.opponentUid).get().then(function(e){var t=!0,n=!1;if(e.exists){var r=e.data();if(t=!r.email&&!r.authMethod&&!r.nostr,r.created&&r.created.toDate)n=Date.now()-r.created.toDate().getTime()<6e5}w(t,n)}).catch(function(){w(!1,!1)}):w(!1,!1);var P=m?"🏆":g?"🤝":"💀",I=m?"VICTORY!":g?"DRAW!":"DEFEAT",_=m?"#22c55e":g?"#eab308":"#ef4444",T=m?"You dominated! "+p+" rounds won.":g?"Evenly matched! "+p+"–"+d+" tie.":"Better luck next time. "+d+" rounds to "+p+".";"function"==typeof showToast&&(m?showToast("🏆 PVP Victory! "+p+"–"+d+" vs "+N(t.opponentName)):g?showToast("🤝 PVP Draw! "+p+"–"+d+" vs "+N(t.opponentName)):showToast("💀 PVP Defeat. "+d+"–"+p+" vs "+N(t.opponentName)));r.innerHTML='
    '+P+'

    '+I+'

    '+T+'
    '+(m?"🏆 WINNER":g?"🤝 DRAW":"LOST")+'
    '+c.score+'
    '+N(s())+'
    '+p+'/5 rounds won
    '+(m||g?g?"🤝 DRAW":"🏆 WINNER":"💀 LOST")+'
    '+l.score+'
    '+N(t.opponentName)+'
    '+d+'/5 rounds won
    '+function(e,t){for(var n="",r=0;r<5;r++){var o=e[r],i=t[r],a="var(--border)",s="—";o&&o.won?(a="#22c55e",s="✓"):i&&i.won?(a="#ef4444",s="✗"):(a="#eab308",s="·"),n+='
    '+s+"
    "}return n}(u,f)+'
    ',t.listenerUnsub&&(t.listenerUnsub(),t.listenerUnsub=null);t.inMatch=!1;var S=o();S&&t.lobbyDocId&&(S.collection("pvp_lobby").doc(t.lobbyDocId).delete().catch(function(){}),t.lobbyDocId=null)}(c))),"forfeit"===c.status&&c.forfeitedBy!==a()){l=t.isPlayer1?"player1":"player2",p=t.isPlayer1?"player2":"player1";for(var g=0,b=0,y=c[l].answers||[],h=c[p].answers||[],x=0;x<5;x++)y[x]&&y[x].won&&g++,h[x]&&h[x].won&&b++;if("manual_leave"===c.forfeitReason)if(g>b){var w=parseInt(localStorage.getItem("btc_pvp_wins")||"0")+1;localStorage.setItem("btc_pvp_wins",w.toString()),U(w,parseInt(localStorage.getItem("btc_pvp_losses")||"0")),"function"==typeof awardPoints&&awardPoints(c[l].score||10,"⚔️ PVP Victory (opponent forfeited)"),D(!0,"Your opponent left the match. You win! 🏆")}else D(!1,"Your opponent left the match. No win or loss recorded.");else D(!1,"Your opponent disconnected. No win or loss recorded.");t.listenerUnsub&&(t.listenerUnsub(),t.listenerUnsub=null)}}},function(e){console.error("PVP match listener error:",e)})}}function A(){var e=o(),q=t.currentQ;if(!e||!t.matchId)return;var ref=e.collection("pvp_matches").doc(t.matchId);e.runTransaction(function(tx){return tx.get(ref).then(function(doc){if(!doc.exists)return;var s=doc.data().status,dq=doc.data().currentQ;if(s==="finished"||s==="forfeit")return;if(s==="active"&&dq===q)return;tx.update(ref,{status:"active",currentQ:q,questionWinner:null,questionStartedAt:firebase.firestore.FieldValue.serverTimestamp()})})}).catch(function(err){console.warn("[PVP] A() tx error:",err)})}function L(e){var n=document.getElementById("pvpOverlay");if(n){var r=e.currentQ,o=e.questions[r];if(o){t.isPlayer1,t.isPlayer1;n.innerHTML='
    You
    '+t.myScore+'
    Question '+(r+1)+' / 5
    '+function(e){for(var n="",r=t.isPlayer1?"player1":"player2",o=e[r].answers||[],i=0;i<5;i++){var a="var(--border)",s="";i'+s+"
    "}return n}(e)+'
    '+N(t.opponentName)+'
    '+t.opponentScore+"
    "+(t.streak>1?'
    🔥 '+t.streak+" streak!
    ":"")+'
    '+N(o.q)+'
    '+o.options.map(function(e,t){return'"}).join("")+'
    ',setTimeout(function(){var e=document.getElementById("pvpTimer");e&&(e.style.width="0%")},100),t._questionTimeout&&clearTimeout(t._questionTimeout),t._questionTimeout=setTimeout(function(){!t.answered&&t.inMatch&&pvpAnswer(r,-1,null)},15e3)}}}function C(e,t,o,i,a,s,c,l,p,d){var u=i[a],f=o[a],v=u&&u.correct,m=!1,g=!1;if(d&&!v)m=!0;else if(!d&&v)g=!0;else{if(!d||!v){var b=n(1);if(b.length>0){var y=r(b[0]),h=t.questions.slice();h[a]=y,e.questions=h}return e[s+".answers"]=o.slice(0,a),e[c+".answers"]=i.slice(0,a),e.questionWinner="reroll",void(e.status="question_result")}g=!0}if(m&&(o[a]=Object.assign({},f,{won:!0}),e[s+".answers"]=o),g){var x=i.slice();x[a]=Object.assign({},u,{won:!0}),e[c+".answers"]=x}for(var w=m?s:c,P=m?l:p,I=m?o:i,_=0,T=I.length-1;T>=0&&(I[T]&&I[T].won);T--)_++;var S=10+(_>1?5*(_-1):0);e[w+".score"]=(P.score||0)+S,e[w+".correct"]=(P.correct||0)+1,e.questionWinner=w;for(var k=1,z=0;z=5?"finished":"question_result"}function D(e,t){var n=document.getElementById("pvpOverlay");if(n){var r=e?"🏆":"🚪",o=e?"#22c55e":"#eab308",i=e?"VICTORY!":"MATCH ENDED";n.innerHTML='
    '+r+'

    '+i+'

    '+t+'
    ',"function"==typeof showToast&&showToast(e?"🏆 You win — opponent forfeited!":"🚪 Opponent left — match voided")}}function U(e,t){"undefined"!=typeof currentUser&¤tUser&&(currentUser.pvpWins=e,currentUser.pvpLosses=t);var n=o(),r=a();n&&r&&n.collection("users").doc(r).update({pvpWins:e,pvpLosses:t}).catch(function(){n.collection("users").doc(r).set({pvpWins:e,pvpLosses:t},{merge:!0}).catch(function(){})})}function N(e){return e?e.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""):""}function j(){"undefined"!=typeof firebase&&firebase.auth&&firebase.auth().onAuthStateChanged(function(e){e&&(l(),"true"===sessionStorage.getItem("btc_pvp_pending")&&(sessionStorage.removeItem("btc_pvp_pending"),setTimeout(function(){"function"==typeof enterPVPMode&&enterPVPMode()},1e3)))}),setTimeout(function(){t.tickerUnsub||l()},5e3),setTimeout(function(){var e=o();e&&e.collection("pvp_lobby").where("status","==","waiting").get().then(function(e){e.forEach(function(e){z(e.data())||e.ref.delete().catch(function(){})})}).catch(function(){})},1e4)}window.pvpAnswer=function(e,n,r){if(!t.answered){t.answered=!0,t._questionTimeout&&(clearTimeout(t._questionTimeout),t._questionTimeout=null);var i=o(),s=a();if(i&&s&&t.matchId){var c=t.questions&&t.questions[e],l=n===c.correct,p=document.getElementById("pvpOptions");if(p){for(var d=p.querySelectorAll("button"),u=0;u=0&&n!==c.correct&&d[n]&&(d[n].style.borderColor="#ef4444",d[n].style.background="rgba(239,68,68,0.15)")}p&&p.insertAdjacentHTML("afterend",'
    '+(l?"✅ Correct! Waiting for opponent...":n<0?"⏰ Time's up!":"❌ Wrong! Waiting for opponent...")+"
    ");var f=t.isPlayer1?"player1":"player2",v={selected:n,correct:l,answeredAt:(new Date).toISOString(),won:!1},m=i.collection("pvp_matches").doc(t.matchId);console.log("[PVP] Submitting answer for Q"+e+", myKey="+f+", correct="+l);var g={},b=[];m.get().then(function(n){if(n.exists){var r=n.data(),o=r[f],i=t.isPlayer1?"player2":"player1";if(!(o.answers&&o.answers.length>e))return(b=(o.answers||[]).slice()).push(v),g[f+".answers"]=b,console.log("[PVP] Writing my answer, oppAnswers.length="+(r[i].answers||[]).length+", qIdx="+e),m.update(g);console.log("[PVP] Already answered Q"+e+", skipping")}else console.error("[PVP] Match doc not found")}).then(function(){console.log("[PVP] Answer written successfully")}).catch(function(e){console.error("[PVP] Answer write FAILED:",e),"function"==typeof showToast&&showToast("⚠️ Failed to submit answer — check connection")})}}},window.addEventListener("pagehide",function(){if(t.lobbyDocId){var e=o();e&&e.collection("pvp_lobby").doc(t.lobbyDocId).delete().catch(function(){})}});document.addEventListener("visibilitychange",function(){if(document.visibilityState==="visible"&&t.inMatch&&t.matchId&&!t.inLobby){var db=o();if(!db)return;db.collection("pvp_matches").doc(t.matchId).get({source:"server"}).then(function(doc){if(!doc.exists)return;var data=doc.data();if(data.status==="active"&&(!document.getElementById("pvpQuestion")||data.currentQ!==t.currentQ)){t.currentQ=data.currentQ;t.answered=!1;t._resultShown=!1;t.questions=data.questions||[];console.log("[PVP] Visibility restored, re-rendering Q"+t.currentQ);var snap={exists:true,data:function(){return data}};if(t._countdownDone)L(data);else t._pendingQuestionData=data}}}).catch(function(){})}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",j):setTimeout(j,2e3),window.enterPVPMode=window.enterPVPMode,window.exitPVPMode=window.exitPVPMode,window.pvpAnswer=window.pvpAnswer,window.PVP_BADGE_DEFS=e}(); \ No newline at end of file +!function(){"use strict";const e=[{id:"pvp_1",name:"First Blood",emoji:"⚔️",desc:"Won your first PVP match",threshold:1,pts:25},{id:"pvp_5",name:"Contender",emoji:"🥊",desc:"Won 5 PVP matches",threshold:5,pts:50},{id:"pvp_25",name:"Gladiator",emoji:"🏟️",desc:"Won 25 PVP matches",threshold:25,pts:100},{id:"pvp_50",name:"Champion",emoji:"🏆",desc:"Won 50 PVP matches",threshold:50,pts:200},{id:"pvp_100",name:"PVP Legend",emoji:"👑",desc:"Won 100 PVP matches",threshold:100,pts:500}];"undefined"!=typeof BADGE_DEFS&&e.forEach(function(e){BADGE_DEFS.some(function(t){return t.id===e.id})||BADGE_DEFS.push({id:e.id,name:e.name,emoji:e.emoji,desc:e.desc,pts:e.pts,check:function(){return parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=e.threshold}})});var t={active:!1,inLobby:!1,inMatch:!1,matchId:null,lobbyDocId:null,opponentName:"",opponentUid:"",questions:[],currentQ:0,myScore:0,opponentScore:0,myCorrect:0,opponentCorrect:0,streak:0,roundWins:0,opponentRoundWins:0,answered:!1,listenerUnsub:null,lobbyUnsub:null,tickerUnsub:null,isPlayer1:!1,_countdownDone:!1,practicing:!1,practiceQ:null,practiceAnswered:!1,practiceCorrect:0,practiceCount:0,_practicePromptTimer:null};function n(e){for(var t=function(){if("undefined"==typeof QUESTION_BANK)return[];for(var e=[],t=Object.keys(QUESTION_BANK),n=0;n0;n--){var r=Math.floor(Math.random()*(n+1)),o=t[n];t[n]=t[r],t[r]=o}return t.slice(0,e)}function r(e){var t=e.wrong.slice(),n=Math.floor(Math.random()*(t.length+1));return t.splice(n,0,e.a),{q:e.q,options:t,correct:n}}function o(){return"undefined"!=typeof firebase&&firebase.firestore?firebase.firestore():null}function i(){return"undefined"!=typeof firebase&&firebase.auth?firebase.auth():null}function a(){var e=i();return e&&e.currentUser?e.currentUser.uid:null}function s(){var e=localStorage.getItem("btc_username");if(e)return e;var t=i();return t&&t.currentUser&&t.currentUser.displayName?t.currentUser.displayName:"Anonymous Pleb"}function c(){return"undefined"!=typeof currentUser&¤tUser&¤tUser.profilePic?currentUser.profilePic:""}function l(){var e=o();e&&(t.tickerUnsub&&t.tickerUnsub(),t.tickerUnsub=e.collection("pvp_lobby").where("status","==","waiting").onSnapshot(function(e){var n=a(),r=[];e.forEach(function(e){var t=e.data();t.uid!==n&&(z(t)?r.push(t):e.ref.delete().catch(function(){}))}),r.length>0&&!t.active?(d(!0),function(){if(t.active||t.inLobby||t.inMatch)return;var e=Date.now();if(e-u0&&t.inLobby&&t.practicing?function(){t.practicing=!1;var e=document.getElementById("pvpPracticeArea");e&&e.remove();var n=document.getElementById("pvpPracticePrompt");n&&n.remove();var r=document.getElementById("pvpLobbyStatus");if(!r)return;r.insertAdjacentHTML("afterend",'
    ⚔️
    OPPONENT FOUND!
    Someone just entered the PVP lobby.
    Ready to battle for real?
    '),"function"==typeof haptic&&haptic("medium")}():d(!1)},function(e){console.log("PVP lobby ticker listener error:",e)}))}var p=!1;function d(e){if(e&&!p){if(p=!0,"undefined"!=typeof TICKER_ITEMS){for(var t=TICKER_ITEMS.length-1;t>=0;t--)-1!==TICKER_ITEMS[t].indexOf("PVP MODE")&&TICKER_ITEMS.splice(t,1);TICKER_ITEMS.unshift("ANOTHER PLAYER IS WAITING FOR YOU IN PVP MODE. ⚔️")}}else if(!e&&p&&(p=!1,"undefined"!=typeof TICKER_ITEMS))for(t=TICKER_ITEMS.length-1;t>=0;t--)-1!==TICKER_ITEMS[t].indexOf("PVP MODE")&&TICKER_ITEMS.splice(t,1)}var u=0,f=9e5;var v=10;function m(){var e=new Date;return"btc_pvp_practice_"+e.getFullYear()+"-"+String(e.getMonth()+1).padStart(2,"0")+"-"+String(e.getDate()).padStart(2,"0")}function g(){return parseInt(localStorage.getItem(m())||"0")}function b(){t._practicePromptTimer&&clearTimeout(t._practicePromptTimer),t._practicePromptTimer=setTimeout(function(){t._practicePromptTimer=null,!t.inLobby||t.inMatch||t.practicing||function(){var e=document.getElementById("pvpLobbyStatus");if(!e)return;var t=g();if(t>=v)return void e.insertAdjacentHTML("afterend",'
    📚
    Daily Practice Complete!
    You\'ve finished your 10 practice questions for today.
    Come back tomorrow for more! 🔥
    ');var n=v-t;e.insertAdjacentHTML("afterend",'
    🧠
    Warm Up While You Wait?
    Practice Bitcoin trivia and earn 10 pts per correct answer!
    '+n+" practice question"+(1!==n?"s":"")+' left today
    ')}()},1e4)}function y(){if(t.practicing&&t.inLobby){var e=g();if(e>=v)h();else{var r=n(1);if(0!==r.length){var o=r[0],i=o.wrong.slice(),a=Math.floor(Math.random()*(i.length+1));i.splice(a,0,o.a),t.practiceQ={q:o.q,options:i,correct:a},t.practiceAnswered=!1;var s=v-e,c=document.getElementById("pvpPracticeArea");c&&c.remove();var l=document.getElementById("pvpLobbyStatus");if(l){var p='
    🧠 Practice Mode
    '+s+" left today · "+t.practiceCorrect+' correct
    '+N(t.practiceQ.q)+'
    '+i.map(function(e,t){return'"}).join("")+"
    ";l.insertAdjacentHTML("afterend",p)}}}}}function h(){t.practicing=!1;var e=document.getElementById("pvpPracticeArea");e&&e.remove();var n=document.getElementById("pvpLobbyStatus");n&&n.insertAdjacentHTML("afterend",'
    🏁
    Practice Complete!
    '+t.practiceCorrect+"/"+t.practiceCount+' correct this session
    You\'ve used all '+"10 practice questions for today.
    Come back tomorrow for more! 🔥
    ")}window.pvpDismissPractice=function(){var e=document.getElementById("pvpPracticePrompt");e&&e.remove()},window.pvpStartPractice=function(){var e=document.getElementById("pvpPracticePrompt");e&&e.remove(),g()>=v?"function"==typeof showToast&&showToast("📚 You've used all 10 practice questions today!"):(t.practicing=!0,t.practiceCorrect=0,t.practiceCount=0,y())},window.pvpPracticeAnswer=function(e,n){if(!t.practiceAnswered&&t.practiceQ){t.practiceAnswered=!0;var r=t.practiceQ,o=e===r.correct,i=document.getElementById("pvpPracticeOptions");if(i){for(var a=i.querySelectorAll("button"),s=0;s'+(o?"✅ Correct! +10 pts":"❌ Wrong — the answer was "+String.fromCharCode(65+r.correct))+"";d+=p>=v?'':'',d+="",i&&i.insertAdjacentHTML("afterend",d)}},window.showNextPracticeQuestion=function(){y()},window.showPracticeDailyLimit=function(){h()},window.pvpAcceptMatch=function(){var e=document.getElementById("pvpPracticeArea");e&&e.remove();var t=document.getElementById("pvpLobbyStatus");if(t){var n=t.querySelector('div[style*="font-weight:700"]');n&&(n.textContent="Connecting to opponent...")}},window.pvpDeclineMatchContinuePractice=function(){var e=document.getElementById("pvpPracticeArea");e&&e.remove(),g()>=v?h():(t.practicing=!0,y())};var x=null;window._pvpQuickName=function(){var e=document.createElement("div");e.id="pvpNameOverlay",e.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;",e.onclick=function(t){t.target===e&&e.remove()},history.pushState({overlay:"pvpName"},"","#pvp"),window.addEventListener("popstate",function e(t){var n=document.getElementById("pvpNameOverlay");n&&n.remove(),window.removeEventListener("popstate",e)},{once:!0}),e.innerHTML='
    ⚔️

    Enter the Arena

    Choose a battle name to play PVP trivia!

    Want to save your wins and get on the leaderboard permanently?
    ',document.body.appendChild(e),setTimeout(function(){var e=document.getElementById("pvpQuickNameInput");e&&e.focus()},100)},window.pvpQuickNameSubmit=async function(){var e=document.getElementById("pvpQuickNameInput"),t=e?e.value.trim():"";if(!t||t.length<2)"function"==typeof showToast&&showToast("Name must be at least 2 characters");else{t.length>20&&(t=t.substring(0,20));try{var n=i(),r=o();if(!n||!r)throw new Error("Firebase services are not available yet. Please wait a moment and try again.");if(!n.currentUser||void 0===n.currentUser.isAnonymous){await n.signInAnonymously();n.currentUser||await new Promise(function(e){var t=n.onAuthStateChanged(function(n){n&&(t(),e())});setTimeout(e,3e3)})}if(!n.currentUser)throw new Error("Sign-in failed. Please try again.");var a=n.currentUser.uid;await r.collection("users").doc(a).set({username:t,points:0,channelsVisited:0,totalVisits:1,streak:0,pvpWins:0,pvpLosses:0,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0}),"function"==typeof loadUser?await loadUser(a):("undefined"!=typeof currentUser&¤tUser||(window.currentUser={}),currentUser.username=t,currentUser.uid=a);var s=document.getElementById("pvpNameOverlay");s&&s.remove(),enterPVPMode()}catch(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Try again"))}}},window.enterPVPMode=function(){var n=i();if(n&&n.currentUser){if(n.currentUser.isAnonymous)if(!("undefined"!=typeof currentUser&¤tUser&¤tUser.username&&"Anon"!==currentUser.username))return void _pvpQuickName();t.active=!0,t.inLobby=!0,t.inMatch=!1,"#pvp"!==window.location.hash&&history.pushState({channel:"pvp"},"","#pvp");var r=document.getElementById("nacho-bubble");r&&(r.classList.remove("show"),r.removeAttribute("data-interactive"));var s=document.getElementById("appsMenu");s&&(s.style.display="none"),function(){var t=document.getElementById("pvpOverlay");t&&t.remove();!function(){if(P)return;P=!0,fetch("data/R_fun-facts.json?v="+Date.now()).then(function(e){return e.json()}).then(function(e){if(e&&e.msgs)for(var t=(w=e.msgs.map(function(e){var t=(e.text||"").replace(/https?:\/\/\S+/g,"").replace(/\n+/g," ").trim();if("-"===t.charAt(0)&&(t=t.substring(1).trim()),t.length>280){var n=t.lastIndexOf(".",280);t=t.substring(0,n>100?n+1:280)+"…"}return t}).filter(function(e){return e.length>20})).length-1;t>0;t--){var n=Math.floor(Math.random()*(t+1)),r=w[t];w[t]=w[n],w[n]=r}}).catch(function(){})}();var n=document.createElement("div");n.id="pvpOverlay",n.style.cssText="position:fixed;inset:0;z-index:100002;background:var(--bg,#0a0a1a);display:flex;flex-direction:column;overflow-y:auto;";var r=parseInt(localStorage.getItem("btc_pvp_wins")||"0"),o=parseInt(localStorage.getItem("btc_pvp_losses")||"0"),i=S();n.innerHTML='
    Home
    '+i.price+'|⛏️'+i.height+'
    ⚔️

    PVP MODE

    Bitcoin Trivia Battles — 1v1
    '+r+'
    Wins
    '+o+'
    Losses
    How It Works
    5 questions per round · First correct answer wins · Streaks = bonus pts · Win 3 of 5 for victory!
    🔍
    Searching for opponent...
    First come, first served matchmaking
    🔗⚔️
    Send this link to a friend right now to battle them in PVP Bitcoin trivia!
    https://bitcoineducation.quest/#pvp
    '+(navigator.share?"":"")+'
    🎉Did You Know?
    Loading fun facts...
    PVP Badges
    '+e.map(function(e){var t=parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=e.threshold;return'
    '+e.emoji+" "+e.name+" ("+e.threshold+"W)
    "}).join("")+'
    ',document.body.appendChild(n),function(){_&&clearInterval(_);I(),_=setInterval(I,12e3)}(),x&&clearInterval(x),x=setInterval(function(){var e=S(),t=document.getElementById("pvpTickerPrice"),n=document.getElementById("pvpTickerHeight");t&&(t.textContent=e.price),n&&(n.textContent=e.height)},3e4)}(),function(){var e=o(),t=a();if(!e||!t)return;e.collection("pvp_lobby").where("status","==","waiting").limit(10).get().then(function(e){var n=!1;e.forEach(function(e){if(!n){var r=e.data();r.uid!==t&&z(r)?(n=!0,A(e.id,r)):e.ref.delete().catch(function(){})}}),n||E(t)}).catch(function(e){console.error("PVP lobby query error:",e),E(t)})}()}else _pvpQuickName()},window.exitPVPMode=function(e){var n=t.inMatch,r=t.inLobby,i=t.matchId;t.isPlayer1,t.isPlayer1;if(n&&i&&!e){var s=o();if(s){var c={status:"forfeit"};c.forfeitedBy=a(),c.forfeitReason="manual_leave",s.collection("pvp_matches").doc(i).update(c).catch(function(){});var l=parseInt(localStorage.getItem("btc_pvp_losses")||"0")+1;localStorage.setItem("btc_pvp_losses",l.toString()),U(parseInt(localStorage.getItem("btc_pvp_wins")||"0"),l),"function"==typeof showToast&&showToast("💀 You forfeited — counted as a loss")}}else r&&!n?"function"==typeof showToast&&showToast("⚔️ Left PVP lobby"):n||r||"function"==typeof showToast&&showToast("⚔️ Left PVP Battle");!function(){t._matchPoll&&(clearInterval(t._matchPoll),t._matchPoll=null);t._heartbeat&&(clearInterval(t._heartbeat),t._heartbeat=null);t._lobbyHeartbeat&&(clearInterval(t._lobbyHeartbeat),t._lobbyHeartbeat=null);t._forceResultTimer&&(clearTimeout(t._forceResultTimer),t._forceResultTimer=null);t._oppTimeoutTimer&&(clearTimeout(t._oppTimeoutTimer),t._oppTimeoutTimer=null);t._p1AdvanceTimer&&(clearTimeout(t._p1AdvanceTimer),t._p1AdvanceTimer=null);(function(){t.practicing=!1,t.practiceQ=null,t.practiceAnswered=!1,t._practicePromptTimer&&(clearTimeout(t._practicePromptTimer),t._practicePromptTimer=null);var e=document.getElementById("pvpPracticeArea");e&&e.remove();var n=document.getElementById("pvpPracticePrompt");n&&n.remove()})(),void(_&&(clearInterval(_),_=null)),void(x&&(clearInterval(x),x=null)),t._resultShown=!1,t._matchResultShown=!1,t._countdownDone=!1,t._pendingQuestionData=null,t.listenerUnsub&&(t.listenerUnsub(),t.listenerUnsub=null);t.lobbyUnsub&&(t.lobbyUnsub(),t.lobbyUnsub=null);var e=o();e&&t.lobbyDocId&&(e.collection("pvp_lobby").doc(t.lobbyDocId).delete().catch(function(){}),t.lobbyDocId=null);t.matchId=null,t.currentQ=0,t.myScore=0,t.opponentScore=0,t.myCorrect=0,t.opponentCorrect=0,t.streak=0,t.roundWins=0,t.opponentRoundWins=0,t.answered=!1,t.questions=[]}(),t.active=!1,t.inLobby=!1,t.inMatch=!1;var p=document.getElementById("pvpOverlay");p&&p.remove(),"#pvp"===window.location.hash&&history.pushState({home:!0},"",window.location.pathname)};var w=[],P=!1;var T=0,_=null;function I(){var e=document.getElementById("pvpFunFact");if(e){var t=function(){if(0===w.length)return"Bitcoin has been running non-stop since January 3, 2009 — over 99.98% uptime!";var e=w[T%w.length];return T++,e}();e.style.opacity="0",setTimeout(function(){e.textContent=t,e.style.opacity="1"},300)}}function S(){var e="--",t="--";if("function"==typeof getNachoLiveData){var n=getNachoLiveData();n.price&&(e="$"+Math.round(n.price).toLocaleString()),n.blockHeight&&(t=n.blockHeight.toLocaleString())}if("--"===e){var r=localStorage.getItem("btc_last_price");r&&(e="$"+Math.round(parseFloat(r)).toLocaleString())}if("--"===t){var o=localStorage.getItem("btc_last_height");o&&(t=parseInt(o).toLocaleString())}return{price:e,height:t}}var k=3e4;function z(e){return!!e.lastSeen&&Date.now()-e.lastSeen=100?o="👑":a>=50?o="🏆":a>=25?o="🏟️":a>=5?o="🥊":a>=1&&(o="⚔️")}return{emoji:n,name:r,pvpBadge:o}}(0,a()),i=c(),l=t.opponentProfilePic||"",p=i?'':o.emoji,d=i?"width:70px;height:70px;border-radius:50%;border:3px solid #f7931a;margin:0 auto 8px;box-shadow:0 0 20px rgba(247,147,26,0.4);overflow:hidden;":"width:70px;height:70px;border-radius:50%;background:linear-gradient(135deg,#f7931a,#e8720c);display:flex;align-items:center;justify-content:center;font-size:1.8rem;margin:0 auto 8px;box-shadow:0 0 20px rgba(247,147,26,0.4);",u=l?'':"🟣",f=l?"width:70px;height:70px;border-radius:50%;border:3px solid #6366f1;margin:0 auto 8px;box-shadow:0 0 20px rgba(99,102,241,0.4);overflow:hidden;":"width:70px;height:70px;border-radius:50%;background:linear-gradient(135deg,#6366f1,#4f46e5);display:flex;align-items:center;justify-content:center;font-size:1.8rem;margin:0 auto 8px;box-shadow:0 0 20px rgba(99,102,241,0.4);";e.innerHTML='
    MATCH FOUND
    Prepare for battle!
    '+p+'
    '+N(n)+'
    '+o.name+(o.pvpBadge?" "+o.pvpBadge:"")+'
    VS
    '+u+'
    '+N(r)+'
    Challenger
    Get ready...
    ',"function"==typeof haptic&&haptic("medium"),setTimeout(function(){var e=document.getElementById("pvpOverlay");e&&(e.style.animation="pvpShake 0.3s ease 2"),"function"==typeof haptic&&haptic("heavy")},1800),setTimeout(function(){var e=document.getElementById("pvpCountdown"),n=document.getElementById("pvpCountdownLabel");if(e){e.style.opacity="1",n&&(n.style.opacity="1"),e.textContent="3",e.style.animation="pvpCountdown 0.5s ease";var r=[2,1,"BATTLE!"],o=0,i=setInterval(function(){if(o>=r.length)return clearInterval(i),e&&(e.textContent="⚔️ BATTLE! ⚔️",e.style.color="#f7931a",e.style.fontSize="3rem",e.style.animation="none",e.offsetHeight,e.style.animation="pvpCountdown 0.5s ease"),"function"==typeof haptic&&haptic("heavy"),void setTimeout(function(){if(t._countdownDone=!0,t.isPlayer1){if(t._pendingQuestionData){var e=t._pendingQuestionData;t._pendingQuestionData=null,t.currentQ=e.currentQ,t.answered=!1,t._resultShown=!1,D(e)}}else B()},1e3);e&&(e.textContent=r[o],e.style.animation="none",e.offsetHeight,e.style.animation="pvpCountdown 0.5s ease",1===r[o]?e.style.color="#ef4444":2===r[o]&&(e.style.color="#fbbf24")),"function"==typeof haptic&&haptic("light"),o++},1e3)}},2500)}}function V(n){var r=o();if(r){t.listenerUnsub&&t.listenerUnsub(),t._heartbeat&&clearInterval(t._heartbeat);var i=t.isPlayer1?"player1LastSeen":"player2LastSeen";t._heartbeat=setInterval(function(){if(t.inMatch&&t.matchId){var e={};e[i]=Date.now(),r.collection("pvp_matches").doc(n).update(e).catch(function(){})}else clearInterval(t._heartbeat)},5e3);var c={};c[i]=Date.now(),r.collection("pvp_matches").doc(n).update(c).catch(function(){}),t.listenerUnsub=r.collection("pvp_matches").doc(n).onSnapshot(function(i){if(i.exists){var c=i.data();"active"!==c.status&&(t._oppTimeoutTimer&&(clearTimeout(t._oppTimeoutTimer),t._oppTimeoutTimer=null),t._forceResultTimer&&(clearTimeout(t._forceResultTimer),t._forceResultTimer=null)),t.questions=c.questions||[];var l=t.isPlayer1?"player1":"player2",p=t.isPlayer1?"player2":"player1";t.myScore=c[l].score,t.opponentScore=c[p].score,t.myCorrect=c[l].correct,t.opponentCorrect=c[p].correct;var d=c[l].answers||[],u=c[p].answers||[];t.roundWins=0,t.opponentRoundWins=0;for(var f=0;fc.currentQ&&m.length<=c.currentQ&&(t._oppTimeoutTimer||(t._oppTimeoutTimer=setTimeout(function(){t._oppTimeoutTimer=null;var e=r.collection("pvp_matches").doc(n);r.runTransaction(function(t){return t.get(e).then(function(n){if(n.exists){var r=n.data();if("active"===r.status){var o=r.currentQ,i=r[p].answers||[];if(!(i.length>o)){var a={selected:-1,correct:!1,answeredAt:(new Date).toISOString(),won:!1},s=i.slice();s.push(a);var c=r[l].answers||[],d={};d[p+".answers"]=s,L(d,r,c.slice(),s,o,l,p,r[l],r[p],c[o].correct),t.update(e,d)}}}})}).catch(function(e){console.error("Opp timeout tx error:",e)})},18e3)))}if("question_result"===c.status&&(t._resultShown||(t._resultShown=!0,function(e){var n=document.getElementById("pvpOverlay");if(!n)return;var r=e.currentQ,o=e.questionWinner,i=t.isPlayer1?"player1":"player2",a=o===i,s="reroll"===o,c=s?"🔄":a?"✅":"❌",l=s?"Both wrong! New question incoming...":a?"You won this round!":N(t.opponentName)+" got it first!",p=s?"#eab308":a?"#22c55e":"#ef4444";a?t.streak++:t.streak=0;n.innerHTML='
    '+c+'
    '+l+"
    "+(t.streak>1?'
    🔥 '+t.streak+" streak! Bonus points!
    ":"")+'
    You
    '+e[i].score+'
    '+N(t.opponentName)+'
    '+e[t.isPlayer1?"player2":"player1"].score+'
    Next question in 3s...
    ';var d=s?2:3,u=setInterval(function(){d--;var e=document.getElementById("pvpNextTimer");e&&(e.textContent=d),d<=0&&(clearInterval(u),t.isPlayer1?t._p1AdvanceTimer=setTimeout(function(){t._p1AdvanceTimer=null,t._resultShown&&t.inMatch&&(s||(t.currentQ=r+1),B())},3e3):(s||(t.currentQ=r+1),B()))},1e3)}(c))),"finished"===c.status&&(t._matchResultShown||(t._matchResultShown=!0,function(n){var r=document.getElementById("pvpOverlay");if(!r)return;for(var i=t.isPlayer1?"player1":"player2",a=t.isPlayer1?"player2":"player1",c=n[i],l=n[a],p=0,d=0,u=c.answers||[],f=l.answers||[],v=0;vd,g=p===d,b="btc_pvp_anon_win_"+(new Date).toISOString().split("T")[0],y=parseInt(localStorage.getItem(b)||"0"),h="btc_pvp_newacct_win_"+(new Date).toISOString().split("T")[0],x=parseInt(localStorage.getItem(h)||"0");function w(t,n){if(m)if(m&&(t&&y>=1||n&&x>=1))"function"==typeof awardPoints&&awardPoints(Math.floor(c.score/2),"⚔️ PVP Win (unranked vs guest)"),"function"==typeof showToast&&showToast("⚔️ Win! Stats not recorded — max 1 ranked win vs guests per day.");else{var r=parseInt(localStorage.getItem("btc_pvp_wins")||"0")+1;localStorage.setItem("btc_pvp_wins",r.toString()),"function"==typeof awardPoints&&awardPoints(c.score,"⚔️ PVP Victory!"),function(t){e.forEach(function(e){if(t>=e.threshold){var n="undefined"!=typeof earnedBadges?earnedBadges:new Set;n.has(e.id)||(n.add(e.id),localStorage.setItem("btc_badges",JSON.stringify([...n])),"function"==typeof showToast&&showToast(e.emoji+" Badge Earned: "+e.name+"! +"+e.pts+" pts"),"function"==typeof awardPoints&&awardPoints(e.pts,e.emoji+" "+e.name),"function"==typeof showBadgeToast&&showBadgeToast(e))}})}(r),U(r,parseInt(localStorage.getItem("btc_pvp_losses")||"0")),t&&localStorage.setItem(b,(y+1).toString()),n&&localStorage.setItem(h,(x+1).toString())}else if(g)"function"==typeof awardPoints&&awardPoints(5,"⚔️ PVP Draw");else{var o=parseInt(localStorage.getItem("btc_pvp_losses")||"0")+1;localStorage.setItem("btc_pvp_losses",o.toString()),"function"==typeof awardPoints&&c.score>0&&awardPoints(Math.floor(c.score/2),"⚔️ PVP Consolation"),U(parseInt(localStorage.getItem("btc_pvp_wins")||"0"),o)}}t.opponentUid&&S?S.collection("users").doc(t.opponentUid).get().then(function(e){var t=!0,n=!1;if(e.exists){var r=e.data();if(t=!r.email&&!r.authMethod&&!r.nostr,r.created&&r.created.toDate)n=Date.now()-r.created.toDate().getTime()<6e5}w(t,n)}).catch(function(){w(!1,!1)}):w(!1,!1);var P=m?"🏆":g?"🤝":"💀",T=m?"VICTORY!":g?"DRAW!":"DEFEAT",_=m?"#22c55e":g?"#eab308":"#ef4444",I=m?"You dominated! "+p+" rounds won.":g?"Evenly matched! "+p+"–"+d+" tie.":"Better luck next time. "+d+" rounds to "+p+".";"function"==typeof showToast&&(m?showToast("🏆 PVP Victory! "+p+"–"+d+" vs "+N(t.opponentName)):g?showToast("🤝 PVP Draw! "+p+"–"+d+" vs "+N(t.opponentName)):showToast("💀 PVP Defeat. "+d+"–"+p+" vs "+N(t.opponentName)));r.innerHTML='
    '+P+'

    '+T+'

    '+I+'
    '+(m?"🏆 WINNER":g?"🤝 DRAW":"LOST")+'
    '+c.score+'
    '+N(s())+'
    '+p+'/5 rounds won
    '+(m||g?g?"🤝 DRAW":"🏆 WINNER":"💀 LOST")+'
    '+l.score+'
    '+N(t.opponentName)+'
    '+d+'/5 rounds won
    '+function(e,t){for(var n="",r=0;r<5;r++){var o=e[r],i=t[r],a="var(--border)",s="—";o&&o.won?(a="#22c55e",s="✓"):i&&i.won?(a="#ef4444",s="✗"):(a="#eab308",s="·"),n+='
    '+s+"
    "}return n}(u,f)+'
    ',t.listenerUnsub&&(t.listenerUnsub(),t.listenerUnsub=null);t.inMatch=!1;var S=o();S&&t.lobbyDocId&&(S.collection("pvp_lobby").doc(t.lobbyDocId).delete().catch(function(){}),t.lobbyDocId=null)}(c))),"forfeit"===c.status&&c.forfeitedBy!==a()){l=t.isPlayer1?"player1":"player2",p=t.isPlayer1?"player2":"player1";for(var b=0,y=0,h=c[l].answers||[],x=c[p].answers||[],w=0;w<5;w++)h[w]&&h[w].won&&b++,x[w]&&x[w].won&&y++;if("manual_leave"===c.forfeitReason)if(b>y){var P=parseInt(localStorage.getItem("btc_pvp_wins")||"0")+1;localStorage.setItem("btc_pvp_wins",P.toString()),U(P,parseInt(localStorage.getItem("btc_pvp_losses")||"0")),"function"==typeof awardPoints&&awardPoints(c[l].score||10,"⚔️ PVP Victory (opponent forfeited)"),C(!0,"Your opponent left the match. You win! 🏆")}else C(!1,"Your opponent left the match. No win or loss recorded.");else C(!1,"Your opponent disconnected. No win or loss recorded.");t.listenerUnsub&&(t.listenerUnsub(),t.listenerUnsub=null)}}},function(e){console.error("PVP match listener error:",e)})}}function B(){var e=o();e&&t.matchId&&e.collection("pvp_matches").doc(t.matchId).update({status:"active",currentQ:t.currentQ,questionWinner:null,questionStartedAt:firebase.firestore.FieldValue.serverTimestamp()})}function D(e){var n=document.getElementById("pvpOverlay");if(n){var r=e.currentQ,o=e.questions[r];if(o){t.isPlayer1,t.isPlayer1;n.innerHTML='
    You
    '+t.myScore+'
    Question '+(r+1)+' / 5
    '+function(e){for(var n="",r=t.isPlayer1?"player1":"player2",o=e[r].answers||[],i=0;i<5;i++){var a="var(--border)",s="";i'+s+"
    "}return n}(e)+'
    '+N(t.opponentName)+'
    '+t.opponentScore+"
    "+(t.streak>1?'
    🔥 '+t.streak+" streak!
    ":"")+'
    '+N(o.q)+'
    '+o.options.map(function(e,t){return'"}).join("")+'
    ',setTimeout(function(){var e=document.getElementById("pvpTimer");e&&(e.style.width="0%")},100),t._questionTimeout&&clearTimeout(t._questionTimeout),t._questionTimeout=setTimeout(function(){!t.answered&&t.inMatch&&pvpAnswer(r,-1,null)},15e3)}}}function L(e,o,i,a,s,c,l,p,d,u){var f=a[s],v=i[s],m=f&&f.correct,g=!1,b=!1;if(u&&!m)g=!0;else if(!u&&m)b=!0;else{if(!u||!m){var y=n(1);if(y.length>0){var h=r(y[0]),x=o.questions.slice();x[s]=h,e.questions=x}return e[c+".answers"]=i.slice(0,s),e[l+".answers"]=a.slice(0,s),e.questionWinner="reroll",void(e.status="question_result")}var w=v&&v.answeredAt?new Date(v.answeredAt).getTime():1/0,P=f&&f.answeredAt?new Date(f.answeredAt).getTime():1/0;w=0&&(S[z]&&S[z].won);z--)k++;var E=10+(k>1?5*(k-1):0);e[_+".score"]=(I.score||0)+E,e[_+".correct"]=(I.correct||0)+1,e.questionWinner=_;for(var A=1,M=0;M=5?"finished":"question_result"}function C(e,t){var n=document.getElementById("pvpOverlay");if(n){var r=e?"🏆":"🚪",o=e?"#22c55e":"#eab308",i=e?"VICTORY!":"MATCH ENDED";n.innerHTML='
    '+r+'

    '+i+'

    '+t+'
    ',"function"==typeof showToast&&showToast(e?"🏆 You win — opponent forfeited!":"🚪 Opponent left — match voided")}}function U(e,t){"undefined"!=typeof currentUser&¤tUser&&(currentUser.pvpWins=e,currentUser.pvpLosses=t);var n=o(),r=a();n&&r&&n.collection("users").doc(r).update({pvpWins:e,pvpLosses:t}).catch(function(){n.collection("users").doc(r).set({pvpWins:e,pvpLosses:t},{merge:!0}).catch(function(){})})}function N(e){return e?e.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""):""}function j(){"undefined"!=typeof firebase&&firebase.auth&&firebase.auth().onAuthStateChanged(function(e){e&&(l(),"true"===sessionStorage.getItem("btc_pvp_pending")&&(sessionStorage.removeItem("btc_pvp_pending"),setTimeout(function(){"function"==typeof enterPVPMode&&enterPVPMode()},1e3)))}),setTimeout(function(){t.tickerUnsub||l()},5e3),setTimeout(function(){var e=o();e&&e.collection("pvp_lobby").where("status","==","waiting").get().then(function(e){e.forEach(function(e){z(e.data())||e.ref.delete().catch(function(){})})}).catch(function(){})},1e4)}window.pvpAnswer=function(e,n,r){if(!t.answered){t.answered=!0,t._questionTimeout&&(clearTimeout(t._questionTimeout),t._questionTimeout=null);var i=o(),s=a();if(i&&s&&t.matchId){var c=t.questions[e],l=n===c.correct,p=document.getElementById("pvpOptions");if(p){for(var d=p.querySelectorAll("button"),u=0;u=0&&n!==c.correct&&d[n]&&(d[n].style.borderColor="#ef4444",d[n].style.background="rgba(239,68,68,0.15)")}p&&p.insertAdjacentHTML("afterend",'
    '+(l?"✅ Correct! Waiting for opponent...":n<0?"⏰ Time's up!":"❌ Wrong! Waiting for opponent...")+"
    ");var f=t.isPlayer1?"player1":"player2",v={selected:n,correct:l,answeredAt:(new Date).toISOString(),won:!1},m=i.collection("pvp_matches").doc(t.matchId);console.log("[PVP] Submitting answer for Q"+e+", myKey="+f+", correct="+l);var g={},b=[];m.get().then(function(n){if(n.exists){var r=n.data(),o=r[f],i=t.isPlayer1?"player2":"player1";if(!(o.answers&&o.answers.length>e))return(b=(o.answers||[]).slice()).push(v),g[f+".answers"]=b,console.log("[PVP] Writing my answer, oppAnswers.length="+(r[i].answers||[]).length+", qIdx="+e),m.update(g);console.log("[PVP] Already answered Q"+e+", skipping")}else console.error("[PVP] Match doc not found")}).then(function(){console.log("[PVP] Answer written successfully")}).catch(function(e){console.error("[PVP] Answer write FAILED:",e),"function"==typeof showToast&&showToast("⚠️ Failed to submit answer — check connection")})}}},window.addEventListener("pagehide",function(){if(t.lobbyDocId){var e=o();e&&e.collection("pvp_lobby").doc(t.lobbyDocId).delete().catch(function(){})}}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",j):setTimeout(j,2e3),window.enterPVPMode=window.enterPVPMode,window.exitPVPMode=window.exitPVPMode,window.pvpAnswer=window.pvpAnswer,window.PVP_BADGE_DEFS=e}(); \ No newline at end of file diff --git a/pvp.js.src b/pvp.js.src index 7e6ea9337..009974f99 100644 --- a/pvp.js.src +++ b/pvp.js.src @@ -581,6 +581,8 @@ try { var auth = getAuth(); + var db = getDb(); + if (!auth || !db) { throw new Error('Firebase services are not available yet. Please wait a moment and try again.'); } if (!auth.currentUser || auth.currentUser.isAnonymous === undefined) { var cred = await auth.signInAnonymously(); // Wait for auth state to fully propagate @@ -716,6 +718,7 @@ if (pvpState._lobbyHeartbeat) { clearInterval(pvpState._lobbyHeartbeat); pvpState._lobbyHeartbeat = null; } if (pvpState._forceResultTimer) { clearTimeout(pvpState._forceResultTimer); pvpState._forceResultTimer = null; } if (pvpState._oppTimeoutTimer) { clearTimeout(pvpState._oppTimeoutTimer); pvpState._oppTimeoutTimer = null; } + if (pvpState._p1AdvanceTimer) { clearTimeout(pvpState._p1AdvanceTimer); pvpState._p1AdvanceTimer = null; } stopPractice(); stopFunFactRotation(); stopPvpTickerUpdates(); @@ -1364,6 +1367,12 @@ if (!doc.exists) return; var data = doc.data(); + // Clear active timers if match is no longer active + if (data.status !== 'active') { + if (pvpState._oppTimeoutTimer) { clearTimeout(pvpState._oppTimeoutTimer); pvpState._oppTimeoutTimer = null; } + if (pvpState._forceResultTimer) { clearTimeout(pvpState._forceResultTimer); pvpState._forceResultTimer = null; } + } + pvpState.questions = data.questions || []; var myKey = pvpState.isPlayer1 ? 'player1' : 'player2'; @@ -1404,8 +1413,10 @@ var oppAns = data[oppKey].answers || []; console.log('[PVP] Snapshot: status=active, currentQ=' + data.currentQ + ', myAns=' + myAns.length + ', oppAns=' + oppAns.length + ', answered=' + pvpState.answered); if (myAns.length > data.currentQ && oppAns.length > data.currentQ && pvpState.answered) { + if (pvpState._oppTimeoutTimer) { clearTimeout(pvpState._oppTimeoutTimer); pvpState._oppTimeoutTimer = null; } if (!pvpState._forceResultTimer) { - console.log('[PVP] Both answered! Starting force-resolve timer (2s)'); + var delay = pvpState.isPlayer1 ? 1500 : 3500; + console.log('[PVP] Both answered! Starting force-resolve timer (' + delay + 'ms)'); pvpState._forceResultTimer = setTimeout(function() { pvpState._forceResultTimer = null; console.log('[PVP] Force-resolve timer fired, running transaction...'); @@ -1427,7 +1438,7 @@ }).then(function() { console.log('[PVP] Force-resolve transaction committed'); }).catch(function(e) { console.error('[PVP] Force-resolve tx error:', e); }); - }, 2000); + }, delay); } } @@ -1633,8 +1644,21 @@ } else if (!myIsCorrect && oppIsCorrect) { oppWon = true; } else if (myIsCorrect && oppIsCorrect) { - // Both correct — first to commit wins (opponent was already in DB) - oppWon = true; + // Both correct — compare answeredAt timestamps + var myTime = (myAnswer && myAnswer.answeredAt) ? new Date(myAnswer.answeredAt).getTime() : Infinity; + var oppTime = (oppAnswer && oppAnswer.answeredAt) ? new Date(oppAnswer.answeredAt).getTime() : Infinity; + if (myTime < oppTime) { + iWon = true; + } else if (oppTime < myTime) { + oppWon = true; + } else { + // Exact tie, fallback to host/isPlayer1 wins the tie breaker + if (pvpState.isPlayer1) { + iWon = true; + } else { + oppWon = true; + } + } } else { // Both wrong — REROLL var newQ = pickRandomQuestions(1); diff --git a/ranking.js b/ranking.js index cf01d98ed..9154d5791 100644 --- a/ranking.js +++ b/ranking.js @@ -5,12 +5,13 @@ // ============================================= const FIREBASE_CONFIG = { - apiKey: "AIzaSyDLwucmRxjoJp2KMBTi2ujf0mlVkgLHyKk", - authDomain: "bitcoin-education-archive.firebaseapp.com", - projectId: "bitcoin-education-archive", - storageBucket: "bitcoin-education-archive.firebasestorage.app", - messagingSenderId: "1055248200518", - appId: "1:1055248200518:web:6c6d64a5ee78e19bfbeb47" + apiKey: "AIzaSyCkUGX2KWaVGmSQXpYJhWDxF_BSiHRX6SM", + authDomain: "btc-archive-test.firebaseapp.com", + projectId: "btc-archive-test", + storageBucket: "btc-archive-test.firebasestorage.app", + messagingSenderId: "60810625669", + appId: "1:60810625669:web:ea4dacd55333e41429dfec", + measurementId: "G-7C2FKDJ8E4" }; // Levels diff --git a/ux-patches.js b/ux-patches.js index 1729ab7fd..0c4766d1d 100644 --- a/ux-patches.js +++ b/ux-patches.js @@ -1489,71 +1489,10 @@ console.log('✅ UX Patches loaded — 24 tasks from the UX Review Report'); // ---- PVP Answer: Server-Side Validation Override ---- // Routes pvpAnswer through Cloud Function instead of direct Firestore write +// REMOVED: Cloud function not used in current project (function() { 'use strict'; - var _origPvpAnswer = null; - function patchPvpAnswer() { - if (typeof window.pvpAnswer !== 'function') return; - if (window._pvpAnswerPatched) return; - window._pvpAnswerPatched = true; - _origPvpAnswer = window.pvpAnswer; - - window.pvpAnswer = function(questionIdx, answerIdx, btnEl) { - // Still do the UI updates from original (disable buttons, show colors) - var t = window._pvpState || {}; - if (t.answered) return; - t.answered = true; - if (t._questionTimeout) { clearTimeout(t._questionTimeout); t._questionTimeout = null; } - - // UI feedback - var questions = t.questions || []; - var q = questions[questionIdx]; - if (q && btnEl) { - var opts = btnEl.parentElement; - if (opts) { - var btns = opts.querySelectorAll('button'); - for (var i = 0; i < btns.length; i++) { - btns[i].disabled = true; - btns[i].style.cursor = 'default'; - btns[i].style.opacity = '0.7'; - } - if (btns[q.correct]) { - btns[q.correct].style.borderColor = '#22c55e'; - btns[q.correct].style.background = 'rgba(34,197,94,0.15)'; - btns[q.correct].style.opacity = '1'; - } - if (answerIdx >= 0 && answerIdx !== q.correct && btns[answerIdx]) { - btns[answerIdx].style.borderColor = '#ef4444'; - btns[answerIdx].style.background = 'rgba(239,68,68,0.15)'; - } - } - if (opts) opts.insertAdjacentHTML('afterend', '
    ' + (answerIdx === q.correct ? '✅ Correct! Waiting...' : answerIdx < 0 ? '⏰ Time\'s up!' : '❌ Wrong! Waiting...') + '
    '); - } - - // Submit via Cloud Function - if (typeof firebase !== 'undefined' && firebase.functions && t.matchId) { - firebase.functions().httpsCallable('pvpSubmitAnswer')({ - matchId: t.matchId, - questionIndex: questionIdx, - answerIndex: answerIdx - }).then(function(result) { - if (result.data && result.data.alreadyAnswered) { - console.log('[PVP] Already answered, idempotent'); - } - }).catch(function(err) { - console.error('[PVP] Server answer submission failed:', err); - if (typeof showToast === 'function') showToast('⚠️ Answer submit failed — check connection'); - }); - } - }; - } - // Patch after PVP loads - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', function() { setTimeout(patchPvpAnswer, 3000); }); - } else { - setTimeout(patchPvpAnswer, 3000); - } // Also re-patch on enterPVPMode — retry until pvp.js loads var _origEnterPVP = null; var _pvpPatchAttempts = 0; @@ -1564,7 +1503,6 @@ console.log('✅ UX Patches loaded — 24 tasks from the UX Review Report'); _origEnterPVP = window.enterPVPMode; window.enterPVPMode = function() { _origEnterPVP.apply(this, arguments); - setTimeout(patchPvpAnswer, 500); // Announce PVP lobby entry in Global Chat var _pvpName = (typeof currentUser !== 'undefined' && currentUser && currentUser.username) ? currentUser.username : null; if (_pvpName && typeof window.nachoGlobalAnnounce === 'function') { From 8e3cde2bd30b177c8df52e05e1dd68383be93b30 Mon Sep 17 00:00:00 2001 From: 0xrasmp Date: Wed, 10 Jun 2026 17:34:16 +0100 Subject: [PATCH 2/7] Route all PVP entry points through _launchPVP for reliable loading --- app.js | 8 ++++---- bundle.js | 2 +- bundle.src.js | 34 ++++++++++++++++++++++++++-------- ranking.js | 4 ++-- 4 files changed, 33 insertions(+), 15 deletions(-) diff --git a/app.js b/app.js index 0f39025d1..55a5beb69 100644 --- a/app.js +++ b/app.js @@ -2827,7 +2827,7 @@ window.nachoQuizAnswer = function(btn, correct) { // P = donate if (key === 'p') { showDonateModal(); return; } // X = PVP Battle - if (key === 'x') { if (typeof enterPVPMode === 'function') enterPVPMode(); return; } + if (key === 'x') { if (typeof _launchPVP === 'function') _launchPVP(); return; } // === Scroll === // J = scroll down @@ -3752,7 +3752,7 @@ window.nachoQuizAnswer = function(btn, correct) { { id: '_art', title: '🎨 Random Art', desc: 'See random Bitcoin art and inspiration', keywords: 'art random artwork creative inspiration gallery', action: 'goRandomArt()' }, { id: '_graphic', title: '📊 Random Graphic', desc: 'See a random Bitcoin graphic or chart', keywords: 'graphic chart data visual infographic random graphics', action: 'goRandomGraphic()' }, { id: '_quiz', title: '🎮 Quiz Me', desc: 'Test your Bitcoin knowledge with Nacho', keywords: 'quiz question test knowledge trivia game answer', action: 'nachoQuizMe()' }, - { id: '_pvp', title: '⚔️ PVP Battle', desc: 'Real-time Bitcoin trivia battles against other players', keywords: 'pvp battle fight 1v1 versus trivia quiz compete multiplayer arena duel challenge opponent leaderboard wins losses', action: 'enterPVPMode()' }, + { id: '_pvp', title: '⚔️ PVP Battle', desc: 'Real-time Bitcoin trivia battles against other players', keywords: 'pvp battle fight 1v1 versus trivia quiz compete multiplayer arena duel challenge opponent leaderboard wins losses', action: '_launchPVP()' }, { id: '_donate', title: '💛 Donate', desc: 'Support Bitcoin Education Archive with sats', keywords: 'donate support tip sats lightning contribute funding', action: 'showDonateModal()' }, { id: '_theme', title: '🌙 Toggle Theme', desc: 'Switch between dark and light mode', keywords: 'theme dark light mode toggle switch appearance color night day', action: 'document.getElementById("themeToggle").click()' }, { id: '_audio', title: '🔊 Toggle Audio', desc: 'Turn sound effects on or off', keywords: 'audio sound music mute volume effects toggle', action: 'toggleAudio()' }, @@ -4410,7 +4410,7 @@ if (locked) { // PVP Battle if (hash === 'pvp' || state.channel === 'pvp') { - if (typeof enterPVPMode === 'function') enterPVPMode(); + if (typeof _launchPVP === 'function') _launchPVP(); return; } @@ -4608,7 +4608,7 @@ if (locked) { if (typeof enterNachoMode === 'function') { enterNachoMode(); return; } break; case 'pvp': - if (typeof enterPVPMode === 'function') { enterPVPMode(); return; } + if (typeof _launchPVP === 'function') { _launchPVP(); return; } break; case 'forum': if (typeof go === 'function') { go('forum'); return; } diff --git a/bundle.js b/bundle.js index 6b230e2b1..7bdff9bf8 100644 --- a/bundle.js +++ b/bundle.js @@ -1 +1 @@ -var CHANNELS={decentralized:{cat:"Properties Layer 1",title:"👪decentralized-censorship-resistant-ungovernable-incorruptible-trustless-unconfiscatable-updatable",desc:"Why no single person, company, or government controls Bitcoin — and why that's the most important feature.",file:"data/D_decentralized.json"},dominant:{cat:"Properties Layer 1",title:"🏆dominant-recognizable-brand-legitimate-limitless-infinite-exponential-transformative-revolutionary",desc:"Bitcoin's brand recognition, network effects, and why it has maintained the #1 position since 2009.",file:"data/D_dominant.json"},money:{cat:"Properties Layer 1",title:"💰money-deflationary-salable-durable-anti-fragile-divisible-portable-transmittable-verifiable-fair",desc:"What money actually is, how it works, and why Bitcoin satisfies every property of sound money better than anything before it.",file:"data/D_money.json"},organic:{cat:"Properties Layer 1",title:"🌳organic-empowering-elegant-freedom-centric-irrefutable-unseizable-irreversible-unbreakable",desc:"How Bitcoin grew from an idea worth nothing to a trillion-dollar network — without marketing, without a company, without a leader.",file:"data/D_organic.json"},peaceful:{cat:"Properties Layer 1",title:"☮peaceful-neutral-voluntary-open-universal-permissionless-borderless-global-inevitable-unstoppable",desc:"Bitcoin is voluntary, permissionless, borderless, and unstoppable. No one forces you to use it — and no one can stop you.",file:"data/D_peaceful.json"},programmable:{cat:"Properties Layer 1",title:"🤖programable-interoperable-deflationary-pseudonymous-opt-in-resilient-adiabatic-egalitarian",desc:"Bitcoin as programmable money — interoperable, pseudonymous, resilient, and thermodynamically sound.",file:"data/D_programmable.json"},scarce:{cat:"Properties Layer 1",title:"🍀scarce-unforgeable-hedge-scalable-p2p-instant-open-source-auditable-inaliable",desc:"Only 21 million will ever exist. Explore what makes Bitcoin the scarcest asset humanity has ever created.",file:"data/D_scarce.json"},secure:{cat:"Properties Layer 1",title:"™secure-fungible-immutable-incorruptible-immalleable-infallible-reliable-predictable-irreplicable",desc:"How Bitcoin's network security makes it virtually impossible to hack — protected by more computing power than anything on Earth.",file:"data/D_secure.json"},supranational:{cat:"Properties Layer 1",title:"🕊supranational-lindy-inviolate-dilution-proof-frictionless-freely-accessible-settlement-finality",desc:"Bitcoin transcends nations and governments. Explore the Lindy Effect, settlement finality, and dilution-proof money.",file:"data/D_supranational.json"},"use-cases":{cat:"Properties Layer 1",title:"✔use-cases",desc:"Real-world uses for Bitcoin: savings, payments, remittances, store of value, and more.",file:"data/D_use-cases.json"},whitepaper:{cat:"Properties Layer 1",title:"📄whitepaper",desc:"The 9-page document that started it all. Published October 31, 2008 by Satoshi Nakamoto — the foundation of Bitcoin.",file:"data/D_whitepaper.json"},bitvm:{cat:"Experienced Topics",title:"🖥bitvm",desc:"BitVM: computation on Bitcoin without changing the protocol. A new frontier for Bitcoin programmability.",file:"data/E_bitvm.json"},"blockchain-timechain":{cat:"Experienced Topics",title:"⛓blockchain-timechain-transactions-addresses",desc:"How the Bitcoin blockchain (timechain) works — blocks, transactions, timestamps, and the immutable ledger.",file:"data/E_blockchain-timechain.json"},"chaumian-mints":{cat:"Experienced Topics",title:"💸layer-2-chaumian-mints-ecash",desc:"Chaumian ecash, Cashu, and blinded signatures — the cutting edge of Bitcoin privacy technology.",file:"data/E_chaumian-mints.json"},consensus:{cat:"Additional Info",title:"🤝Consensus",desc:"How Bitcoin achieves consensus without a central authority — Nakamoto Consensus and beyond.",file:"data/H_consensus.json"},"core-source-code":{cat:"Experienced Topics",title:"💾core-source-code-forks-testnet-future-potential-upgrades",desc:"Bitcoin Core's source code, forks, testnet, and the open-source development process.",file:"data/E_core-source-code.json"},cryptography:{cat:"Experienced Topics",title:"🔒cryptography-cypherpunks",desc:"The cryptographic foundations of Bitcoin — SHA-256, elliptic curves, digital signatures, and the cypherpunk legacy.",file:"data/E_cryptography.json"},"ctv-covenants":{cat:"Experienced Topics",title:"📜ctv-bip119-covenants",desc:"BIP-119, CTV, and Bitcoin covenants — proposed upgrades and the debates around them.",file:"data/E_ctv-covenants.json"},developers:{cat:"Experienced Topics",title:"🖥developers",desc:"Building on Bitcoin — resources, guides, and paths for developers who want to contribute.",file:"data/E_developers.json"},"difficulty-adjustment":{cat:"Experienced Topics",title:"😤difficulty-adjustment",desc:"The most elegant part of Bitcoin's design — how the network self-adjusts every 2,016 blocks.",file:"data/E_difficulty-adjustment.json"},energy:{cat:"Experienced Topics",title:"💡energy",desc:"The truth about Bitcoin's energy use: 0.1% of global energy, renewable mining, methane capture, and grid stabilization.",file:"data/E_energy.json"},"evidence-against-alts":{cat:"Experienced Topics",title:"⚠evidence-against-ethereum-other-alt-coins-crypto-defi-nfts-web3-monero-bsv-bch-cbdcs-other-projects",desc:"Why every altcoin fails against Bitcoin — premines, centralization, broken promises, and the evidence.",file:"data/E_evidence-against-alts.json"},"extension-blocks":{cat:"Experienced Topics",title:"🚧extension-blocks-and-other-proposed-scaling-solutions",desc:"Extension blocks and other proposed scaling solutions for Bitcoin.",file:"data/E_extension-blocks.json"},"fedi-ark":{cat:"Experienced Topics",title:"🛡layer-2-fedi-ark",desc:"Fedimints, Ark, and Bitcoin's privacy/scaling layers — community custody with enhanced privacy.",file:"data/E_fedi-ark.json"},"investment-strategy":{cat:"Experienced Topics",title:"🤑investment-strategy-taxes-retirement-inheritance-loans-donate-gift-consulting-remittance",desc:"DCA, HODL, lump sum strategies, taxes, retirement planning, and thinking long-term with Bitcoin.",file:"data/E_investment-strategy.json"},"layer-2-lightning":{cat:"Experienced Topics",title:"⚡layer-2-lightning",desc:"The Lightning Network: instant, nearly-free Bitcoin payments. How Bitcoin scales without sacrificing decentralization.",file:"data/E_layer-2-lightning.json"},"layer-3-sidechains":{cat:"Experienced Topics",title:"📱layer-3-sidechain-applications",desc:"Sidechains, Liquid Network, and layer-3 applications built on top of Bitcoin.",file:"data/E_layer-3-sidechains.json"},maximalism:{cat:"Experienced Topics",title:"💯maximalism",desc:"Why people who study Bitcoin the most become maximalists. The case for Bitcoin-only.",file:"data/E_maximalism.json"},mining:{cat:"Experienced Topics",title:"🌋mining",desc:"How Bitcoin mining actually works — nonces, SHA-256 hashing, difficulty adjustment, and the brute-force lottery.",file:"data/E_mining.json"},nodes:{cat:"Experienced Topics",title:"💻nodes",desc:"Run your own Bitcoin node. Don't trust, verify. How 14,000+ nodes keep the network decentralized.",file:"data/E_nodes.json"},"op-codes":{cat:"Experienced Topics",title:"👨‍💻op-codes-simplicity",desc:"OP_CAT, Simplicity, and Bitcoin's scripting language — the building blocks of smart functionality.",file:"data/E_op-codes.json"},"pow-vs-pos":{cat:"Experienced Topics",title:"💪proof-of-work-vs-proof-of-stake",desc:"Why Proof of Work is fundamentally superior to Proof of Stake — energy, security, fairness, and decentralization.",file:"data/E_pow-vs-pos.json"},"privacy-nonkyc":{cat:"Experienced Topics",title:"🤫privacy-nonkyc-stacking-self-sovereignty",desc:"Financial privacy as a human right. KYC, non-KYC stacking, and protecting your sovereignty.",file:"data/E_privacy-nonkyc.json"},"problems-of-money":{cat:"Experienced Topics",title:"📉the-problems-of-todays-money-and-freedom",desc:"The broken fiat system: inflation, money printing, the Cantillon Effect, and why today's money is failing everyone.",file:"data/E_problems-of-money.json"},regulation:{cat:"Experienced Topics",title:"🏛regulation-policy-legal",desc:"Bitcoin and government: bans, adoption, legal tender, ETFs, and why regulation can't stop decentralization.",file:"data/E_regulation.json"},"self-custody":{cat:"Experienced Topics",title:"🔑personal-storage-self-custody-security",desc:"Not your keys, not your coins. Learn how to truly own your Bitcoin with wallets, seed phrases, and security.",file:"data/E_self-custody.json"},"smart-contracts":{cat:"Experienced Topics",title:"📱smart-contracts",desc:"Smart contracts on Bitcoin — what's possible, what's coming, and why Bitcoin's approach is different.",file:"data/E_smart-contracts.json"},stablecoins:{cat:"Additional Info",title:"🪙Stablecoins",desc:"The role of stablecoins in the Bitcoin economy — and why they're not a threat to Bitcoin.",file:"data/H_stablecoins.json"},"0_mining__hashing":{cat:"Additional Info",title:"0⃣Mining (Hashing)",desc:"Deep dive into Bitcoin mining and hashing — how SHA-256 works at the bit level.",file:"data/H_0_mining__hashing.json"},"100_sats":{cat:"Additional Info",title:"💯100 sats",desc:"What can you do with just 100 satoshis? More than you think.",file:"data/H_100_sats.json"},"1_first_principles":{cat:"Additional Info",title:"1⃣First Principles",desc:"First principles thinking applied to Bitcoin — reasoning from fundamentals, not analogies.",file:"data/H_1_first_principles.json"},"2__solved_technical_problems":{cat:"Additional Info",title:"2⃣ Solved Technical Problems",desc:"The technical problems Bitcoin solved — digital scarcity, double-spending, and Byzantine fault tolerance.",file:"data/H_2__solved_technical_problems.json"},analogies:{cat:"Additional Info",title:"🔋Analogies",desc:"The best analogies for explaining Bitcoin to anyone — from trees to brains to hearts.",file:"data/H_analogies.json"},austrian_school_of_economics:{cat:"Additional Info",title:"🇦🇹Austrian School of Economics",desc:"Austrian Economics and Bitcoin: Mises, Hayek, sound money theory, and the intellectual foundation.",file:"data/H_austrian_school_of_economics.json"},bip119:{cat:"Additional Info",title:"🚧BIP119",desc:"BIP-119 (CheckTemplateVerify) — what it is, why it's controversial, and the community debate.",file:"data/H_bip119.json"},bitcoin_exam:{cat:"Additional Info",title:"🎓Bitcoin Exam",desc:"Test questions for a Bitcoin exam — study material and self-assessment.",file:"data/H_bitcoin_exam.json"},bitcoin_vs_real_estate:{cat:"Additional Info",title:"Bitcoin vs Real Estate",desc:"Bitcoin vs. real estate as an investment — comparing the two hardest assets.",file:"data/H_bitcoin_vs_real_estate.json"},"block_time-block-size":{cat:"Additional Info",title:"⏰Block Time-Block-Size",desc:"Why Bitcoin uses 10-minute blocks and how block size affects the network.",file:"data/H_block_time-block-size.json"},burn_bitcoin:{cat:"Additional Info",title:"Burn bitcoin",desc:"How Bitcoin can be burned (made permanently unspendable) and why people do it.",file:"data/H_burn_bitcoin.json"},byzantine_generals__problem:{cat:"Additional Info",title:"⚔Byzantine Generals’ Problem",desc:"The Byzantine Generals' Problem — the computer science challenge Satoshi solved.",file:"data/H_byzantine_generals__problem.json"},"chaumian_e-cash_and_blind_signatures":{cat:"Additional Info",title:"💲Chaumian E-cash and Blind Signatures",desc:"David Chaum's ecash, blind signatures, and the cryptographic foundations of digital privacy.",file:"data/H_chaumian_e-cash_and_blind_signatures.json"},coin_mixing_coinjoin_coin_control_utxo:{cat:"Additional Info",title:"🌀Coin Mixing/Coinjoin/Coin Control/UTXO Management",desc:"CoinJoin, coin mixing, UTXO management — advanced Bitcoin privacy techniques.",file:"data/H_coin_mixing_coinjoin_coin_control_utxo.json"},cyles:{cat:"Additional Info",title:"🚲Cyles",desc:"Bitcoin's 4-year cycles, Gartner Hype Cycles, and whether the pattern continues.",file:"data/H_cyles.json"},derivation_path:{cat:"Additional Info",title:"↕Derivation Path",desc:"HD wallet derivation paths — how your seed phrase generates all your addresses.",file:"data/H_derivation_path.json"},discrete_log_contracts__dlcs:{cat:"Additional Info",title:"📝Discrete Log Contracts (DLCs)?",desc:"DLCs (Discrete Log Contracts) — smart contracts on Bitcoin using oracle signatures.",file:"data/H_discrete_log_contracts__dlcs.json"},"dollar-bitcoin_milkshake_theory":{cat:"Additional Info",title:"🥤Dollar-Bitcoin Milkshake Theory",desc:"The Dollar-Bitcoin Milkshake Theory — how global dollar demand and Bitcoin intersect.",file:"data/H_dollar-bitcoin_milkshake_theory.json"},dust:{cat:"Additional Info",title:"⏳Dust",desc:"Dust UTXOs: what they are, why they're a problem, and how to manage them.",file:"data/H_dust.json"},elevator_pitches:{cat:"Additional Info",title:"↕Elevator Pitches",desc:"Quick 20-30 second explanations of why Bitcoin matters — for every audience.",file:"data/H_elevator_pitches.json"},environment___energy:{cat:"Additional Info",title:"🌳Environment & Energy",desc:"Bitcoin and the environment: energy usage facts, renewable mining, and debunking the FUD.",file:"data/H_environment___energy.json"},faith___religion:{cat:"Additional Info",title:"🙏Faith & Religion",desc:"Bitcoin and faith — how sound money relates to religious and spiritual values.",file:"data/H_faith___religion.json"},fedimints:{cat:"Additional Info",title:"💚Fedimints",desc:"Fedimints: community custody with enhanced privacy using federated Chaumian mints.",file:"data/H_fedimints.json"},feedback_loops:{cat:"Additional Info",title:"➰Feedback Loops",desc:"Bitcoin's feedback loops — the self-reinforcing cycles that drive adoption and security.",file:"data/H_feedback_loops.json"},free_and_open_source_software__foss:{cat:"Additional Info",title:"💿Free and Open Source Software (FOSS)",desc:"Free and open source software (FOSS) projects connected to Bitcoin.",file:"data/H_free_and_open_source_software__foss.json"},game_theory:{cat:"Additional Info",title:"🏈Game Theory",desc:"Game theory and Bitcoin: Nash equilibrium, prisoner's dilemma, and strategic incentives.",file:"data/H_game_theory.json"},geopolitics___macroeconomics:{cat:"Additional Info",title:"💰Geopolitics & Macroeconomics",desc:"Bitcoin's role in geopolitics: nation-state adoption, reserve currencies, and macro trends.",file:"data/H_geopolitics___macroeconomics.json"},governance:{cat:"Additional Info",title:"🏛Governance",desc:"How Bitcoin is governed — consensus mechanisms, BIPs, and decentralized decision-making.",file:"data/H_governance.json"},ham_radio:{cat:"Additional Info",title:"Ham Radio",desc:"Using Bitcoin without internet — ham radio, mesh networks, and offline transactions.",file:"data/H_ham_radio.json"},human_rights__social_justice_and_freedo:{cat:"Additional Info",title:"🗽Human Rights, Social Justice and Freedom",desc:"Bitcoin as a tool for human rights, social justice, and financial freedom worldwide.",file:"data/H_human_rights__social_justice_and_freedo.json"},improved_incentive_structure:{cat:"Additional Info",title:"✅Improved Incentive Structure",desc:"How Bitcoin's incentive structure improves civilization — aligning individual and collective interests.",file:"data/H_improved_incentive_structure.json"},laws_of_thermodynamics:{cat:"Additional Info",title:"🔥Laws of Thermodynamics",desc:"How Bitcoin follows the laws of thermodynamics — energy, entropy, and proof of work.",file:"data/H_laws_of_thermodynamics.json"},lightning_node:{cat:"Additional Info",title:"⚡ Lightning Node",desc:"Running a Lightning Network node — setup guides, routing, and earning sats.",file:"data/H_lightning_node.json"},lindy_effect:{cat:"Additional Info",title:"👴Lindy Effect",desc:"The Lindy Effect: the longer Bitcoin survives, the longer it will survive.",file:"data/H_lindy_effect.json"},market_cap:{cat:"Additional Info",title:"🧢Market Cap",desc:"Bitcoin's market cap potential — can it reach millions per coin? The math says yes.",file:"data/H_market_cap.json"},math:{cat:"Additional Info",title:"➕Math",desc:"The mathematics of Bitcoin — from SHA-256 to elliptic curves to probability.",file:"data/H_math.json"},mathematics:{cat:"Additional Info",title:"➕Mathematics",desc:"Advanced mathematical concepts underlying Bitcoin's protocol and security.",file:"data/H_mathematics.json"},mev:{cat:"Additional Info",title:"⛏MEV",desc:"MEV (Miner Extractable Value) in Bitcoin — what it is and its implications.",file:"data/H_mev.json"},network_effects:{cat:"Additional Info",title:"🌐Network Effects",desc:"Bitcoin's network effects — why the most adopted network wins and keeps winning.",file:"data/H_network_effects.json"},open_source:{cat:"Additional Info",title:"⭕Open Source",desc:"What free and open source really means — and why it matters for Bitcoin.",file:"data/H_open_source.json"},oracle:{cat:"Additional Info",title:"🔮Oracle",desc:"Oracles in Bitcoin — how external data connects to the blockchain.",file:"data/H_oracle.json"},"orange-pilling":{cat:"Additional Info",title:"🟠Orange-Pilling",desc:"The art of orange-pilling — strategies for explaining Bitcoin to different audiences.",file:"data/H_orange-pilling.json"},ordinals:{cat:"Additional Info",title:"Ordinals",desc:"Bitcoin Ordinals and inscriptions — NFTs on the world's most secure blockchain.",file:"data/H_ordinals.json"},ordinals__nfts_on_bitcoin__and_block_spa:{cat:"Additional Info",title:"Ordinals, NFTs on Bitcoin, and Block Space",desc:"The Ordinals debate: NFTs on Bitcoin, block space economics, and community perspectives.",file:"data/H_ordinals__nfts_on_bitcoin__and_block_spa.json"},"peace_and_anti-war":{cat:"Additional Info",title:"☮Peace and Anti-War",desc:"Can a Bitcoin Standard end wars? The case for Bitcoin as a force for peace.",file:"data/H_peace_and_anti-war.json"},philosophy:{cat:"Additional Info",title:"🍎Philosophy",desc:"The philosophy of Bitcoin — from first principles to existential implications.",file:"data/H_philosophy.json"},politics:{cat:"Additional Info",title:"🏛Politics",desc:"Bitcoin and politics — how Bitcoin intersects with government policy and elections.",file:"data/H_politics.json"},predictions:{cat:"Additional Info",title:"🔮Predictions",desc:"Bitcoin predictions timestamped by the community — bold calls and their outcomes.",file:"data/H_predictions.json"},public_key_vs_private_key:{cat:"Additional Info",title:"🗝Public Key vs Private Key",desc:"Public keys vs. private keys — the cryptographic foundation of Bitcoin ownership.",file:"data/H_public_key_vs_private_key.json"},rbf:{cat:"Additional Info",title:"↔RBF",desc:"Replace-By-Fee (RBF) — how to speed up stuck Bitcoin transactions.",file:"data/H_rbf.json"},"referral-links":{cat:"Referral Links",title:"🔗free-btc-referral-links",desc:"Curated Bitcoin referral links — earn free sats with trusted platforms like River, Fold, and Strike.",file:"data/H_referral-links.json"},risks__threats__attack_vectors__weaknes:{cat:"Additional Info",title:"⚔Risks, Threats, Attack Vectors, Weaknesses, Issues",desc:"Bitcoin's risks, threats, and attack vectors — what could go wrong and why it probably won't.",file:"data/H_risks__threats__attack_vectors__weaknes.json"},rollups:{cat:"Additional Info",title:"🥐Rollups",desc:"Rollups on Bitcoin — scaling and privacy solutions using off-chain computation.",file:"data/H_rollups.json"},sats__or__bits:{cat:"Additional Info",title:'"Sats" or "Bits"?',desc:"The sats vs. bits debate — which denomination should Bitcoin use?",file:"data/H_sats__or__bits.json"},scalability:{cat:"Additional Info",title:"🌐Scalability",desc:"Can Bitcoin scale to serve the world? Layers, Lightning, and the path forward.",file:"data/H_scalability.json"},sidechains:{cat:"Additional Info",title:"♻Sidechains",desc:"Bitcoin sidechains like Liquid — benefits, tradeoffs, and use cases.",file:"data/H_sidechains.json"},simplified_payment_verification__spv:{cat:"Additional Info",title:"✔Simplified Payment Verification (SPV)",desc:"SPV (Simplified Payment Verification) — lightweight Bitcoin verification without a full node.",file:"data/H_simplified_payment_verification__spv.json"},soft_vs_hard_forks:{cat:"Additional Info",title:"🍴Soft vs Hard Forks",desc:"Soft forks vs. hard forks — how Bitcoin upgrades while maintaining consensus.",file:"data/H_soft_vs_hard_forks.json"},softwar:{cat:"Additional Info",title:"Softwar",desc:"Jason Lowery's Softwar thesis — Bitcoin as a non-lethal alternative to physical warfare.",file:"data/H_softwar.json"},stratum_v2:{cat:"Additional Info",title:"🟩Stratum V2",desc:"Stratum V2 — the next-generation mining protocol for better decentralization and efficiency.",file:"data/H_stratum_v2.json"},submarine_swap:{cat:"Additional Info",title:"⛵Submarine Swap",desc:"Submarine swaps — trustlessly moving Bitcoin between on-chain and Lightning.",file:"data/H_submarine_swap.json"},swaps:{cat:"Additional Info",title:"↔Swaps",desc:"How to swap between on-chain Bitcoin and Lightning — tools, techniques, and protocols.",file:"data/H_swaps.json"},ta_tips:{cat:"Additional Info",title:"📈TA Tips",desc:"Technical analysis tips for Bitcoin — chart patterns, indicators, and trading education.",file:"data/H_ta_tips.json"},tail_emission:{cat:"Additional Info",title:"🐈Tail Emission",desc:"The tail emission debate — should Bitcoin ever have perpetual block rewards?",file:"data/H_tail_emission.json"},taproot:{cat:"Additional Info",title:"🧰Taproot",desc:"Taproot: Bitcoin's latest major upgrade — Schnorr signatures, script improvements, and privacy.",file:"data/H_taproot.json"},taro:{cat:"Additional Info",title:"🥕Taro",desc:"Taro (now Taproot Assets) — issuing assets on the Bitcoin and Lightning networks.",file:"data/H_taro.json"},the_future:{cat:"Additional Info",title:"🔮The Future",desc:"How Bitcoin could change the future — hyperbitcoinization, global adoption, and beyond.",file:"data/H_the_future.json"},time:{cat:"Additional Info",title:"⏰Time",desc:"How Bitcoin keeps time — block time, timestamps, and the decentralized clock.",file:"data/H_time.json"},time_preference:{cat:"Additional Info",title:"🕑Time Preference",desc:"Time preference: how sound money encourages long-term thinking and civilization building.",file:"data/H_time_preference.json"},toxicity:{cat:"Additional Info",title:"☣ Toxicity",desc:"Is Bitcoin community toxicity real? Or is it integrity? The debate and its meaning.",file:"data/H_toxicity.json"},transaction_fees:{cat:"Additional Info",title:"💲Transaction Fees",desc:"Bitcoin transaction fees — how they work, fee markets, and long-term sustainability.",file:"data/H_transaction_fees.json"},unpopular_opinions:{cat:"Additional Info",title:"💀Unpopular Opinions",desc:"Unpopular opinions in the Bitcoin space — controversial takes and honest debates.",file:"data/H_unpopular_opinions.json"},utxos:{cat:"Additional Info",title:"🕳UTXOs",desc:"UTXOs (Unspent Transaction Outputs) — the fundamental building block of Bitcoin transactions.",file:"data/H_utxos.json"},vbyte:{cat:"Additional Info",title:"🏋vByte",desc:"Virtual bytes (vBytes) — how Bitcoin measures transaction weight for fee calculation.",file:"data/H_vbyte.json"},"apps-tools":{cat:"Resources",title:"🍎apps-tools-services-models",desc:"Bitcoin apps, tools, services, and platforms — everything you need to use Bitcoin daily.",file:"data/R_apps-tools.json"},"art-inspiration":{cat:"Resources",title:"🤩art-inspiration-motivation",desc:"Bitcoin art, inspiration, and motivational content from the community.",file:"data/R_art-inspiration.json"},"articles-threads":{cat:"Resources",title:"📃articles-threads",desc:"The best Bitcoin articles and Twitter threads — curated deep dives into every aspect of Bitcoin.",file:"data/R_articles-threads.json"},books:{cat:"Resources",title:"📚books",desc:"The essential Bitcoin reading list: The Bitcoin Standard, 21 Lessons, Mastering Bitcoin, and more.",file:"data/R_books.json"},charts:{cat:"Resources",title:"📊charts",desc:"Bitcoin price charts, on-chain analytics, stock-to-flow, and data visualizations.",file:"data/R_charts.json"},curriculum:{cat:"Resources",title:"🎓curriculum-presentations",desc:"Bitcoin education curriculum and presentations for teachers and students.",file:"data/R_curriculum.json"},"faq-glossary":{cat:"Resources",title:"❓faq-glossary-search-ai-calendar",desc:"Bitcoin FAQ, glossary of terms, and quick answers to common questions.",file:"data/R_faq-glossary.json"},"fun-facts":{cat:"Resources",title:"🎉fun-facts",desc:"Mind-blowing Bitcoin trivia: Pizza Day, Satoshi's birthday code, lost coins, and 200+ amazing facts.",file:"data/R_fun-facts.json"},games:{cat:"Resources",title:"🎮games",desc:"Bitcoin-themed games and gamified learning experiences.",file:"data/R_games.json"},"giga-chad":{cat:"Resources",title:"👑giga-chad",desc:"Michael Saylor, MicroStrategy, and the corporate Bitcoin movement.",file:"data/R_giga-chad.json"},graphics:{cat:"Resources",title:"🎨graphics",desc:"Bitcoin infographics, charts, diagrams, and visual explanations.",file:"data/R_graphics.json"},hardware:{cat:"Resources",title:"💻hardware",desc:"Bitcoin hardware: mining rigs, hardware wallets, nodes, and open-source projects like Bitaxe.",file:"data/R_hardware.json"},health:{cat:"Resources",title:"🥩health",desc:"Bitcoin and health: low time preference living, breaking free from the system.",file:"data/R_health.json"},history:{cat:"Resources",title:"📆history",desc:"The complete history of Bitcoin — from the cypherpunks to today.",file:"data/R_history.json"},"informational-sites":{cat:"Resources",title:"📃informational-sites-courses-workshops-newsletters-projects-communities-meetups-conferences",desc:"Bitcoin dashboards, tools, courses, newsletters, communities, and educational websites.",file:"data/R_informational-sites.json"},international:{cat:"Resources",title:"🌍international",desc:"Bitcoin resources in multiple languages and global adoption stories.",file:"data/R_international.json"},"jobs-earn":{cat:"Resources",title:"👷job-postings-employer-info-entrepreneurship-earn-bitcoin-stack-sats",desc:"Bitcoin job boards, entrepreneurship resources, and ways to earn sats.",file:"data/R_jobs-earn.json"},"memes-funny":{cat:"Resources",title:"😂memes-funny",desc:"The best Bitcoin memes, jokes, and humor from the community. Laugh while you learn.",file:"data/R_memes-funny.json"},"misconceptions-fud":{cat:"Resources",title:"🤡common-misconceptions-fud-debunked",desc:"Every Bitcoin myth debunked: too volatile, wastes energy, used by criminals, no intrinsic value — all wrong.",file:"data/R_misconceptions-fud.json"},"movies-tv":{cat:"Resources",title:"🎬movies-tv-documentaries",desc:"Bitcoin documentaries, films, and TV appearances. From The Big Short to Bitcoin-specific docs.",file:"data/R_movies-tv.json"},music:{cat:"Resources",title:"🎵music",desc:"Bitcoin-inspired music, songs, and audio content from the community.",file:"data/R_music.json"},"news-adoption":{cat:"Resources",title:"📰news-adoption",desc:"Latest Bitcoin news, adoption milestones, and real-world usage stories.",file:"data/R_news-adoption.json"},nostr:{cat:"Resources",title:"💜nostr",desc:"Nostr: the decentralized social protocol Bitcoiners are building on. Social media you can't be censored from.",file:"data/R_nostr.json"},"one-stop-shop":{cat:"Resources",title:"🛑one-stop-shop",desc:"The best resources to understand Bitcoin's value as fast as possible. Start here if you're new.",file:"data/R_one-stop-shop.json"},podcasts:{cat:"Resources",title:"🔊podcasts",desc:"Top Bitcoin podcasts: Bitcoin Audible, What Bitcoin Did, Stephan Livera, and more.",file:"data/R_podcasts.json"},"poems-stories":{cat:"Resources",title:"📒poems-stories-jokes",desc:"Bitcoin poetry, short stories, jokes, and creative writing from the community.",file:"data/R_poems-stories.json"},"projects-diy":{cat:"Resources",title:"🔧projects-diy",desc:"DIY Bitcoin projects: build your own node, Lightning ATM, and more.",file:"data/R_projects-diy.json"},"research-theses":{cat:"Resources",title:"✍research-theses",desc:"Academic research papers and theses on Bitcoin, monetary policy, and cryptographic systems.",file:"data/R_research-theses.json"},"satoshi-nakamoto":{cat:"Resources",title:"🦸satoshi-nakamoto",desc:"The mystery of Bitcoin's creator: who was Satoshi Nakamoto? The evidence, theories, and legacy.",file:"data/R_satoshi-nakamoto.json"},"social-media":{cat:"Resources",title:"👍social-media-proponents",desc:"Bitcoin Twitter/X accounts, influencers, and social media communities to follow.",file:"data/R_social-media.json"},"swag-merch":{cat:"Resources",title:"👕swag-merch-businesses-spend",desc:"Bitcoin merchandise, clothing, and businesses where you can spend your sats.",file:"data/R_swag-merch.json"},videos:{cat:"Resources",title:"📺videos",desc:"Must-watch Bitcoin lectures, talks, and presentations from Andreas Antonopoulos, Michael Saylor, and others.",file:"data/R_videos.json"},web5:{cat:"Resources",title:"5⃣web5",desc:"Web5 and decentralized web technologies built on Bitcoin.",file:"data/R_web5.json"}},_SAFE_COVER_PLACEHOLDER="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjMWUxYTJlIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZpbGw9IiNmNzkzMWEiIGZvbnQtc2l6ZT0iMjAiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj7wnY61PC90ZXh0Pjwvc3ZnPg==";function _safeCover(e){if(!e||"string"!=typeof e||""===e.trim())return _SAFE_COVER_PLACEHOLDER;var t=e.trim(),o=t.toLowerCase();return/^(javascript|data:text\/html|vbscript|blob):/i.test(o)?(console.warn("[XSS BLOCKED] Malicious image URL scheme rejected:",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER):/^(https:\/\/|data:image\/)/i.test(t)?t.replace(/["'<>\\]/g,""):(console.warn("[XSS BLOCKED] Invalid URL scheme (must be https:// or data:image/):",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER)}function safeJSON(e,t){try{var o=localStorage.getItem(e);return null===o?t:JSON.parse(o)}catch(o){console.warn('safeJSON: corrupted data for key "'+e+'", resetting.',o);try{localStorage.removeItem(e)}catch(e){}return t}}function escapeHtml(e){if(!e)return"";var t=document.createElement("div");return t.appendChild(document.createTextNode(e)),t.innerHTML}function sanitizeUrl(e){return e?(e=e.trim(),/^(javascript|data|vbscript|blob):/i.test(e)?"":e):""}function timeAgo(e){if(!e)return"";var t;t=e.toDate?e.toDate():e instanceof Date?e:new Date(e);var o=Math.floor((Date.now()-t.getTime())/1e3);return o<60?"just now":o<3600?Math.floor(o/60)+"m ago":o<86400?Math.floor(o/3600)+"h ago":o<604800?Math.floor(o/86400)+"d ago":t.toLocaleDateString()}function isPremium(){return void 0!==currentUser&¤tUser&¤tUser.premium&&!0===currentUser.premium.active}function getSatCap(){return isPremium()?21e3:1e4}!function(){var e=[],t=[];window.registerInterval=function(t,o,n){var i=setInterval(t,o);return e.push({id:i,fn:t,ms:o,name:n||"unnamed"}),i},document.addEventListener("visibilitychange",function(){document.hidden?(e.forEach(function(e){clearInterval(e.id)}),t=e.slice(),e=[]):(t.forEach(function(t){t.fn(),t.id=setInterval(t.fn,t.ms),e.push(t)}),t=[])})}(),window._factionNameStyle=function(e){return"cyber_hornets"===e?"color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;font-weight:700;":"honey_badgers"===e?"color:#1a1a1a;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff;font-weight:700;":""};var PREMIUM_CONFIG={FREE_SAT_CAP:1e4,PREMIUM_SAT_CAP:21e3,FREE_SPINS:1,PREMIUM_SPINS:3,MONTHLY_PRICE_USD:4.99,YEARLY_PRICE_USD:42,LIFETIME_SATS:21e4,TIER_NAME:"Bitcoin Maxi"};const FIREBASE_CONFIG={apiKey:"AIzaSyCkUGX2KWaVGmSQXpYJhWDxF_BSiHRX6SM",authDomain:"btc-archive-test.firebaseapp.com",projectId:"btc-archive-test",storageBucket:"btc-archive-test.firebasestorage.app",messagingSenderId:"60810625669",appId:"1:60810625669:web:ea4dacd55333e41429dfec",measurementId:"G-7C2FKDJ8E4"},LEVELS=[{name:"Normie",emoji:"🟢",min:0},{name:"Curious",emoji:"🔵",min:10},{name:"Pleb",emoji:"🟠",min:144},{name:"Pleb II",emoji:"🟠🟠",min:170},{name:"Pleb III",emoji:"🟠🟠🟠",min:256},{name:"Stacker",emoji:"📦",min:500},{name:"Stacker II",emoji:"📦📦",min:1913},{name:"Stacker III",emoji:"📦📦📦",min:2016},{name:"Maxi",emoji:"🔥",min:2140},{name:"Maxi II",emoji:"🔥🔥",min:6102},{name:"Maxi III",emoji:"🔥🔥🔥",min:8888},{name:"Papa John",emoji:"🍕",min:1e4},{name:"Full Node",emoji:"🖥️",min:18333},{name:"Whale",emoji:"🐋",min:5e4},{name:"Sovereign",emoji:"🏴",min:1e5},{name:"Cypherpunk",emoji:"🔒",min:133337},{name:"Satoshi",emoji:"👑",min:21e4}];function _renderQRCode(e,t,o){if(window.qrcode&&"function"==typeof window.qrcode)_drawQR(e,t,o);else{var n=document.createElement("script");n.src="https://cdnjs.cloudflare.com/ajax/libs/qrcode-generator/1.4.4/qrcode.min.js",n.integrity="sha384-mZT2gIty7ZDdOGkxfP6joZcYdMW1Jvj9dRlfpTmaJAKKXTqzygtB22k7FLe+KZC1",n.crossOrigin="anonymous",n.onload=function(){_drawQR(e,t,o)},n.onerror=function(){e.innerHTML='
    '+t+"
    "},document.head.appendChild(n)}}function _drawQR(e,t,o){try{var n=qrcode(0,"M");n.addData(t),n.make();var i=document.createElement("img");i.src=n.createDataURL(6,4),i.width=o,i.height=o,i.alt="QR Code",i.style.cssText="border-radius:8px;image-rendering:pixelated;",e.innerHTML="",e.appendChild(i)}catch(t){e.innerHTML='
    QR generation failed
    '}}const POINTS={visit:5,openChannel:10,readTime:15,explore10:50,streak:100};let db,auth,currentUser=null,signInAttempts=0,signInLockout=0,redirectResultResolved=!1,redirectResultPromise=Promise.resolve(null),sessionChannels=new Set,readTimer=null,readSeconds=0,lastReadAward=0,rankingReady=!1,allTimeChannels=new Set,lastLevelName="",lastLevelMin=0,levelUpReady=!1;function initRanking(){try{firebase.initializeApp(FIREBASE_CONFIG),db=firebase.firestore(),db.enablePersistence({synchronizeTabs:!0}).catch(function(e){"failed-precondition"!==e.code&&"unimplemented"!==e.code&&console.log("Persistence error:",e.code)}),auth=firebase.auth(),auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).catch(function(){}),auth.isSignInWithEmailLink(window.location.href)&&handleEmailSignIn(),redirectResultPromise=auth.getRedirectResult().then(async function(e){if(redirectResultResolved=!0,console.log("[Auth] getRedirectResult:",e?e.user?e.user.uid:"no user":"null"),!e||!e.user)return null;const t=e.user;sessionStorage.setItem("btc_redirect_auth","1");const o=await db.collection("users").doc(t.uid).get(),n=localStorage.getItem("btc_anon_uid");let i=null;try{i=JSON.parse(localStorage.getItem("btc_anon_data"))}catch(e){}if(localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),o.exists){if(i&&!o.data().mergedAnon){await o.ref.update({mergedAnon:!0});var a=Math.min(i.points||0,500);a>0&&"function"==typeof awardPoints&&await awardPoints(a,"🔗 Anonymous progress merged")}}else{i?(i.email=t.email||"",i.username||(i.username=t.displayName||"Bitcoiner"),await db.collection("users").doc(t.uid).set(i)):await db.collection("users").doc(t.uid).set({username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(t.uid)}if(n&&n!==t.uid)try{await db.collection("users").doc(n).delete()}catch(e){}return loadUser(t.uid),updateAuthButton(),"function"==typeof hideUsernamePrompt&&hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(t.displayName||t.email||"Bitcoiner")),t}).catch(function(e){return redirectResultResolved=!0,"auth/popup-closed-by-user"!==e.code&&console.log("Redirect result error:",e),null});let o=!0,n=auth.isSignInWithEmailLink(window.location.href);var e=localStorage.getItem("btc_pwa_auth_pending"),t=!!localStorage.getItem("btc_anon_uid")||"1"===sessionStorage.getItem("btc_redirect_pending")||!!e;e&&(localStorage.removeItem("btc_pwa_auth_pending"),console.log("[Auth] PWA auth pending detected")),t&&console.log("[Auth] Detected pending redirect return"),auth.onAuthStateChanged(e=>{if(console.log("[Auth] onAuthStateChanged:",e?e.isAnonymous?"anon:"+e.uid:"real:"+e.uid:"null","firstEvent:",o,"pendingRedirect:",t),e&&!e.isAnonymous){var i=localStorage.getItem("btc_last_auth_uid");i&&i!==e.uid&&(console.log("[Auth] Account switch detected:",i,"->",e.uid,"— clearing localStorage"),clearUserLocalStorage()),localStorage.setItem("btc_last_auth_uid",e.uid)}if(o){if(o=!1,n)return;if(e&&!e.isAnonymous)console.log("[Auth] Real user on first event:",e.uid),sessionStorage.removeItem("btc_redirect_auth"),loadUser(e.uid).then(function(){currentUser&¤tUser.username&&setTimeout(function(){"function"==typeof showToast&&showToast("👋 Welcome back, "+escapeHtml(currentUser.username||"")+"!")},2e3)}).catch(function(){});else if(e&&e.isAnonymous)if(t){console.log("[Auth] Anon user but pending redirect — waiting 8s for real auth...");var a=setTimeout(function(){auth.currentUser&&!auth.currentUser.isAnonymous?(console.log("[Auth] Real user appeared after wait:",auth.currentUser.uid),loadUser(auth.currentUser.uid)):(console.log("[Auth] No real user after 8s — loading anon"),loadUserLocal(e.uid)),localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),localStorage.removeItem("btc_pwa_auth_pending"),sessionStorage.removeItem("btc_redirect_pending")},8e3);redirectResultPromise.then(function(e){e&&clearTimeout(a)})}else loadUserLocal(e.uid);else if(redirectResultResolved&&!t)auth.signInAnonymously().then(()=>{});else{var r=setTimeout(function(){auth.currentUser||(console.log("[Auth] 10s timeout with no user — going anonymous"),localStorage.removeItem("btc_pwa_auth_pending"),auth.signInAnonymously().then(()=>{}))},1e4);redirectResultPromise.then(function(e){clearTimeout(r),e||auth.currentUser||auth.signInAnonymously().then(()=>{})})}}else if(e){if(currentUser&¤tUser.uid===e.uid)return void updateAuthButton();e.isAnonymous?loadUserLocal(e.uid):loadUser(e.uid)}else currentUser=null,redirectResultResolved?auth.signInAnonymously().then(()=>{}):redirectResultPromise.then(function(e){e||auth.currentUser||auth.signInAnonymously().then(()=>{})})})}catch(e){console.error("Ranking init error:",e),setTimeout(function(){"function"==typeof showToast&&showToast("⚠️ Init error: "+(e.message||e))},2e3)}}async function handleEmailSignIn(){var e=window.location.href;let t=null;var o=new URLSearchParams(window.location.search);return o.get("signin_email")&&(t=decodeURIComponent(o.get("signin_email"))),t||(t=localStorage.getItem("btc_signin_email")),t?finishEmailSignIn(t,e):new Promise(function(o){var n=document.createElement("div");n.id="emailConfirmOverlay",n.style.cssText="position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:20px;",n.innerHTML='
    📧
    Confirm Your Email
    It looks like you opened this link on a different device. Enter the email you used to sign up:
    Cancel
    ',document.body.appendChild(n);var i=document.getElementById("crossDeviceEmail");function a(){var a=i.value.trim().toLowerCase();a&&a.includes("@")?(n.remove(),t=a,o(finishEmailSignIn(t,e))):"function"==typeof showToast&&showToast("Please enter a valid email")}document.getElementById("crossDeviceSubmit").onclick=a,i.addEventListener("keydown",function(e){"Enter"===e.key&&a()}),setTimeout(function(){i.focus()},100)})}async function finishEmailSignIn(e,t){if(e)try{const i=auth.currentUser;let a=null,r=null;if(i&&i.isAnonymous){a=i.uid,console.log("[Email Sign-In] Anon user found:",a);try{const e=await db.collection("users").doc(a).get();e.exists&&(r=e.data()),console.log("[Email Sign-In] Anon data loaded:",!!r)}catch(e){console.log("[Email Sign-In] Anon data load failed (non-fatal):",e.code)}}console.log("[Email Sign-In] Starting signInWithEmailLink for:",e);const s=await auth.signInWithEmailLink(e,t);console.log("[Email Sign-In] Sign-in result:",s.user?s.user.uid:"no user"),localStorage.removeItem("btc_signin_email");const l=s.user.uid;console.log("[Email Sign-In] Waiting for auth token propagation...");for(var o=0;o<5;o++){await new Promise(e=>setTimeout(e,200));try{await db.collection("users").doc(l).get(),console.log("[Email Sign-In] Firestore auth ready after",200*(o+1),"ms");break}catch(e){if("permission-denied"===e.code){console.log("[Email Sign-In] Permission denied on retry "+(o+1)+", waiting for token propagation...");continue}throw e}}console.log("[Email Sign-In] Fetching existing user doc:",l);const c=await db.collection("users").doc(l).get();if(console.log("[Email Sign-In] Existing doc exists:",c.exists),!c.exists&&r)r.email=e,await db.collection("users").doc(l).set(r);else if(c.exists&&r){const e=c.data();var n=Math.min(r.points||0,500);!e.mergedAnon&&n>(e.points||0)&&await c.ref.update({points:Math.max(n,e.points||0),channelsVisited:Math.max(r.channelsVisited||0,e.channelsVisited||0),totalVisits:(e.totalVisits||0)+(r.totalVisits||0),mergedAnon:!0})}if(a&&a!==l)try{await db.collection("users").doc(a).delete()}catch(e){}window.history.replaceState(null,"",window.location.pathname+window.location.hash);const d=localStorage.getItem("btc_pending_username"),u=(localStorage.getItem("btc_pending_email"),localStorage.getItem("btc_pending_giveaway"));if(d&&!c.exists){const t={username:d,email:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};if(u){t.lightningAddress=u,t.giveaway={entered:!0,lightningAddress:u,enteredAt:(new Date).toISOString()};try{await db.collection("giveaway_entries").doc(l).set({username:d,lightningAddress:u,email:e,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:l})}catch(e){}}await db.collection("users").doc(l).set(t);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(l)}localStorage.removeItem("btc_pending_username"),localStorage.removeItem("btc_pending_email"),localStorage.removeItem("btc_pending_giveaway"),localStorage.removeItem("btc_wallet_enc"),localStorage.removeItem("btc_wallet_addrs"),loadUser(l),showToast("✅ Email verified! Signed in as "+escapeHtml(d||e)),u&&setTimeout(function(){showToast("🎉 You're entered for the 25,000 sats giveaway! Good luck!")},2e3)}catch(e){console.error("[Email Sign-In] Full error:",e.code,e.message,e.stack),"permission-denied"===e.code?(showToast("⚠️ Permission denied. Try refreshing the page or clearing cache."),console.error("[Email Sign-In] Firestore permission denied - auth state may not be ready")):"auth/invalid-action-code"===e.code||"auth/expired-action-code"===e.code?showToast("⚠️ This sign-in link has expired. Please request a new one."):"auth/invalid-email"===e.code?showToast("⚠️ Email mismatch. Make sure you enter the same email you signed up with."):showToast("Sign-in error ("+(e.code||"unknown")+"). Please try again."),window.history.replaceState(null,"",window.location.pathname+window.location.hash),auth.signInAnonymously()}else showToast("⚠️ Could not determine your email. Please sign in again from the app.")}var GOOGLE_CLIENT_ID="1055248200518-jcn5efjp7vhk0vm8cbmj4mfsgc0edkga.apps.googleusercontent.com";async function signInWithGIS(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){var n=e.anonUid,i=e.anonData;google.accounts.id.initialize({client_id:GOOGLE_CLIENT_ID,callback:async function(e){if(e&&e.credential)try{var a=firebase.auth.GoogleAuthProvider.credential(e.credential),r=await auth.signInWithCredential(a);try{google.accounts.id.cancel()}catch(e){}var s=document.getElementById("gsi-temp-btn");if(s){var l=s.closest('div[style*="position:fixed"]');l?l.remove():s.remove()}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()}),await _handleSignInResultGlobal(r.user,n,i),t(r.user)}catch(e){o(e)}else o(new Error("No credential received"))},auto_select:!1,cancel_on_tap_outside:!0,context:"signin",ux_mode:"popup"}),google.accounts.id.prompt(function(e){(e.isNotDisplayed()||e.isSkippedMoment())&&(console.log("[Auth] One Tap not shown, falling back to Firebase popup"),o(new Error("One Tap unavailable")))})})}function showPWAAuthFallback(e){var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='
    🔐
    '+e+' Sign-In
    '+e+' sign-in requires a browser window. Open the site in your browser to sign in.
    ',document.body.appendChild(t)}window.signInWithGoogle=async function(){if(!/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||"")&&"undefined"!=typeof google&&google.accounts&&google.accounts.id)try{return void await signInWithGIS()}catch(e){console.warn("[Auth] GIS failed, falling back to Firebase popup:",e);try{google.accounts.id.cancel()}catch(e){}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()})}await signInWithProvider(new firebase.auth.GoogleAuthProvider)},window.signInWithTwitter=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.TwitterAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("Twitter")}await signInWithProvider(new firebase.auth.TwitterAuthProvider)},window.signInWithGithub=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.GithubAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("GitHub")}await signInWithProvider(new firebase.auth.GithubAuthProvider)};var FB_APP_ID="1400842698021858";async function signInWithFBSDK(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){FB.login(function(n){if(n.authResponse){var i=firebase.auth.FacebookAuthProvider.credential(n.authResponse.accessToken);auth.signInWithCredential(i).then(async function(o){await _handleSignInResultGlobal(o.user,e.anonUid,e.anonData),t(o.user)}).catch(o)}else o(new Error("Facebook login cancelled"))},{scope:"email,public_profile"})})}function checkRateLimit(){const e=Date.now();return e5&&(signInLockout=e+6e4,signInAttempts=0,showToast("⏳ Too many attempts. Please wait 60 seconds."),1)))}function isInAppBrowser(){var e=navigator.userAgent||"";return/FBAN|FBAV|Instagram|Twitter|Line\/|Snapchat|BytedanceWebview|musical_ly|TikTok|Weibo|MicroMessenger|LinkedInApp|Telegram/i.test(e)}async function _saveAnonDataGlobal(){var e=auth.currentUser,t=null,o=null;if(e&&e.isAnonymous){t=e.uid;try{var n=await db.collection("users").doc(t).get();n.exists&&(o=n.data())}catch(e){}}return{anonUid:t,anonData:o}}async function _handleSignInResultGlobal(e,t,o){var n=await db.collection("users").doc(e.uid).get();if(n.exists){if(o){var i=n.data(),a=Math.min(o.points||0,500);!i.mergedAnon&&a>(i.points||0)&&await n.ref.update({points:Math.max(a,i.points||0),channelsVisited:Math.max(o.channelsVisited||0,i.channelsVisited||0),totalVisits:(i.totalVisits||0)+(o.totalVisits||0),mergedAnon:!0})}!n.data().email&&e.email&&await n.ref.update({email:e.email})}else o?(o.email=e.email||"",o.username||(o.username=e.displayName||"Bitcoiner"),await db.collection("users").doc(e.uid).set(o)):await db.collection("users").doc(e.uid).set({username:e.displayName||"Bitcoiner",email:e.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()});if(t&&t!==e.uid)try{await db.collection("users").doc(t).delete()}catch(e){}if(loadUser(e.uid),n.exists)hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(e.displayName||e.email||"Bitcoiner"));else{"function"==typeof attachReferral&&attachReferral(e.uid),showGiveawayPrompt(e.uid,e.displayName||e.email||"Bitcoiner");try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},1500)}catch(e){}}}async function signInWithProvider(e){if(checkRateLimit()){if(isInAppBrowser()){var t=navigator.userAgent||"",o=/iPhone|iPad/i.test(t)?'Tap the share icon (↑) → "Open in Safari"':/Android/i.test(t)?'Tap ⋮ (menu) → "Open in Browser"':"Open this page in your default browser",n=document.createElement("div");return n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.9);padding:20px;",n.innerHTML='
    🌐

    Open in Browser

    Sign-in doesn\'t work inside apps. '+o+'

    ',void document.body.appendChild(n)}var i=/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||""),a=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(i||a)try{showToast("⏳ Opening sign-in...");const t=auth.currentUser;t&&t.isAnonymous&&(localStorage.setItem("btc_anon_uid",t.uid),db.collection("users").doc(t.uid).get().then(function(e){e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}).catch(function(){}));try{const t=await auth.signInWithPopup(e);if(t&&t.user){const{anonUid:e,anonData:o}=await s();return void await r(t.user,e,o)}}catch(t){return console.log("[Auth] Mobile popup failed, falling back to redirect:",t.code),sessionStorage.setItem("btc_redirect_pending","1"),localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}}catch(e){return console.error("Mobile sign-in error:",e),void showToast("Sign-in failed: "+(e.message||"Unknown error"))}try{const{anonUid:t,anonData:o}=await s(),n=await auth.signInWithPopup(e);await r(n.user,t,o)}catch(t){if(console.error("Provider sign-in error:",t.code,t.message,t),"auth/popup-blocked"===t.code||"auth/cancelled-popup-request"===t.code||"auth/popup-closed-by-user"===t.code||"auth/internal-error"===t.code){try{showToast("⏳ Opening sign-in page...");const t=auth.currentUser;if(t&&t.isAnonymous){localStorage.setItem("btc_anon_uid",t.uid);try{const e=await db.collection("users").doc(t.uid).get();e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}catch(e){}}return localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}catch(e){console.error("Redirect fallback also failed:",e),showToast("Sign-in failed. Please try a different browser.")}return}if("auth/popup-closed-by-user"===t.code)return;"auth/unauthorized-domain"===t.code?showToast("⚠️ This domain is not authorized for sign-in. Please contact support."):"auth/operation-not-allowed"===t.code?showToast("⚠️ This sign-in method is not enabled. Try a different option."):"auth/account-exists-with-different-credential"===t.code?showToast("⚠️ An account with this email exists using a different sign-in method. Try another option."):"auth/network-request-failed"===t.code?showToast("⚠️ Network error. Check your connection and try again."):showToast("Sign-in error ("+(t.code||"unknown")+"). Please try again.")}}async function r(e,t,o){return _handleSignInResultGlobal(e,t,o)}async function s(){return _saveAnonDataGlobal()}}function showGiveawayPrompt(e,t){const o=document.getElementById("usernameModal");o.querySelector(".username-box").innerHTML="

    🎉 Welcome, "+t+'!

    Your account is all set. Want to enter the giveaway?

    Enter a Lightning address so we can send you the sats if you win! 🏆

    ',o.classList.add("open"),document.getElementById("giveawayCheckboxProvider").addEventListener("change",function(){document.getElementById("giveawayLnProvider").parentElement.style.display=this.checked?"flex":"none"})}async function submitGiveawayProvider(e,t){var o=document.getElementById("giveawayCheckboxProvider"),n=document.getElementById("giveawayLnProvider"),i=n?n.value.trim():"";if(o&&o.checked){if(!i)return n&&(n.style.borderColor="#ef4444"),void showToast("⚡ Please enter a Lightning address!");try{await db.collection("users").doc(e).update({lightningAddress:i,giveaway:{entered:!0,lightningAddress:i,enteredAt:(new Date).toISOString()}}),void 0!==currentUser&¤tUser&&(currentUser.lightningAddress=i),await db.collection("giveaway_entries").doc(e).set({username:t,lightningAddress:i,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:e}),showToast("🎉 You're entered for the 25,000 sats giveaway! Good luck!")}catch(e){console.log("Giveaway save error:",e)}}hideUsernamePrompt(),showToast("✅ Signed in as "+t);var a=document.getElementById("giveawayBanner");a&&(a.style.display="none")}async function sendMagicLink(e){const t={url:window.location.origin+window.location.pathname+"?signin_email="+encodeURIComponent(e),handleCodeInApp:!0};try{return await auth.sendSignInLinkToEmail(e,t),localStorage.setItem("btc_signin_email",e),!0}catch(e){return console.log("Magic link error:",e),!1}}function loadUserLocal(e){var t=parseInt(localStorage.getItem("btc_points")||"0"),o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");currentUser={uid:e,points:t,channelsVisited:o.length,readChannels:o,totalVisits:parseInt(localStorage.getItem("btc_total_visits")||"1"),streak:parseInt(localStorage.getItem("btc_streak")||"0"),lastVisit:localStorage.getItem("btc_last_visit")||"",_isLocal:!0},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,restoreVisitedUI(),updateRankUI(),_checkCapOnLoad(),updateAuthButton(),"function"==typeof renderProgressRings&&renderProgressRings(),"function"==typeof renderExplorationMap&&renderExplorationMap(),startReadTimer()}async function loadUser(e,t){const o=t||await db.collection("users").doc(e).get();if(o.exists){currentUser={uid:e,...o.data()},currentUser.visitedChannelsList&¤tUser.visitedChannelsList.forEach(e=>allTimeChannels.add(e));const t=auth.currentUser&&!auth.currentUser.isAnonymous;var n=[...new Set([...Array.isArray(currentUser.visitedChannelsList)?currentUser.visitedChannelsList:[],...Array.isArray(currentUser.readChannels)?currentUser.readChannels:[]])];if(n.length>0){if(t)localStorage.setItem("btc_visited_channels",JSON.stringify(n));else{let e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=[...new Set([...e,...n])];localStorage.setItem("btc_visited_channels",JSON.stringify(t))}restoreVisitedUI()}else t&&(localStorage.setItem("btc_visited_channels","[]"),restoreVisitedUI());if(currentUser.favorites){if(t)localStorage.setItem("btc_favs",JSON.stringify(currentUser.favorites));else{let e=JSON.parse(localStorage.getItem("btc_favs")||"[]"),t=[...new Set([...e,...currentUser.favorites])];localStorage.setItem("btc_favs",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else t&&(localStorage.setItem("btc_favs","[]"),"function"==typeof renderFavs&&renderFavs());if(currentUser.bookmarks){if(t)localStorage.setItem("btc_bookmarks",JSON.stringify(currentUser.bookmarks));else{let e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]"),t=currentUser.bookmarks.concat(e.filter(function(e){return!currentUser.bookmarks.some(function(t){return t.channel===e.channel&&t.idx===e.idx})}));localStorage.setItem("btc_bookmarks",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else if(t){var i=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");i.length>0&&db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({bookmarks:i}).catch(function(){})}if(currentUser.username&&localStorage.setItem("btc_username",currentUser.username),currentUser.streak>0&&!currentUser.bestStreak&&(currentUser.bestStreak=currentUser.streak),rankingReady=!0,updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),awardVisitPoints(),startReadTimer(),auth.currentUser.isAnonymous||db.collection("users").doc(e).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),t){if(currentUser.hiddenBadges){var a=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),r=[...new Set([...a,...currentUser.hiddenBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(r))}if(currentUser.donationBadges&¤tUser.donationBadges.length>0){var s=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),l=[...new Set([...s,...currentUser.donationBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(l))}if(currentUser.visibleBadges){var c=JSON.parse(localStorage.getItem("btc_badges")||"[]"),d=[...new Set([...c,...currentUser.visibleBadges])];localStorage.setItem("btc_badges",JSON.stringify(d))}if(currentUser.spinClosetItems){var u=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]"),p=[...new Set([...u,...currentUser.spinClosetItems])];localStorage.setItem("btc_spin_closet_items",JSON.stringify(p))}if(currentUser.scholarPassed&&localStorage.setItem("btc_scholar_passed","true"),currentUser.nachoMilestones&&localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(currentUser.nachoMilestones)),currentUser.celebratedState){var m=currentUser.celebratedState;m.nachoMilestones&&localStorage.setItem("btc_nacho_milestones",JSON.stringify(m.nachoMilestones)),m.nachoCatComplete&&localStorage.setItem("btc_nacho_cat_complete",JSON.stringify(m.nachoCatComplete)),m.nachoLevelCelebrated&&localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(m.nachoLevelCelebrated)),m.nachoItemsNotified&&localStorage.setItem("btc_nacho_items_notified",JSON.stringify(m.nachoItemsNotified))}if(currentUser.nachoInteractions){var h=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),g=currentUser.nachoInteractions||0;localStorage.setItem("btc_nacho_interactions",Math.max(h,g).toString())}if(currentUser.nachoQuestions){var f=parseInt(localStorage.getItem("btc_nacho_questions")||"0"),y=currentUser.nachoQuestions||0;localStorage.setItem("btc_nacho_questions",Math.max(f,y).toString())}}if(localStorage.setItem("btc_pvp_wins",String(currentUser.pvpWins||0)),localStorage.setItem("btc_pvp_losses",String(currentUser.pvpLosses||0)),currentUser.nachoNickname&&(localStorage.setItem("btc_nacho_nickname",currentUser.nachoNickname),"function"==typeof updateNachoNameUI&&updateNachoNameUI(currentUser.nachoNickname)),t){if(currentUser.lastSpinDate){var b=localStorage.getItem("btc_last_spin")||"";currentUser.lastSpinDate>b&&localStorage.setItem("btc_last_spin",currentUser.lastSpinDate),"function"==typeof updateSpinBanner&&updateSpinBanner()}if(currentUser.prediction&&(localStorage.getItem("btc_prediction")||localStorage.setItem("btc_prediction",JSON.stringify(currentUser.prediction))),currentUser.nachoStoryDays&&Array.isArray(currentUser.nachoStoryDays)){var v=safeJSON("btc_nacho_story_days",[]);currentUser.nachoStoryDays.length>v.length&&localStorage.setItem("btc_nacho_story_days",JSON.stringify(currentUser.nachoStoryDays))}if(currentUser.nachoStoryProgress){var w=parseInt(localStorage.getItem("btc_nacho_story_highest")||"0");currentUser.nachoStoryProgress>w&&localStorage.setItem("btc_nacho_story_highest",currentUser.nachoStoryProgress.toString())}if(currentUser.nachoStoryDate){var x=localStorage.getItem("btc_nacho_story_date")||"";currentUser.nachoStoryDate>x&&localStorage.setItem("btc_nacho_story_date",currentUser.nachoStoryDate)}}window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0;var k=getLevel(currentUser.points||0);lastLevelName=k.name,lastLevelMin=k.min,localStorage.getItem("btc_highest_level_seen")||localStorage.setItem("btc_highest_level_seen",k.min.toString()),setTimeout(function(){levelUpReady=!0},3e3),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showContinueReading&&showContinueReading(),updateAuthButton(),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging()}else{const t=auth.currentUser;if(t&&!t.isAnonymous){const o={username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};await db.collection("users").doc(e).set(o),currentUser={uid:e,...o},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton()}}}window.fbAsyncInit=function(){FB.init({appId:FB_APP_ID,cookie:!0,xfbml:!1,version:"v19.0"})},window.signInWithFacebook=async function(){if("undefined"!=typeof FB)try{return void await signInWithFBSDK()}catch(e){if("Facebook login cancelled"===e.message)return;console.warn("[Auth] FB SDK failed:",e)}await signInWithProvider(new firebase.auth.FacebookAuthProvider)},window.signInWithNostr=async function(){if(checkRateLimit()){var e=!!window.nostr,t=document.createElement("div");t.id="nostrAuthOverlay",t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

    🟣 Sign in with Nostr

    '+(e?'':'
    🔌
    No Extension Detected
    Install Alby or nos2x for one-click login
    ')+'
    or
    🔒 Your nsec is used only in your browser to sign a one-time login event. It is never sent to our servers or stored anywhere.
    or
    ',document.body.appendChild(t)}},window.nostrSignInWithExtension=async function(){if(window.nostr){var e=document.getElementById("nostrAuthStatus");e&&(e.innerHTML='Requesting key from extension...');try{var t=await window.nostr.getPublicKey();if(!t||!/^[a-f0-9]{64}$/.test(t))return void(e&&(e.innerHTML='Could not get public key'));e&&(e.innerHTML='Signing auth event...');var o=await window.nostr.signEvent({kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:t});if(!o||!o.sig)return void(e&&(e.innerHTML='Signing cancelled'));await nostrCompleteAuth(t,o.sig,o)}catch(t){console.error("Nostr extension error:",t),e&&(e.innerHTML='Extension error: '+(t.message||"Unknown")+"")}}else showToast("Extension not found")},window.nostrSignInWithNsec=async function(){var e=(document.getElementById("nostrNsecInput").value||"").trim(),t=document.getElementById("nostrAuthStatus"),o=document.getElementById("nostrNsecBtn");if(e)if(e.startsWith("nsec1")){o.disabled=!0,o.textContent="Loading crypto library...",t&&(t.innerHTML='Loading...');try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.integrity="sha384-GwmNxV/GnZt+zRBR/Hhtu5D4MKfbxeJSApW44ARryGYtj3MFheHMFgiEZ7tVnrln",o.crossOrigin="anonymous",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools;t&&(t.innerHTML='Decoding nsec...'),o.textContent="Signing...";var i=n.nip19.decode(e);if(!i||"nsec"!==i.type)return t&&(t.innerHTML='Invalid nsec'),o.disabled=!1,void(o.textContent="Sign In with nsec");var a=i.data;"string"!=typeof a&&(a=Array.from(new Uint8Array(a)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""));var r=n.getPublicKey(a),s={kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:r};s.id=n.getEventHash(s),s.sig=n.signEvent(s,a),document.getElementById("nostrNsecInput").value="",t&&(t.innerHTML='Verifying signature...'),await nostrCompleteAuth(r,s.sig,s)}catch(e){console.error("Nostr nsec error:",e),t&&(t.innerHTML='Error: '+(e.message||"Failed to sign")+""),o.disabled=!1,o.textContent="Sign In with nsec"}}else t&&(t.innerHTML='Invalid nsec format. Must start with nsec1');else showToast("Please paste your nsec")},window.nostrSignInWithNpub=async function(){var e=(document.getElementById("nostrNpubInput").value||"").trim(),t=document.getElementById("nostrAuthStatus");if(e){var o=e;if(e.startsWith("npub1"))try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools.nip19.decode(e);n&&"npub"===n.type&&"string"!=typeof(o=n.data)&&(o=Array.from(new Uint8Array(o)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""))}catch(e){return void(t&&(t.innerHTML='Invalid npub format'))}if(/^[a-f0-9]{64}$/.test(o)){t&&(t.innerHTML='Linking Nostr identity...');try{auth.currentUser||await auth.signInAnonymously();var i=auth.currentUser.uid;await db.collection("users").doc(i).set({nostr:o,lastLogin:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0}),currentUser&&(currentUser.nostr=o);var a=document.getElementById("nostrAuthOverlay");a&&a.remove(),showToast("🟣 Nostr identity linked! (npub)")}catch(e){t&&(t.innerHTML='Error: '+(e.message||"Unknown")+"")}}else t&&(t.innerHTML='Invalid public key')}else showToast("Please paste your npub")},window.nostrCompleteAuth=async function(e,t,o){var n=document.getElementById("nostrAuthStatus");try{var i=firebase.functions().httpsCallable("nostrAuth"),a=await i({pubkey:e,sig:t,event:o});if(a.data&&a.data.token){await auth.signInWithCustomToken(a.data.token);var r=a.data.uid,s=await db.collection("users").doc(r).get();if(!s.exists||!s.data().username){var l={username:"npub..."+e.substring(0,8),nostr:e,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};s.exists||(l.points=0,l.channelsVisited=0,l.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(r).set(l,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(r),hideUsernamePrompt();var c=document.getElementById("nostrAuthOverlay");c&&c.remove(),showToast("🟣 Signed in with Nostr!")}else n&&(n.innerHTML='Auth failed — no token received')}catch(e){console.error("Nostr auth error:",e),n&&(n.innerHTML='Verification failed: '+(e.message||"Unknown")+"")}},window.signInWithLightning=async function(){if(checkRateLimit()){var e=document.createElement("div");e.id="lnAuthModal",e.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.8);",e.onclick=function(t){t.target===e&&e.remove()},e.innerHTML='

    Lightning Login

    Scan this QR code with your Lightning wallet (Alby, Zeus, Phoenix, BlueWallet, etc.)

    Generating challenge...

    Connecting to server...

    ',document.body.appendChild(e);try{var t=firebase.functions().httpsCallable("lnAuthChallenge"),o=await t();if(!document.getElementById("lnAuthModal"))return;if(!o.data||!o.data.k1||!o.data.lnurl)return"function"==typeof showToast&&showToast("Failed to generate login challenge"),void e.remove();var n=o.data.k1,i=o.data.lnurl,a=document.getElementById("lnAuthQR");if(a)if(a.innerHTML="",a.style.display="inline-block","function"==typeof _renderQRCode)_renderQRCode(a,"lightning:"+i,220);else{var r=document.createElement("img");r.src="https://api.qrserver.com/v1/create-qr-code/?size=220x220&data="+encodeURIComponent("lightning:"+i),r.width=220,r.height=220,r.alt="Lightning Auth QR",r.style.cssText="border-radius:8px;",a.appendChild(r)}var s=document.getElementById("lnAuthCopyWrap");s&&(s.style.display="block",s.innerHTML="");var l=document.getElementById("lnAuthStatus");l&&(l.textContent="Waiting for wallet...",l.style.color="var(--accent)");var c=firebase.functions().httpsCallable("lnAuthVerify"),d=0,u=setInterval(async function(){if(++d>60||!document.getElementById("lnAuthModal"))clearInterval(u);else try{var e=await c({k1:n});if(e.data&&e.data.token){clearInterval(u);var t=document.getElementById("lnAuthStatus");t&&(t.textContent="✅ Authenticated!"),await auth.signInWithCustomToken(e.data.token);var o=e.data.uid,i=await db.collection("users").doc(o).get();if(!i.exists||!i.data().username){var a={username:"⚡anon-"+n.substring(0,8),authMethod:"lightning",totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};i.exists||(a.points=0,a.channelsVisited=0,a.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(o).set(a,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(o),hideUsernamePrompt(),setTimeout(function(){var e=document.getElementById("lnAuthModal");e&&e.remove()},1e3),"function"==typeof showToast&&showToast("⚡ Signed in with Lightning!")}}catch(e){"not-found"!==e.code&&console.log("LN auth poll:",e.message)}},2e3)}catch(e){console.error("Lightning auth error:",e),"function"==typeof showToast&&showToast("Lightning sign-in failed. Try again.");var p=document.getElementById("lnAuthModal");p&&p.remove()}}},window.sendReturningMagicLink=async function(){var e=document.getElementById("returningEmailInput");if(e){var t=e.value.trim();if(!t||!t.includes("@"))return showToast("📧 Please enter a valid email address"),void(e&&(e.style.borderColor="#ef4444"));e.disabled=!0;var o=e.nextElementSibling;o&&(o.disabled=!0,o.textContent="Sending..."),await sendMagicLink(t)?(showToast("📧 Magic link sent! Check your email to sign in."),o&&(o.textContent="✅ Sent!"),hideUsernamePrompt()):(showToast("❌ Could not send magic link. Try again."),e.disabled=!1,o&&(o.disabled=!1,o.textContent="Send Link"))}};var _authBtnSignedIn=!1;function updateAuthButton(){const e=document.getElementById("authBtn");if(e){var t=auth&&auth.currentUser,o=t&&!t.isAnonymous,n=currentUser&¤tUser.username,i=localStorage.getItem("btc_username"),a=n||i||t&&t.displayName||"",r=t&&t.uid&&(t.uid.startsWith("nostr:")||t.uid.startsWith("ln:"));if(o||r||a)_authBtnSignedIn=!0;else{if(_authBtnSignedIn&&t)return;t||(_authBtnSignedIn=!1)}if(_authBtnSignedIn){var s=a||"My Account";e.innerHTML="⚙️ "+("function"==typeof escapeHtml?escapeHtml(s):s)+" — Settings",e.onclick=function(){showSettings()},e.style.display=window.innerWidth<=900?"none":"block",e.style.background="none",e.style.border="2px solid #3b82f6",e.style.color="#3b82f6",e.onmouseover=function(){this.style.background="#3b82f6",this.style.color="#fff"},e.onmouseout=function(){this.style.background="none",this.style.color="#3b82f6"}}else(!t||t&&t.isAnonymous)&&(e.textContent="Create Free Account / Sign In",e.style.display="block",e.style.background="var(--accent)",e.style.border="none",e.style.color="#000",e.onmouseover=function(){this.style.transform="scale(1.02)"},e.onmouseout=function(){this.style.transform="scale(1)"});var l=document.getElementById("guestPointsBanner");l&&_authBtnSignedIn&&(l.style.display="none");var c=document.getElementById("giveawayBanner");c&&_authBtnSignedIn&&(currentUser&¤tUser.giveaway?(c.innerHTML='
    🎉 25,000 SATS GIVEAWAY 🎉
    You\'re entered! Good luck! 🍀
    ✅ Entered
    ',c.onclick=function(){showSettings()}):(c.querySelector("div:last-child")&&(c.querySelector("div:last-child").textContent="⚙️ View Your Profile →"),c.onclick=function(){showSettings()}))}}function sanitizeInput(e){return e.replace(/<[^>]*>/g,"").replace(/[<>"'&]/g,"").trim()}window.sanitizeInput=sanitizeInput,window.syncCelebratedState=function(){if(void 0!==db&&auth&&auth.currentUser){var e={nachoMilestones:safeJSON("btc_nacho_milestones",[]),nachoCatComplete:safeJSON("btc_nacho_cat_complete",[]),nachoLevelCelebrated:safeJSON("btc_nacho_level_celebrated",[]),nachoItemsNotified:safeJSON("btc_nacho_items_notified",[])};db.collection("users").doc(auth.currentUser.uid).update({celebratedState:e}).catch(function(){})}};const PROFANITY_LIST=["fuck","shit","ass","bitch","dick","cock","pussy","cunt","damn","hell","bastard","slut","whore","fag","faggot","nigger","nigga","retard","retarded","penis","vagina","porn","sex","anal","cum","jizz","dildo","tits","boob","nude","naked","hentai","milf","orgasm","erect","molest","rape","pedo","nazi","hitler","kkk","jihad","terrorist","kill","murder","suicide","die","stfu","gtfo","wank","twat","bollocks","arse","shag","piss","crap","douche","skank","thot","incel","simp","onlyfans","xnxx","pornhub","xvideos","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","aroused","erection","erectile","climax","ejaculat","deepthroat","rimjob","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes","twerk","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","zipperhead","jap","paki","wop","dago","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","acab","supremacy","genocide","lynch"];function containsProfanity(e){const t=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g," "),o=t.split(/\s+/);for(const e of o)if(PROFANITY_LIST.includes(e))return!0;const n=t.replace(/\s/g,"");for(const e of PROFANITY_LIST)if(e.length>=4&&n.includes(e))return!0;return!1}async function createUser(e,t,o,n,i){if(void 0===auth||!auth)return showToast("⏳ Loading... please try again in a moment."),void("function"==typeof initRanking&&initRanking());if(!auth.currentUser)try{await auth.signInAnonymously(),auth.currentUser||await new Promise(e=>{const t=auth.onAuthStateChanged(o=>{o&&(t(),e())});setTimeout(()=>{e()},3e3)})}catch(e){return console.log("Anonymous sign-in error:",e),void showToast("Error creating account. Please try again.")}if(!auth.currentUser)return void showToast("Error: Could not authenticate. Please refresh and try again.");const a=auth.currentUser.uid;if(clearUserData(),!(e=(e=sanitizeInput(e)).replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim())||e.length<2)return void showToast("⚠️ Username must be at least 2 characters (letters, numbers, basic symbols only).");if(containsProfanity(e))return void showToast("⚠️ That username is not allowed. Please choose another.");t&&(t=sanitizeInput(t));const r={username:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};if(t&&(r.email=t),i&&(r.country=i),window._signupFaction&&(r.faction=window._signupFaction,window._signupFaction=null),o&&n){r.lightningAddress=n,r.giveaway={entered:!0,lightningAddress:n,enteredAt:(new Date).toISOString()};try{await db.collection("giveaway_entries").doc(a).set({username:e,lightningAddress:n,email:t||null,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:a})}catch(e){console.log("Giveaway entry save error:",e)}}await db.collection("users").doc(a).set(r);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}currentUser={uid:a,...r},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton(),awardPoints(POINTS.visit,"Welcome bonus!"),startReadTimer(),hideUsernamePrompt();try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},800)}catch(e){}var s=document.getElementById("giveawayBanner");s&&(s.style.display="none"),"function"==typeof attachReferral&&attachReferral(a),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging();try{var l=JSON.parse(localStorage.getItem("btc_buddy_pending")||"null");l&&l.goal&&(localStorage.removeItem("btc_buddy_pending"),"function"==typeof _submitBuddyFromOnboarding&&setTimeout(function(){_submitBuddyFromOnboarding(l.level||"beginner",l.goal)},2e3))}catch(e){}}async function awardVisitPoints(){if(!currentUser)return;const e=(new Date).toISOString().split("T")[0],t=new Date(Date.now()-864e5).toISOString().split("T")[0];if(currentUser.lastVisit===e)return;let o=!1,n=0,i=POINTS.visit,a=1;if(currentUser.lastVisit===t)a=(currentUser.streak||0)+1,a%7==0?(n=Math.min(25,5*Math.floor(a/7)),o=!0):a%5==0&&(i+=POINTS.streak,o=!0);else if(currentUser.lastVisit!==e){var r=currentUser.streak||0;currentUser.streakFreezes>0?(a=r+1,currentUser.streakFreezes--,o=!0,setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze ticket was used to save your "+a+"-day streak! ("+(currentUser.streakFreezes||0)+" freezes remaining)")},3e3)):r>1&&setTimeout(function(){showToast("💔 Your "+r+"-day streak was broken! Earn 🧊 Freeze Tickets from the Daily Spin to protect your streak next time.")},3e3)}if(currentUser._isLocal);else{try{var s=firebase.functions().httpsCallable("recordDailyVisit"),l=await s({});if(l.data&&l.data.success&&!l.data.alreadyVisited){a=l.data.streak||1,n=l.data.bonusTickets||0;var c=l.data.bestStreak||a;currentUser.streak=a,currentUser.bestStreak=c,currentUser.lastVisit=e,currentUser.totalVisits=l.data.totalVisits||(currentUser.totalVisits||0)+1,n>0&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+n),l.data.usedFreeze&&(currentUser.streakFreezes=Math.max(0,(currentUser.streakFreezes||0)-1),setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze was used to save your "+a+"-day streak!")},3e3))}}catch(e){console.warn("[VISIT] Cloud Function failed:",e.message)}var d=i+5*n;d>0&&await awardPoints(d,"✅ Daily visit"+(a>1?" ("+a+"-day streak!)":""))}n>0?("function"==typeof notifySelfStreak&¬ifySelfStreak(a),setTimeout(function(){showToast("🔥 STREAK MILESTONE! Day "+a+": Earned +"+n+" Bonus Tickets! 🎟️")},3500)):o&&showToast("🔥 Day "+currentUser.streak+" streak! +"+(POINTS.visit+POINTS.streak)+" XP"),updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen()}async function awardPoints(e,t,o,n,i){if(currentUser&&rankingReady&&(e=parseInt(e),!(isNaN(e)||e<0||e>2200)&&(0!==e||n||i))){window._pointAwardTimes=window._pointAwardTimes||[];var a=Date.now();if(window._pointAwardTimes=window._pointAwardTimes.filter(function(e){return a-e<6e4}),!(window._pointAwardTimes.length>=20)){if(window._pointAwardTimes.push(a),currentUser._isLocal){var r=500,s=(new Date).toISOString().split("T")[0],l="btc_daily_pts_"+s,c=parseInt(localStorage.getItem(l)||"0",10);isNaN(c)&&(c=0);var d={tctv_watch_10m:6e5,daily_spin:864e5,daily_visit:72e6}[t];if(d){var u="btc_cd_"+t,p=parseInt(localStorage.getItem(u)||"0",10);if(p&&Date.now()-p0&&f&&f!==s){g-=y=Math.min(g,r);try{localStorage.setItem(m,String(g))}catch(e){}}var b=e,v=0;if(c>=r?(b=0,v=e):c+e>r&&(v=e-(b=r-c)),(_=b+y)>0){var w=(parseInt(localStorage.getItem("btc_points")||"0",10)||0)+_;try{localStorage.setItem("btc_points",String(w)),b>0&&localStorage.setItem(l,String(c+b))}catch(e){}currentUser.points=w,_showPointsToast(b,t),"function"==typeof notifySelfPoints&¬ifySelfPoints(b,t),y>0&&"function"==typeof showToast&&setTimeout(function(){showToast("♻️ +"+y+" overflow pts redeemed from prior day!",4e3)},1200)}if(v>0){g+=v;try{localStorage.setItem(m,String(g)),localStorage.setItem(h,s)}catch(e){}var x="btc_overflow_notified_"+s;if(!localStorage.getItem(x)){try{localStorage.setItem(x,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap reached (500)! +"+v+" XP banked as overflow — they roll over tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}else if(c+b>=r){var k="btc_daily_cap_notified_"+s;if(!localStorage.getItem(k)){try{localStorage.setItem(k,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}return updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),void("function"==typeof nachoOnPoints&&nachoOnPoints(e))}auth.currentUser.isAnonymous||db.collection("users").doc(auth.currentUser.uid).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),e>0&&t&&"function"==typeof notifySelfPoints&¬ifySelfPoints(e,t);try{var B=firebase.functions().httpsCallable("awardPoints"),S={pts:e,action:t||"",reason:t||""};o&&(S.channelId=o),n&&(S.tickets=n),i&&(S.streakFreezes=i);var T=await B(S);if(T.data&&T.data.dailyActionCapped&&"function"==typeof showToast&&showToast("⏳ "+(T.data.error||"Daily limit reached for this action."),6e3),T.data&&T.data.cooldown&&"function"==typeof showToast&&showToast("⏳ "+(T.data.error||"Slow down a bit."),4e3),T.data&&T.data.success){b=T.data.awarded||0,y=T.data.overflowRedeemed||0,v=T.data.overflowAdded||0;var _,I=T.data.pendingOverflow||0;if((_=b+y)>0&&(currentUser.points=(currentUser.points||0)+_,_showPointsToast(b,t),y>0&&setTimeout(function(){showToast("♻️ +"+y+" overflow pts redeemed from prior day!",4e3)},1200)),v>0){m="btc_overflow_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(m)||(localStorage.setItem(m,"1"),showToast("🎯 Daily cap reached (500)! +"+v+" XP banked as overflow — they roll over tomorrow.",8e3),_updateCapIndicator(!0));try{localStorage.setItem("btc_pts_overflow",String(I))}catch(e){}}else T.data.capped&&(k="btc_daily_cap_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(k)||(localStorage.setItem(k,"1"),showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow.",8e3),_updateCapIndicator(!0)))}}catch(e){console.warn("[POINTS] Cloud Function failed:",e.message),"function"==typeof showToast&&showToast("⏳ XP will sync when connection restores")}updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),"function"==typeof nachoOnPoints&&nachoOnPoints(e)}}}function _showPointsToast(e,t){var o=!1;e>=25?o=!0:t&&t.length>0&&(window._lastPtsToast=window._lastPtsToast||0,Date.now()-window._lastPtsToast>3e4&&(o=!0)),o&&t&&(window._lastPtsToast=Date.now(),showToast("+"+e+" XP — "+t,2500))}function refreshLeaderboardIfOpen(){var e=document.getElementById("leaderboard");if(e&&e.classList.contains("open")&&!e.classList.contains("minimized")){window._lbCache=null,window._lbCacheTime=null;var t=e.querySelector(".lb-me .lb-score");t&¤tUser&&(t.textContent=(currentUser.points||0).toLocaleString()+" XP")}}async function onChannelOpen(e){if("function"==typeof nachoOnChannel&&nachoOnChannel(e),currentUser&&rankingReady){if(!allTimeChannels.has(e)){allTimeChannels.add(e),sessionChannels.add(e);let t=POINTS.openChannel;if(window._dailyBoosts&&window._dailyBoosts.includes(e)&&(t*=2,setTimeout(()=>{showToast("⚡ 2X XP! Daily boost applied! +"+t+" XP")},2e3)),currentUser._isLocal,currentUser.channelsVisited=(currentUser.channelsVisited||0)+1,currentUser.readChannels?-1===currentUser.readChannels.indexOf(e)&¤tUser.readChannels.push(e):currentUser.readChannels=[e],Array.isArray(currentUser.visitedChannelsList)||(currentUser.visitedChannelsList=[]),-1===currentUser.visitedChannelsList.indexOf(e)&¤tUser.visitedChannelsList.push(e),await awardPoints(t,"📖 New channel explored",e),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showToast){const e=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,t=Math.round(allTimeChannels.size/e*100);showToast("🗺️ Exploration Map: "+allTimeChannels.size+" channels reached ("+t+"%)")}10===allTimeChannels.size&&await awardPoints(POINTS.explore10,"Explorer bonus! 10 topics 🎉")}readSeconds=0,lastReadAward=0,syncReadToFirebase(e),"function"==typeof onChannelVisitForQuest&&onChannelVisitForQuest(e)}}async function syncReadToFirebase(e){}async function syncFavsToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_favs")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({favorites:e})}catch(e){}}async function syncBookmarksToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({bookmarks:e})}catch(e){}}function restoreVisitedUI(){JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})})}window.notifySelfPoints=function(e,t){if(e&&!(e<1)&&t&&""!==t){var o={pts:e,reason:t,ts:Date.now(),read:!1};try{var n=JSON.parse(localStorage.getItem("btc_points_log")||"[]");n.push(o),n.length>100&&(n=n.slice(n.length-100)),localStorage.setItem("btc_points_log",JSON.stringify(n))}catch(e){}"function"==typeof _updatePointsBadge&&_updatePointsBadge()}},window.syncBookmarksToFirebase=syncBookmarksToFirebase;let lastActivityTime=Date.now(),lastScrollPos=0,hasScrolledSinceLastAward=!1;function trackActivity(){lastActivityTime=Date.now()}function trackScroll(){const e=document.getElementById("main");e&&Math.abs(e.scrollTop-lastScrollPos)>30&&(lastScrollPos=e.scrollTop,hasScrolledSinceLastAward=!0,lastActivityTime=Date.now())}function startReadTimer(){readTimer&&clearInterval(readTimer),readTimer=setInterval(async()=>{if(currentUser&&rankingReady&&!document.hidden&&!((Date.now()-lastActivityTime)/1e3>45)&&hasScrolledSinceLastAward&&(readSeconds++,sessionStorage.setItem("btc_channel_read_seconds",readSeconds.toString()),readSeconds-lastReadAward>=30)){lastReadAward=readSeconds,hasScrolledSinceLastAward=!1;var e="btc_read_cap_"+(window.currentChannelId||"unknown")+"_"+(new Date).toISOString().split("T")[0],t=parseInt(localStorage.getItem(e)||"0");if(t>=5)return;localStorage.setItem(e,(t+1).toString()),await awardPoints(POINTS.readTime,"")}},1e3)}function getLevel(e){let t=LEVELS[0];for(const o of LEVELS)e>=o.min&&(t=o);const o=LEVELS.indexOf(t)+1,n=o
    '+o.emoji+''+t.toLocaleString()+' XP
    Sign in to keep your XP & get on the leaderboard!
    Sign Up Free →
    ",e.style.display="flex"}}else e&&(e.style.display="none");else e&&(e.style.display="none")}function _updateCapIndicator(e){var t=document.getElementById("userDisplay");if(t){var o,n="btc_daily_pts_"+(new Date).toISOString().split("T")[0],i=parseInt(localStorage.getItem(n)||"0"),a=parseInt(localStorage.getItem("btc_pts_overflow")||"0");e||i>=500?(t.style.borderColor="#ef4444",t.style.boxShadow="0 0 12px rgba(239,68,68,0.3)",t.title="🎯 Daily XP cap reached (500/500)"+(a>0?"\n💫 Overflow: "+a+" pts (rolls over tomorrow)":""),document.getElementById("dailyCapBadge")||((o=document.createElement("span")).id="dailyCapBadge",o.style.cssText="position:absolute;top:-6px;left:-6px;background:#ef4444;color:#fff;font-size:0.55rem;font-weight:800;padding:2px 6px;border-radius:8px;z-index:2;pointer-events:none;",o.textContent="CAP",t.style.position="fixed",t.appendChild(o))):(t.style.borderColor="var(--border)",t.style.boxShadow="0 2px 10px rgba(0,0,0,0.2)",t.title="",(o=document.getElementById("dailyCapBadge"))&&o.remove())}}function _checkCapOnLoad(){var e="btc_daily_pts_"+(new Date).toISOString().split("T")[0];parseInt(localStorage.getItem(e)||"0")>=500&&setTimeout(function(){_updateCapIndicator(!0)},2e3)}function updateRankUI(){if(!currentUser)return;var e=document.getElementById("giveawayBanner");e&¤tUser.username&&(e.style.display="none");const t=getLevel(currentUser.points||0);!lastLevelName&&t.name&&(lastLevelName=t.name,lastLevelMin=t.min),updateGuestPointsBanner(),updateUserDisplay(t);const o=parseInt(localStorage.getItem("btc_highest_level_seen")||"0");if(levelUpReady&&lastLevelName&&lastLevelName!==t.name&&t.min>lastLevelMin&&t.min>o){showLevelUpCelebration(t),localStorage.setItem("btc_highest_level_seen",t.min.toString()),"function"==typeof notifySelfLevelUp&¬ifySelfLevelUp(t.min,t.name,t.emoji);var n=currentUser&¤tUser.username?currentUser.username:null,i=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:"";if(n&&"function"==typeof window.nachoGlobalAnnounce&&window.nachoGlobalAnnounce(t.emoji+" @"+n+" just leveled up to "+t.emoji+" "+t.name+"! Congrats! 🎉",i),"function"==typeof window.contributeSatoshiFavor){var a=t.name||"",r=null;["Pleb","Pleb II","Pleb III","Stacker","Stacker II","Stacker III"].includes(a)?r="level_up":["Maxi","Maxi II","Maxi III"].includes(a)?r="level_up_5":["Papa John","Full Node","Whale","Sovereign","Cypherpunk","Satoshi"].includes(a)&&(r="level_up_10"),r&&window.contributeSatoshiFavor(r,a)}}lastLevelName=t.name,lastLevelMin=t.min;const s=document.getElementById("rankBar");if(!s)return;let l="";t.next&&(l='
    '+(t.next.min-currentUser.points)+" XP to "+t.next.emoji+" "+t.next.name+"
    ");const c=auth.currentUser&&auth.currentUser.isAnonymous&¤tUser.username?'':"",d=currentUser.streak||0,u=d>0&&(d%7==0||30===d||100===d||365===d),p=currentUser.bestStreak||0,m=d>0||p>0?'🔥 '+d+(p>0?"("+p+")":"")+" day streak"+(u?" ✨":"")+"":"",h=(currentUser.orangeTickets||0)>0?''+currentUser.orangeTickets+"":"";s.innerHTML='
    '+t.emoji+" "+t.name+''+escapeHtml(currentUser.username||"Anon")+''+(currentUser.points||0).toLocaleString()+" XP"+m+h+"
    "+l+c,s.style.display="flex"}function getUserDisplayEmoji(e){var t=void 0!==currentUser&¤tUser?currentUser.displayBadge:null;if(t){if(void 0!==BADGE_DEFS)for(var o=0;o0?'🔥'+currentUser.streak+"":"",s=getUserDisplayEmoji(e);let l=document.getElementById("userDisplay");if(l||(l=document.createElement("div"),l.id="userDisplay",document.body.appendChild(l)),n||auth.currentUser&&auth.currentUser.isAnonymous&&!i){if(u=window.innerWidth<=900)return l.setAttribute("data-mob-hidden","1"),void(l.style.display="none");if("1"===sessionStorage.getItem("btc_signin_banner_dismissed"))return l.classList.add("user-hidden"),void(l.style.display="none");l.classList.remove("user-hidden"),l.setAttribute("data-anon","1"),u?l.style.cssText="position:fixed;bottom:70px;left:12px;right:12px;z-index:200;display:flex;align-items:center;gap:10px;padding:10px 16px;background:linear-gradient(135deg,#1a1a2e,#2d1f4e);border:2px solid #f7931a;border-radius:14px;box-shadow:0 4px 20px rgba(247,147,26,0.3);font-size:0.85rem;cursor:pointer;":((c=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((d=document.createElement("div")).id="userDisplayContainer",d.style.padding="0 20px 16px",d.style.borderBottom="1px solid var(--border)",c.parentNode.insertBefore(d,c.nextSibling),d.appendChild(l)),l.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:12px;background:rgba(247,147,26,0.05);border:1px solid rgba(247,147,26,0.2);border-radius:12px;cursor:default;transition:0.3s;width:100%;"),l.onclick=function(e){!u&&e.target.closest("button")||showSettingsPage("account")},l.innerHTML=(u?'':"")+'
    '+e.emoji+'GUEST'+a.toLocaleString()+" XP
    "+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
    ';return e&&(o+='
    $'+Math.round(e).toLocaleString()+"
    "),t&&(o+='⛓️ '+t.toLocaleString()+""),o+"
    "}()+(u?'
    Sign in to keep XP & enter giveaway!
    ':"")+"
    "+(u?"":'
    ')+(u?"":'
    SIGN UP
    ')+(u?'
    Sign Up →
    ':"")}else{l.removeAttribute("data-anon"),l.removeAttribute("data-mob-hidden");var c,d,u=window.innerWidth<=900,p=document.getElementById("dashboardFloatBtn");if(p||((p=document.createElement("div")).id="dashboardFloatBtn",p.className="fab-btn",p.innerHTML="📊",p.title="Bitcoin Metrics",document.body.appendChild(p)),p.onclick=function(){"function"==typeof toggleDashboard&&toggleDashboard()},u)return void(l.style.display="none");if(u)l.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:8px;padding:8px 14px;background:var(--bg-side);border:1px solid var(--border);border-radius:10px;font-size:0.8rem;cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,0.2);";else(c=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((d=document.createElement("div")).id="userDisplayContainer",d.style.padding="0 20px 16px",d.style.borderBottom="1px solid var(--border)",c.parentNode.insertBefore(d,c.nextSibling),d.appendChild(l)),l.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:10px;background:rgba(255,255,255,0.03);border:1px solid var(--border);border-radius:10px;cursor:pointer;width:100%;";l.onclick=function(e){e.target.closest("a")||showSettings()};var m,h=currentUser.username||auth.currentUser&&auth.currentUser.displayName||"Anon";m=currentUser.displayBadge?''+s+' '+e.emoji+"":''+e.emoji+"",l.innerHTML='
    '+m+''+escapeHtml(h)+""+(r?''+r+"":"")+"
    "+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
    ';return e&&(o+='
    $'+Math.round(e).toLocaleString()+"
    "),t&&(o+='⛓️ '+t.toLocaleString()+""),(o+=''+a.toLocaleString()+" XP")+"
    "}()+"
    "+(u?"":'
    ')}l.style.display="flex";const g=document.getElementById("mobileUserInfo");if(g&&window.innerWidth<=900){var f=s;currentUser.displayBadge&&(f+=" "+e.emoji),a=currentUser.points||0;var y=parseFloat(localStorage.getItem("btc_last_price"))||0,b=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(y=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(b=nachoLiveData.blockHeight);var v=''+f+" "+escapeHtml(currentUser.username||(n?"Anonymous":"Anon"))+"";y&&(v+=' $'+Math.round(y).toLocaleString()+""),b&&(v+=' ⛓️ '+b.toLocaleString()+""),v+=' '+a.toLocaleString()+" XP",g.innerHTML=v,g.style.display="inline",g.style.maxWidth="none"}const w=document.getElementById("welcomeBanner");if(w&¤tUser.username){updateAuthButton();const t=currentUser.streak||0,o=currentUser.bestStreak||0,n=t>0||o>0?' · 🔥 '+t+(o>0?"("+o+")":"")+" day streak":"";w.innerHTML=''+e.emoji+' Welcome back, '+escapeHtml(currentUser.username||"Anon")+'! · '+e.name+" · "+(currentUser.points||0).toLocaleString()+" XP"+n+'
    ⚙️ Tap here for Account & Settings
    ',w.style.display="block",w.removeAttribute("data-simplified-hidden")}}document.addEventListener("mousemove",trackActivity),document.addEventListener("keydown",trackActivity),document.addEventListener("touchstart",trackActivity,{passive:!0}),document.addEventListener("click",trackActivity),setInterval(trackScroll,2e3),window.toggleGuestPointsBanner=function(){var e=document.getElementById("guestPointsBanner");if(e){var t=!e.classList.contains("banner-min");e.classList.toggle("banner-min",t);try{localStorage.setItem("btc_signin_banner_min",t?"1":"0")}catch(e){}updateGuestPointsBanner()}};let lbAutoShown=!1;function showLeaderboardAuto(){lbAutoShown||(lbAutoShown=!0,document.getElementById("leaderboard").classList.contains("open")||toggleLeaderboard())}function expandLeaderboard(e){e&&e.stopPropagation(),document.querySelectorAll(".lb-extra").forEach(e=>e.style.display="flex");const t=document.getElementById("lbShowMore");t&&t.remove()}function minimizeLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}function hideLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}function _lbOutsideClose(e){var t=document.getElementById("leaderboard");if(t&&t.classList.contains("open")&&!t.classList.contains("minimized")&&!t.contains(e.target)){var o=document.getElementById("rankBar");if(!o||!o.contains(e.target)){var n=document.getElementById("lbFloatBtn");n&&n.contains(e.target)||document.getElementById("userProfileModal")||(t.classList.remove("open"),t.classList.remove("minimized"),n&&(n.style.display="flex"))}}}function applyOLEDTheme(){const e="true"===localStorage.getItem("btc_theme_oled"),t="light"!==document.body.getAttribute("data-theme");e&&t?document.body.classList.add("oled-theme"):document.body.classList.remove("oled-theme")}function _lbBadgeEmoji(e){var t=[],o="undefined"!=typeof Intl&&Intl.Segmenter?Array.from(new Intl.Segmenter("en",{granularity:"grapheme"}).segment(e)).map(function(e){return e.segment}):null;o?t=o:t=e.match(/\p{Emoji_Presentation}(\u200d\p{Emoji_Presentation})*/gu)||[e];if(t.length<=1)return e;var n=2===t.length?"0.6rem":"0.5rem";return''+t.map(function(e){return""+e+""}).join("")+""}async function toggleLeaderboard(){const e=document.getElementById("leaderboard");if(!e)return;const t=document.getElementById("lbFloatBtn");if(e.classList.contains("open")&&!e.classList.contains("minimized"))return e.classList.remove("open"),e.classList.remove("minimized"),void(t&&(t.style.display="flex"));if(e.classList.remove("minimized"),e.innerHTML='
    Loading leaderboard...
    ',e.classList.add("open"),t&&(t.style.display="none"),("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{window._sharedAudioCtx||(window._sharedAudioCtx=new(window.AudioContext||window.webkitAudioContext));var o=window._sharedAudioCtx;"suspended"===o.state&&o.resume();const e="undefined"!=typeof audioVolume?audioVolume:.5,t=o.currentTime,n=o.createOscillator(),i=o.createGain();n.connect(i),i.connect(o.destination),n.type="sine",n.frequency.setValueAtTime(200,t),n.frequency.exponentialRampToValueAtTime(800,t+.15),i.gain.setValueAtTime(.08*e,t),i.gain.exponentialRampToValueAtTime(.001,t+.2),n.start(t),n.stop(t+.2),[880,1175].forEach((n,i)=>{const a=o.createOscillator(),r=o.createGain();a.connect(r),r.connect(o.destination),a.type="triangle",a.frequency.value=n,r.gain.setValueAtTime(.1*e,t+.1+.08*i),r.gain.exponentialRampToValueAtTime(.001,t+.1+.08*i+.3),a.start(t+.1+.08*i),a.stop(t+.1+.08*i+.3)})}catch(e){}try{var n=Date.now(),i=window._lbCache&&window._lbCacheTime&&n-window._lbCacheTime<12e4;let t=[];i?t=window._lbCache:((await db.collection("users").orderBy("points","desc").limit(150).get()).forEach(e=>{const o=e.data(),n=auth.currentUser&&e.id===auth.currentUser.uid;o.points>0&&(!o.ghostMode||n)&&t.push({id:e.id,...o})}),window._lbCache=t,window._lbCacheTime=n);let o='
    🏆 Leaderboard — tap to expand
    ';o+='

    🏆 Leaderboard

    ',o+='
    ',Math.min(10,t.length),t.forEach((e,t)=>{const n=t+1,i=getLevel(e.points||0),a=auth.currentUser&&e.id===auth.currentUser.uid;a&¤tUser&&(e.points||0)>(currentUser.points||0)&&(currentUser.points=e.points,updateRankUI());const r=1===n?"🥇":2===n?"🥈":3===n?"🥉":"#"+n,s=n>10?' style="display:none;" class="lb-row lb-extra'+(a?" lb-me":"")+'"':' class="lb-row'+(a?" lb-me":"")+'"';var l="function"==typeof onlineStatusDot?onlineStatusDot(e.lastSeen):"";let c="";e.earnedHidden&&e.earnedHidden.includes("cert_scholar")&&(c+=" 🎓"),e.earnedHidden&&e.earnedHidden.includes("cert_tech")&&(c+=" 🛠️");var d=e.profilePic?'':"",u=JSON.stringify({recipientName:e.username||"Anon",recipientUid:e.id,lightningAddress:e.lightningAddress||e.lightning||"",context:"leaderboard",label:"Tip "+(e.username||"Anon")}).replace(/'/g,"'").replace(/"/g,"""),p=e.faction?window._factionNameStyle(e.faction):"";o+="'+r+''+_lbBadgeEmoji(i.emoji)+'"+(d?d+" ":"")+escapeHtml(e.username||"Anon")+l+c+''+(e.points||0).toLocaleString()+' XP
    '}),t.length>10&&(o+='"),o+="","function"==typeof getBadgeHTML&&(o+='

    Your Badges

    '+getBadgeHTML()+"
    "),o+='

    ⚔️ PVP Leaderboard

    Loading PVP rankings...
    ',o+='

    Levels

    ';for(const e of LEVELS)o+='
    '+e.emoji+" "+e.name+""+(0===e.min?"0 XP":e.min+"+ XP")+"
    ";o+="
    ",e.innerHTML=o,_loadPVPLeaderboard()}catch(t){console.error("[Leaderboard] Error:",t),e.innerHTML='
    Error loading leaderboard: '+(t.message||"Unknown error")+"
    "}}async function _loadPVPLeaderboard(){var e=document.getElementById("pvpLeaderboardList");if(e)try{var t,o,n=Date.now();window._pvpLbCache&&window._pvpLbCacheTime&&n-window._pvpLbCacheTime<3e5?(t=window._pvpLbCache.wins,o=window._pvpLbCache.losses):([t,o]=await Promise.all([db.collection("users").where("pvpWins",">",0).orderBy("pvpWins","desc").limit(50).get(),db.collection("users").where("pvpLosses",">",0).orderBy("pvpLosses","desc").limit(50).get()]),window._pvpLbCache={wins:t,losses:o},window._pvpLbCacheTime=n);var i={},a=auth.currentUser?auth.currentUser.uid:null;function r(e){if(!i[e.id]){var t=e.data();if(!t.ghostMode||e.id===a){var o=t.pvpWins||0,n=t.pvpLosses||0,r=o+n;if(0!==r){var s=r>0?o/r*100:0;i[e.id]={id:e.id,username:escapeHtml(t.username||"Anon"),wins:o,losses:n,total:r,winRate:s,isMe:e.id===a,lightningAddress:t.lightningAddress||t.lightning||""}}}}}t.forEach(r),o.forEach(r);var s=Object.values(i);if(0===s.length)return void(e.innerHTML='
    No PVP battles yet — be the first to compete!
    ');s.sort(function(e,t){return t.winRate-e.winRate||t.wins-e.wins});var l="";s.forEach(function(e,t){var o=t+1,n=1===o?"🥇":2===o?"🥈":3===o?"🥉":"#"+o,i=e.wins>=100?"👑":e.wins>=50?"🏆":e.wins>=25?"🏟️":e.wins>=5?"🥊":"⚔️",a=o>10?' style="display:none;" class="lb-row pvp-lb-extra'+(e.isMe?" lb-me":"")+'"':' class="lb-row'+(e.isMe?" lb-me":"")+'"',r=JSON.stringify({recipientName:e.username,recipientUid:e.id,lightningAddress:e.lightningAddress,context:"pvp",label:"Tip "+e.username}).replace(/'/g,"'").replace(/"/g,""");l+="'+n+''+i+''+e.username+''+e.wins+"W – "+e.losses+'L'}),s.length>10&&(l+=""),e.innerHTML=l||'
    No PVP battles yet!
    '}catch(c){e.innerHTML='
    No PVP battles yet — be the first to compete!
    '}}document.addEventListener("mousedown",_lbOutsideClose,!0),document.addEventListener("touchstart",_lbOutsideClose,!0),window.toggleOLEDTheme=function(){const e="true"===localStorage.getItem("btc_theme_oled");localStorage.setItem("btc_theme_oled",!e),applyOLEDTheme(),showSettingsPage("prefs"),showToast(e?"Deep sea mode disabled":"🖤 Midnight OLED enabled!")},document.addEventListener("DOMContentLoaded",applyOLEDTheme),window.showDeleteAccountConfirm=function(){var e=document.createElement("div");e.id="deleteAccountOverlay",e.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;",e.onclick=function(t){t.target===e&&e.remove()};var t=currentUser&¤tUser.username?currentUser.username:"your account",o=currentUser&¤tUser.points||0,n=currentUser&¤tUser.streak||0;e.innerHTML='
    ⚠️

    Delete Your Account?

    This will permanently delete everything associated with '+escapeHtml(t)+':
    '+o.toLocaleString()+" XP and all badges
    "+(n>0?"
    "+n+"-day streak
    ":"")+'
    ❌ All forum posts and replies
    ❌ Marketplace listings
    ❌ DM conversations
    ❌ Nacho chat history
    ❌ Leaderboard ranking
    ❌ Orange Tickets and quest progress
    ⚠️ This action is IRREVERSIBLE. There is no undo.
    ',document.body.appendChild(e)},window.confirmDeleteAccount=async function(){var e=document.getElementById("deleteConfirmInput");if(e&&"DELETE"===e.value){var t=document.getElementById("deleteConfirmBtn");t&&(t.disabled=!0,t.textContent="Deleting...");try{var o=auth.currentUser;if(!o)throw new Error("Not signed in");var n=o.uid;try{await db.collection("users").doc(n).delete()}catch(e){console.warn("User doc delete failed:",e)}try{var i=await db.collection("forum_posts").where("authorId","==",n).get(),a=db.batch();i.forEach(function(e){a.delete(e.ref)}),i.empty||await a.commit()}catch(e){console.warn("Forum posts delete failed:",e)}try{var r=await db.collection("forum_replies").where("authorId","==",n).get(),s=db.batch();r.forEach(function(e){s.delete(e.ref)}),r.empty||await s.commit()}catch(e){console.warn("Forum replies delete failed:",e)}try{var l=await db.collection("marketplace").where("sellerUid","==",n).get(),c=db.batch();l.forEach(function(e){c.delete(e.ref)}),l.empty||await c.commit()}catch(e){console.warn("Marketplace delete failed:",e)}try{var d=await db.collection("conversations").where("participants","array-contains",n).get(),u=db.batch();d.forEach(function(e){u.delete(e.ref)}),d.empty||await u.commit()}catch(e){console.warn("DM delete failed:",e)}try{var p=await db.collection("suggestions").where("uid","==",n).get(),m=db.batch();p.forEach(function(e){m.delete(e.ref)}),p.empty||await m.commit()}catch(e){console.warn("Suggestions delete failed:",e)}for(var h=[],g=0;gclick to ask!'),document.querySelectorAll('[id*="nachoCloset"]').forEach(function(t){var o=t.querySelector('[style*="letter-spacing"]');o&&-1!==o.textContent.indexOf("'s Closet")&&(o.textContent="🦌 "+e+"'s Closet")}),document.querySelectorAll('[style*="font-weight:800"]').forEach(function(t){-1!==t.textContent.indexOf("'s Story")&&(t.textContent=e+"'s Story")})}};var _toastQueue=[];function showToast(e,t){window._directLinkMode||(window._nachoBusy?_toastQueue.push({msg:e,duration:t}):_showToastNow(e,t))}function _showToastNow(e,t){var o=t||2500;const n=document.createElement("div");n.className="rank-toast";var i="object"==typeof e?e.msg:e;n.innerHTML=i.replace(/<(script|svg|img|iframe|object|embed|form|input|link|style|meta|base)[^>]*>/gi,"").replace(/on\w+\s*=/gi,"data-blocked="),"object"==typeof e&&e.duration&&(o=e.duration),document.body.appendChild(n),requestAnimationFrame(()=>n.classList.add("show")),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>n.remove(),400)},o)}function showUsernamePrompt(){try{if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)return void showAccountInfo();if(currentUser&¤tUser.username)return void showAccountInfo();if(!redirectResultResolved)return showToast("⏳ Loading account..."),void redirectResultPromise.then(function(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous||currentUser&¤tUser.username?showAccountInfo():(document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash))});document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash)}catch(e){"function"==typeof showToast&&showToast("Settings error: "+e.message),console.error("showUsernamePrompt error:",e)}}function showAccountInfo(){showSettingsPage("account")}setInterval(function(){!window._nachoBusy&&_toastQueue.length>0&&_showToastNow(_toastQueue.shift())},2e3),window.showSignInOnly=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)showAccountInfo();else{var e=document.getElementById("usernameModal");e&&(e.classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash),setTimeout(function(){var t=e.querySelector(".username-box");if(t){var o=t.querySelector("h2"),n=t.querySelector("p"),i=document.getElementById("usernameInput"),a=document.getElementById("emailInput"),r=document.getElementById("giveawaySection"),s=t.querySelector('button[onclick="submitUsername()"]'),l=a?a.nextElementSibling:null;l&&"P"===l.tagName&&(l.style.display="none"),o&&(o.style.display="none"),n&&(n.style.display="none"),i&&(i.style.display="none"),a&&(a.style.display="none"),r&&(r.style.display="none"),s&&(s.style.display="none");var c=r?r.nextElementSibling:null;c&&"SCRIPT"===c.tagName&&(c.style.display="none");var d=document.getElementById("signInOnlyHeader");d||((d=document.createElement("div")).id="signInOnlyHeader",d.innerHTML='
    🔐

    Welcome Back!

    Sign in to your account

    ',t.insertBefore(d,t.firstChild));var u=document.getElementById("emailSignInSection");if(u){var p=u.querySelector("p");p&&(p.innerHTML='Sign in with your email:')}var m=document.getElementById("signInOnlyNewHere");if(!m){(m=document.createElement("div")).id="signInOnlyNewHere",m.innerHTML='
    ';var h=t.querySelector(".skip");h?t.insertBefore(m,h):t.appendChild(m)}}},50))}},window._restoreSignUpForm=function(){var e=document.getElementById("usernameModal");if(e){var t=e.querySelector(".username-box");if(t){var o=document.getElementById("signInOnlyHeader");o&&o.remove();var n=document.getElementById("signInOnlyNewHere");n&&n.remove();var i=t.querySelector("h2"),a=t.querySelector("p"),r=document.getElementById("usernameInput"),s=document.getElementById("emailInput"),l=document.getElementById("giveawaySection"),c=t.querySelector('button[onclick="submitUsername()"]'),d=s?s.nextElementSibling:null;d&&"P"===d.tagName&&(d.style.display=""),i&&(i.style.display=""),a&&(a.style.display=""),r&&(r.style.display=""),s&&(s.style.display=""),l&&(l.style.display=""),c&&(c.style.display="");var u=document.getElementById("emailSignInSection");if(u){var p=u.querySelector("p");p&&(p.innerHTML="Already have an account? Sign in with your email:")}}}};let settingsTab="account";function shortcutRow(e,t){return'
    '+e+'
    '+t+"
    "}function showSettingsPage(e){try{settingsTab=e||"account";const Ye=document.getElementById("usernameModal"),Xe=Ye.querySelector(".username-box");if(!Ye)return void("function"==typeof showToast&&showToast("Error: modal not found"));if(!Xe)return void("function"==typeof showToast&&showToast("Error: username-box not found"));const Ke=void 0!==auth&&auth?auth.currentUser:null;if(!Ke)return void Ye.classList.add("open");const $e=getLevel(currentUser&¤tUser.points||0);let Ze="";if(Ze+='
    ',["account","scholar","sats","prefs","security","data"].forEach(e=>{const t=settingsTab===e;Ze+=""}),Ze+="
    ","account"===settingsTab){var t=Ke.isAnonymous,o=getUserDisplayEmoji($e),n=currentUser&¤tUser.profilePic||"",i=n?'':'
    '+o+"
    ";Ze+='
    '+i+'
    '+(currentUser&¤tUser.username||"Bitcoiner")+'
    '+$e.name+" · "+(currentUser&¤tUser.points||0).toLocaleString()+" XP"+(currentUser&¤tUser.faction?" · "+("cyber_hornets"===currentUser.faction?"🐝 Cyber Hornets":"🦡 Honey Badgers"):"")+"
    ";var a=currentUser&¤tUser.country||"";Ze+='
    🌍 Country
    Optional · Shown on your public profile
    ';var r=currentUser&¤tUser.faction||"";Ze+='
    ⚔️ Faction
    Choose your allegiance! New faction features coming soon — no competitive advantage to either choice.
    🐝
    Cyber Hornets
    The swarm protects the network
    '+("cyber_hornets"===r?'
    ✓ Joined
    ':"")+'
    🦡
    Honey Badgers
    Honey badger don\'t care
    '+("honey_badgers"===r?'
    ✓ Joined
    ':"")+"
    ",Ze+='
    📷 Profile Picture
    '+(n?'':'
    👤
    ')+'
    "+(n?' ':"")+'
    Square image recommended · Max 2MB
    ';var s="",l='
    Account Details
    ';Ke.email&&(l+='
    Email'+Ke.email+"
    "),Ke.displayName&&(l+='
    Name'+Ke.displayName+"
    ");let et="Anonymous";if(Ke.providerData&&Ke.providerData.length>0){const tt=Ke.providerData[0].providerId;"google.com"===tt?et="Google":"twitter.com"===tt?et="Twitter/X":"github.com"===tt?et="GitHub":"facebook.com"===tt?et="Facebook":"password"===tt&&(et="Email")}if(l+='
    Sign-in method'+et+"
    ",currentUser&¤tUser.created&&(l+='
    Member since'+(currentUser.created.toDate?currentUser.created.toDate().toLocaleDateString():new Date(currentUser.created).toLocaleDateString())+"
    "),s+=l+="
    ",!t){var c=currentUser&¤tUser.displayBadge||"",d=[];void 0!==earnedBadges&&void 0!==BADGE_DEFS&&BADGE_DEFS.forEach(function(e){earnedBadges.has(e.id)&&d.push({id:e.id,emoji:e.emoji,name:e.name})});var u=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]");if(void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){-1!==u.indexOf(e.id)&&d.push({id:e.id,emoji:e.hidden&&e.revealEmoji||e.emoji,name:e.hidden&&e.revealName||e.name})}),d.length>0){var p=$e.emoji+" Rank (default)";if(c){var m=d.find(function(e){return e.id===c});m&&(p=m.emoji+" "+m.name)}var h='
    Choose a badge to show next to your name instead of your rank emoji.
    ';h+='
    '+$e.emoji+'
    '+$e.name+' (Default)
    Your current rank emoji
    '+(c?"":'')+"
    ";for(var g=0;g'+f.emoji+'
    '+f.name+"
    "+(y?'':"")+"
    "}s+="
    🏅 Display Badge
    "+p+'
    ")+"
    "}}s+='
    ✏️ Change Username
    Current username: '+(currentUser&¤tUser.username||"")+'
    ',s+='';var b=currentUser&¤tUser.bio||"",v=[],w=[];[{k:"website",e:"🌐",l:"Website",p:"https://yoursite.com",m:100,t:"url"},{k:"twitter",e:"𝕏",l:"Twitter/X",p:"@yourusername",m:30},{k:"nostr",e:"🟣",l:"Nostr",p:"npub... or NIP-05",m:80},{k:"instagram",e:"📸",l:"Instagram",p:"@yourusername",m:30},{k:"tiktok",e:"🎵",l:"TikTok",p:"@yourusername",m:30},{k:"github",e:"🐙",l:"GitHub",p:"yourusername",m:40},{k:"contactEmail",e:"📧",l:"Email",p:"you@example.com",m:80,t:"email",note:"public"},{k:"lightning",e:"⚡",l:"Lightning",p:"you@walletofsatoshi.com",m:80}].forEach(function(e){currentUser&¤tUser[e.k]?v.push(e):w.push(e)}),Ze+='
    📝 Public Profile
    Visible when someone clicks your name on the leaderboard
    ",Ze+='
    🔗 Links & Socials
    ',Ze+='
    ',v.forEach(function(e){var t=currentUser&¤tUser[e.k]||"";Ze+=''}),Ze+="
    ",w.length>0&&(Ze+='
    "),Ze+='
    ',currentUser&&(currentUser.lightning||currentUser.lightningAddress)||(Ze+='
    Connect a Lightning Wallet
    Tip other users and receive tips from the community!
    '),Ze+="",Ze+='",Ze+=''}else if("_artist_removed"===settingsTab){var x=currentUser&¤tUser.artistProfile||{};void 0!==db&&auth&&auth.currentUser&&auth.currentUser.uid,Ze+='
    🎸
    Artist Profile
    Set up your artist presence on Bitcoin Beats
    ',Ze+='
    🎤 Stage Name
    Shows on your tracks and artist page. Leave blank to use your username.
    ',Ze+='
    📝 Artist Bio
    Music-specific bio. Your general bio is in Account tab.
    ',Ze+='
    🎵 Genres
    Comma-separated. Shows as tags on your artist page.
    ',Ze+='
    🔗 Music Links
    🌊
    🟢
    🎵
    📺
    🔗
    ',Ze+='
    Lightning Tips
    '+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?"✅ Lightning Address set: "+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ No Lightning Address set. Go to Account tab or set up in ⚡ Wallet to receive tips!")+"
    ",Ze+='',Ze+="'}else if("scholar"===settingsTab){Ze+='
    🎓
    Bitcoin Scholar

    Master Bitcoin through quests, certifications, and flashcards.

    ',Ze+='
    Channel Quests

    Test your knowledge on any Bitcoin topic with guided quiz questions.

    ';var k="true"===localStorage.getItem("btc_scholar_prop_passed");Ze+='
    '+(k?"✅":"📜")+'
    Bitcoin Scholar Certification

    25 questions on the economic properties and scarcity of Bitcoin. 80% to pass. One attempt per day.

    ";var B="true"===localStorage.getItem("btc_scholar_tech_passed");Ze+='
    '+(B?"✅":"🛠️")+'
    Bitcoin Protocol Expert

    25 questions on highly technical topics: BIPs, Script, SegWit, Taproot, and Networking.

    ",Ze+="

    Prepare for quests and exams with interactive flashcards.

    ",[{name:"Bitcoin Basics",emoji:"₿"},{name:"Security & Storage",emoji:"🔑"},{name:"Lightning Network",emoji:"⚡"},{name:"Mining & Energy",emoji:"⛏️"},{name:"Economics & Money",emoji:"💰"},{name:"History & Culture",emoji:"📜"},{name:"Privacy & Sovereignty",emoji:"🕵️"},{name:"Nodes & P2P",emoji:"📡"},{name:"Wallets & Tools",emoji:"💼"},{name:"Common Myths",emoji:"🚫"},{name:"Austrian Economics",emoji:"🇦🇹"},{name:"Cypherpunk History",emoji:"🔐"},{name:"Bitcoin Governance",emoji:"🏛️"},{name:"Satoshi Nakamoto",emoji:"🦸"},{name:"Global Impact",emoji:"🌍"},{name:"El Salvador & Adoption",emoji:"🇸🇻"},{name:"Technical Deep Dives",emoji:"🔬"}].forEach(function(e){Ze+=""}),Ze+="
    ",Ze+="",Ze+='"}else if("signal"===settingsTab){var _;Ze+='
    📡
    The Weekly Signal

    Curated Bitcoin insights and site updates.

    ',S=null===(_=localStorage.getItem("btc_ticker_enabled"))?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===_,Ze+="
    📊Live Ticker on Home
    ",Ze+='
    📡 Live Signals
    ',Ze+='
    ',Ze+="",Ze+='
    📚 Featured Deep Dives
    ',[{date:"Feb 26, 2026",title:"Why Proof of Stake is just Fiat 2.0",snippet:"Most cryptos claim to be better than Bitcoin because they use less energy. But Gigi explains why energy IS the point — PoW converts real-world resources into unforgeable security.",channel:"pow-vs-pos"},{date:"Feb 19, 2026",title:"The Great Definancialization",snippet:"Parker Lewis breaks down why we don't need thousands of stocks, bonds, and derivatives if we have one form of hard money that can't be debased.",channel:"problems-of-money"},{date:"Feb 12, 2026",title:"The 21 Million Cap is Inviolate",snippet:"Why even if every miner in the world wanted to change the supply, they couldn't. The users run the rules.",channel:"scarce"},{date:"Feb 5, 2026",title:"Not Your Keys, Not Your Coins",snippet:"After another exchange collapse, the importance of self-custody has never been clearer. Here's how to take control.",channel:"self-custody"},{date:"Jan 29, 2026",title:"The Halving: Scarcity You Can Verify",snippet:"Every 210,000 blocks, the supply issuance gets cut in half. No vote. No committee. Just code.",channel:"difficulty-adjustment"}].forEach(function(e){Ze+='
    '+e.date.toUpperCase()+'
    '+e.title+'
    '+e.snippet+"
    '}),setTimeout(function(){var e=document.getElementById("signalLiveNews");e&&fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=(e.snippet||"").replace(/<[^>]+>/g,""),a=e.link||"";n+='
    SIGNAL #'+(t+1)+''+(e.date||"").toUpperCase()+'
    '+o+"
    "+(i?'
    '+i+"
    ":"")+(a?'
    Read full article →
    ':"")+"
    "}),o.innerHTML=n;var i=function(){var t=document.getElementById("signalArrowL"),o=document.getElementById("signalArrowR");t&&o&&(e.scrollWidth>e.clientWidth+10?(t.style.display=e.scrollLeft>10?"flex":"none",o.style.display=e.scrollLeft+e.clientWidth✅ You\'re subscribed to The Signal!':'
    📧
    Get The Signal via Email

    Weekly curated Bitcoin insights. No spam, pure signal.

    '}else if("tickets"===settingsTab){const ot=!Ke||Ke.isAnonymous;ot?Ze+='
    Orange Tickets
    Sign in with Google, Twitter, or GitHub to start earning Orange Tickets and get your referral link!
    ':(Ze+="function"==typeof renderTicketsSection?renderTicketsSection():"",Ze+="function"==typeof renderReferralSection?renderReferralSection():"",Ze+='
    How to Earn Tickets
    📅 Daily Login: +1 ticket just for visiting.
    🎡 Spin the Wheel: Spin daily for bonus tickets!
    👥 Referrals: Earn 50 tickets per friend who signs up and reaches Maxi rank (2,140+ pts). Verified automatically.
    🏅 Badges: Unlock at 25 🐟, 50 🦈, and 100 🐋 tickets.
    ⭐ Bonus: Each ticket = +5 XP towards your rank.
    🏆 Giveaways: More tickets = higher chance of winning sats!
    '),ot||"function"!=typeof loadReferralStatsUI||setTimeout(loadReferralStatsUI,100)}else if("sats"===settingsTab){var I=window._satsSubTab||"claim",C=(t=Ke.isAnonymous,currentUser&¤tUser.points||0),E=currentUser&¤tUser.pointsClaimed||0,A=currentUser&¤tUser.pointsDonated||0,z=C-E,M=currentUser&¤tUser.satsWithdrawn||0,P=Math.floor(Math.max(0,z)/10),L="function"==typeof getSatCap?getSatCap():1e4,U=Math.max(0,L-M),q=Math.min(P,500,U),N=currentUser&¤tUser.lastSatsClaim||null,H=N?new Date(N.seconds?1e3*N.seconds:N).getTime()+864e5:0,D=Date.now(),O=N&&Dj&&(j=F.length)}catch(nt){}var G=Ke.metadata&&Ke.metadata.creationTime?new Date(Ke.metadata.creationTime):null,V=G?Math.floor((D-G.getTime())/864e5):0,Q=Ke.email&&Ke.emailVerified,J=!t&&Q&&V>=7&&j>=10,Y=P>=100;if(Ze+='
    ',Ze+='',Ze+='',Ze+="
    ","donate"!==I){Ze+='
    ',Ze+='
    ',Ze+='
    Claim Real Sats
    ',Ze+='
    Earn XP → Convert to real Bitcoin over Lightning
    ',Ze+="
    ",Ze+='
    ',Ze+='
    Your Balance
    ',Ze+='
    ⚡ '+P.toLocaleString()+" claimable sats
    ",Ze+='
    '+z.toLocaleString()+" unclaimed XP of "+C.toLocaleString()+" total
    ",Ze+='
    Lifetime withdrawn: '+M.toLocaleString()+" / 10,000 sats
    ",Ze+="
    ",Ze+=!t&&J&&Y&&!O&&q>=100?'":O?'
    ⏳ Next claim in '+W+"
    ":!Y&&J?'
    Need '+(100-P)+" more sats ("+10*(100-P)+" XP) to reach minimum claim
    ":'
    Complete requirements below to claim
    ',Ze+='
    ',Ze+='
    📋 Requirements
    ',[{met:!t,label:"Signed in (not anonymous)",detail:t?"Sign in with email, Google, etc.":"✓ Signed in"},{met:Q,label:"Email verified",detail:Q?"✓ "+Ke.email:"Link & verify your email in Account tab"},{met:V>=7,label:"Account age ≥ 7 days",detail:V>=7?"✓ "+V+" days old":V+"/7 days — "+(7-V)+" more to go"},{met:j>=10,label:"Read ≥ 10 topics",detail:j>=10?"✓ "+j+" topics read":j+"/10 topics — read "+(10-j)+" more"},{met:Y,label:"Minimum 100 sats (1,000 pts)",detail:Y?"✓ "+P+" sats available":P+"/100 sats — earn "+10*(100-P)+" more XP"}].forEach(function(e){Ze+='
    ',Ze+=''+(e.met?"✅":"⬜")+"",Ze+='
    '+e.label+"
    ",Ze+='
    '+e.detail+"
    "}),Ze+="
    ",Ze+='
    ',Ze+='
    ⚡ How It Works
    ',Ze+='
    ',Ze+="• 1,000 XP = 100 sats — earn XP by reading, quests, and daily visits
    ",Ze+="• Min claim: 100 sats (1,000 XP)
    ",Ze+="• Max claim: 500 sats/day
    ",Ze+="• 1 claim per 24 hours
    ",Ze+="• Lifetime max: 10,000 sats per account
    ",Ze+="• Daily XP cap: 500 XP (50 sats worth) to prevent abuse
    ",Ze+="• Unclaimed sats roll over — no expiration
    ",Ze+="• Payouts via Lightning Network ⚡
    ",Ze+="
    ",Ze+='
    ',Ze+="💚 Zero fees for you! We pay all Lightning network fees so you receive the full amount you claim. You earned it!",Ze+="
    ",Ze+='
    ',Ze+="",Ze+='
    ",Ze+='
    ',Ze+='
    📜 Withdrawal History
    ',Ze+='
    Loading...
    ',Ze+="
    ";var K=currentUser&&(currentUser.lightning||currentUser.lightningAddress)||"";Ze+='
    ',Ze+='
    Lightning Address
    For receiving tips from other users
    ',K&&(Ze+='
    '+escapeHtml(K)+"
    "),Ze+='
    ',Ze+='
    ',K||(Ze+='
    💡 Get one from Wallet of Satoshi, Alby, Coinos, or Strike.
    '),Ze+="
    "}else{var $=Math.max(0,C-E-A);r=currentUser&¤tUser.faction||"",Ze+='
    ',Ze+='
    ❤️
    ',Ze+='
    Donate XP for Charity
    ',Ze+='
    1,000 XP = 1,000 sats donated — 10× more impact than claiming
    ',Ze+="
    ",Ze+='
    ',Ze+='
    Available to Donate
    ',Ze+='
    ❤️ '+$.toLocaleString()+" XP
    ",Ze+='
    '+C.toLocaleString()+" total − "+E.toLocaleString()+" claimed − "+A.toLocaleString()+" donated
    ",Ze+="
    ",t?Ze+='
    🔐 Sign in to donate XP
    ':r?(Ze+='
    ',[5,10,25,50,100].forEach(function(e){var t=Math.floor($*e/100);Ze+='"}),Ze+="
    ",Ze+='
    ',Ze+='',Ze+="
    ",Ze+='
    ',Ze+='',Ze+="
    ",Ze+='',A>0&&(Ze+='
    '+A.toLocaleString()+" XP already donated — thank you! ❤️
    ")):(Ze+='
    ',Ze+='
    ⚔️
    ',Ze+='
    Choose Your Faction First
    ',Ze+='
    Your faction’s donation total is tracked for the community leaderboard.
    ',Ze+='',Ze+="
    "),Ze+='
    ',Ze+='',Ze+='',Ze+="
    "}}else if("prefs"===settingsTab){const it="light"!==document.body.getAttribute("data-theme"),at="true"===localStorage.getItem("btc_theme_oled"),rt=localStorage.getItem("btc_font_size")||"medium";Ze+="
    🎨 Appearance
    Theme
    Font Size
    ',["small","medium","large"].forEach(function(e){var t=rt===e,o=e.charAt(0).toUpperCase()+e.slice(1);Ze+=""}),Ze+="
    ",Ze+='
    🌐 Language
    Translate the site to your preferred language
    ',setTimeout(function(){const e=document.getElementById("langSelect"),t=localStorage.getItem("btc_lang")||"";e&&(e.value=t)},50);const st="undefined"==typeof audioEnabled||audioEnabled,lt="undefined"!=typeof audioVolume?audioVolume:.5;Ze+='
    🔊 Sound
    Sound Effects
    Volume
    ',Ze+="",Ze+='"}else Ze+=""}var Fe=localStorage.getItem("btc_nacho_nickname")||"Nacho";if(Ze+='
    🏷️ Name Your Buck
    Currently: '+escapeHtml(Fe)+'
    ',"function"==typeof getNachoStoryProgress){var Ge=getNachoStoryProgress(),Ve=Ge>=10,Qe=escapeHtml(Fe);Ze+='
    📖
    '+Qe+'\'s Story
    '+(Ve?"✅ Complete!":"A new chapter unlocks every day!")+'
    '+Ge+'/10
    "}"function"==typeof renderNachoClosetUI&&(void 0===window._expanded_closet&&(window._expanded_closet=!1),window._pendingClosetScroll&&(window._expanded_closet=!0),Ze+='
    👗 '+escapeHtml(Fe)+'\'s Closet
    '+(window._expanded_closet?"▾":"▸")+"
    ",window._expanded_closet&&(Ze+='
    '),Ze+="
    "),"function"==typeof renderStickerBook&&(Ze+='
    🎨 Sticker Book
    '+(window._expanded_stickers?"▾":"▸")+"
    ",window._expanded_stickers&&(Ze+='
    '+renderStickerBook()+"
    "),Ze+="
    "),Ze+='
    🔒 Privacy
    We do not sell, share, or monetize your data. Ever.
    The only data we store is your username, points, and progress — just enough to power your experience. No tracking, no ads, no third-party analytics. Your data is yours.
    ',Ze+="",Ze+='",Ze+="",Ze+='"}if(Ze+='Close',Xe.innerHTML=Ze,Ye.classList.add("open"),"sats"===settingsTab&&"function"==typeof loadSatsHistory&&setTimeout(loadSatsHistory,100),"sats"===settingsTab&&(window._toggleSatsCharityNote=function(){var e=document.getElementById("satsCharityNote"),t=document.getElementById("satsCharityNoteArrow");if(e){var o="none"!==e.style.display;e.style.display=o?"none":"block",t&&(t.textContent=o?"▼":"▲")}},window._satsCharitySetAmt=function(e){var t=document.getElementById("satsCharityAmtInput");t&&(t.value=e>0?e:"")},window._satsCharitySubmit=function(){if("undefined"!=typeof firebase&&firebase.functions){var e=document.getElementById("satsCharityAmtInput"),t=parseInt(e?e.value:"")||0,o=void 0!==currentUser&¤tUser?Math.max(0,(currentUser.points||0)-(currentUser.pointsClaimed||0)-(currentUser.pointsDonated||0)):0;if(!t||t<1)"function"==typeof showToast&&showToast("Enter a valid amount");else if(t>o)"function"==typeof showToast&&showToast("Not enough available XP ("+o.toLocaleString()+" available)");else{var n=!!document.getElementById("satsCharityAnonToggle")&&document.getElementById("satsCharityAnonToggle").checked,i=document.querySelector('[onclick="window._satsCharitySubmit()"]');i&&(i.disabled=!0,i.textContent="Donating..."),firebase.functions().httpsCallable("donatePoints")({amount:t,anonymous:n}).then(function(e){void 0!==currentUser&¤tUser&&(currentUser.pointsDonated=(currentUser.pointsDonated||0)+t,e.data&&e.data.bonusPts&&(currentUser.points=(currentUser.points||0)+e.data.bonusPts));var o=e.data&&e.data.newBadges&&e.data.newBadges.length>0?" +"+e.data.newBadges.length+" badge"+(e.data.newBadges.length>1?"s":"")+" unlocked!":"";"function"==typeof showToast&&showToast("❤️ Thank you! "+t.toLocaleString()+" XP donated ("+t.toLocaleString()+" sats pledged to charity)."+o,5e3),"function"==typeof window._charityThankYou&&window._charityThankYou(t,e.data&&e.data.newBadges||[],e.data&&e.data.bonusPts||0);var n=e.data&&e.data.newBadges||[];if(n.length>0&&"function"==typeof window.contributeSatoshiFavor){var i={donor_100:"🤷 Giving Pleb",donor_500:"💛 Stack Sharer",donor_1000:"🧡 Community Builder",donor_5000:"❤️ Archive Patron",donor_10000:"🔥 Sats Saint",donor_25000:"⚡ Lightning Philanthropist",donor_50000:"🏆 Satoshi's Steward",donor_100000:"👑 Legend of the Archive"};n.forEach(function(e){i[e]&&window.contributeSatoshiFavor("badge_earned",i[e]).catch(function(){})})}void 0!==window._charityStatsLoaded&&(window._charityStatsLoaded=!1),showSettingsPage("sats")}).catch(function(e){i&&(i.disabled=!1,i.textContent="❤️ Donate XP for Charity"),"function"==typeof showToast&&showToast("❌ "+(e.message||"Donation failed. Try again."),4e3)})}}}),"data"===settingsTab&&"function"==typeof loadReferralStatsUI&&Ke&&!Ke.isAnonymous&&setTimeout(loadReferralStatsUI,100),"data"===settingsTab&&"function"==typeof renderNachoClosetUI){var Je=document.getElementById("nachoClosetContainer");Je&&(renderNachoClosetUI(Je),window._pendingClosetScroll&&setTimeout(function(){Je.scrollIntoView({behavior:"smooth",block:"center"}),window._pendingClosetScroll=!1},300))}}catch(_t){"function"==typeof showToast&&showToast("Settings page error: "+_t.message),console.error("showSettingsPage error:",_t)}}function changeLanguage(e){const t=document.getElementById("langStatus");if(!e){const e=document.querySelector(".goog-te-banner-frame");e&&e.remove();var o=document.querySelector("iframe.goog-te-banner-frame");o&&o.remove();var n=document.querySelector(".skiptranslate");return n&&n.remove(),document.body.style.top="",document.body.style.position="",document.documentElement.style.overflow="",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=."+location.hostname,localStorage.setItem("btc_lang",""),t&&(t.innerHTML='✅ Switched to English'),document.documentElement.classList.remove("translated-ltr","translated-rtl"),document.querySelectorAll('font[style*="vertical-align: inherit"]').forEach(function(e){var t=e.parentNode;t&&t.replaceChild(document.createTextNode(e.textContent),e)}),void setTimeout(function(){showSettingsPage("prefs")},200)}if(localStorage.setItem("btc_lang",e),document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname,t&&(t.innerHTML='Translating...'),document.getElementById("gtranslate"))triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!');else{const o=document.createElement("script");o.id="gtranslate",o.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(o),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget"),setTimeout(()=>{triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!')},1500)};const n=document.createElement("div");n.id="gtranslateWidget",n.style.display="none",document.body.appendChild(n)}}function triggerGoogleTranslate(e){const t=document.querySelector(".goog-te-combo");t&&(t.value=e,t.dispatchEvent(new Event("change")))}function setFontSize(e){localStorage.setItem("btc_font_size",e);const t="small"===e?"14px":"medium"===e?"16px":"18px";document.documentElement.style.fontSize=t,showSettingsPage("prefs")}async function saveProfile(){var e=document.getElementById("profileStatus");if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in with Google, Facebook, Twitter, or email to save your profile!"),e&&(e.innerHTML='🔒 Create a free account to save your profile'),void("function"==typeof showUsernamePrompt&&setTimeout(showUsernamePrompt,1500));var t=auth.currentUser.uid,o=document.getElementById("profileBio")?document.getElementById("profileBio").value.trim():"",n=document.getElementById("countryInput"),i=n?n.value.trim().substring(0,60):"";if(i&&window._countryList&&-1===window._countryList.indexOf(i))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void n.focus();var a={bio:o,country:i};["website","twitter","nostr","instagram","tiktok","github","contactEmail","lightning"].forEach(function(e){var t,o=document.getElementById("profile_"+e);if(o){var n=o.value.trim();"lightning"===e?(n=n.replace(/[\\'"<>]/g,""))&&!n.match(/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)&&(n=""):n="contactEmail"===e||"nostr"===e?n.replace(/[\\'"<>]/g,""):(t=n)?(t=t.trim(),/^(javascript|data|vbscript|blob):/i.test(t)?"":t):"",a[e]=n}else currentUser&&void 0!==currentUser[e]&&(document.querySelector('.pf-link-row[data-key="'+e+'"]')||(a[e]=""))});try{e&&(e.innerHTML='Saving...'),await db.collection("users").doc(t).update(a),Object.assign(currentUser,a),e&&(e.innerHTML='✅ Profile saved!'),"function"==typeof showToast&&showToast("✅ Profile saved successfully!"),setTimeout(function(){e&&(e.innerHTML=""),showSettingsPage("account")},1500)}catch(t){console.error("Error saving profile:",t),e&&(e.innerHTML='❌ Error saving'),"function"==typeof showToast&&showToast("❌ Error saving profile")}}function _pasteFieldFallback(e){e.focus(),e.value="",e.setSelectionRange(0,0);try{document.execCommand("paste")}catch(e){}"function"==typeof showToast&&showToast("📋 Field ready — tap and hold, then tap Paste",5e3)}function clearUserLocalStorage(){for(var e=["btc_theme_oled","btc_font_size","btc_volume","btc_lang","btc_haptic","btc_soundscape","btc_ticker_enabled","btc_ios_a2hs_dismissed","btc_pwa_dismissed","btc_swipe_hint_shown","btc_last_auth_uid","btc_signin_email","btc_pending_email","btc_pending_username","btc_pending_giveaway"],t=[],o=0;o
    Scan this QR code with your authenticator app:
    Or enter this key manually: '+(t.data.secret||"")+'
    ')}}catch(e){showToast("Error setting up authenticator: "+(e.message||"try again"))}}async function verifyTotpSetup(){var e=document.getElementById("totpVerifyCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpVerify");await t({code:e.value.trim()}),showToast("✅ Authenticator app enabled!"),showSettingsPage("security")}catch(e){showToast("Invalid code. Try again.")}else showToast("Enter a 6-digit code")}async function disableTotp(){var e=document.getElementById("totpDisableCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpDisable");await t({code:e.value.trim()}),showToast("Authenticator app disabled"),showSettingsPage("security")}catch(e){showToast("Invalid code")}else showToast("Enter your current code")}function clearUserData(){["btc_visited_channels","btc_favs","btc_hidden_badges","btc_asked_questions","btc_scholar_passed","btc_scholar_attempt_date","btc_badges","btc_last_channel","btc_signin_email","btc_nacho_equipped","btc_nacho_items_notified","btc_points","btc_total_visits","btc_streak","btc_last_visit"].forEach(function(e){localStorage.removeItem(e)}),currentUser=null}function showSignInPrompt(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous?showSettings():showUsernamePrompt()}function _generateDeviceFingerprint(){try{var e=document.createElement("canvas"),t=e.getContext("2d");t.textBaseline="top",t.font="14px Arial",t.fillText("Bitcoin Education 🦌",2,2);for(var o=e.toDataURL(),n=[navigator.userAgent||"",screen.width+"x"+screen.height,screen.colorDepth,(new Date).getTimezoneOffset(),navigator.language||"",navigator.hardwareConcurrency||0,(navigator.deviceMemory||0).toString(),void 0!==window.ontouchstart?"touch":"no-touch",o.substring(o.length-50)].join("|"),i=0,a=0;a{const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.frequency.value=o,i.type=n<3?"sine":"triangle",a.gain.setValueAtTime(.12*e,t.currentTime+.1*n),a.gain.exponentialRampToValueAtTime(.001,t.currentTime+.1*n+.6),i.start(t.currentTime+.1*n),i.stop(t.currentTime+.1*n+.6)})}catch(e){}"function"==typeof launchConfetti&&launchConfetti();const o=document.createElement("div");o.id="levelUpModal",o.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;animation:fadeIn 0.4s;",o.innerHTML='
    '+e.emoji+'
    ⬆️ LEVEL UP!
    '+e.name+'
    You\'ve reached '+e.min.toLocaleString()+'+ XP!
    '+getLevelFlavor(e.name)+'
    ',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function getLevelFlavor(e){return{Curious:"You're starting to see what all the fuss is about.",Pleb:"Welcome to the pleb life. You're one of us now.","Pleb II":"170 — the block height when Satoshi mined the first 1,000 blocks. You're going deeper.","Pleb III":"256 — the number of bits in a private key. You're becoming unbreakable.",Stacker:"Stacking sats and stacking knowledge. Impressive.","Stacker II":"Double stacking! 1913 — the year the Fed was born. You know why that matters.","Stacker III":"Triple stack mode. 2016 — the year the halving changed everything.",Maxi:"2140 — when the last sat is mined. There is no second best. You know it.","Maxi II":"6102 — Executive Order 6102 banned gold. They can't ban Bitcoin. Double the conviction.","Maxi III":"8888 — triple maxi. The signal only gets stronger.","Papa John":"10,000 BTC for two pizzas. Never forget. 🍕 You've earned your slice.","Full Node":"18,333 — port 18333. You verify everything yourself. Don't trust, verify.",Whale:"50,000 strong. You move markets. Unstoppable, just like Bitcoin.",Sovereign:"Self-sovereign. 100K channels deep. No permission needed. You ARE the bank.",Cypherpunk:"133,337 — leet beyond leet. Privacy is a right, not a privilege. Code is law.",Satoshi:"The pinnacle. You've achieved legendary status."}[e]||"You're leveling up!"}window.showSettings=function(){if(void 0===auth||!auth)return"function"==typeof showToast&&showToast("⚠️ Firebase not ready. Retrying..."),"function"==typeof initRanking&&initRanking(),void setTimeout(function(){void 0!==auth&&auth?showUsernamePrompt():"function"==typeof showToast&&showToast("❌ Could not load. Please refresh the page.")},2e3);showUsernamePrompt()},window._countryList=["Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burundi","Cabo Verde","Cambodia","Cameroon","Canada","Central African Republic","Chad","Chile","China","Colombia","Comoros","Congo","Costa Rica","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Eswatini","Ethiopia","Fiji","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Grenada","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Ivory Coast","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","North Korea","North Macedonia","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","Sudan","Suriname","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor-Leste","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Yemen","Zambia","Zimbabwe"],window._filterCountryList=function(){var e=document.getElementById("countryInput"),t=document.getElementById("countryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
    '+l+"
    "}n.length>8&&(i+='
    +'+(n.length-8)+" more — keep typing
    "),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectCountry=function(e){var t=document.getElementById("countryInput"),o=document.getElementById("countryDropdown");t&&(t.value=e),o&&(o.style.display="none")},window._selectFaction=async function(e){try{var t=auth?auth.currentUser:null;if(!t)return void("function"==typeof showToast&&showToast("Sign in to choose a faction"));if(t.isAnonymous)return void("function"==typeof showToast&&showToast("Create an account to choose a faction"));var o=currentUser&¤tUser.faction||null,n=!o;await db.collection("users").doc(t.uid).update({faction:e}),currentUser&&(currentUser.faction=e),"function"==typeof showToast&&showToast("cyber_hornets"===e?"🐝 Welcome to the Cyber Hornets!":"🦡 Welcome to the Honey Badgers!"),showSettingsPage("account"),n&&"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("syncUserFactionPoints")({newFaction:e,previousFaction:o}).then(function(e){e.data&&e.data.pointsSynced>0&&"function"==typeof showToast&&showToast("⚡ "+e.data.pointsSynced+" past SF point"+(1!==e.data.pointsSynced?"s":"")+" credited to your faction!")}).catch(function(e){console.warn("[FACTION] syncUserFactionPoints failed:",e)})}catch(e){console.error("Faction select error:",e),"function"==typeof showToast&&showToast("Error saving faction")}},window._filterSignupCountry=function(){var e=document.getElementById("signupCountryInput"),t=document.getElementById("signupCountryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
    '+l+"
    "}n.length>8&&(i+='
    +'+(n.length-8)+" more — keep typing
    "),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectSignupCountry=function(e){var t=document.getElementById("signupCountryInput"),o=document.getElementById("signupCountryDropdown");t&&(t.value=e),o&&(o.style.display="none")},document.addEventListener("click",function(e){[["countryDropdown","countryAutocomplete"],["signupCountryDropdown","signupCountryAutocomplete"]].forEach(function(t){var o=document.getElementById(t[0]),n=document.getElementById(t[1]);o&&n&&!n.contains(e.target)&&(o.style.display="none")})}),function(){const e=localStorage.getItem("btc_lang");if(e){document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname;const t=document.createElement("script");t.id="gtranslate",t.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(t),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget")};const o=document.createElement("div");o.id="gtranslateWidget",o.style.display="none",document.body.appendChild(o)}}(),window.setSoundscape=function(e){localStorage.setItem("btc_soundscape",e),"function"==typeof updateSoundscape&&updateSoundscape(e),showSettingsPage("prefs")},window._removedProfileLinks={},window.profileLinkRemoved=function(e){window._removedProfileLinks[e]=!0},window.addProfileLink=function(e,t,o,n,i,a){var r=document.getElementById("profileLinksArea");if(r){var s=document.createElement("div");s.className="pf-link-row",s.setAttribute("data-key",e),s.style.cssText="display:flex;align-items:center;gap:12px;margin-bottom:12px;background:rgba(255,255,255,0.02);padding:10px;border-radius:12px;border:1px solid var(--border);",s.innerHTML=''+t+'',r.appendChild(s);var l=document.getElementById("addLinkMenu");l&&(l.style.display="none");var c=document.getElementById("profile_"+e);c&&c.focus()}},window.handleProfilePicUpload=function(e){var t=e.files&&e.files[0];if(t){var o=document.getElementById("pfpUploadStatus");if(t.type.match(/^image\//))if(t.size>2097152)o&&(o.innerHTML='❌ Image too large (max 2MB)');else{o&&(o.innerHTML='Processing...');var n=new FileReader;n.onload=function(e){var t=new Image;t.onload=function(){var e=128,n=document.createElement("canvas");n.width=e,n.height=e;var i,a,r=n.getContext("2d"),s=Math.min(t.width,t.height);i=(t.width-s)/2,a=(t.height-s)/2,r.drawImage(t,i,a,s,s,0,0,e,e);var l=n.toDataURL("image/jpeg",.8);auth&&auth.currentUser?db.collection("users").doc(auth.currentUser.uid).update({profilePic:l}).then(function(){currentUser&&(currentUser.profilePic=l),window._lbCache=null,o&&(o.innerHTML='✅ Profile picture saved!'),"function"==typeof showToast&&showToast("📷 Profile picture updated!"),setTimeout(function(){showSettingsPage("account")},1e3)}).catch(function(e){o&&(o.innerHTML='❌ Save failed: '+e.message+"")}):o&&(o.innerHTML='❌ Not signed in')},t.onerror=function(){o&&(o.innerHTML='❌ Could not load image')},t.src=e.target.result},n.readAsDataURL(t)}else o&&(o.innerHTML='❌ Please select an image file')}},window.removeProfilePic=function(){auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({profilePic:""}).then(function(){currentUser&&(currentUser.profilePic=""),window._lbCache=null,"function"==typeof showToast&&showToast("📷 Profile picture removed"),showSettingsPage("account")}).catch(function(){})},window.showArtistProfileModal=function(){if(auth&&auth.currentUser){var e=document.getElementById("artistProfileModal");e&&e.remove();var t=currentUser&¤tUser.artistProfile||{},o=auth.currentUser.uid,n=document.createElement("div");n.id="artistProfileModal",n.style.cssText="position:fixed;inset:0;z-index:500000;background:rgba(0,0,0,0.85);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",n.onclick=function(e){e.target===n&&n.remove()},n.innerHTML='
    🎸
    Artist Profile
    Set up your artist presence on Bitcoin Beats
    🎤 Stage Name
    Leave blank to use your username.
    📝 Artist Bio
    🎵 Genres
    🔗 Music Links
    🌐
    𝕏
    📸
    '+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?'✅ Lightning: '+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ Set a Lightning Address in Account or Wallet to receive tips!")+'
    ',document.body.appendChild(n)}else"function"==typeof showToast&&showToast("Sign in first")},window.saveArtistProfile=function(){if(auth&&auth.currentUser&&void 0!==db){var e=document.getElementById("artistSaveBtn");e&&(e.disabled=!0,e.textContent="Saving...");var t={stageName:(document.getElementById("artistStageName").value||"").trim().substring(0,40),bio:(document.getElementById("artistBio").value||"").trim().substring(0,500),genres:(document.getElementById("artistGenres").value||"").trim().substring(0,100),website:(document.getElementById("artistLinkWebsite").value||"").trim().substring(0,200),x:(document.getElementById("artistLinkX").value||"").trim().substring(0,50),instagram:(document.getElementById("artistLinkInstagram").value||"").trim().substring(0,50)};db.collection("users").doc(auth.currentUser.uid).update({artistProfile:t}).then(function(){currentUser&&(currentUser.artistProfile=t),"function"==typeof showToast&&showToast("🎸 Artist profile saved!"),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")}).catch(function(t){console.error("Artist profile save error:",t),"function"==typeof showToast&&showToast("Error saving: "+(t.message||"Unknown")),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")})}else"function"==typeof showToast&&showToast("Sign in to save your artist profile")},window.pasteToField=function(e){var t=document.getElementById(e);t&&(navigator.clipboard&&navigator.clipboard.readText?navigator.clipboard.readText().then(function(e){e?(t.value=e.trim(),t.style.borderColor="var(--accent)",t.dispatchEvent(new Event("input",{bubbles:!0})),"function"==typeof showToast&&showToast("📋 Pasted!")):_pasteFieldFallback(t)}).catch(function(){_pasteFieldFallback(t)}):_pasteFieldFallback(t))},window.loadSignalContent=function(){var e=document.getElementById("signalLiveNews");e&&!e.getAttribute("data-loaded")&&(e.setAttribute("data-loaded","1"),fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=e.link||"";n+='
    SIGNAL #'+(t+1)+'
    '+o+"
    "+(i?'
    Read →
    ':"")+"
    "}),o.innerHTML=n}}).catch(function(){}))},window.expandSignUpBanner=function(){sessionStorage.removeItem("btc_signin_banner_dismissed");var e=document.getElementById("mobileSignUpPill");e&&e.remove();var t=document.getElementById("userDisplay");t&&t.classList.remove("user-hidden"),"function"==typeof updateUserDisplay&&updateUserDisplay()},window.minimizeSignUpBanner=function(){sessionStorage.setItem("btc_signin_banner_dismissed","1");var e=document.getElementById("userDisplay");if(window.innerWidth<=900){e&&(e.classList.add("user-hidden"),e.style.display="none");var t=document.getElementById("mobileSignUpPill");t||((t=document.createElement("div")).id="mobileSignUpPill",document.body.appendChild(t)),t.style.cssText="position:fixed;bottom:70px;left:12px;z-index:200;display:flex;align-items:center;gap:6px;padding:8px 12px 8px 16px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",t.innerHTML='🔐 Sign Up',t.onclick=function(){window.expandSignUpBanner()}}else{if(!e)return;e.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:6px;padding:6px 14px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",e.innerHTML='🔐 Sign Up',e.onclick=function(){window.expandSignUpBanner()}}},window.clearUserLocalStorage=clearUserLocalStorage,window.hideUsernamePrompt=function(){const e=document.getElementById("usernameModal");if(e&&e.classList.remove("open"),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn(),"function"==typeof window._onSettingsClose){var t=window._onSettingsClose;window._onSettingsClose=null,setTimeout(t,150)}},window.submitUsername=async function(){try{var e=document.getElementById("usernameInput")||document.getElementById("newUsername");if(!e)return void console.error("[submitUsername] No input found");var t=e.value.trim();if(!t)return void showToast("Please enter a username!");if(t.length<2)return void showToast("Username must be at least 2 characters");if(t.length>20)return void showToast("Username must be 20 characters or less");if(containsProfanity(t))return void showToast("⚠️ That username is not allowed.");if(document.getElementById("usernameInput")){var o=document.getElementById("emailInput"),n=o?o.value.trim():"",i=document.getElementById("signupCountryInput"),a=i?i.value.trim().substring(0,60):"";if(a&&window._countryList&&-1===window._countryList.indexOf(a))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void i.focus();var r=document.getElementById("giveawayCheckbox"),s=document.getElementById("giveawayLnAddress"),l=r&&r.checked,c=s?s.value.trim():"";return l&&!c?(s&&(s.style.borderColor="#ef4444",s.focus()),void showToast("⚡ Enter a Lightning address to enter the giveaway, or uncheck the box to skip.")):n&&await sendMagicLink(n)?(localStorage.setItem("btc_pending_username",t),localStorage.setItem("btc_pending_email",n),l&&c&&localStorage.setItem("btc_pending_giveaway",c),showToast("📧 Check your email for a verification link!"),hideUsernamePrompt(),void await createUser(t,n,l,c,a)):void await createUser(t,n,l,c,a)}if(!currentUser||currentUser._isLocal)return void showToast("Sign in first to change username");var d=document.getElementById("usernameStatus");d&&(d.innerHTML="Saving...");try{await db.collection("users").doc(currentUser.uid).update({username:t,username_lower:t.toLowerCase()}),currentUser.username=t,updateAuthButton(),updateRankUI(),d&&(d.innerHTML="✅ Username updated!"),showToast("✅ Username changed to "+t)}catch(e){d&&(d.innerHTML="❌ Error saving"),showToast("Error updating username. Try again.")}}catch(e){console.error("[submitUsername] Uncaught error:",e),"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown error. Please try again."))}},window.exportUserData=function(){if(!currentUser)return;const e=JSON.stringify(currentUser,null,2),t=new Blob([e],{type:"application/json"}),o=URL.createObjectURL(t),n=document.createElement("a");n.href=o,n.download="bitcoin_archive_user_data.json",n.click()},(!localStorage.getItem("btc_last_price")||Date.now()-parseInt(localStorage.getItem("btc_price_ts")||"0")>3e5)&&fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd&&(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),localStorage.setItem("btc_price_ts",Date.now().toString()))}).catch(function(){}),(!localStorage.getItem("btc_last_height")||Date.now()-parseInt(localStorage.getItem("btc_height_ts")||"0")>3e5)&&fetch("https://mempool.space/api/blocks/tip/height").then(function(e){return e.text()}).then(function(e){var t=parseInt(e);t&&(localStorage.setItem("btc_last_height",t.toString()),localStorage.setItem("btc_height_ts",Date.now().toString()))}).catch(function(){}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",initRanking):initRanking(),void 0!==toggleLeaderboard&&(window.toggleLeaderboard=toggleLeaderboard),void 0!==showUsernamePrompt&&(window.showUsernamePrompt=showUsernamePrompt),window.setDisplayBadge=function(e){if(currentUser){currentUser.displayBadge=e||"",void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({displayBadge:e||""}).catch(function(){}),localStorage.setItem("btc_display_badge",e||""),updateRankUI(),updateAuthButton(),showToast(e?"🏅 Display badge updated!":"🏅 Using default rank emoji");var t=document.getElementById("badgePickerPanel");if(t){var o="function"==typeof getLevel?getLevel(currentUser&¤tUser.points||0):{emoji:"🌱",name:"Newbie"},n=[];void 0!==earnedBadges&&void 0!==BADGE_DEFS&&BADGE_DEFS.forEach(function(e){earnedBadges.has(e.id)&&n.push({id:e.id,emoji:e.emoji,name:e.name})});var i=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]");void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){-1!==i.indexOf(e.id)&&n.push({id:e.id,emoji:e.hidden&&e.revealEmoji||e.emoji,name:e.hidden&&e.revealName||e.name})});var a=e||"",r='
    Choose a badge to show next to your name instead of your rank emoji.
    ';r+='
    '+o.emoji+'
    '+o.name+' (Default)
    Your current rank emoji
    '+(a?"":'')+"
    ",n.forEach(function(e){var t=a===e.id;r+="
    '+e.emoji+'
    '+e.name+"
    "+(t?'':"")+"
    "}),r+="
    ",t.innerHTML=r,t.style.display="block"}}},"undefined"==typeof changeUsername&&(window.changeUsername=async function(e){if(!e){var t=document.getElementById("newUsername");t&&(e=t.value.trim())}if(e&&(e=e.replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim()),!e||e.length<2)showToast("Username must be at least 2 characters (ASCII only)");else if(e.length>20)showToast("Username max 20 characters");else if(containsProfanity(e))showToast("⚠️ That username is not allowed.");else if("function"!=typeof isCleanText||isCleanText(e)){if(localStorage.setItem("btc_username",e),currentUser&&(currentUser.username=e),updateAuthButton(),updateRankUI(),auth&&auth.currentUser&&db)try{await db.collection("users").doc(auth.currentUser.uid).update({username:e,username_lower:e.toLowerCase()})}catch(e){console.warn("Username Firestore save failed:",e)}showToast("✅ Username updated to "+e);var o=document.querySelector('[id="currentUsernameLabel"]');o||document.querySelectorAll("div, span").forEach(function(e){-1===e.textContent.indexOf("Current username:")||o||(o=e)}),o&&(o.innerHTML='Current username: '+("function"==typeof escapeHtml?escapeHtml(e):e)+"");var n=document.querySelector('button[onclick*="changeUsername"]');n&&(n.textContent="✅ Saved!",n.style.background="#22c55e",setTimeout(function(){n.textContent="Save New Username",n.style.background="var(--accent)"},2e3))}else showToast("Username contains inappropriate language")}),window.togglePushNotifications=async function(){try{if(!("Notification"in window))return void showToast("Notifications not supported in this browser");"granted"===await Notification.requestPermission()?(localStorage.setItem("btc_push_enabled","true"),showToast("🔔 Notifications Enabled!")):(localStorage.setItem("btc_push_enabled","false"),showToast("❌ Notification permission denied")),showSettingsPage("prefs")}catch(e){console.error(e)}},"undefined"==typeof sendEmailVerification&&(window.sendEmailVerification=function(){auth&&auth.currentUser&&auth.currentUser.sendEmailVerification&&auth.currentUser.sendEmailVerification().then(function(){showToast("📧 Verification email sent!")}).catch(function(){showToast("Could not send verification email")})}),"undefined"==typeof disable2FA&&(window.disable2FA=function(){showToast("2FA management coming soon")}),"undefined"==typeof startMFAEnroll&&(window.startMFAEnroll=function(){showToast("2FA enrollment coming soon")}),"undefined"==typeof verifyMFACode&&(window.verifyMFACode=function(){showToast("2FA verification coming soon")}),"undefined"==typeof sendPasswordReset&&(window.sendPasswordReset=function(){auth&&auth.currentUser&&auth.currentUser.email&&auth.sendPasswordResetEmail(auth.currentUser.email).then(function(){showToast("📧 Password reset email sent!")}).catch(function(){showToast("Could not send reset email")})}),"undefined"==typeof confirmDeleteAccount&&(window.confirmDeleteAccount=function(){if(confirm("Are you sure you want to delete your account? This cannot be undone.")&&auth&&auth.currentUser){var e=auth.currentUser.uid;db.collection("users").doc(e).delete().then(function(){return auth.currentUser.delete()}).then(function(){localStorage.clear(),location.reload()}).catch(function(e){showToast("Error: "+e.message)})}}),window.saveSatsLnAddress=async function(){var e=document.getElementById("satsLnAddrInput"),t=document.getElementById("satsLnAddrStatus");if(e){var o=e.value.trim();if(o&&(!o.includes("@")||o.length<5))t&&(t.innerHTML='Enter a valid Lightning Address (e.g. you@walletofsatoshi.com)');else if(void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{t&&(t.innerHTML='Saving…'),await db.collection("users").doc(auth.currentUser.uid).update({lightning:o}),void 0!==currentUser&¤tUser&&(currentUser.lightning=o),o?(t&&(t.innerHTML='✅ Lightning Address saved!'),"function"==typeof showToast&&showToast("⚡ Lightning Address saved!"),"true"!==localStorage.getItem("btc_lightning_setup")&&(localStorage.setItem("btc_lightning_setup","true"),"function"==typeof awardPoints&&awardPoints(100,"⚡ Lightning wallet setup!"),"function"==typeof showToast&&setTimeout(function(){showToast("⚡🏅 Lightning Rod badge earned! +100 pts")},1500),"function"==typeof initBadges&&setTimeout(initBadges,2e3))):t&&(t.innerHTML='Lightning Address removed.')}catch(e){t&&(t.innerHTML='Error saving — try again')}else t&&(t.innerHTML='Sign in to save your Lightning Address')}},window.initSatsClaim=function(){if(console.log("[SATS] initSatsClaim called",{currentUser:!!currentUser,auth:!!auth,authUser:!!auth?.currentUser,isAnon:auth?.currentUser?.isAnonymous}),!currentUser||!auth||!auth.currentUser||auth.currentUser.isAnonymous)return console.log("[SATS] BLOCKED: auth check failed"),void showToast("Sign in to claim sats");var e=(currentUser.points||0)-(currentUser.pointsClaimed||0),t=Math.floor(Math.max(0,e)/10),o=currentUser.satsWithdrawn||0,n="function"==typeof getSatCap?getSatCap():1e4,i=Math.max(0,n-o),a=Math.min(t,500,i);if(console.log("[SATS] maxClaim:",a,"| satsBalance:",t,"| lifetimeLeft:",i,"| satsWithdrawn:",o),a<100)return console.log("[SATS] BLOCKED: maxClaim < 100"),void showToast("⚡ Need at least 100 claimable sats (1,000 unclaimed XP) to withdraw. Keep earning!",5e3);console.log("[SATS] Passed all checks, showing overlay");var r=document.createElement("div");r.id="satsClaimOverlay",r.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:10002;display:flex;align-items:center;justify-content:center;padding:16px;",setTimeout(function(){r.onclick=function(e){e.target===r&&r.remove()}},200);var s='
    ';s+='
    Claim Sats
    ',s+='
    ',s+='
    You can claim up to
    ',s+='
    ⚡ '+a+" sats
    ",s+="
    ",s+='',s+='',s+='
    Open your Lightning wallet, create an invoice for the amount you want (100-'+a+' sats), and paste it here.
    💚 Zero fees — we pay all Lightning network fees so you receive the full amount!
    ',s+='',s+='',s+='',s+="
    ",r.innerHTML=s,document.body.appendChild(r)},window._satsClaimInProgress=!1,window.submitSatsClaim=async function(){if(!window._satsClaimInProgress){var e=document.getElementById("satsClaimBtn"),t=document.getElementById("satsClaimInvoice"),o=document.getElementById("satsClaimError");if(e&&t){var n=t.value.trim();if(n&&n.toLowerCase().startsWith("lnbc")){o&&(o.style.display="none"),window._satsClaimInProgress=!0,e.disabled=!0,e.textContent="⏳ Sending sats...",e.style.opacity="0.6";try{var i=firebase.functions().httpsCallable("claimSats"),a=_generateDeviceFingerprint(),r=await i({invoice:n,fingerprint:a});if(r.data&&r.data.success){var s=r.data.amount||0;currentUser.pointsClaimed=(currentUser.pointsClaimed||0)+10*s,currentUser.satsWithdrawn=(currentUser.satsWithdrawn||0)+s,currentUser.lastSatsClaim=new Date,document.getElementById("satsClaimOverlay").remove(),window._satsClaimInProgress=!1,"function"==typeof notifySelfSatsClaim&¬ifySelfSatsClaim(s),"function"==typeof launchConfetti&&launchConfetti();var l=currentUser.satsWithdrawn||s,c="function"==typeof getSatCap?getSatCap():1e4,d=Math.max(0,c-l),u=document.createElement("div");u.id="satsCelebration",u.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.3s;",u.onclick=function(e){e.target===u&&u.remove()},u.innerHTML='
    ⚡🎉

    Sats Claimed!

    '+s+' sats
    sent to your Lightning wallet ⚡
    Check your wallet to confirm!
    ⚡ '+d.toLocaleString()+' sats remaining to claim!
    '+l.toLocaleString()+' / 10,000 lifetime total claimed
    🧡 Thank you for learning Bitcoin with us!
    ',document.body.appendChild(u),setTimeout(function(){showSettingsPage("sats")},500)}else{var p=r.data&&r.data.error?r.data.error:"Claim failed — try again";o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}catch(t){console.error("Sats claim error:",t),p=t.message||"Claim failed — try again",o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}else o&&(o.textContent="Please paste a valid Lightning invoice (starts with lnbc...)",o.style.display="block")}}},window.loadSatsHistory=function(){var e=document.getElementById("satsHistory");e&¤tUser&&db?db.collection("users").doc(currentUser.uid).collection("sats_withdrawals").orderBy("timestamp","desc").get().then(function(t){if(t.empty)e.textContent="No withdrawals yet";else{var o=0,n="function"==typeof getSatCap?getSatCap():1e4,i="";t.forEach(function(e){var t=e.data(),n=parseInt(t.amount)||0;o+=n;var a=t.timestamp?new Date(1e3*t.timestamp.seconds).toLocaleDateString():"—";i+='
    '+a+'⚡ '+n+" sats
    "});var a=Math.max(0,n-o),r=Math.min(100,Math.round(o/n*100)),s=r>=90?"#ef4444":r>=60?"#eab308":"#22c55e",l='
    Lifetime Claimed⚡ '+o.toLocaleString()+" / "+n.toLocaleString()+' sats
    '+r+'% used'+a.toLocaleString()+" sats remaining
    ";e.innerHTML=l+i}}).catch(function(){e.textContent="Could not load history"}):e&&(e.textContent="Sign in to view history")};const BADGE_DEFS=[{id:"pow_first_step",name:"First Step",emoji:"👟",desc:"Synced your first walk via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_marathoner",name:"Marathoner",emoji:"🏃‍♂️",desc:"Hit the 42km daily cap in Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_streak_3",name:"3-Day Streak",emoji:"🔥",desc:"Synced walks 3 days in a row via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_streak_7",name:"7-Day Streak",emoji:"🔥",desc:"Synced walks 7 days in a row via Proof of Walk",check:()=>!1,pts:300,hidden:!1},{id:"pow_streak_30",name:"30-Day Streak",emoji:"💎",desc:"Synced walks 30 days in a row via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_10",name:"10 km Club",emoji:"🥾",desc:"Walked 10 km lifetime via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_km_50",name:"50 km Club",emoji:"🚶",desc:"Walked 50 km lifetime via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_km_100",name:"Century Walker",emoji:"🏅",desc:"Walked 100 km lifetime via Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_km_500",name:"500 km Legend",emoji:"🏔️",desc:"Walked 500 km lifetime via Proof of Walk",check:()=>!1,pts:500,hidden:!1},{id:"pow_km_1000",name:"1,000 km Titan",emoji:"🌍",desc:"Walked 1,000 km lifetime via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_5000",name:"To the Moon",emoji:"🌕",desc:"Walked 5,000 km lifetime via Proof of Walk",check:()=>!1,pts:2500,hidden:!1},{id:"first_channel",name:"First Steps",emoji:"👶",desc:"Opened your first channel",check:e=>e.length>=1,pts:10},{id:"explorer_10",name:"Explorer",emoji:"🧭",desc:"Visited 10 topics",check:e=>e.length>=10,pts:15},{id:"explorer_25",name:"Trailblazer",emoji:"🗺️",desc:"Visited 25 topics",check:e=>e.length>=25,pts:30},{id:"explorer_50",name:"Pathfinder",emoji:"🏕️",desc:"Visited 50 topics",check:e=>e.length>=50,pts:50},{id:"explorer_100",name:"Cartographer",emoji:"🌍",desc:"Visited 100 topics",check:e=>e.length>=100,pts:100},{id:"explorer_all",name:"Completionist",emoji:"🗝️",desc:"Visited every single topic",check:(e,t)=>e.length>=t,pts:500},{id:"foundation_builder",name:"Foundation Builder",emoji:"🧱",desc:"Read all Layer 1 Properties (Orange)",check:e=>["whitepaper","decentralized","scarce","secure","money","peaceful","dominant","organic","supranational","programmable","use-cases"].every(t=>e.includes(t)),pts:75},{id:"experienced_pro",name:"Deep Diver",emoji:"🤿",desc:"Read all Experienced Topics (Purple)",check:e=>["maximalism","problems-of-money","self-custody","privacy-nonkyc","nodes","mining","pow-vs-pos","energy","difficulty-adjustment","layer-2-lightning","fedi-ark","chaumian-mints","ctv-covenants","extension-blocks","op-codes","bitvm","layer-3-sidechains","stablecoins","smart-contracts","blockchain-timechain","regulation","cryptography","core-source-code","developers","investment-strategy","evidence-against-alts","consensus"].every(t=>e.includes(t)),pts:150},{id:"librarian",name:"The Librarian",emoji:"📚",desc:"Read all Resource topics (Blue)",check:e=>["one-stop-shop","faq-glossary","nostr","misconceptions-fud","books","videos","podcasts","articles-threads","informational-sites","curriculum","research-theses","games","music","movies-tv","hardware","poems-stories","apps-tools","projects-diy","art-inspiration","graphics","charts","swag-merch","jobs-earn","social-media","fun-facts","news-adoption","history","international","satoshi-nakamoto","giga-chad","health","web5","memes-funny"].every(t=>e.includes(t)),pts:150},{id:"quest_1",name:"Quester",emoji:"⚔️",desc:"Completed your first Quest",check:(e,t,o)=>o>=1,pts:10},{id:"quest_3",name:"Quest Master",emoji:"📜",desc:"Completed 3 Quests",check:(e,t,o)=>o>=3,pts:25},{id:"quest_5",name:"Quest Legend",emoji:"🏰",desc:"Completed 5 Quests",check:(e,t,o)=>o>=5,pts:50},{id:"bookworm",name:"Bookworm",emoji:"📖",desc:"Saved 5 topics to favorites",check:()=>JSON.parse(localStorage.getItem("btc_favs")||"[]").length>=5,pts:20},{id:"night_owl",name:"Night Owl",emoji:"🦉",desc:"Browsing between midnight and 5am",check:()=>{const e=(new Date).getHours();return e>=0&&e<5},pts:15},{id:"early_bird",name:"Early Bird",emoji:"🐦",desc:"Browsing between 5am and 7am",check:()=>{const e=(new Date).getHours();return e>=5&&e<7},pts:15},{id:"cert_scholar",name:"Bitcoin Scholar",emoji:"🎓",desc:"Passed the Bitcoin Scholar Certification",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed"),pts:50},{id:"tctv_tuned_in",name:"Tuned In",emoji:"📺",desc:"Watched 10 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=10,pts:10},{id:"tctv_couch_potato",name:"Couch Potato",emoji:"🛋️",desc:"Watched 60 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=60,pts:25},{id:"tctv_binge_watcher",name:"Binge Watcher",emoji:"🍿",desc:"Watched 5 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=300,pts:50},{id:"tctv_couch_king",name:"Couch King",emoji:"🛌",desc:"Watched 24 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=1440,pts:100},{id:"tctv_satellite",name:"Satellite",emoji:"🛰️",desc:"Watched 100 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=6e3,pts:750},{id:"cert_tech",name:"Protocol Expert",emoji:"🛠️",desc:"Passed the Technical Protocol Expert Certification",check:()=>"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:100},{id:"nacho_chatterbox",name:"Nacho Chatterbox",emoji:"🦌",desc:"Interacted with Nacho 50+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=50,pts:30},{id:"nacho_bestie",name:"Nacho's Bestie",emoji:"🧡",desc:"Interacted with Nacho 250+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=250,pts:200},{id:"chat_first",name:"First Words",emoji:"💦",desc:"Sent your first message in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=1,pts:10},{id:"chat_10",name:"Chatty",emoji:"🗣️",desc:"Sent 10 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=10,pts:15},{id:"chat_50",name:"Conversationalist",emoji:"💬",desc:"Sent 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=50,pts:25},{id:"chat_100",name:"Town Crier",emoji:"📢",desc:"Sent 100 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=100,pts:50},{id:"chat_500",name:"Chat Legend",emoji:"📯",desc:"Sent 500 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=500,pts:250},{id:"chat_streak_3",name:"Regular",emoji:"📅",desc:"Chatted 3 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=3,pts:20},{id:"chat_streak_7",name:"Devoted Chatter",emoji:"💪",desc:"Chatted 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=7,pts:50},{id:"chat_streak_30",name:"Chat Addict",emoji:"💠",desc:"Chatted 30 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=30,pts:300},{id:"dj_first",name:"First Set",emoji:"🎧",desc:"DJed for the first time in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=1,pts:25},{id:"dj_5",name:"Resident DJ",emoji:"🎛️",desc:"DJed 5 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=5,pts:50},{id:"dj_25",name:"Club Legend",emoji:"🎶",desc:"DJed 25 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=25,pts:300},{id:"dj_songs_10",name:"Playlist Pro",emoji:"📻",desc:"Broadcast 10 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=10,pts:30},{id:"dj_songs_50",name:"Jukebox Hero",emoji:"🎵",desc:"Broadcast 50 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=50,pts:75},{id:"dj_songs_100",name:"Vinyl Master",emoji:"🎼",desc:"Broadcast 100 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=100,pts:400},{id:"dj_listener",name:"Good Listener",emoji:"🔊",desc:"Tuned in to 10 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=10,pts:20},{id:"dj_listener_50",name:"Groupie",emoji:"🤘",desc:"Tuned in to 50 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=50,pts:150},{id:"producer_1",name:"Producer",emoji:"🎤",desc:"Uploaded your first song to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=1,pts:50},{id:"producer_10",name:"Discographer",emoji:"💿",desc:"Uploaded 10 songs to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=10,pts:100},{id:"pvp_first",name:"First Blood",emoji:"🩸",desc:"Won your first PVP battle",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=1,pts:25},{id:"pvp_5",name:"Contender",emoji:"🥊",desc:"Won 5 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=5,pts:50},{id:"pvp_25",name:"Gladiator",emoji:"🏟️",desc:"Won 25 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=25,pts:100},{id:"pvp_50",name:"Champion",emoji:"🏆",desc:"Won 50 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=50,pts:200},{id:"pvp_100",name:"PVP Legend",emoji:"🥇",desc:"Won 100 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=100,pts:1e3},{id:"forum_5",name:"Voice of the People",emoji:"📣",desc:"Made 5 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=5,pts:25},{id:"forum_25",name:"Thought Leader",emoji:"🧠",desc:"Made 25 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=25,pts:75},{id:"article_1",name:"Author",emoji:"✍️",desc:"Published your first article",check:()=>parseInt(localStorage.getItem("btc_articles_published")||"0")>=1,pts:50},{id:"streak_7",name:"Week Warrior",emoji:"🔥",desc:"7-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=7,pts:50},{id:"streak_30",name:"Monthly Maxi",emoji:"🦾",desc:"30-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=30,pts:150},{id:"streak_100",name:"Diamond Hands",emoji:"💎",desc:"100-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=100,pts:1e3},{id:"streak_365",name:"HODLer Supreme",emoji:"🪩",desc:"365-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=365,pts:5e3},{id:"irl_host",name:"Event Host",emoji:"🎪",desc:"Hosted your first IRL event",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=1,pts:50},{id:"irl_host_5",name:"Community Builder",emoji:"🏗️",desc:"Hosted 5 IRL events",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=5,pts:150},{id:"sats_first",name:"First Sats",emoji:"🪙",desc:"Claimed your first sats from the faucet",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1,pts:25},{id:"sats_1k",name:"Stacker",emoji:"📦",desc:"Claimed 1,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e3,pts:100},{id:"sats_5k",name:"Sat Whale",emoji:"🧊",desc:"Claimed 5,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=5e3,pts:250},{id:"predict_1",name:"Oracle",emoji:"🎱",desc:"Made your first price prediction",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.total||0)>=1,pts:10},{id:"predict_correct_5",name:"Crystal Ball",emoji:"🏐",desc:"5 correct predictions",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.correct||0)>=5,pts:75},{id:"first_purchase",name:"Bitcoiner",emoji:"🛒",desc:"Completed the First Bitcoin Purchase guide",check:()=>"true"===localStorage.getItem("btc_fp_completed"),pts:100},{id:"lightning_setup",name:"Lightning Rod",emoji:"⚡",desc:"Set up a Lightning wallet or added a Lightning address",check:()=>"true"===localStorage.getItem("btc_lightning_setup"),pts:100},{id:"trail_meadow",name:"Meadow Walker",emoji:"🌿",desc:"Completed The Meadow trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("meadow")}catch(e){return!1}},pts:200},{id:"trail_mountain",name:"Mountain Climber",emoji:"⛰️",desc:"Completed The Mountain trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("mountain")}catch(e){return!1}},pts:400},{id:"trail_summit",name:"Summit Conqueror",emoji:"🏔️",desc:"Completed The Summit trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("summit")}catch(e){return!1}},pts:750},{id:"trail_all",name:"Trail Master",emoji:"🏁",desc:"Completed all three Nacho's Trails",check:()=>{try{var e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]");return e.includes("meadow")&&e.includes("mountain")&&e.includes("summit")}catch(e){return!1}},pts:500},{id:"tip_first",name:"First Tip",emoji:"💸",desc:"Sent your first Lightning tip",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=1,pts:25},{id:"tip_10",name:"Generous Pleb",emoji:"💛",desc:"Tipped 10 times",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=10,pts:75},{id:"tip_whale",name:"Whale Tipper",emoji:"🐳",desc:"Tipped 1,000+ sats total",check:()=>parseInt(localStorage.getItem("btc_tips_total_sats")||"0")>=1e3,pts:150},{id:"tip_magnet",name:"Tip Magnet",emoji:"🧲",desc:"Received 10 tips from others",check:()=>parseInt(localStorage.getItem("btc_tips_received")||"0")>=10,pts:100},{id:"referral_1",name:"First Referral",emoji:"🔗",desc:"Referred 1 friend who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=1,pts:50},{id:"referral_5",name:"Connector",emoji:"🤝",desc:"Referred 5 friends who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=5,pts:100},{id:"referral_10",name:"Network Effect",emoji:"🌐",desc:"Referred 10 friends to Bitcoin education",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=10,pts:200},{id:"referral_25",name:"Orange Pill Machine",emoji:"💊",desc:"Orange-pilled 25 people via your link",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=25,pts:500},{id:"referral_50",name:"Super Spreader",emoji:"📡",desc:"Referred 50 people — legend status",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=50,pts:1e3},{id:"referral_100",name:"Viral Plebian",emoji:"👑",desc:"Referred 100 people — you are the movement",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=100,pts:2500},{id:"referred",name:"Referred Friend",emoji:"🫂",desc:"Joined Bitcoin Education Archive via a referral link",check:()=>void 0!==currentUser&¤tUser&&!!currentUser.referredBy,pts:25},{id:"dm_first",name:"DM Starter",emoji:"✉️",desc:"Sent your first direct message",check:()=>parseInt(localStorage.getItem("btc_dms_sent")||"0")>=1,pts:15},{id:"react_50",name:"Reaction King",emoji:"❤️",desc:"Reacted to 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_reactions")||"0")>=50,pts:50},{id:"predict_streak_3",name:"Oracle Streak",emoji:"🎯",desc:"3 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=3,pts:50},{id:"predict_streak_10",name:"Nostradamus",emoji:"🔮",desc:"10 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=10,pts:250},{id:"spin_30",name:"Lucky Spinner",emoji:"🎰",desc:"Spun the wheel 30 days total",check:()=>parseInt(localStorage.getItem("btc_spin_count")||"0")>=30,pts:75},{id:"spin_streak_7",name:"Spin Streak",emoji:"🎡",desc:"Spun 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_spin_streak")||"0")>=7,pts:50},{id:"spin_jackpot",name:"Jackpot Winner",emoji:"🌟",desc:"Hit the RARE drop on the spin wheel",check:()=>"true"===localStorage.getItem("btc_spin_hit_rare"),pts:100},{id:"cert_double",name:"Double Scholar",emoji:"🏛️",desc:"Earned both Scholar AND Protocol Expert certifications",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed")&&"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:250},{id:"sf_first_hash",name:"First Hash",emoji:"⛏️",desc:"Generated your first hash during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1,pts:10},{id:"sf_10_hashes",name:"Pickaxe Swinger",emoji:"💥",desc:"Generated 10 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=10,pts:25},{id:"sf_50_hashes",name:"Mine Foreman",emoji:"🪨",desc:"Generated 50 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=50,pts:75},{id:"sf_100_hashes",name:"Hash Machine",emoji:"🔩",desc:"Generated 100 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=100,pts:150},{id:"sf_500_hashes",name:"ASIC Mode",emoji:"🖥️",desc:"Generated 500 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=500,pts:500},{id:"sf_1000_hashes",name:"Mining Rig",emoji:"🏭",desc:"Generated 1,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e3,pts:1e3},{id:"sf_10000_hashes",name:"Hash Lord",emoji:"☄️",desc:"Generated 10,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e4,pts:2100},{id:"sf_low_hash",name:"Lucky Strike",emoji:"⭐",desc:"Mined a hash under 1,000,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e6,pts:50},{id:"sf_ultra_low",name:"Golden Nonce",emoji:"✨",desc:"Mined a hash under 100,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e5,pts:200},{id:"sf_block_solver",name:"Block Solver",emoji:"🌞",desc:"Solved a block! Hash under the difficulty target",check:()=>"true"===localStorage.getItem("btc_sf_solved_block"),pts:1e3},{id:"sf_contributor",name:"Community Miner",emoji:"🤝",desc:"Contributed to activating Satoshi's Favor 3 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=3,pts:50},{id:"sf_contributor_10",name:"Favor Champion",emoji:"🏅",desc:"Contributed to activating Satoshi's Favor 10 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=10,pts:200},{id:"raid_first",name:"Raid Recruit",emoji:"🛡️",desc:"Dealt damage to your first Raid Boss",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=1,pts:10},{id:"raid_5",name:"Raid Warrior",emoji:"🗡️",desc:"Dealt 5 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=5,pts:50},{id:"raid_10",name:"Raid Veteran",emoji:"⚙️",desc:"Dealt 10 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=10,pts:100},{id:"raid_25",name:"Raid Commander",emoji:"⚜️",desc:"Dealt 25 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=25,pts:250},{id:"raid_50",name:"Raid Legend",emoji:"👑",desc:"Dealt 50 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=50,pts:750},{id:"raid_100",name:"Raid Warlord",emoji:"🔱",desc:"Dealt 100 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=100,pts:1500},{id:"raid_boss_slayer",name:"Boss Slayer",emoji:"💀",desc:"Participated in defeating a Raid Boss",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=1,pts:50},{id:"raid_boss_slayer_5",name:"Boss Hunter",emoji:"🐉",desc:"Participated in defeating 5 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=5,pts:150},{id:"raid_boss_slayer_10",name:"Dragon Slayer",emoji:"🐲",desc:"Participated in defeating 10 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=10,pts:500},{id:"raid_winner",name:"Raid Champion",emoji:"🎖️",desc:"Won the sats lottery after a Raid Boss defeat",check:()=>"true"===localStorage.getItem("btc_raid_winner"),pts:250}];let earnedBadges=new Set,badgeCheckInterval=null;function initBadges(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(e=>earnedBadges.add(e)),badgeCheckInterval=setInterval(checkBadges,3e4),setInterval(function(){if(window._visibleBadgeQueue&&0!==window._visibleBadgeQueue.length&&!window._nachoBusy){var e=document.getElementById("nacho-bubble");e&&e.classList.contains("show")||document.getElementById("badgeCelebration")||showBadgeToast(window._visibleBadgeQueue.shift())}},5e3)}function checkBadges(){if(!window._visibleBadgesReady)return;if(window._nachoBusy)return;const e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=void 0!==completedQuests?completedQuests.size:0;for(const a of BADGE_DEFS)if(!earnedBadges.has(a.id))try{if(a.check(e,t,o)){earnedBadges.add(a.id),localStorage.setItem("btc_badges",JSON.stringify([...earnedBadges])),"function"==typeof window._raidOnBadgeEarned&&window._raidOnBadgeEarned(),"function"==typeof window.contributeSatoshiFavor&&(void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username,window.contributeSatoshiFavor("badge_earned",a.emoji+" "+a.name).catch(function(){}));var n=document.getElementById("nacho-bubble");window._nachoBusy||n&&n.classList.contains("show")?(window._visibleBadgeQueue||(window._visibleBadgeQueue=[]),window._visibleBadgeQueue.push(a)):showBadgeToast(a);var i=a.pts||20;if("function"==typeof awardPoints&&awardPoints(i,"Badge: "+a.name+" "+a.emoji),void 0!==db&&void 0!==auth&&auth.currentUser)try{db.collection("users").doc(auth.currentUser.uid).update({visibleBadges:firebase.firestore.FieldValue.arrayUnion(a.id)})}catch(e){}}}catch(e){}}window._visibleBadgesReady=!1,window.markVisibleBadgesReady=function(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(function(e){earnedBadges.add(e)});var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>e.length&&(e=currentUser.readChannels),void 0!==CHANNELS&&Object.keys(CHANNELS).length,void 0!==completedQuests&&completedQuests.size;var t=!1,o=[];void 0!==currentUser&¤tUser&¤tUser.visibleBadges&&(o=currentUser.visibleBadges);for(var n=0;n𝕏 Share on Twitter'),o.innerHTML='
    '+e.emoji+'
    🎉 Badge Earned!
    '+e.name+'
    '+e.desc+'
    +20 XP
    '+r+'
    ',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function copyBadgeLink(e,t){const o="I earned the "+e+" "+t+" badge on Bitcoin Education Archive!\nhttps://bitcoineducation.quest";navigator.clipboard.writeText(o).then(()=>{"function"==typeof showToast&&showToast("📋 Copied to clipboard!")})}function launchConfetti(){const e=document.createElement("canvas");e.id="confettiCanvas",e.style.cssText="position:fixed;inset:0;z-index:500;pointer-events:none;",e.width=window.innerWidth,e.height=window.innerHeight,document.body.appendChild(e);const t=e.getContext("2d"),o=[],n=["#f7931a","#ea580c","#fbbf24","#f59e0b","#ff6b00","#ff9500","#ffb800","#fff"];for(let t=0;t<120;t++)o.push({x:e.width/2+100*(Math.random()-.5),y:e.height/2,vx:16*(Math.random()-.5),vy:16*(Math.random()-1)-4,size:8*Math.random()+3,color:n[Math.floor(Math.random()*n.length)],rotation:360*Math.random(),rotSpeed:12*(Math.random()-.5),gravity:.12+.08*Math.random(),opacity:1,shape:Math.random()>.5?"rect":"circle"});let i=0;requestAnimationFrame(function n(){t.clearRect(0,0,e.width,e.height);let a=!1;o.forEach(o=>{o.x+=o.vx,o.vy+=o.gravity,o.y+=o.vy,o.rotation+=o.rotSpeed,o.vx*=.99,i>40&&(o.opacity-=.015),o.opacity>0&&o.y{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=o,i.type="sine",a.gain.setValueAtTime(.15*t,e.currentTime+.12*n),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.12*n+.5),i.start(e.currentTime+.12*n),i.stop(e.currentTime+.12*n+.5)})}catch(e){}}function getBadgeHTML(){var e={};function t(t,o){var n=t.filter(function(t){return!e[t.id]&&o(t)});return n.forEach(function(t){e[t.id]=!0}),n}const o={"🧭 Discovery":t(BADGE_DEFS,e=>e.id.includes("explorer")||"first_channel"===e.id||"bookworm"===e.id),"🧠 Knowledge":t(BADGE_DEFS,e=>e.id.includes("builder")||e.id.includes("diver")||e.id.includes("librarian")||e.id.includes("quest")||e.id.includes("cert_")),"🦌 Trails":t(BADGE_DEFS,e=>e.id.startsWith("trail_")),"💬 Global Chat":t(BADGE_DEFS,e=>e.id.startsWith("chat_")),"🦌 Nacho":t(BADGE_DEFS,e=>e.id.startsWith("nacho_")),"📺 Timechain TV":t(BADGE_DEFS,e=>e.id.startsWith("tctv_")),"🎧 DJ Mode":t(BADGE_DEFS,e=>e.id.startsWith("dj_")),"🎵 Music":t(BADGE_DEFS,e=>e.id.startsWith("producer")),"⚔️ PVP":t(BADGE_DEFS,e=>e.id.startsWith("pvp_")),"📝 Forum":t(BADGE_DEFS,e=>e.id.startsWith("forum_")||e.id.startsWith("article_")),"🔥 Streaks":t(BADGE_DEFS,e=>e.id.startsWith("streak_")),"🤝 Community":t(BADGE_DEFS,e=>e.id.startsWith("irl_")||e.id.startsWith("referral_")),"⚡ Sats & Lightning":t(BADGE_DEFS,e=>e.id.startsWith("sats_")||"lightning_setup"===e.id||e.id.startsWith("tip_")),"🔮 Predictions":t(BADGE_DEFS,e=>e.id.startsWith("predict_")),"💬 Social":t(BADGE_DEFS,e=>e.id.startsWith("dm_")||"react_50"===e.id),"🎡 Spin Wheel":t(BADGE_DEFS,e=>e.id.startsWith("spin_")),"⛏️ Satoshi's Favor":t(BADGE_DEFS,e=>e.id.startsWith("sf_")),"🐲 Raid Boss":t(BADGE_DEFS,e=>e.id.startsWith("raid_")),"🌙 Fun":t(BADGE_DEFS,e=>"night_owl"===e.id||"early_bird"===e.id),"🏆 Milestones":t(BADGE_DEFS,t=>!e[t.id])};let n='';n+='
    ';var i=0;for(const[e,t]of Object.entries(o)){if(0===t.length)continue;var a="bc_"+ ++i;const o=t.filter(e=>earnedBadges.has(e.id)).length,r=o===t.length;n+='
    ',n+="",n+='
    "}if(void 0!==HIDDEN_BADGES){const e=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),t=HIDDEN_BADGES.filter(function(e){return!e.hidden});if(t.length>0){var r="bc_"+ ++i,s=t.filter(function(t){return e.includes(t.id)}).length,l=s===t.length;n+='
    ',n+="",n+='
    "}const o=HIDDEN_BADGES.filter(function(e){return e.hidden}),a=o.some(function(t){return e.includes(t.id)}),u=o.length,p=o.filter(function(t){return e.includes(t.id)}).length;var c="bc_"+ ++i,d=p===u;if(n+='
    ',n+="",n+='
    "}return n}window._showBadgeTip=function(e,t){e.stopPropagation();var o=document.getElementById("badgeFloatTip");if(o){var n=t.querySelector(".badge-tooltip"),i=n?n.innerHTML:t.getAttribute("title")||"";if(i){if("block"===o.style.display&&o._srcEl===t)return o.style.display="none",o._srcEl=null,void t.classList.remove("tapped");document.querySelectorAll(".badge-item.tapped").forEach(function(e){e.classList.remove("tapped")}),t.classList.add("tapped"),o._srcEl=t,o.innerHTML=i,o.style.display="block";var a=(e.touches?e.touches[0].clientX:e.clientX)||0,r=(e.touches?e.touches[0].clientY:e.clientY)||0;o.style.left="0px",o.style.top="0px";var s=o.offsetWidth||220,l=o.offsetHeight||80,c=window.innerWidth,d=window.innerHeight,u=Math.min(a-s/2,c-s-10);u=Math.max(u,10);var p=r-l-12;p<10&&(p=r+24),p+l>d-10&&(p=d-l-10),o.style.left=u+"px",o.style.top=p+"px"}}},document.addEventListener("click",function(e){var t=document.getElementById("badgeFloatTip");t&&"none"!==t.style.display&&(e.target.closest(".badge-item")||(t.style.display="none",t._srcEl=null,document.querySelectorAll(".badge-item.tapped").forEach(function(e){e.classList.remove("tapped")})))},!0),window._badgeSearch=function(e){var t=(e||"").trim().toLowerCase(),o=document.getElementById("badgeSearchResults");if(o){if(document.querySelectorAll(".badge-item.badge-search-highlight").forEach(function(e){e.classList.remove("badge-search-highlight")}),!t)return o.style.display="none",void(o.innerHTML="");var n=[];void 0!==BADGE_DEFS&&(n=n.concat(BADGE_DEFS)),void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){e.hidden||n.push(e)});var i=n.filter(function(e){return e.name.toLowerCase().includes(t)||(e.desc||"").toLowerCase().includes(t)}).slice(0,8);if(0===i.length)return o.innerHTML='
    No badges found for "'+escapeHtml(e)+'"
    ',void(o.style.display="block");var a="";i.forEach(function(e){var t=earnedBadges.has(e.id)||JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]").includes(e.id);a+="
    '+(t?e.emoji:e.lockedEmoji||"🔘")+'
    '+escapeHtml(e.name)+'
    '+(t?"✅ ":"🔒 ")+escapeHtml(e.desc)+"
    "}),o.innerHTML=a,o.style.display="block"}},window._badgeSearchJump=function(e){var t=document.getElementById("badgeSearchResults"),o=document.getElementById("badgeSearchInput");t&&(t.style.display="none",t.innerHTML=""),o&&(o.value=""),document.querySelectorAll(".badge-item.badge-search-highlight").forEach(function(e){e.classList.remove("badge-search-highlight")});var n=document.querySelector('.badge-item[data-badge-id="'+e+'"]');if(n){var i=n.closest(".badges-grid");if(i&&"none"===i.style.display){i.style.display="grid";var a=i.previousElementSibling;if(a){var r=a.querySelector(".bca");r&&(r.textContent="▼")}}n.classList.add("badge-search-highlight"),setTimeout(function(){n.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(function(){n.classList.remove("badge-search-highlight")},2500)},100)}},setTimeout(initBadges,2e3);const TICKET_CONFIG={dailyLogin:1,referral:50,referralSignupBonus:50,referralPointsThreshold:2140,pointsPerTicket:5};function getReferralCode(){return currentUser&¤tUser.uid?currentUser.uid.substring(0,8):null}function getReferralLink(){const e=getReferralCode();return e?window.location.origin+window.location.pathname+"?ref="+e:""}function captureReferralCode(){const e=new URLSearchParams(window.location.search).get("ref");if(e&&e.length>=6&&(localStorage.setItem("btc_referral_code",e),window.history&&window.history.replaceState)){const e=window.location.pathname+window.location.hash;window.history.replaceState({},"",e)}}async function awardDailyTicket(){try{if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;const e=(new Date).toISOString().split("T")[0];if(currentUser.lastTicketDate===e)return;const t=TICKET_CONFIG.dailyLogin,o=t*TICKET_CONFIG.pointsPerTicket,n=(currentUser.orangeTickets||0)+t;if("function"==typeof awardPoints){const e=await awardPoints(o,"🎟️ Daily tickets",null,t);if(!e||!e.success)return}currentUser.lastTicketDate=e,currentUser.orangeTickets=(currentUser.orangeTickets||0)+t,setTimeout(function(){"function"==typeof showToast&&showToast("🎟️ +1 Orange Ticket — Welcome back! (Total: "+n+")")},2500),"function"==typeof updateRankUI&&updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}catch(e){console.warn("Daily ticket error:",e)}}async function attachReferral(e){const t=localStorage.getItem("btc_referral_code");if(t&&!e.startsWith(t))try{const o=await db.collection("users").where("referralCode","==",t).limit(1).get();let n=null;n=o.empty?null:o.docs[0].id,await db.collection("users").doc(e).update({referredBy:t,referralVerified:!1}),await db.collection("referrals").doc(e).set({referredUser:e,referrerCode:t,referrerUid:n||"",createdAt:firebase.firestore.FieldValue.serverTimestamp(),verified:!1,ticketsAwarded:!1}),localStorage.removeItem("btc_referral_code")}catch(e){console.log("Referral attach error:",e)}}async function checkReferralQualifications(){if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;if(window._referralChecked)return;window._referralChecked=!0;const e=getReferralCode();if(e)try{const t=await db.collection("referrals").where("referrerCode","==",e).where("ticketsAwarded","==",!1).get();if(t.empty)return;let o=0;for(const e of t.docs){const t=e.data().referredUser,n=await db.collection("users").doc(t).get();if(!n.exists)continue;const i=n.data();(i.points||0)>=TICKET_CONFIG.referralPointsThreshold&&(i.totalVisits||0)>=2&&(o+=TICKET_CONFIG.referral,await db.collection("referrals").doc(e.id).update({verified:!0,ticketsAwarded:!0,verifiedAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("users").doc(t).update({referralVerified:!0}))}if(o>0){const e=o*TICKET_CONFIG.pointsPerTicket;currentUser.orangeTickets,"function"==typeof awardPoints&&await awardPoints(e,"🎟️ Referral tickets",null,o),currentUser.orangeTickets=(currentUser.orangeTickets||0)+o,showToast("🎟️ +"+o+" Orange Tickets — Referral"+(o>50?"s":"")+" verified!"),"function"==typeof notifySelfReferral&¬ifySelfReferral(o),updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}}catch(e){console.log("Referral check error:",e)}}async function ensureReferralCode(){if(currentUser&&db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&!currentUser.referralCode){const e=getReferralCode();e&&(await db.collection("users").doc(currentUser.uid).update({referralCode:e}),currentUser.referralCode=e)}}async function getReferralStats(){if(!currentUser||!db)return{total:0,verified:0,pending:0};const e=getReferralCode();if(!e)return{total:0,verified:0,pending:0};try{const t=await db.collection("referrals").where("referrerCode","==",e).get();let o=t.size,n=0,i=0;return t.forEach(e=>{e.data().verified?n++:i++}),{total:o,verified:n,pending:i}}catch(e){return{total:0,verified:0,pending:0}}}function renderTicketsSection(){return'
    Orange Tickets
    '+(currentUser&¤tUser.orangeTickets||0)+'
    Earn tickets by logging in daily (+1), spinning the daily wheel, and referring friends (+50 per verified referral!). Each ticket earned also awards 5 bonus points!

    🏆 The more tickets you have, the higher your chance of winning our 25,000 sats giveaways!
    📅
    Daily Login
    +1 ticket
    🤝
    Referral
    +50 tickets
    '}function renderReferralSection(){const e=getReferralLink();return getReferralCode()?'
    🔗 Referral Program
    Share your link with friends. Earn 50 Orange Tickets for each referral who logs in and earns 2,140+ points (Maxi rank).
    Loading referral stats...
    ':""}function copyReferralLink(){const e=document.getElementById("referralLinkInput");e&&(navigator.clipboard?navigator.clipboard.writeText(e.value).then(function(){showToast("🔗 Referral link copied!")}):(e.select(),document.execCommand("copy"),showToast("🔗 Referral link copied!")))}async function loadReferralStatsUI(){const e=document.getElementById("referralStats");if(!e)return;const t=await getReferralStats();0===t.total?e.innerHTML='No referrals yet. Share your link to start earning!':e.innerHTML='
    👥 Total: '+t.total+'✅ Verified: '+t.verified+'⏳ Pending: '+t.pending+"
    "}async function onUserLoadedTickets(){currentUser&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(await ensureReferralCode(),await awardDailyTicket(),checkReferralQualifications().catch(function(){}))}function getEquippedItems(){try{return JSON.parse(localStorage.getItem("btc_nacho_equipped_multi")||"{}")}catch(e){return{}}}function getEquippedItem(){var e=getEquippedItems();return Object.values(e)[0]||localStorage.getItem("btc_nacho_equipped")||null}window.awardTickets=async function(e,t){if(e&&!(e<1)&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&void 0!==currentUser&¤tUser){currentUser.orangeTickets;var o=e*TICKET_CONFIG.pointsPerTicket;try{"function"==typeof awardPoints&&await awardPoints(o,"🎟️ "+(t||"Orange Tickets"),null,e),currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,"function"==typeof updateRankUI&&updateRankUI()}catch(e){console.warn("[tickets] Award error:",e)}"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Tickets! "+(t||""))}},"undefined"!=typeof window&&captureReferralCode(),function(){const e=function(){const e=(new Date).toISOString().split("T")[0];if(void 0===CHANNELS)return[];const t=Object.keys(CHANNELS),o=[];let n=0;for(let t=0;t{const t=document.querySelector("[onclick*=\"go('"+e+"'\"]");if(t){const e=document.createElement("span");e.style.cssText="position:absolute;top:4px;right:4px;background:#f7931a;color:#fff;font-size:0.55rem;font-weight:900;padding:2px 5px;border-radius:4px;box-shadow:0 0 10px rgba(247,147,26,0.4);",e.textContent="2X PTS",t.style.position="relative",t.appendChild(e)}}),window._dailyBoosts=e}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}(),function(){let e={price:null,blockHeight:null,fees:null,mempoolSize:null,lastFetch:0};const t=3e5;async function o(){const o=Date.now();if(!(o-e.lastFetch900:"true"===e)){var t=document.getElementById("btcTicker");return t&&t.remove(),void document.body.classList.remove("ticker-visible")}var n=document.getElementById("btcTicker");n||((n=document.createElement("div")).id="btcTicker",document.body.prepend(n)),document.body.classList.add("ticker-visible"),n.style.cssText="position:fixed;top:0;left:0;right:0;z-index:10005;background:#030712;border-bottom:1px solid #f7931a;padding:0;height:32px;overflow:hidden;display:flex;align-items:center;font-family:inherit;font-size:0.75rem;color:#94a3b8;line-height:32px;";var i=document.createElement("div");i.id="tickerScroller",i.style.cssText="display:flex;white-space:nowrap;width:max-content;animation:btcTickerScroll 25s linear infinite;will-change:transform;";const a='\n
    \n \n 📡 LOADING SIGNAL...\n \n
    ';i.innerHTML=a+a+a+a,n.innerHTML="",n.appendChild(i);var r=document.getElementById("btcTickerStyle");r||((r=document.createElement("style")).id="btcTickerStyle",document.head.appendChild(r)),r.textContent="\n @keyframes btcTickerScroll { 0% { transform: translateX(0); } 100% { transform: translateX(-50%); } }\n #btcTicker:hover #tickerScroller { animation-play-state: paused; }\n @media(max-width:900px) { \n body.ticker-visible .mobile-bar { top: 32px !important; }\n body.ticker-visible main { padding-top: 130px !important; }\n body.ticker-visible aside { top: 130px !important; z-index: 10006; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n #btcTicker { font-size: 0.65rem; height: 32px; }\n body.ticker-visible .progress-bar { top: 118px !important; }\n }\n @media(min-width:901px) { \n body.ticker-visible aside { padding-top: 32px; }\n body.ticker-visible main { padding-top: 32px; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n body.ticker-visible .progress-bar { top: 32px !important; }\n }",fetch("newsletter-data.json?v="+Date.now()).then(e=>e.json()).then(e=>{const t=n.querySelectorAll(".t-news-items");if(t&&e.news){let o="";e.news.forEach((e,t)=>{var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #'+(t+1)+""+n+""}),t.forEach(e=>e.innerHTML=o)}}).catch(e=>{n.querySelectorAll(".t-news-items").forEach(e=>e.innerHTML="📡 TECHNICAL SIGNAL OFFLINE")}),o(),setInterval(function(){o()},6e4);var s="";setInterval(function(){fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(e){var t=document.querySelectorAll(".t-news-items");if(t.length>0&&e.news&&e.news.length>0){var o="";if(e.news.slice(0,3).forEach(function(e,t){var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #'+(t+1)+""+n+""}),o!==s){s=o;var n=document.getElementById("tickerScroller");t.forEach(function(e){e.innerHTML=o}),n&&(n.style.animation="none",n.offsetHeight,n.style.animation="btcTickerScroll 25s linear infinite")}}}).catch(function(){})},18e5)}function i(e){return e?e>=1e3?"$"+Math.round(e).toLocaleString():"$"+e.toFixed(2):null}window.getNachoLiveData=function(){return e},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",n):n(),window.nachoLiveAnswer=function(t){var o=t.toLowerCase();if(/price|how much is|what.?s bitcoin at|current price|btc price|bitcoin worth|bitcoin cost/.test(o)){var n,a=e.price;if(a||(n=parseFloat(localStorage.getItem("btc_last_price")))&&n>0&&(a=n),!a)return null;var r=i(a),s=["Bitcoin is currently at "+r+"! Still early, {name}. 📈🦌","The current BTC price is "+r+". Number go up technology! 📊","Right now, 1 BTC = "+r+". How many sats are you stacking, {name}? ⚡"];return{answer:s[Math.floor(Math.random()*s.length)],channel:"charts",channelName:"Charts"}}if(/block height|current block|what block|how many blocks|latest block/.test(o))return e.blockHeight?{answer:"We're currently at block "+e.blockHeight.toLocaleString()+"! Every block is history being written, {name}. ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:(n=localStorage.getItem("btc_last_height"))?{answer:"I'm still syncing, but the last block I saw was "+parseInt(n).toLocaleString()+"! ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:null;if(/halving|halvening|next halving|when.*halving|halving countdown/.test(o)){var l=function(){var t=e.blockHeight;if(!t)return null;var o=21e4*Math.ceil(t/21e4),n=o-t;return{nextHalving:o,blocksLeft:n,daysLeft:Math.round(10*n/1440)}}();return l?{answer:"The next halving is at block "+l.nextHalving.toLocaleString()+" -- that's "+l.blocksLeft.toLocaleString()+" blocks away (~"+l.daysLeft+" days). Tick tock, {name}! ⏰",channel:"scarce",channelName:"Scarce"}:null}return null},window.nachoLiveMessage=function(){if(Math.random()>.15)return null;if(o(),!e.price)return null;var t=[];if(e.price){var n=i(e.price);t.push({pose:"cool",text:"BTC is at "+n+" right now, {name}. Just thought you should know. 😎📈"})}return e.blockHeight&&t.push({pose:"brain",text:"We just passed block "+e.blockHeight.toLocaleString()+". Every block is a heartbeat of the network. ⛓️💓"}),0===t.length?null:t[Math.floor(Math.random()*t.length)]},setTimeout(o,3e3),setInterval(o,t),window.toggleTickerSetting=function(){var e=localStorage.getItem("btc_ticker_enabled");if(null===e?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===e){localStorage.setItem("btc_ticker_enabled","false");var t=document.getElementById("btcTicker");t&&t.remove(),document.body.classList.remove("ticker-visible"),"function"==typeof showToast&&showToast("📡 Signal ticker hidden. Refresh to fully apply.")}else localStorage.setItem("btc_ticker_enabled","true"),window._tickerInitialized=!1,n(),"function"==typeof showToast&&showToast("📡 Signal ticker enabled!");"function"==typeof showSettingsPage&&showSettingsPage("prefs")}}(),function(){const e="\"Nacho\"🦌');\">",t='
    🛋️
    🍿
    ';function o(){return"timechain-tv"===window.currentPage||"#timechain-tv"===window.location.hash}const n={default:"🦌",wave:"👋",think:"🤔",celebrate:"🎉",point:"👆",eyes:"👀",fire:"🔥",brain:"🧠",cool:"😎",sleep:"💤",cheese:"🧀",love:"🧡"};window._btcData={price:null,height:null,halvingBlocks:null,lastUpdate:0};const i={whitepaper:{pose:"brain",text:"It looks like you're reading the whitepaper! This is where it all started — 9 pages that changed the world! 📜"},"self-custody":{pose:"point",text:"It looks like you're learning about self-custody! Remember: Nacho keys, nacho cheese. 🧀🔑"},"investment-strategy":{pose:"think",text:"It looks like you're planning your stack strategy! Pro tip: DCA and chill. Time in the market beats timing the market. 📈"},mining:{pose:"fire",text:"It looks like you're exploring mining! Every 10 minutes a new block is born. Beautiful, isn't it? ⛏️"},"privacy-nonkyc":{pose:"eyes",text:"It looks like you value your privacy! Good. A wise buck never reveals his forest location. 🕵️"},"layer-2-lightning":{pose:"celebrate",text:"It looks like you're exploring Lightning! This is how Bitcoin scales to millions of transactions per second! ⚡⚡"},"fun-facts":{pose:"cool",text:"It looks like you're browsing fun facts! This channel is my personal favorite. Don't tell the others. 🤫"},history:{pose:"brain",text:"It looks like you're studying Bitcoin history! Those who don't learn history are doomed to repeat it. 📚"},charts:{pose:"eyes",text:"It looks like you're checking the charts! Number go up technology, am I right? 📊"},"problems-of-money":{pose:"think",text:"It looks like you're learning why fiat is broken! This is where many people get orange-pilled. 🟠"},"giga-chad":{pose:"fire",text:"It looks like you're in the Giga Chad channel! Based and orange-pilled. 💪"},"memes-funny":{pose:"celebrate",text:"It looks like you're looking at memes! A deer of culture, I see. 😏"},"evidence-against-alts":{pose:"cool",text:"It looks like you're reading about altcoins! Spoiler: there's only Bitcoin. 🦌"},scarce:{pose:"brain",text:"It looks like you're learning about scarcity! Only 21 million will ever exist. Even I can't make more. 💎"},decentralized:{pose:"fire",text:"It looks like you're exploring decentralization! No single point of failure. Like a forest — cut one tree, the rest stand strong. 🌲"},secure:{pose:"point",text:"It looks like you're reading about Bitcoin's security! More computing power secures this network than anything else on Earth. 🔒"},money:{pose:"think",text:"It looks like you're learning what money really is! Hint: it's not what the government tells you. 💰"},programmable:{pose:"brain",text:"It looks like you're exploring programmable money! Smart contracts on Bitcoin — the future is being built right here. 🔧"},consensus:{pose:"think",text:"It looks like you're studying consensus! This is how thousands of nodes agree without a boss. Democracy at the protocol level. 🤝"},"difficulty-adjustment":{pose:"brain",text:"It looks like you're learning about the difficulty adjustment! The most elegant part of Bitcoin's design, in my humble deer opinion. ⚙️"},"blockchain-timechain":{pose:"fire",text:"It looks like you're reading about the timechain! Fun fact: many Bitcoiners prefer 'timechain' over 'blockchain.' ⛓️"},"pow-vs-pos":{pose:"cool",text:"It looks like you're comparing PoW vs PoS! Spoiler: Proof of Work wins. Always has. 🏆"},"articles-threads":{pose:"brain",text:"It looks like you're browsing articles! This channel has some of the best Bitcoin writing ever published. Take your time! 📰"},books:{pose:"love",text:"It looks like you're checking out Bitcoin books! The Bitcoin Standard changed my life. Well, my deer life. 📖"},podcasts:{pose:"cool",text:"It looks like you're browsing podcasts! Great for learning while you graze... I mean, commute. 🎧"},"movies-tv":{pose:"celebrate",text:"It looks like you're looking at Bitcoin movies! Grab some popcorn (and cheese). 🍿🧀"},"one-stop-shop":{pose:"point",text:"It looks like you're in the one-stop shop! This is the starter pack — everything a newcomer needs. 🎁"},regulation:{pose:"think",text:"It looks like you're reading about regulation! Governments are slowly figuring out they can't stop Bitcoin. 🏛️"},nodes:{pose:"fire",text:"It looks like you're learning about nodes! Running your own node = verifying everything yourself. Trust no one! 🖥️"},geopolitics___macroeconomics:{pose:"brain",text:"It looks like you're exploring the macro picture! Bitcoin isn't just money — it's a geopolitical shift. 🌍"},"jobs-earn":{pose:"celebrate",text:"It looks like you're checking out Bitcoin jobs! Get paid in sats — the dream! 💼⚡"},"apps-tools-services-models":{pose:"point",text:"It looks like you're browsing Bitcoin tools and apps! So many ways to use the network. 🛠️"},music:{pose:"celebrate",text:"It looks like you're checking Bitcoin music! Yes, there are Bitcoin songs. And yes, they slap. 🎵"},"art-inspiration":{pose:"love",text:"It looks like you're browsing Bitcoin art! Creativity meets sound money. Beautiful. 🎨"},games:{pose:"cool",text:"It looks like you're checking out Bitcoin games! Learn while you play — my kind of strategy. 🎮"},health:{pose:"love",text:"It looks like you're in the health channel! Sound money, sound body, sound mind. 🏋️"},nostr:{pose:"fire",text:"It looks like you're exploring Nostr! Decentralized social media — Bitcoin's best friend. 💜"},curriculum:{pose:"brain",text:"It looks like you're looking at Bitcoin education materials! Perfect for teachers and students! 📝"},"misconceptions-fud":{pose:"cool",text:"It looks like you're fighting FUD! Arm yourself with facts. This channel is your ammo. 🛡️"},cryptography:{pose:"brain",text:"It looks like you're diving into cryptography! This is the math that makes Bitcoin unbreakable. 🔢"},"tail-emission":{pose:"think",text:"It looks like you're reading about tail emission! A big debate in the Bitcoin world. What do you think? 🤔"},stablecoins:{pose:"eyes",text:"It looks like you're reading about stablecoins! Useful on-ramps, but remember — Bitcoin is the exit. 🚪"}},a=[{pose:"brain",text:"📜 Have you read Bitcoin's Whitepaper? It's only 9 pages and it started a revolution! Read it here → 🦌"},{pose:"fire",text:'🔥 Pro tip: Read the Bitcoin Whitepaper — it\'s the Genesis document! Only 9 pages changed the world forever. Check it out →'},{pose:"point",text:"💡 Tip: The sidebar on the left has ALL topics organized by category. Tap a category to expand it!"},{pose:"point",text:"💡 Tip: Click the 🎲 dice button to jump to a random channel — great for discovering new topics!"},{pose:"point",text:"💡 Tip: Use the 🔍 search button to find any subject across all 146+ topics instantly!"},{pose:"point",text:"💡 Tip: Click the Bitcoin logo at the top to return to the homepage anytime!"},{pose:"point",text:"💡 Tip: Hit the ⭐ button on any channel to save it to your favorites for quick access!"},{pose:"point",text:"💡 Tip: Your Exploration Map on the homepage shows every channel you've visited. Try to light them all up! 🗺️"},{pose:"point",text:"💡 Tip: Channels you've already read get a ✓ checkmark in the sidebar. Track your progress!"},{pose:"brain",text:"💡 Tip: You earn XP by visiting daily (+5), opening new topics (+10), and reading (+15 per 30 sec)!"},{pose:"point",text:"💡 Tip: Check the leaderboard to see how you rank against other Bitcoiners! Click your rank bar at the bottom."},{pose:"fire",text:"💡 Tip: Keep a daily streak going! Every 5 days in a row = bonus 100 points! 🔥"},{pose:"point",text:"💡 Tip: There are 9 rank levels from Normie to Satoshi. What level are you? Check Settings → Data!"},{pose:"cheese",text:"💡 Tip: Earn Orange Tickets daily just by logging in! More tickets = higher giveaway chances! 🎟️"},{pose:"point",text:"💡 Tip: Share your referral link (Settings → Tickets) and earn 50 tickets for each verified friend!"},{pose:"celebrate",text:"💡 Tip: Each Orange Ticket also gives you 5 bonus XP! Tickets + points = double reward! 🎟️⭐"},{pose:"brain",text:"💡 Tip: Hit 'Start a Quest' in the sidebar to test your Bitcoin knowledge and earn XP! ⚡"},{pose:"fire",text:"💡 Tip: The Bitcoin Scholar Certification Quest is the ultimate test — pass it to earn the 🎓 badge + 300 points!"},{pose:"eyes",text:"💡 Tip: There are 9 hidden badges to unlock! Each one awards points. Explore the site to discover them all! 🏅"},{pose:"point",text:"💡 Tip: Badges scale in points from 25 to 1,000! The hardest ones are worth the most! 💰"},{pose:"point",text:"💡 Tip: Click your username or the sign-in button to access your Settings — Account, Tickets, Prefs, Security, Data!"},{pose:"point",text:"💡 Tip: You can switch between dark and light theme in Settings → Prefs! 🌙☀️"},{pose:"point",text:"💡 Tip: The site works offline too! Add it to your home screen as an app! 📱"},{pose:"point",text:"💡 Tip: You can export all your data anytime in Settings → Data. Your data is yours! 📥"},{pose:"point",text:"💡 Tip: Don't like me? Long-press to hide me. But I'll miss you. 🥺 (You can bring me back in Settings → Prefs)"},{pose:"brain",text:"💡 Tip: YouTube videos are embedded right in the channels — click to play without leaving the site! 🎬"},{pose:"point",text:"💡 Tip: Tweets are embedded too! Click '▶ Click to display tweet' to expand them. 🐦"},{pose:"fire",text:'📺 Tip: Timechain TV streams 21 curated channels 24/7 — earn 10 pts per 10 min watched! Tune in →'},{pose:"cheese",text:'🛋️ Tip: Couch with me on Timechain TV — I react to every channel you tune into! 🍿 Let\'s chill →'},{pose:"point",text:"💡 Tip: Timechain TV has a global clock — every viewer on the same channel sees the same moment. True synchronized TV! ⏰"},{pose:"celebrate",text:"👑 Tip: Watch 24 hours on Timechain TV to unlock the 👑 Couch King badge + 100 points!"},{pose:"point",text:"💡 Tip: The Quote of the Day on the homepage changes daily — click it to jump to the related channel! 💬"},{pose:"point",text:"💡 Tip: New to Bitcoin? Start with the 'one-stop-shop' channel — it has everything to get you started! 🎯"},{pose:"brain",text:"💡 Tip: Channels are organized into Properties, Experienced Topics, Resources, and Additional Info. Start with Properties!"},{pose:"point",text:"💡 Tip: Post in the PlebTalk to earn the 📣 Town Crier badge + 100 points! Press T or find it in the sidebar."},{pose:"point",text:"💡 Tip: Reply to PlebTalk posts to earn the 💬 Conversationalist badge + 75 points! Join the discussion!"},{pose:"cheese",text:"💡 Tip: LightningMart lets you buy and sell with Bitcoin! List an item to earn the 🏪 Merchant badge! Press S to check it out."},{pose:"point",text:"💡 Tip: Found something cool on LightningMart? Contact the seller to earn the 🛍️ Shopper badge!"},{pose:"celebrate",text:"💡 Tip: Check out my closet in Settings → Nacho! You can dress me up with items you unlock! 🎽🦌"},{pose:"point",text:"💡 Tip: Closet items are colorable! Equip an item, then tap 🎨 Color to customize it! 🌈"},{pose:"fire",text:"💡 Tip: Spin the Daily Wheel every day for free Orange Tickets! Look for the banner at the top of the homepage! 🎡"},{pose:"fire",text:"💡 Tip: Press N to enter Nacho Mode — a full chat experience where I answer your Bitcoin questions with AI! 🦌🧠"},{pose:"point",text:"💡 Tip: In Nacho Mode, press ↑ to recall your previous questions — just like in a chat app!"},{pose:"brain",text:"💡 Tip: Nacho Mode shows the live Bitcoin price in the header! Check it anytime! ₿"},{pose:"point",text:"💡 Tip: Tap the 🧒 button in Nacho Mode to toggle ELI5 mode — I'll explain everything in super simple language!"},{pose:"celebrate",text:"💡 Tip: In Nacho Mode, tap '🗺️ Start Bitcoin Journey' for a guided 10-step learning path from beginner to pro!"},{pose:"point",text:"💡 Tip: Tap '🎮 Quiz Me' in Nacho Mode to test your knowledge and earn XP! 🏆"},{pose:"point",text:"💡 Tip: Nacho Mode has topic chips — tap them if you don't know what to ask! ⚡ Lightning, ⛏️ Mining, and more!"},{pose:"brain",text:"💡 Tip: Every answer in Nacho Mode has 👍👎 buttons — your feedback helps me get smarter!"},{pose:"point",text:"💡 Tip: You can share any Nacho answer with the 📤 Share button — spread the Bitcoin knowledge! 🌍"},{pose:"fire",text:"💡 Tip: Use your voice! Tap 🎙️ in Nacho Mode to ask me questions by speaking! 🗣️"},{pose:"point",text:"💡 Tip: Nacho Mode saves your full chat history — come back anytime to pick up where you left off!"},{pose:"celebrate",text:"💡 Tip: Ask me 10, 25, 50, or 100 questions in Nacho Mode to unlock special milestones! 🎉"},{pose:"fire",text:"💡 Tip: We have a PlebTalk! Press T or click '🗣️ PlebTalk' in the sidebar to discuss Bitcoin! 💬"},{pose:"point",text:"💡 Tip: In PlebTalk, upvote great posts with ⚡ and earn +10 points for posting, +5 for replying!"},{pose:"brain",text:"💡 Tip: PlebTalk posts can include links! Share interesting Bitcoin articles or resources with the community! 🔗"},{pose:"point",text:"💡 Tip: Set up your profile in Settings → Account! Add a bio, website, Twitter, Nostr, and Lightning address! 📝"},{pose:"eyes",text:"💡 Tip: Click any user on the leaderboard to see their profile — including their bio and social links! 👀"},{pose:"fire",text:"💡 Tip: The Scholar Certification awards 2,100 points — that's 21 million in sats! The magic number! 🎓"},{pose:"cheese",text:"💡 Tip: Dress me up! Check out Nacho's Closet in Settings → Stats/Nacho. Unlock items as our friendship grows! 👔🦌"},{pose:"cool",text:"💡 Tip: I wear my closet items in Nacho Mode too! Equip something and check out my hero section! 🦸"},{pose:"point",text:"💡 Tip: Press ? to see ALL keyboard shortcuts! N=Nacho, T=PlebTalk, P=Donate, L=Leaderboard, and more! ⌨️"},{pose:"point",text:"💡 Tip: Press A to quickly ask me a question from any page — no need to enter Nacho Mode! 🦌"},{pose:"cool",text:"💡 Tip: You can sign in with Nostr! If you have Alby or nos2x, click the 🟣 Nostr button on the sign-in page! ⚡"},{pose:"love",text:"💡 Tip: Press P to open the donation page — support the archive with Lightning! Every sat counts! ⚡🧡"},{pose:"point",text:"💡 Tip: The site supports 15+ languages! Change it in Settings → Prefs. I can even answer in your language! 🌍"},{pose:"point",text:"💡 Tip: You can DM any user! Tap their name on the leaderboard → 💬 Message. Your inbox is in the DMs tab! 📬"},{pose:"eyes",text:"💡 Tip: DMs are protected — you need 50 points and a 24h-old account to message. No scammers allowed! 🛡️"},{pose:"point",text:"💡 Tip: Never share your seed phrase, private keys, or send Bitcoin to strangers in DMs! Stay safe! 🔒"},{pose:"fire",text:"💡 Tip: Challenge other Bitcoiners to PVP trivia battles! Press X or find ⚔️ PVP in the sidebar! Who knows more? 🏆"},{pose:"celebrate",text:"💡 Tip: Win PVP battles to climb the PVP leaderboard! Your wins and losses show on your profile! ⚔️"},{pose:"fire",text:"💡 Tip: Bitcoin Beats is our community music platform! Listen, upload, and discover tracks made by Bitcoiners! 🎸🦌"},{pose:"point",text:"💡 Tip: Tap a song title on Bitcoin Beats to see full track details — artist, genre, play count, and more! 🎵"},{pose:"celebrate",text:"💡 Tip: Upload your own music on Bitcoin Beats! Hit the Upload tab and share your sound with the community! 🎤"},{pose:"point",text:"💡 Tip: Like tracks on Bitcoin Beats with ❤️ and leave comments! Support Bitcoin musicians! 🎶"},{pose:"fire",text:"💡 Tip: IRL Sync helps you find Bitcoin meetups near you! Create events, RSVP, and meet Bitcoiners in person! 🤝"},{pose:"point",text:"💡 Tip: Can't find a meetup near you? Create one on IRL Sync! Be the node that connects your local community! 🌐"},{pose:"point",text:"💡 Tip: Try the Price Prediction game! Guess if Bitcoin goes up or down in 24h and track your accuracy! 📈📉"},{pose:"celebrate",text:"💡 Tip: I have a story to tell! Tap the 📖 next to me for a new chapter every day. It's an adventure! 🦌✨"}],r=[{pose:"celebrate",text:"You're doing great, {name}! Most people never even start learning about Bitcoin. You're already ahead. 🦌💪"},{pose:"fire",text:"Keep going, {name}! You're stacking knowledge like a true pleb! 📚🔥"},{pose:"love",text:"Nacho is proud of your progress, {name}! You're further down the rabbit hole than most. 🐇"},{pose:"cool",text:"Stay humble, stack sats, stack knowledge. You're doing all three, {name}. 😎"},{pose:"celebrate",text:"Every channel you read makes the FUD weaker, {name}! Keep it up! 💪"},{pose:"brain",text:"{name}, your brain is getting more orange-pilled by the minute! 🧠🟠"},{pose:"fire",text:"Tick tock, next block... and you're getting smarter with each one, {name}! ⏰"},{pose:"love",text:"The fact that you're here learning puts you ahead of 99% of people, {name}. For real. 🧡"},{pose:"celebrate",text:"Imagine telling your future self you were learning about Bitcoin in 2026, {name}. They'll thank you! 🙏"},{pose:"fire",text:"{name}, you're building generational knowledge right now. No big deal. 🏗️"},{pose:"cool",text:"Diamond hands start with a diamond mind. You're forging yours right now, {name}! 💎🧠"},{pose:"love",text:"The journey of a thousand sats begins with a single channel, {name}. You've read way more than that! 🦌"},{pose:"celebrate",text:"You're not just learning Bitcoin, {name} — you're opting out of the broken system. Respect. ✊"},{pose:"fire",text:"Number go up, knowledge go up. You're winning on both fronts, {name}! 📈🧠"},{pose:"brain",text:"Every nocioner who ever became a maxi started exactly where you are, {name}. Keep reading! 📖"}],s=[{pose:"cheese",text:"Nacho keys, nacho cheese. It's not just a tagline, it's a lifestyle. 🧀🔑"},{pose:"fire",text:"Nacho sats... They're all mine! 💰🦌"},{pose:"cheese",text:"My seed phrase? 24 different types of cheese. Very secure. Very delicious. 🔐🧀"},{pose:"cheese",text:"Bitcoin fixes everything. Except my cheese addiction. Some things are unfixable. 🧀"},{pose:"cool",text:"Live Free or Die — that's the New Hampshire motto. Also my approach to Bitcoin. 🦌🗻"},{pose:"fire",text:"These antlers aren't just for show. I'm the strongest buck in NH and the most orange-pilled. 💪🦌"},{pose:"default",text:"In a world of unlimited printing, be a limited supply. Like Bitcoin. And like me — there's only one Nacho. 🦌"},{pose:"default",text:"Some people have angel investors. You have an angel deer. You're welcome. 😇🦌"},{pose:"cool",text:"I'm not saying I'm Satoshi, but have you ever seen us in the same room? 🤫"},{pose:"eyes",text:"I've been watching you learn, {name}. Not in a creepy way. In a proud buck way. 👀"},{pose:"sleep",text:"*yawns* Don't mind me, just HODLing this corner of your screen... 💤"},{pose:"fire",text:"Few understand this... but YOU will, {name}. That's why you're here. 🔥"},{pose:"think",text:"What's a deer's favorite block? The next one! ⛏️"},{pose:"celebrate",text:"Why did Bitcoin break up with the dollar? It found someone with less baggage and a fixed supply! 💔😂"},{pose:"cool",text:"I told my friend to buy Bitcoin in 2015. He bought Dogecoin instead. We don't talk anymore. 🐕"},{pose:"think",text:"An altcoiner walks into a bar. Orders a round for everyone. Card declines. 😂"},{pose:"cheese",text:"How does a Bitcoiner cut their pizza? Into 100 million slices. 🍕"},{pose:"cool",text:"My financial advisor said diversify. So I have Bitcoin on a hardware wallet AND a paper backup. 😎"},{pose:"celebrate",text:"Knock knock. Who's there? Fiat. Fiat who? Exactly. Nobody remembers it either. 🪦"},{pose:"think",text:"What's the difference between a dollar and a Bitcoin? One goes to zero, the other came from zero. 📉📈"},{pose:"default",text:"I tried to explain Bitcoin to a goldfish once. Went about as well as explaining it to Peter Schiff. 🐟"},{pose:"cool",text:"Bitcoiners don't have FOMO. They have FONGO — Fear Of Not Getting Orange-pilled. 🟠"},{pose:"brain",text:"₿ Fact: Satoshi Nakamoto's identity is still unknown. Could be one person, could be a group. Could be a deer. 🦌"},{pose:"brain",text:"₿ Fact: The Bitcoin pizza transaction in 2010 used 10,000 BTC for two pizzas. That's billions today. 🍕"},{pose:"brain",text:"₿ Fact: There will only ever be 21 million Bitcoin. About 19.5 million have already been mined! 💎"},{pose:"brain",text:"₿ Fact: Bitcoin's network has never been hacked. Not once. 13+ years of perfect security. 🔒"},{pose:"brain",text:"₿ Fact: The smallest unit of Bitcoin is called a 'satoshi' — 0.00000001 BTC. You can own sats! ⚡"},{pose:"brain",text:"₿ Fact: El Salvador was the first country to make Bitcoin legal tender in 2021! 🇸🇻"},{pose:"brain",text:"₿ Fact: Bitcoin mining uses less energy than clothes dryers in the US. But nobody writes angry articles about dryers. 🧺"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is only 9 pages long. The US tax code is over 75,000 pages. Which one works better? 📜"},{pose:"brain",text:"₿ Fact: 'HODL' came from a typo in a passionate forum post in 2013. It became the most famous word in crypto. 😂"},{pose:"brain",text:"₿ Fact: Bitcoin processes over $10 billion in transactions daily. And it never takes a day off! 💰"},{pose:"brain",text:"₿ Fact: The genesis block contains a hidden message: 'Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"₿ Fact: You can run a full Bitcoin node on a Raspberry Pi for about $50. Be your own bank! 🖥️"},{pose:"brain",text:"₿ Fact: Bitcoin's inflation rate is now lower than gold's. Digital gold? More like better-than-gold. 🥇"},{pose:"brain",text:"₿ Fact: The Lightning Network can handle millions of transactions per second. Visa does about 1,700. ⚡"},{pose:"brain",text:"₿ Fact: About 20% of all Bitcoin is estimated to be permanently lost. That makes yours even more scarce! 🔑"},{pose:"brain",text:"₿ Fact: Bitcoin's first price was $0.000994 — less than a tenth of a penny! For 10 months it had NO price at all. 💰"},{pose:"brain",text:"₿ Fact: The chance of guessing someone's private key is the same as winning Powerball 7 times in a row! 🎰🔐"},{pose:"brain",text:"₿ Fact: The first Bitcoin faucet gave away 5 WHOLE BITCOINS per person just for solving a captcha! 🤯"},{pose:"brain",text:"₿ Fact: You only need the FIRST 4 LETTERS of each seed word to restore your wallet. All 2,048 BIP39 words have unique first 4 letters! 🔑"},{pose:"brain",text:"₿ Fact: 'Bacon' repeated 24 times is technically a valid Bitcoin seed phrase. It passes the checksum! 🥓"},{pose:"brain",text:"₿ Fact: Bitcoin has 99.987% uptime — only 14 hours of downtime in 15+ years. That rivals Google and Amazon! 🏆"},{pose:"brain",text:"₿ Fact: Satoshi's birthday (April 5) is the date of Executive Order 6102, when the US made it ILLEGAL to own gold! 🎂📜"},{pose:"brain",text:"₿ Fact: The difficulty adjustment happens every 2,016 blocks. Read that backwards: 6102 — the gold confiscation order! 🤯"},{pose:"brain",text:"₿ Fact: 2-3 million Bitcoin are permanently lost forever. That makes YOUR sats even more scarce! 💎"},{pose:"brain",text:"₿ Fact: Satoshi wrote 575 forum posts, 31,000 lines of code, used 22,000+ addresses, and never reused one! 📝"},{pose:"brain",text:"₿ Fact: Satoshi's ~1 million Bitcoin have NEVER moved. Not one satoshi. Worth tens of billions. 👑"},{pose:"brain",text:"₿ Fact: 70% of ALL US dollars in circulation were created after 2008. Over 40% since 2020 alone! 💸"},{pose:"brain",text:"₿ Fact: One dollar today buys what 4 CENTS bought in 1913. That's a 96% loss in purchasing power! 📉"},{pose:"brain",text:"₿ Fact: In August 2010, a bug created 184 BILLION fake Bitcoin. The community fixed it in hours! The largest reorg ever — 53 blocks. 😱"},{pose:"brain",text:"₿ Fact: 61% of Ethereum nodes run in the cloud. Amazon alone hosts ~25% of them. Bitcoin nodes run on Raspberry Pis worldwide! ☁️🆚🖥️"},{pose:"brain",text:"₿ Fact: Milton Friedman, Nobel Prize economist, predicted Bitcoin in 1999 — 10 years before it existed! 🔮"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is encoded IN the blockchain at block 230,009. It will exist as long as Bitcoin does! 📄⛓️"},{pose:"brain",text:"₿ Fact: In July 2024, a tiny Bitaxe miner with just 3 TH/s found a block — a 1-in-3,500 YEAR chance! ⛏️🎯"},{pose:"brain",text:"₿ Fact: 99% of all Bitcoin will be mined by 2035. The very last fraction won't be mined until ~2140! ⏳"},{pose:"brain",text:"₿ Fact: The original Bitcoin code contained the beginnings of a POKER GAME that Satoshi started but never finished! 🃏"},{pose:"brain",text:"₿ Fact: Only 0.06% of Bitcoin Core's code remains unchanged from what Satoshi originally wrote. Open source at its finest! 💻"},{pose:"brain",text:"₿ Fact: Christmas lights in the US alone consume more energy than the entire Bitcoin network! 🎄⚡"},{pose:"brain",text:"₿ Fact: Bitcoin mining captures methane that's 84x more warming than CO2, turning waste into sound money! 🌱"},{pose:"brain",text:"₿ Fact: NO ONE who bought Bitcoin and held for 4+ years has EVER lost money. Not once in 15+ years! 📈 (NFA)"},{pose:"brain",text:"₿ Fact: Michael Saylor said The Bitcoin Standard was 'the most impactful on our way of thinking at MicroStrategy.' 📚"},{pose:"brain",text:"₿ Fact: Gigi calls Bitcoin 'an inexhaustible teacher.' His 21 Lessons is free at 21lessons.com! 📖🧡"},{pose:"brain",text:"₿ Fact: Tomer Strolight says Satoshi's coins aren't the real treasure. The real treasure is the journey Bitcoin sends you on! 👑"},{pose:"brain",text:"₿ Fact: Bitcoin is to money what zero was to mathematics — the missing piece that makes everything work better! 🔢"},{pose:"brain",text:"₿ Fact: Every aspect of Bitcoin is TEXT — and text is speech, protected by the First Amendment! You can't ban math. 🗽"},{pose:"brain",text:"₿ Fact: Only about 2-4% of the world owns any Bitcoin. If you hold sats, you're still incredibly early! 🌍"},{pose:"think",text:'"The root problem with conventional currency is all the trust that\'s required to make it work." — Satoshi 🧠'},{pose:"think",text:'"Give me control of a nation\'s money and I care not who makes its laws." — Mayer Rothschild 🏦'},{pose:"think",text:'"We have elected to put our money and faith in a mathematical framework free of politics." — Tyler Winklevoss 🔢'},{pose:"think",text:'"Bitcoin is the most important invention since the internet." 🌐'},{pose:"fire",text:'"Fix the money, fix the world." Simple as that. 🔧🌍'},{pose:"think",text:'"Bitcoin is a swarm of cyber hornets serving the goddess of wisdom." — Michael Saylor 🐝'},{pose:"cool",text:'"Running Bitcoin." — Hal Finney, January 10, 2009. The first tweet about Bitcoin. 🏃'},{pose:"celebrate",text:"HODL your knowledge. Never sell what you've learned! 💎🙌"},{pose:"think",text:"Roses are red, fiat is dead, stack sats instead! 🌹"},{pose:"cool",text:"I've been orange-pilled since the day I grew these antlers. 🟠🦌"},{pose:"celebrate",text:"What's stronger — my antlers or Bitcoin's security? Trick question. Both unbreakable. 💪🔒"},{pose:"default",text:"The deer in New Hampshire are talking about Bitcoin. Okay, it's just me. But still. 🗻🦌"},{pose:"cheese",text:"If I had a satoshi for every time someone asked me about crypto... I'd tell them it's Bitcoin, not crypto. 🧀"},{pose:"cool",text:"My antlers pick up the Bitcoin network signal. That's not true, but it sounds cool. 📡🦌"},{pose:"fire",text:"They said Bitcoin was dead 477 times, {name}. And here we are. Still stacking. 🦌💪"},{pose:"eyes",text:"The forest is full of distractions. I stick to the trail marked ₿. 🌲"},{pose:"celebrate",text:"When in doubt, zoom out, {name}. That goes for the chart AND the rabbit hole. 🔭"},{pose:"cool",text:"Oh deer, another all-time high? I'm not surprised. 🦌📈"},{pose:"cheese",text:"What do you call a deer who loves Bitcoin? A buck-hodler! 🦌💎"},{pose:"celebrate",text:"I'm fawned of Bitcoin. Get it? ...I'll see myself out. 🦌😂"},{pose:"think",text:"People say Bitcoin is hard to understand. I say it's deer-ly obvious! 🦌💡"},{pose:"cool",text:"I don't always check the charts, but when I doe, I HODL. 🦌😎"},{pose:"fire",text:"Just earned some sats! Another buck in the wallet! 💰🦌"},{pose:"cheese",text:"Why do deer make great Bitcoiners? Because we never sell — we just stag-ger through the dips! 🦌📉📈"},{pose:"celebrate",text:"This site really helps you get to the hart of Bitcoin! ...Sorry, deer puns are my specialty. 🦌❤️"},{pose:"think",text:"Fiat currency is on its last legs. Lucky for me, I have four of them! 🦌🏃"},{pose:"cool",text:"Did you hear about the deer who understood Bitcoin? He was considered a doe-cipherpunk! 🦌🛡️"},{pose:"fire",text:"Some say the Bitcoin market is wild. Well, I AM a wild animal, so I fit right in! 🦌🔥"},{pose:"cheese",text:"I tried mining Bitcoin with my hooves. It was un-fawn-tunately not very efficient. ⛏️🦌"},{pose:"celebrate",text:"What's a deer's favorite cryptocurrency? Bit-coin, because we love our bits of grass too! 🌿🦌"},{pose:"think",text:"My financial advice? Be a deer and HODL. That's not real advice though, I'm literally a deer. 🦌📜"},{pose:"cool",text:"They call me a stag-ger-ing intellect when it comes to Bitcoin. Okay, I call myself that. 🦌🧠"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 That's not just my catchphrase — it's financial wisdom from a deer."},{pose:"cheese",text:"Remember folks: Nacho keys, nacho cheese! If you don't hold the keys, you don't hold the cheddar. 🧀"},{pose:"fire",text:"I'm not just any deer. I'm a New Hampshire buck — Live Free or Die. And I choose Bitcoin. 🗻🦌"},{pose:"cool",text:"Why did the deer buy a hardware wallet? Because he was tired of getting buck-ed by exchanges! 🦌🔐"},{pose:"think",text:"What do you call a deer who understands monetary policy? A buck who knows his doe! 🦌💰"},{pose:"celebrate",text:"I told my doe friend about Bitcoin. Now she's a whole doe-llar maximalist! 🦌🟠"},{pose:"cheese",text:"I'm not fawning over altcoins. I'm a Bitcoin-only buck. Always have been, always will be. 🦌"},{pose:"fire",text:"My antlers pick up the Bitcoin signal better than any antenna. Built-in orange frequency! 📡🦌"},{pose:"cool",text:"They say a buck in the hand is worth two in the bush. I say a sat stacked is worth a thousand fiat notes. 💎"},{pose:"think",text:"What's a deer's favorite consensus mechanism? Proof of Antlers! 🦌⛏️ ...okay, it's Proof of Work."},{pose:"celebrate",text:"Just a buck from the Granite State, orange-pilling the internet one human at a time! 🗻🟠"},{pose:"cheese",text:"I tried explaining multisig to a squirrel. He said he'd rather just bury his nuts. Different strokes! 🐿️🦌"},{pose:"default",text:"Some deer migrate south for winter. I migrate to the blockchain. It's warmer there. ⛓️🦌"},{pose:"fire",text:"These antlers have been HODLing since block 1. Diamond antlers. 💎🦌"},{pose:"cool",text:"New Hampshire motto: Live Free or Die. Bitcoin motto: Don't Trust, Verify. Same energy. 🦌🗽"},{pose:"think",text:"What do you get when a deer reads the whitepaper? An un-fawn-gettable experience! 📄🦌"},{pose:"cheese",text:"A buck walks into a bar. Orders a round for everyone. Pays in Lightning. ⚡🦌 Instant. Nearly free."},{pose:"celebrate",text:"I'm the most antler-preneurial deer you'll ever meet. My business? Bitcoin education! 🦌📚"},{pose:"default",text:"Fun deer fact: I shed my antlers every year and grow them back bigger. Just like Bitcoin sheds FUD and grows back stronger! 🦌📈"},{pose:"fire",text:"The forest has bears and bulls. I'm a buck — and bucks are ALWAYS bullish on Bitcoin! 🦌🚀"},{pose:"cool",text:"In NH we have no sales tax and no income tax. We also have me, the most based buck in the state. 🗻🦌"},{pose:"cheese",text:"Nacho keys, nacho cheese! Nacho node, nacho rules! Nacho seed phrase, nacho sats! 🧀🔑🦌"},{pose:"think",text:"What's a deer's least favorite thing? A central bank. We prefer de-deer-centralization! 🦌🏛️"},{pose:"celebrate",text:"Why am I orange? Because I was born orange-pilled, {name}! It's in my fur! 🟠🦌"},{pose:"brain",text:"🧠 Bitcoin fact: The first Bitcoin transaction was 10,000 BTC for two pizzas on May 22, 2010. We celebrate it as Bitcoin Pizza Day every year! 🍕"},{pose:"brain",text:"🧠 Did you know? Satoshi Nakamoto mined ~1.1 million BTC and never moved a single one. That's conviction. 🦌"},{pose:"brain",text:"🧠 Fact: Bitcoin's code has been running since January 3, 2009 with 99.99% uptime. No CEO, no office, no downtime. 🏆"},{pose:"brain",text:"🧠 The Genesis Block contains the message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"🧠 There will only ever be 21 million Bitcoin. Currently ~19.6 million have been mined, and ~4 million are estimated lost forever. 🔢"},{pose:"brain",text:"🧠 Bitcoin's difficulty adjustment happens every 2,016 blocks (~2 weeks). It's the most elegant part of the protocol! ⚙️"},{pose:"brain",text:"🧠 Hal Finney received the first-ever Bitcoin transaction from Satoshi on January 12, 2009. His tweet: 'Running bitcoin.' 🏃"},{pose:"brain",text:"🧠 Bitcoin mining doesn't solve 'complex math problems.' Miners guess random nonces and hash them through SHA-256. It's a brute-force lottery! 🎲"},{pose:"brain",text:"🧠 The Lightning Network can process millions of transactions per second. Visa does about 65,000. ⚡"},{pose:"brain",text:"🧠 Bitcoin uses less than 0.1% of global energy. And over 50% of mining uses renewable energy sources. 🌱"},{pose:"brain",text:"🧠 The smallest unit of Bitcoin is called a 'satoshi' — 1 BTC = 100,000,000 sats. Named after the creator! ⚡"},{pose:"brain",text:"🧠 In 2021, El Salvador became the first country to adopt Bitcoin as legal tender. 🇸🇻"},{pose:"brain",text:"🧠 Fact: Bitcoin has survived over 470+ 'obituaries' — media declaring it dead. It's still here. It's still growing. 💀→🚀"},{pose:"brain",text:"🧠 The Bitcoin network is secured by more computational power than all the world's supercomputers combined. 🛡️"},{pose:"brain",text:"🧠 'Not your keys, not your coins' — this phrase became famous after the Mt. Gox hack in 2014 where 850,000 BTC were lost. 🔑"},{pose:"brain",text:"🧠 Bitcoin's stock-to-flow ratio after the 2024 halving is higher than gold's. It's the hardest money ever created. 💎"},{pose:"brain",text:"🧠 The Blocksize Wars of 2015-2017 proved that users — not miners or corporations — control Bitcoin's rules. 🏛️"},{pose:"brain",text:"🧠 Fun fact: You can run a full Bitcoin node on a $50 Raspberry Pi. Don't trust, verify! 🖥️"},{pose:"brain",text:"🧠 Bitcoin was worth $0 in 2009. If you bought $1 of Bitcoin at $0.001, you'd have billions today. Time in the market beats timing the market! ⏰"},{pose:"brain",text:"🧠 The Cantillon Effect: when governments print money, those closest to the printer benefit first. Bitcoin eliminates this unfair advantage. 💡"},{pose:"brain",text:"🧠 CoinJoin transactions mix multiple users' inputs together, making it nearly impossible to trace who sent what to whom. Privacy matters! 🤫"},{pose:"brain",text:"🧠 Satoshi's last known message was in April 2011: 'I've moved on to other things.' The greatest mic drop in history. 🎤⬇️"},{pose:"brain",text:"🧠 Taproot, activated in 2021, brought Schnorr signatures to Bitcoin — improving privacy and enabling more complex smart contracts. 🧰"},{pose:"brain",text:"🧠 The Bitcoin whitepaper is only 9 pages long. Nine pages that changed the world. Have you read it? 📄"},{pose:"brain",text:"🧠 Bitcoin's hash rate is measured in exahashes per second. One exahash = 1 quintillion hashes. Per SECOND. 🤯"}],l=[{pose:"wave",text:"👋 Hey, {name}! I'm Nacho — a strong buck from New Hampshire! Click me anytime for Bitcoin tips and wisdom. 🦌💪"},{pose:"wave",text:"👋 Welcome back, {name}! Your friendly NH buck missed you! Ready to tackle some Bitcoin knowledge today? 💪"},{pose:"wave",text:"👋 Nacho here, {name}! The strongest buck in New Hampshire and your Bitcoin guide. Let's learn something! 🦌"},{pose:"wave",text:"Hey {name}! 🦌 Back for more? I've got 145 channels of Bitcoin knowledge waiting for you!"},{pose:"cool",text:"Yo {name}! 😎 Nacho's in the house. What are we learning about today?"},{pose:"fire",text:"🔥 {name}! Another day, another sat stacked. Let's make today count!"},{pose:"celebrate",text:"{name}! 🎉 Great to see you. Did you know this archive has over 8,800 Bitcoin messages? Dig in!"},{pose:"brain",text:"Welcome, {name}! 🧠 Fun fact: the more you learn about Bitcoin, the more you realize there's always more to learn."},{pose:"love",text:"🧡 {name}! Nacho here. I've been guarding this archive for you. Let's explore together!"},{pose:"default",text:"Hey {name}! Tick tock, next block. What's on your mind today? 🦌⏰"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 Welcome back, {name}. What are we diving into?"},{pose:"wave",text:"👋 Good to see you, {name}! Remember — every channel you read makes you harder to scam. Knowledge is armor!"},{pose:"fire",text:"{name}! 🦌🔥 The orange pill hits different when you study the fundamentals. Let's go!"}],c=[{pose:"eyes",text:"Great choice, {name}! I'll be over here if you need me. 👀"},{pose:"cool",text:"Ooh, excellent pick, {name}! You've got good taste. 😎"},{pose:"brain",text:"This one's a good read, {name}! Take your time. 🧠"},{pose:"fire",text:"One of my favorites! Dig in, {name}! 🦌🔥"},{pose:"love",text:"Nice, {name}! This channel has great stuff in it. 🧡"}],d=[{pose:"celebrate",text:"Nice, {name}! Points are stacking up! 🎉"},{pose:"fire",text:"{name}, you're on fire! Nacho approves! 🔥"},{pose:"celebrate",text:"Cha-ching, {name}! The knowledge is paying off! 💰"}],u=["default","eyes","default","think","default","cheese","default","cool","default","sleep","default"];let p=0,m=null,h=!0,g=null;window.clearNachoBubbleTimeout=function(){clearTimeout(g),g=null};let f=0,y=0,b=new Set,v=0,w="default";function x(){var n=localStorage.getItem("btc_nacho_hidden");"true"!==n&&"user"!==n||(h=!1);const i=document.createElement("style");i.textContent="\n #nacho-container {\n position: fixed;\n bottom: 80px;\n left: 330px;\n z-index: 250;\n display: flex;\n align-items: flex-end;\n gap: 0;\n pointer-events: none;\n transition: opacity 0.3s, transform 0.3s;\n }\n #nacho-container.hidden { opacity: 0; transform: translateY(30px); pointer-events: none; }\n\n #nacho-avatar {\n width: 110px;\n height: 110px;\n background: none;\n border-radius: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n pointer-events: auto;\n filter: drop-shadow(0 6px 16px rgba(0,0,0,0.5));\n transition: transform 0.15s;\n user-select: none;\n position: relative;\n flex-shrink: 0;\n z-index: 2;\n overflow: visible;\n }\n #nacho-avatar { -webkit-user-select: none; }\n #nacho-avatar:hover { transform: scale(1.08) rotate(-3deg); }\n #nacho-avatar:active { transform: scale(0.93); }\n #nacho-avatar .nacho-btn-stack {\n position: absolute;\n top: -5px;\n right: -4px;\n display: flex;\n flex-direction: column;\n gap: 4px;\n z-index: 5;\n }\n #nacho-avatar .nacho-closet-btn, #nacho-avatar .nacho-story-btn {\n font-size: 0.85rem;\n cursor: pointer;\n pointer-events: auto;\n background: var(--card-bg, #1a1a2e);\n border: 1px solid var(--border, #333);\n border-radius: 50%;\n width: 26px;\n height: 26px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: 0.2s;\n opacity: 0.5;\n position: relative;\n }\n #nacho-avatar .nacho-closet-btn:hover, #nacho-avatar .nacho-story-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n border-color: #f7931a;\n }\n .nacho-notif-dot {\n position: absolute;\n top: -2px;\n right: -2px;\n width: 8px;\n height: 8px;\n background: #ef4444;\n border-radius: 50%;\n border: 1.5px solid var(--card-bg, #1a1a2e);\n z-index: 6;\n pointer-events: none;\n }\n #nacho-avatar .nacho-name {\n position: absolute;\n bottom: -46px;\n left: 50%;\n transform: translateX(-50%);\n font-size: 0.7rem;\n color: #f7931a;\n font-weight: 800;\n letter-spacing: 1.5px;\n white-space: nowrap;\n text-transform: uppercase;\n text-shadow: 0 1px 4px rgba(0,0,0,0.5);\n line-height: 1.3;\n text-align: center;\n pointer-events: auto;\n cursor: pointer;\n padding: 4px 12px;\n border-radius: 8px;\n transition: background 0.2s;\n }\n #nacho-avatar .nacho-name:hover {\n background: rgba(247,147,26,0.15);\n }\n\n /* Nacho speech bubble — high contrast, always readable */\n #nacho-bubble {\n background: #111827;\n border: 2px solid #f7931a;\n border-radius: 16px;\n padding: 16px 20px 16px 18px;\n max-width: 300px;\n min-width: 200px;\n color: #f8f8f8;\n font-size: 0.9rem;\n line-height: 1.55;\n pointer-events: none;\n box-shadow: 0 8px 32px rgba(0,0,0,0.7), 0 0 12px rgba(247,147,26,0.25);\n opacity: 0;\n transform: translateY(8px) scale(0.9);\n transition: opacity 0.35s cubic-bezier(0.34, 1.56, 0.64, 1), transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);\n cursor: pointer;\n position: relative;\n margin-left: -6px;\n margin-bottom: 16px;\n z-index: 1000;\n }\n #nacho-bubble::before {\n content: '';\n position: absolute;\n bottom: 10px;\n left: -10px;\n width: 0; height: 0;\n border-top: 10px solid transparent;\n border-bottom: 10px solid transparent;\n border-right: 10px solid #f7931a;\n }\n #nacho-bubble::after {\n content: '';\n position: absolute;\n bottom: 12px;\n left: -7px;\n width: 0; height: 0;\n border-top: 8px solid transparent;\n border-bottom: 8px solid transparent;\n border-right: 8px solid #111827;\n }\n #nacho-bubble.show { opacity: 1; transform: translateY(0) scale(1); pointer-events: auto; }\n\n .nacho-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 6px;\n }\n .nacho-label {\n font-size: 0.65rem;\n color: #f7931a;\n font-weight: 800;\n text-transform: uppercase;\n letter-spacing: 1px;\n }\n .nacho-x {\n color: var(--text-faint, #666);\n font-size: 0.75rem;\n cursor: pointer;\n opacity: 0.4;\n transition: opacity 0.2s;\n padding: 2px 4px;\n }\n .nacho-x:hover { opacity: 1; }\n #nacho-text { word-wrap: break-word; max-height: 60vh; overflow-y: auto; -webkit-overflow-scrolling: touch; padding-right: 4px; }\n\n /* Clippy-style idle animations — mimic the paper clip's fidgeting */\n\n /* 1. Tap tap — like Clippy tapping on the screen */\n /* Nacho victory flight — Lightning bolt ⚡ across the full screen! */\n @keyframes nachoFly {\n /* ⚡ Lightning bolt: high-energy erratic takeoff, zigzag, and sonic boom reentry \n */\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 5% { transform: translate(-5px, 10px) rotate(-10deg) scale(0.9); }\n 10% { transform: translate(15vw, -20vh) rotate(20deg) scale(1.1); }\n 20% { transform: translate(40vw, -5vh) rotate(-15deg) scale(1); }\n 30% { transform: translate(65vw, -45vh) rotate(35deg) scale(1.2); }\n 45% { transform: translate(90vw, -10vh) rotate(-20deg) scale(1.1); }\n 60% { transform: translate(110vw, -60vh) rotate(45deg) scale(1.4); opacity: 1; }\n 61% { transform: translate(110vw, -60vh); opacity: 0; }\n /* Sonic boom reentry from the top left */\n 85% { transform: translate(-50vw, -50vh) rotate(-45deg) scale(2); opacity: 0; }\n 90% { transform: translate(-10vw, -10vh) rotate(-20deg) scale(1.5); opacity: 1; filter: brightness(3) blur(2px); }\n 95% { transform: translate(0, -20px) rotate(0deg) scale(1.1); filter: brightness(1); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n @keyframes nachoFlyMobile {\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 8% { transform: translate(-2vw, 5vh) rotate(-10deg) scale(0.9); }\n 15% { transform: translate(25vw, -30vh) rotate(15deg) scale(1.1); }\n 30% { transform: translate(60vw, -5vh) rotate(-15deg) scale(1); }\n 50% { transform: translate(85vw, -50vh) rotate(30deg) scale(1.3); }\n 65% { transform: translate(105vw, -20vh) rotate(10deg) scale(1.2); opacity: 1; }\n 66% { transform: translate(105vw, -20vh); opacity: 0; }\n /* Reentry from top */\n 88% { transform: translate(0, -80vh) rotate(0deg) scale(1.5); opacity: 0; }\n 94% { transform: translate(0, -10px) rotate(0deg) scale(1.1); opacity: 1; filter: brightness(2); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n #nacho-avatar.flying {\n animation: nachoFly 2.8s linear forwards;\n z-index: 999;\n filter: drop-shadow(0 0 20px rgba(247,147,26,0.8)) drop-shadow(0 0 40px rgba(234,88,12,0.4));\n }\n @media (max-width: 900px) {\n #nacho-avatar.flying {\n animation: nachoFlyMobile 2.4s linear forwards;\n }\n }\n /* Lightning trail particles */\n .nacho-trail {\n position: fixed;\n pointer-events: none;\n z-index: 998;\n font-size: 1.2rem;\n opacity: 1;\n transition: none;\n animation: nachoTrailFade 0.8s ease-out forwards;\n }\n .nacho-trail.stuck-cleanup { display: none !important; }\n @keyframes nachoTrailFade {\n 0% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(1.3); }\n 100% { opacity: 0; transform: scale(0.3); }\n }\n\n @keyframes nachoTap {\n 0%, 100% { transform: translateY(0); }\n 10% { transform: translateY(-6px); }\n 20% { transform: translateY(0); }\n 30% { transform: translateY(-4px); }\n 40% { transform: translateY(0); }\n }\n /* 2. Lean and look — Clippy tilting to peek at your screen */\n @keyframes nachoLean {\n 0%, 100% { transform: rotate(0deg) translateX(0); }\n 30% { transform: rotate(8deg) translateX(3px); }\n 50% { transform: rotate(8deg) translateX(3px); }\n 80% { transform: rotate(0deg) translateX(0); }\n }\n /* 3. Bored wiggle — Clippy fidgeting when idle */\n @keyframes nachoWiggle {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-6deg); }\n 30% { transform: rotate(5deg); }\n 45% { transform: rotate(-4deg); }\n 60% { transform: rotate(3deg); }\n 75% { transform: rotate(-2deg); }\n 90% { transform: rotate(0deg); }\n }\n /* 4. Bounce — Clippy's excited hop */\n @keyframes nachoBounce {\n 0%, 100% { transform: translateY(0) scale(1); }\n 20% { transform: translateY(-8px) scale(1.05); }\n 40% { transform: translateY(0) scale(0.97); }\n 55% { transform: translateY(-4px) scale(1.02); }\n 70% { transform: translateY(0) scale(0.99); }\n 85% { transform: translateY(-2px) scale(1.01); }\n }\n /* 5. Stretch — Clippy stretching/yawning */\n @keyframes nachoStretch {\n 0%, 100% { transform: scaleY(1) scaleX(1); }\n 25% { transform: scaleY(1.12) scaleX(0.92); }\n 50% { transform: scaleY(0.92) scaleX(1.08); }\n 75% { transform: scaleY(1.05) scaleX(0.97); }\n }\n /* 6. Look around — Clippy looking left and right */\n @keyframes nachoLook {\n 0%, 100% { transform: translateX(0); }\n 20% { transform: translateX(-5px); }\n 40% { transform: translateX(-5px); }\n 60% { transform: translateX(5px); }\n 80% { transform: translateX(5px); }\n }\n /* 7. Wave — Clippy waving at you */\n @keyframes nachoWave {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-12deg); }\n 30% { transform: rotate(10deg); }\n 45% { transform: rotate(-8deg); }\n 60% { transform: rotate(6deg); }\n 75% { transform: rotate(-3deg); }\n }\n /* 8. Sleepy bob — Clippy nodding off */\n @keyframes nachoSleepy {\n 0%, 100% { transform: translateY(0) rotate(0deg); }\n 30% { transform: translateY(2px) rotate(3deg); }\n 50% { transform: translateY(3px) rotate(5deg); }\n 70% { transform: translateY(2px) rotate(3deg); }\n }\n /* 9. Couch sway — for Timechain TV */\n @keyframes nachoSway {\n 0%, 100% { transform: rotate(-1deg) translateY(0); }\n 50% { transform: rotate(1deg) translateY(-3px); }\n }\n\n #nacho-avatar.anim-tap { animation: nachoTap 2s ease-in-out infinite; }\n #nacho-avatar.anim-lean { animation: nachoLean 3.5s ease-in-out infinite; }\n #nacho-avatar.anim-wiggle { animation: nachoWiggle 2.5s ease-in-out infinite; }\n #nacho-avatar.anim-bounce { animation: nachoBounce 1.8s ease-in-out infinite; }\n #nacho-avatar.anim-stretch { animation: nachoStretch 3s ease-in-out infinite; }\n #nacho-avatar.anim-look { animation: nachoLook 4s ease-in-out infinite; }\n #nacho-avatar.anim-wave { animation: nachoWave 1.5s ease-in-out infinite; }\n #nacho-avatar.anim-sleepy { animation: nachoSleepy 4s ease-in-out infinite; }\n\n /* Tablet — sidebar is 280px */\n @media (max-width: 1100px) {\n #nacho-container { left: 290px; }\n #nacho-avatar { width: 95px; height: 95px; }\n }\n /* Mobile — sidebar hidden, Nacho goes bottom-left, above clutter */\n @media (max-width: 900px) {\n #nacho-container { bottom: calc(50vh - 30px); left: 12px; }\n #nacho-avatar { width: 68px; height: 68px; }\n #nacho-bubble {\n position: fixed;\n bottom: calc(50vh + 50px);\n left: 12px;\n right: 12px;\n max-width: calc(100vw - 24px);\n max-height: 40vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n min-width: unset;\n width: auto;\n font-size: 0.9rem;\n padding: 16px 18px;\n margin-left: 0;\n border-radius: 14px;\n }\n #nacho-bubble::before, #nacho-bubble::after { display: none; }\n #nacho-avatar .nacho-name { font-size: 0.7rem; bottom: -44px; padding: 5px 14px; }\n }\n @media (max-width: 480px) {\n #nacho-container { bottom: calc(50vh - 40px); left: 10px; }\n #nacho-avatar { width: 60px; height: 60px; }\n #nacho-bubble {\n bottom: calc(50vh + 30px);\n left: 10px;\n right: 10px;\n max-width: calc(100vw - 20px);\n max-height: 38vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n font-size: 0.85rem;\n padding: 14px 16px;\n }\n #nacho-avatar .nacho-name { font-size: 0.65rem; bottom: -40px; padding: 5px 12px; }\n }\n\n /* Bring-back toggle */\n #nacho-toggle {\n position: fixed; bottom: 80px; left: 330px; z-index: 250;\n width: 52px; height: 52px;\n background: radial-gradient(circle, #fff 60%, rgba(255,255,255,0.85) 100%);\n border: 2px solid rgba(247,147,26,0.5);\n border-radius: 50%; display: none; align-items: center; justify-content: center;\n font-size: 1.6rem; cursor: pointer; opacity: 0.9; transition: all 0.3s;\n box-shadow: 0 2px 12px rgba(0,0,0,0.3), 0 0 0 3px rgba(247,147,26,0.15);\n }\n #nacho-toggle:hover { opacity: 1; transform: scale(1.1); box-shadow: 0 4px 20px rgba(247,147,26,0.4), 0 0 0 4px rgba(247,147,26,0.25); }\n @media (max-width: 1100px) { #nacho-toggle { left: 290px; } }\n @media (max-width: 900px) { #nacho-toggle { bottom: calc(50vh - 30px); left: 12px; width: 46px; height: 46px; font-size: 1.3rem; } }\n @media (max-width: 480px) { #nacho-toggle { bottom: calc(50vh - 40px); left: 10px; width: 44px; height: 44px; font-size: 1.2rem; } }\n ",document.head.appendChild(i);const a=document.createElement("div");a.id="nacho-container",h||a.classList.add("hidden");const r=o()?t:e,s=o()?"width:120px;height:100px;":"";a.innerHTML='
    '+r+'Nacho
    click to ask!
    👔📖
    🦌 '+("function"==typeof nachoNickname?nachoNickname():"Nacho")+' says
    ',document.body.appendChild(a);var c=document.getElementById("nachoClosetBtn");if(c){var d=!1;function g(){window._expanded_closet=!0,window._pendingClosetScroll=!0;try{"function"==typeof showSettings&&showSettings();var e=0;setTimeout(function t(){e++;var o=document.getElementById("usernameModal");o&&o.classList.contains("open")&&"function"==typeof showSettingsPage?showSettingsPage("data"):e<10&&setTimeout(t,150)},200)}catch(e){}"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear()}c.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),c.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d=!0},{passive:!1}),c.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),d&&(d=!1,g())},{passive:!1}),c.addEventListener("click",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d||g(),d=!1},!1)}window.updateNachoNotifs=function(){var e=document.getElementById("nachoStoryNotif");if(e){var t=safeJSON("btc_nacho_story_days",[]),o=(new Date).toISOString().split("T")[0],n=t.length,i=-1===t.indexOf(o)&&n<7,a=0===n,r=localStorage.getItem("btc_nacho_story_notif_dismissed")===o;e.style.display=r||!i&&!a?"none":"block"}var s=document.getElementById("nachoClosetNotif");if(s){var l=safeJSON("btc_spin_closet_items",[]),c=safeJSON("btc_closet_viewed",[]),d=l.some(function(e){return-1===c.indexOf(e)});s.style.display=d?"block":"none"}},window.nachoStoryNotifClear=function(){var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_nacho_story_notif_dismissed",e);var t=document.getElementById("nachoStoryNotif");t&&(t.style.display="none")},window.nachoClosetNotifClear=function(){var e=safeJSON("btc_spin_closet_items",[]);localStorage.setItem("btc_closet_viewed",JSON.stringify(e));var t=document.getElementById("nachoClosetNotif");t&&(t.style.display="none")},setTimeout(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},2e3),setInterval(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},6e4);const f=document.createElement("div");function b(){const e=document.getElementById("nachoModeContainer"),t=document.getElementById("irl-sync-view"),o=document.getElementById("searchOverlay"),n=document.querySelector(".ticker-wrap"),i=e&&"none"!==e.style.display||t&&null!==t.offsetParent||o&&"flex"===o.style.display;if(n){n.style.transition="transform 0.4s ease",n.style.transform=i?"translateY(-100%)":"translateY(0)";const e=document.getElementById("menuToggle");e&&(e.style.opacity=i?"0.2":"1")}}f.id="nacho-toggle",f.innerHTML="🦌",f.title="Bring back Nacho",f.onclick=function(){showNacho()},h||(f.style.display="flex"),document.body.appendChild(f),function(){var e=document.getElementById("nacho-avatar");if(e){var t=null,o=!1;e.addEventListener("touchstart",function(e){o=!1,t=setTimeout(function(){o=!0,"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t),o&&(o=!1)}),e.addEventListener("touchmove",function(){clearTimeout(t)}),e.addEventListener("contextmenu",function(e){e.preventDefault(),"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")})}}(),setTimeout(function(){if(h){var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=0;try{o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length}catch(e){}if(t<=3&&o<5){var n=parseInt(localStorage.getItem("btc_nacho_onboarding")||"1");if(k("wave"),1===n?(S('
    Hey there! I\'m Nacho, your Bitcoin education buddy! 🦌🧡

    Here\'s what you can do here:
    📚 Read 145+ Bitcoin topics — tap any in the sidebar
    🎡 Spin daily for free tickets & rewards
    Take quests to test your knowledge

    '),localStorage.setItem("btc_nacho_onboarding","2")):2===n&&o>=1?(S('
    Nice, you explored your first channel! 🎉

    Keep going — every channel you read earns you +10 XP. Here are some popular ones:

    '),localStorage.setItem("btc_nacho_onboarding","3")):3===n&&o>=3?(k("celebrate"),S('
    You\'re on fire! 🔥 '+o+' channels explored!

    Did you know you can:
    🗣️ Chat in PlebTalk — discuss Bitcoin with the community
    Browse LightningMart — buy & sell for sats
    🎓 Take the Scholar Exam — earn your Bitcoin certification

    '),localStorage.setItem("btc_nacho_onboarding","4")):4===n&&o>=5&&(k("brain"),S('
    You\'re becoming a real Bitcoiner! 🧡

    Pro tips:
    📖 Read Nacho\'s Story — a new chapter unlocks each day
    📚 Study with Flashcards to prepare for quests
    🏆 Check the Leaderboard — see where you rank
    💬 Ask me anything about Bitcoin anytime!

    — End of tour. I\'ll still be here if you need me! 🦌
    '),localStorage.setItem("btc_nacho_onboarding","5")),n<=4)return}k((e="function"==typeof nachoTimeGreeting&&Math.random()<.6?nachoTimeGreeting():U(l)).pose),S(e.text),"function"==typeof nachoPlaySound&&nachoPlaySound("pop"),setTimeout(function(){if("function"==typeof nachoStreakMessage){var e=nachoStreakMessage();e&&B(e.text,e.pose)}},12e3)}},2e3),clearInterval(m),m=setInterval(function(){if(!h)return;const e=document.getElementById("nacho-bubble");if(e&&e.classList.contains("show"))return;const t=document.getElementById("nacho-avatar");if(!t)return;p=(p+1)%u.length,k(u[p]),["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(e=>t.classList.remove(e));const o={default:["anim-tap","anim-look","anim-wiggle"],eyes:["anim-lean","anim-look"],think:["anim-lean","anim-tap"],cheese:["anim-bounce","anim-wiggle"],cool:["anim-lean","anim-tap"],sleep:["anim-sleepy"],wave:["anim-wave"],celebrate:["anim-bounce"],fire:["anim-bounce","anim-wiggle"],love:["anim-stretch","anim-tap"],brain:["anim-lean","anim-look"],point:["anim-tap","anim-lean"]}[w]||["anim-tap","anim-wiggle"];t.classList.add(U(o))},8e3),setInterval(z,55e3);const v=window.enterNachoMode;window.enterNachoMode=function(e){"function"==typeof v&&v(e),setTimeout(b,100)};const x=window.exitNachoMode;window.exitNachoMode=function(e){"function"==typeof x&&x(e),setTimeout(b,100)};const T=window.go;window.go=function(e,t,o){"function"==typeof T&&T(e,t,o),setTimeout(b,100)};const _=window.goHome;window.goHome=function(e){"function"==typeof _&&_(e),setTimeout(b,100)},setTimeout(function(){"undefined"!=typeof APP_PAGES&&APP_PAGES.forEach(e=>{"PlebTalk"===e.title&&(e.title="Pleb Talk"),"LightningMart"===e.title&&(e.title="Lightning Mart")})},2e3),window.addEventListener("beforeunload",function(e){const t=document.getElementById("questModal");t&&t.classList.contains("open")&&(e.preventDefault(),e.returnValue="You have an active Quest! Your progress will be lost.")}),window.showSkeletonLoader=function(e,t){const o=document.getElementById(e);if(!o)return;let n='
    ';for(let e=0;e<(t||6);e++)n+='
    ';n+="
    ",o.innerHTML=n},setInterval(function(){var e=document.getElementById("nacho-bubble");if(!h||e&&e.classList.contains("show"))return;const t=Math.random();if(t<.3)k("wave"),setTimeout(()=>k("neutral"),400);else if(t<.6){const e=document.getElementById("nacho-avatar");e&&(e.style.transform="scale(1.1) rotate(5deg)",setTimeout(()=>e.style.transform="",500))}},2e4),setInterval(function(){if(h&&!(y>=12)&&!(Math.random()>.2||window._lastChannelOpenTime&&Date.now()-window._lastChannelOpenTime<3e4)){var e=document.getElementById("nacho-bubble");if(!(e&&e.classList.contains("show")&&"true"===e.getAttribute("data-interactive")||window._nachoMode)){var t=document.getElementById("questModal");t&&t.classList.contains("open")||"function"==typeof showNachoTrivia&&showNachoTrivia()}}},18e4)}function k(e){w=e||"default";const t=document.getElementById("nacho-pose-emoji");t&&(t.textContent=n[w]||n.default)}function B(e,t){!h||y>=12||Date.now()-f<5e4||b.has(e)||T(e,t)}function S(e,t){if(h){var o=document.getElementById("questModal");o&&o.classList.contains("open")||T(e,t)}}function T(e,t){if(window._nachoDirectLinkCooldown&&Date.now()s.classList.remove(e));var l="";if(-1===e.indexOf("'+c[d].label+"";break}var u=-1!==e.indexOf("60&&Math.abs(o)>2*Math.abs(n)&&hideBubble(!0)}},{passive:!0}),function(){var e=!1,t=0,o=0,n=0,i=0,a=!1,r=null;function s(){return document.getElementById("nacho-container")}function l(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;var n=window.innerWidth-40,i=window.innerHeight-40;t.left>=0&&t.left<=n&&t.top>=0&&t.top<=i&&(o.style.left=t.left+"px",o.style.bottom="auto",o.style.top=t.top+"px",o.style.right="auto")}catch(e){}}function c(){var e=s();if(e){var t=document.getElementById("nacho-bubble");if(t){var o=e.getBoundingClientRect(),n=window.innerWidth;window.innerHeight,o.left>n/2?(t.style.marginLeft="",t.style.marginRight="-6px",t.style.alignSelf="flex-end",t.querySelector(":scope"),t.style.setProperty("--bubble-side","right")):(t.style.marginLeft="-6px",t.style.marginRight="",t.style.alignSelf=""),o.top<200?(t.style.order="2",t.style.marginBottom="0",t.style.marginTop="8px"):(t.style.order="",t.style.marginBottom="16px",t.style.marginTop="")}}}setTimeout(l,500),window.addEventListener("resize",function(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;t.left=Math.max(0,Math.min(t.left,window.innerWidth-60)),t.top=Math.max(0,Math.min(t.top,window.innerHeight-60)),o.style.left=t.left+"px",o.style.top=t.top+"px",localStorage.setItem("btc_nacho_position",JSON.stringify(t))}catch(e){}}),document.addEventListener("touchstart",function(l){var c=document.getElementById("nachoDragHandle");if(c&&c.contains(l.target)){l.preventDefault();var d=s();if(d){a=!1,r=d,t=l.touches[0].clientX,o=l.touches[0].clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,e=!0,d.style.transition="none",d.style.opacity="0.85",c.style.background="rgba(247,147,26,0.9)",c.querySelector("span").style.color="#fff"}}},{passive:!1}),document.addEventListener("touchmove",function(s){if(e&&r){var l=s.touches[0].clientX-t,c=s.touches[0].clientY-o;if(!(!a&&Math.abs(l)<8&&Math.abs(c)<8)){a=!0,s.preventDefault(),s.stopPropagation();var d=Math.max(0,Math.min(n+l,window.innerWidth-60)),u=Math.max(0,Math.min(i+c,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}},{passive:!1}),document.addEventListener("touchend",function(t){if(e){e=!1,r&&(r.style.transition="",r.style.opacity="");var o=document.getElementById("nachoDragHandle");if(o){o.style.background="rgba(255,255,255,0.9)";var n=o.querySelector("span");n&&(n.style.color="#888")}if(a&&r){var i=r.getBoundingClientRect(),s=Math.max(0,Math.min(Math.round(i.left),window.innerWidth-60)),l=Math.max(0,Math.min(Math.round(i.top),window.innerHeight-60));r.style.left=s+"px",r.style.top=l+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:s,top:l})),setTimeout(c,50),t.preventDefault()}r=null}},{passive:!1}),document.addEventListener("mousedown",function(l){var c=document.getElementById("nachoDragHandle");if(c&&c.contains(l.target)){var d=s();if(d){e=!0,a=!1,r=d,t=l.clientX,o=l.clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,d.style.transition="none",l.preventDefault()}}}),document.addEventListener("mousemove",function(s){if(e&&r){var l=s.clientX-t,c=s.clientY-o;if(!(!a&&Math.abs(l)<8&&Math.abs(c)<8)){a=!0;var d=Math.max(0,Math.min(n+l,window.innerWidth-60)),u=Math.max(0,Math.min(i+c,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}}),document.addEventListener("mouseup",function(t){if(e){if(e=!1,r&&(r.style.transition=""),a&&r){var o=r.getBoundingClientRect(),n=Math.max(0,Math.min(Math.round(o.left),window.innerWidth-60)),i=Math.max(0,Math.min(Math.round(o.top),window.innerHeight-60));r.style.left=n+"px",r.style.top=i+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:n,top:i})),setTimeout(c,50)}r=null}});var d=window.showNacho;window.showNacho=function(){d.apply(this,arguments),l(),setTimeout(c,200)},setTimeout(c,1e3),document.addEventListener("dblclick",function(e){var t=document.getElementById("nacho-avatar");if(t&&t.contains(e.target)){localStorage.removeItem("btc_nacho_position");var o=s();o&&(o.style.left="",o.style.top="",o.style.bottom="",o.style.right=""),"function"==typeof showToast&&showToast("🦌 Nacho reset to default position!"),setTimeout(c,100)}})}(),window.hideBubble=function(e){var t=document.getElementById("nacho-bubble");if(e||!t||"true"!==t.getAttribute("data-interactive")){window._nachoBusy=!1,localStorage.setItem("btc_nacho_clicked","true"),setTimeout(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},2e3);var o=document.getElementById("nacho-avatar");t&&t.classList.remove("show"),clearTimeout(g),setTimeout(function(){k("default"),o&&o.classList.add("anim-tap")},500)}};let C=0,E=[],A=0;function z(){if(!h||y>=12)return;if(Math.random()>.3)return;if("function"==typeof nachoCheckMilestone){var e=nachoCheckMilestone();if(e)return S(e.text,e.pose),void setTimeout(nachoFly,500)}if("function"==typeof nachoLiveMessage&&Math.random()<.2){var t=nachoLiveMessage();if(t)return void B(t.text,t.pose)}if("function"==typeof checkNachoNewItems){var o=checkNachoNewItems();if(o)return S(o.text,o.pose),void("function"==typeof nachoPlaySound&&nachoPlaySound("coin"))}var n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var l=Math.random(),c=("new"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&l<.15?NACHO_CLOSET_TIPS:l<.6?a:l<.8?r:s:"regular"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&l<.1?NACHO_CLOSET_TIPS:l<.4?s:l<.7?a:r:"undefined"!=typeof NACHO_CLOSET_TIPS&&l<.15?NACHO_CLOSET_TIPS:l<.65?s:l<.9?r:a).filter(e=>!b.has(e.text));if(0===c.length&&0===(c=[...s,...r].filter(e=>!b.has(e.text))).length)return;const d=U(c);B(d.text,d.pose)}window.nachoClick=function(){if(window._nachoActionClicked)return void(window._nachoActionClicked=!1);const e=Date.now();if(E.push(e),E.length>3&&E.shift(),3===E.length&&E[2]-E[0]<600&&e-A>5e3)return E=[],A=e,v=e,"function"==typeof nachoFly&&nachoFly(),void S(personalize("Wheeeee! ⚡🦌⚡"));if(E.length>=2&&E[E.length-1]-E[E.length-2]<400&&E.length<3)return E=[],v=e,"function"==typeof hideNacho&&hideNacho(),void("function"==typeof showToast&&showToast("🦌 Nacho hidden — tap the 🦌 button to bring him back!"));if(e-v<1500)return;v=e,localStorage.setItem("btc_nacho_clicked","true"),"function"==typeof checkHiddenBadges&&checkHiddenBadges(),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoPlaySound&&nachoPlaySound("click");const t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show"))return void hideBubble();if(C++,C%3==0&&"function"==typeof showNachoInput)return void showNachoInput();var o,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var l=(o="new"===i?[...a,...a,...r,...s]:"regular"===i?[...a,...s,...s,...r]:[...s,...s,...s,...r]).filter(e=>!b.has(e.text));const c=U(l.length>3?l:o);f=0,k(c.pose),S(c.text,c.pose)},window.showNacho=function(){h=!0,localStorage.removeItem("btc_nacho_hidden"),document.getElementById("nacho-container").classList.remove("hidden"),document.getElementById("nacho-toggle").style.display="none",f=0;var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=void 0!==currentUser&¤tUser&¤tUser.channelsVisited||0;if(t<=2&&o<3&&!localStorage.getItem("btc_nacho_tour_shown"))return[{text:"Welcome to the Bitcoin Education Archive, {name}! I'm Nacho, your deer guide! 🦌",pose:"wave",delay:0},{text:"Click the grid icons to explore Bitcoin topics. Start with the orange ones — they're beginner-friendly! 📚",pose:"point",delay:4e3},{text:"See the 🔥 number? That's your streak! Come back daily to keep it growing. ⚡",pose:"fire",delay:8e3},{text:"Tap me anytime to chat, or double-tap to enter Nacho Mode for deep conversations! 💬",pose:"cheese",delay:12e3}].forEach(function(e,t){setTimeout(function(){t>0&&k(e.pose),S(personalize(e.text))},e.delay)}),void localStorage.setItem("btc_nacho_tour_shown","true");if(t>2&&t<=10&&o<10){var n=["Pro tip {name}: Use the ⚡ tab to check the Bitcoin price anytime! 📈","Did you know? Completing a Quest earns you bonus Orange Tickets! 🎟️","Try tapping the Menu (☰) to see your progress on the Exploration Map! 🗺️","You can customize my outfit in Settings → Stats/Nacho → Closet! 👔"];e=n[Math.floor(Math.random()*n.length)],k("cool")}else if(t>20){var i=["Tick tock, next block! Ready for some high-signal learning, {name}? 🧱","Welcome back, master HODLer! I've been keeping the Archive warm for you. 🦌🔥","I noticed you've visited many channels. Want to test your knowledge with a Quest today? ⚡","Back for your daily dose of decentralization? Let's dive in! 📘"];e=i[Math.floor(Math.random()*i.length)],k("brain")}else if(t>5){var a=["Hey {name}, great to see you again! ✨","Welcome back! Ready to stack some more knowledge? 📚","I missed you! Check out my closet if you've earned new items! 👔","You're making great progress on your Exploration Map! 🗺️"];e=a[Math.floor(Math.random()*a.length)],k("wave")}else e="I'm back, {name}! Miss me? 🦌",k("wave");S(personalize(e))},window.hideNacho=function(){h=!1,localStorage.setItem("btc_nacho_hidden","user"),document.getElementById("nacho-container").classList.add("hidden"),document.getElementById("nacho-toggle").style.display="flex"},window.nachoOnPage=function(e){var t;if(h&&("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoNickname&&nachoNickname(),"forum"===e?t=[{pose:"wave",text:personalize("Welcome to PlebTalk, {name}! 🗣️ This is where Bitcoiners discuss ideas. Jump in!")},{pose:"point",text:"💡 Post a new topic to earn +10 points, or reply to an existing one for +5. Quality content gets upvoted!"},{pose:"brain",text:"Remember — this is a Bitcoin-only space. Stay respectful, stay on topic, and attack ideas, not people! 🤝"},{pose:"cheese",text:personalize("Psst {name}... earn the 📣 Town Crier badge by posting in PlebTalk! Your first post counts!")},{pose:"fire",text:"🔥 Pro tip: Upvote posts you find valuable with ⚡ — it helps the best content rise to the top!"}]:"marketplace"===e&&(t=[{pose:"wave",text:personalize("Welcome to LightningMart, {name}! ⚡ Buy and sell with Bitcoin — the way it should be!")},{pose:"point",text:"💡 All prices are in sats. Sellers set their own prices. Payments happen directly between buyer and seller."},{pose:"cheese",text:"🛒 List your first item to earn the 🏪 Merchant badge! Books, hardware, merch — whatever you've got!"},{pose:"brain",text:"🛡️ Safety first! Meet in public for local trades, use Lightning for instant payments, and report suspicious listings."},{pose:"fire",text:personalize("Pro tip {name}: add a Lightning address to your listing so buyers can pay you instantly! ⚡")}]),t)){var o=t[Math.floor(Math.random()*t.length)];S(o.text,o.pose)}},window.nachoOnChannel=function(e){if(h){if("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoChannelIntro){var t=nachoChannelIntro(e);if(t)return void S(t.text,t.pose)}if("function"==typeof nachoCategoryCheck){var o=nachoCategoryCheck(e);if(o)return S(o.text,o.pose),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),void setTimeout(nachoFly,500)}if(i[e]&&Math.random()<.6){const t=i[e];return void B(t.text,t.pose)}if(parseInt(sessionStorage.getItem("btc_channel_read_seconds")||"0")>=30+Math.floor(90*Math.random())&&Math.random()<.3&&"undefined"!=typeof QUEST_QUESTIONS&&QUEST_QUESTIONS.length>0){var n=void 0!==CHANNELS?CHANNELS[e]:null,a=n?n.cat:"",r=QUEST_QUESTIONS.filter(function(e){return e.category&&a&&-1!==e.category.toLowerCase().indexOf(a.toLowerCase().split(" ")[0])});0===r.length&&(r=QUEST_QUESTIONS);for(var s=r[Math.floor(Math.random()*r.length)],l='
    🎮 Quick Quiz!
    '+s.question+"
    ",d=s.options||[],u=0;u'+d[u]+"";return S(l,"brain"),void sessionStorage.setItem("btc_channel_read_seconds","0")}if(Math.random()<.25){const e=U(c);B(e.text,e.pose)}}},window.nachoBubbleQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n=e.parentElement,i=n.querySelectorAll("button");if(i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1";var a=document.createElement("div");a.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#22c55e;",a.textContent="✅ Correct! +5 pts",n.appendChild(a),"function"==typeof awardPoints&&awardPoints(5,"🎮 Quiz correct!"),"function"==typeof haptic&&haptic("success")}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("true")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var r=document.createElement("div");r.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#ef4444;",r.textContent="❌ Not quite! The correct answer is highlighted.",n.appendChild(r)}clearTimeout(g);var s=document.getElementById("nacho-bubble");s&&s.setAttribute("data-interactive","true")},window.nachoOnPoints=function(e){if(!h)return;if(e>=250)return void setTimeout(nachoFly,500);if(Math.random()>.2)return;const t=U(d);B(t.text,t.pose)},window.nachoFly=function(){var e=document.getElementById("nacho-avatar");if(e&&!e.classList.contains("flying")){["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(function(t){e.classList.remove(t)}),e.classList.add("flying");var t="false"!==localStorage.getItem("btc_nacho_sound"),o=[1200,1800,1400,2200,1600,2800];[0,400,800,1200,1600,2e3].forEach(function(n,i){setTimeout(function(){t&&e.classList.contains("flying")&&function(e){if("function"!=typeof canPlaySound||canPlaySound())try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();o.connect(n),n.connect(t.destination),o.frequency.value=e,o.type="sawtooth",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.12),o.start(t.currentTime),o.stop(t.currentTime+.12)}catch(e){}}(o[i])},n)});var n=["⚡","✨","🔥","⚡","💫","⚡"],i=setInterval(function(){if(e.classList.contains("flying")){var t=e.getBoundingClientRect(),o=document.createElement("div");o.className="nacho-trail",o.textContent=n[Math.floor(Math.random()*n.length)],o.style.left=t.left+t.width/2+(20*Math.random()-10)+"px",o.style.top=t.top+t.height/2+(20*Math.random()-10)+"px",document.body.appendChild(o),setTimeout(function(){o.parentNode&&o.remove()},600)}else clearInterval(i)},40);e.addEventListener("animationend",function o(){if(e.classList.remove("flying"),e.classList.add("anim-bounce"),e.removeEventListener("animationend",o),clearInterval(i),t&&("function"!=typeof canPlaySound||canPlaySound()))try{var n=new(window.AudioContext||window.webkitAudioContext),a=n.createOscillator(),r=n.createGain();a.connect(r),r.connect(n.destination),a.frequency.value=300,a.type="sine",r.gain.setValueAtTime(.08,n.currentTime),r.gain.exponentialRampToValueAtTime(.001,n.currentTime+.2),a.start(n.currentTime),a.stop(n.currentTime+.2)}catch(e){}})}},window.nachoOnQuest=function(e){h&&(f=0,e?(k("celebrate"),S(personalize("{name}, you CRUSHED that quest! This buck is VERY impressed! 🦌🎉🔥")),setTimeout(nachoFly,500)):(k("love"),S(personalize("Hey {name}, some questions are hard! Read up and try again — Nacho believes in you! 🦌💪"))))},window.nachoOnSearch=function(){!h||Math.random()>.3||B("Looking for something? I'd help search but I don't have thumbs. Good luck! 🔍🦌","think")},window.nachoOnFinishChannel=function(){if(!h||Math.random()>.3)return;const e=U([{pose:"celebrate",text:"You read the whole thing! Dedicated. I respect that. 🦌👏"},{pose:"point",text:"All done? Hit the 🎲 to find your next channel!"},{pose:"fire",text:"Knowledge: stacked. You're a machine! 💪"}]);B(e.text,e.pose)},window.nachoUserName=function(){return void 0!==currentUser&¤tUser&¤tUser.username?String(currentUser.username).replace(//g,">").replace(/"/g,"""):""};let M=0,P=0,L=!1;function U(e){return e[Math.floor(Math.random()*e.length)]}window.DeviceMotionEvent&&window.addEventListener("devicemotion",function(e){if(h&&!L){var t=e.accelerationIncludingGravity;if(t&&Math.sqrt(t.x*t.x+t.y*t.y+t.z*t.z)>28){var o=Date.now();o-M>1e3&&(P=0),M=o,P++,P>=2&&(L=!0,P=0,"function"==typeof haptic&&haptic("heavy"),"function"==typeof nachoFly&&nachoFly(),S(personalize("Whoa, {name}! Too much coffee? ⚡🦌🌪️")),setTimeout(function(){L=!1},3e3))}}},!0),window.personalize=function(e){var t=nachoUserName();if(e=t?e.replace(/\{name\}/g,t):e.replace(/,?\s*\{name\}\s*,?\s*/g,function(e){return 0===e.indexOf(",")&&e.lastIndexOf(",")>0?", ":","===e.charAt(0)?" ":""}),window._btcData){var o=window._btcData.price;if(!o)try{o=parseFloat(localStorage.getItem("btc_last_price"))}catch(e){}const t=o?"$"+Math.round(o).toLocaleString():"over $60,000",n=window._btcData.height?window._btcData.height.toLocaleString():"over 840,000",i=window._btcData.halvingBlocks?window._btcData.halvingBlocks.toLocaleString():"less than 150,000";e=(e=(e=e.replace(/\{price\}/g,t)).replace(/\{height\}/g,n)).replace(/\{halving\}/g,i)}return e.replace(/ +/g," ").replace(/^ ,/,"").replace(/, ,/g,",").trim()};let q=null;document.addEventListener("DOMContentLoaded",function(){setTimeout(function(){const e=document.getElementById("nacho-avatar");function t(e){"touchstart"===e.type&&e.preventDefault(),q=setTimeout(function(){hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho is hiding. Click the small 🦌 to bring him back!")},800)}function o(){clearTimeout(q)}e&&(e.addEventListener("mousedown",t),e.addEventListener("mouseup",o),e.addEventListener("mouseleave",o),e.addEventListener("touchstart",t,{passive:!1}),e.addEventListener("touchend",o),e.addEventListener("touchmove",o))},1e3)}),document.addEventListener("click",function(e){var t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show")){var o=document.getElementById("nacho-container");o&&o.contains(e.target)||hideBubble(!0)}}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",x):x(),function(){var e="btc_nacho_position",t=null,o=null,n=!1,i=0,a=0,r=0,s=0,l=!1;function c(){return t||(t=document.getElementById("nacho-container")),t}function d(){return o||(o=document.getElementById("nachoDragHandle")),o}function u(){try{var t=JSON.parse(localStorage.getItem(e));if(t&&"number"==typeof t.left&&"number"==typeof t.bottom){var o=c();if(o){var n=window.innerWidth-80,i=window.innerHeight-80,a=Math.max(0,Math.min(t.left,n)),r=Math.max(0,Math.min(t.bottom,i));o.style.left=a+"px",o.style.bottom=r+"px",o.style.right="auto",o.style.top="auto",o.style.position="fixed"}}}catch(e){}}function p(t,o){try{localStorage.setItem(e,JSON.stringify({left:t,bottom:o}))}catch(e){}}function m(e,t){var o=c();if(o){n=!0,l=!1,i=e,a=t;var u=o.getBoundingClientRect();r=u.left,s=window.innerHeight-u.bottom,o.style.transition="none",o.style.cursor="grabbing";var p=d();p&&(p.style.cursor="grabbing")}}function h(e,t){if(n){var o=e-i,d=t-a;if(l||!(Math.abs(o)+Math.abs(d)<8)){l=!0;var u=c();if(u){var p=r+o,m=s-d;p=Math.max(0,Math.min(p,window.innerWidth-80)),m=Math.max(0,Math.min(m,window.innerHeight-80)),u.style.left=p+"px",u.style.bottom=m+"px",u.style.right="auto",u.style.top="auto",u.style.position="fixed"}}}}function g(){if(n){n=!1;var e=c();if(e&&(e.style.transition="",e.style.cursor="",l)){var t=e.getBoundingClientRect();p(t.left,window.innerHeight-t.bottom)}var o=d();o&&(o.style.cursor="grab")}}function f(){var e=d();if(e){if(!e._dragInit){e._dragInit=!0,e.addEventListener("mousedown",function(e){e.preventDefault(),e.stopPropagation(),m(e.clientX,e.clientY)}),document.addEventListener("mousemove",function(e){n&&(e.preventDefault(),h(e.clientX,e.clientY))}),document.addEventListener("mouseup",g),e.addEventListener("touchstart",function(e){1===e.touches.length&&(e.stopPropagation(),m(e.touches[0].clientX,e.touches[0].clientY))},{passive:!0}),document.addEventListener("touchmove",function(e){n&&1===e.touches.length&&h(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("touchend",function(){n&&g()});var t=document.getElementById("nacho-avatar");t&&t.addEventListener("click",function(e){l&&(e.stopPropagation(),e.preventDefault(),l=!1)},!0),u(),function(){var e=document.getElementById("nacho-toggle");if(e&&!e._dragInit){e._dragInit=!0;var t=!1,o=0,n=0,i=0,a=0,r=!1;e.addEventListener("mousedown",function(s){t=!0,r=!1,o=s.clientX,n=s.clientY;var l=e.getBoundingClientRect();i=l.left,a=window.innerHeight-l.bottom,e.style.transition="none"}),e.addEventListener("touchstart",function(s){if(1===s.touches.length){t=!0,r=!1,o=s.touches[0].clientX,n=s.touches[0].clientY;var l=e.getBoundingClientRect();i=l.left,a=window.innerHeight-l.bottom,e.style.transition="none"}},{passive:!0}),document.addEventListener("mousemove",function(e){s(e.clientX,e.clientY)}),document.addEventListener("touchmove",function(e){t&&1===e.touches.length&&s(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("mouseup",l),document.addEventListener("touchend",l),e.addEventListener("click",function(e){r&&(e.stopPropagation(),e.preventDefault(),r=!1)},!0)}function s(s,l){if(t){var c=s-o,d=l-n;if(r||!(Math.abs(c)+Math.abs(d)<8)){r=!0;var u=Math.max(0,Math.min(i+c,window.innerWidth-50)),p=Math.max(0,Math.min(a-d,window.innerHeight-50));e.style.left=u+"px",e.style.bottom=p+"px",e.style.right="auto",e.style.top="auto"}}}function l(){if(t&&(t=!1,e.style.transition="",r)){var o=e.getBoundingClientRect();p(o.left,window.innerHeight-o.bottom)}}}(),window.addEventListener("resize",function(){u()})}}else setTimeout(f,1e3)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(f,500)}):setTimeout(f,500)}(),setInterval(function(){document.querySelectorAll(".nacho-trail").forEach(function(e){e.remove()})},3e3),window.updateNachoAvatarForPage=function(){var n=document.getElementById("nacho-avatar");if(n){var i=o();if(i!==("1"===n.getAttribute("data-tctv"))){n.setAttribute("data-tctv",i?"1":"0"),i?(n.style.width="120px",n.style.height="100px",n.innerHTML=t+'Nacho
    click to ask!
    👔📖
    '):(n.style.width="",n.style.height="",n.innerHTML=e+'Nacho
    click to ask!
    👔📖
    ');var a=document.getElementById("nachoClosetBtn");if(a){var r=!1;a.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),a.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),r=!0},{passive:!1}),a.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),r&&(r=!1,window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},200),"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear())},{passive:!1})}}}};var N=window.go;N&&(window.go=function(){var e=N.apply(this,arguments);return setTimeout(window.updateNachoAvatarForPage,100),e})}(),function(){window.nachoTimeGreeting=function(){var e=(new Date).getHours(),t=((new Date).getDay(),"function"==typeof nachoUserName?nachoUserName():""),o=t?", "+t:"";return e>=5&&e<12?{pose:"wave",text:"Good morning"+o+"! ☀️ Ready to learn some Bitcoin today?"}:e>=12&&e<17?{pose:"wave",text:"Good afternoon"+o+"! 🌤️ Let's stack some knowledge!"}:e>=17&&e<21?{pose:"wave",text:"Good evening"+o+"! 🌅 Great time to dive into some Bitcoin education!"}:e>=21||e<2?{pose:"cool",text:"Late night study session"+o+"? 🌙 Respect! The night owl and the night deer, learning together. 🦉🦌"}:{pose:"sleep",text:"Whoa"+o+", it's the middle of the night! 😴 Your dedication is legendary. Most deer would be asleep right now!"}},window.nachoStreakMessage=function(){if(void 0===currentUser||!currentUser)return null;var e=currentUser.streak||0,t="function"==typeof nachoUserName?nachoUserName():"",o=t?", "+t:"";return e>=30?{pose:"fire",text:e+"-day streak"+o+"! You're absolutely unstoppable! 🔥🦌👑"}:e>=14?{pose:"fire",text:e+"-day streak"+o+"! Two weeks straight! You're a machine! 🔥💪"}:e>=7?{pose:"celebrate",text:e+"-day streak"+o+"! A whole week! Nacho is very impressed! 🎉🔥"}:e>=3?{pose:"love",text:e+"-day streak"+o+"! Keep it going! 🔥"}:null};const e=[100,250,500,1e3,2100,5e3,1e4,21e3];window.nachoCheckMilestone=function(){if(void 0===currentUser||!currentUser)return null;for(var t=currentUser.points||0,o=JSON.parse(localStorage.getItem("btc_nacho_milestones")||"[]"),n="function"==typeof nachoUserName?nachoUserName():"",i=n?", "+n:"",a=[],r=0;r=s&&!o.includes(s)&&(a.push(s),o.push(s))}if(0===a.length)return null;localStorage.setItem("btc_nacho_milestones",JSON.stringify(o)),"function"==typeof syncCelebratedState&&syncCelebratedState();var l=a[0],c="function"==typeof getLevel?getLevel(t):null,d=c?" You're now rank: "+c.emoji+" "+c.name+"!":"";if(a.length>1&&"function"==typeof forceShowBubble)for(var u=1;u=3){var s=r.wrong.slice(0,3),l=Math.floor(4*Math.random());s.splice(l,0,r.a),e.push({q:r.q,options:s,correct:l,pts:10,_fromBank:!0})}}}var c=JSON.parse(localStorage.getItem("btc_nacho_trivia_asked")||"[]");c.length>.8*e.length&&(c=[],localStorage.removeItem("btc_nacho_trivia_asked"));var d=e.filter(function(e,t){return!c.includes(e._fromBank?"qb_"+e.q.substring(0,30):t)});if(0===d.length)return null;var u=d[Math.floor(Math.random()*d.length)],p=u._fromBank?"qb_"+u.q.substring(0,30):e.indexOf(u);return c.push(p),localStorage.setItem("btc_nacho_trivia_asked",JSON.stringify(c)),{trivia:u,index:idx}},window.showNachoTrivia=function(){if(window._nachoBusy)return!1;var e=nachoTrivia();if(!e)return!1;var t=e.trivia,o=document.getElementById("nacho-bubble"),n=document.getElementById("nacho-text");if(!o||!n)return!1;"function"==typeof setPose&&setPose("think"),o.setAttribute("data-interactive","true"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout();for(var i='
    🧠 Quick Trivia! (+'+t.pts+' pts)
    '+t.q+"
    ",a=0;a'+String.fromCharCode(65+a)+". "+t.options[a]+"";return n.innerHTML=i,o.classList.add("show"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout(),!0},window.nachoTriviaAnswer=function(e,t,o,n){for(var i=n.parentElement.querySelectorAll("button"),a=0;a","function"==typeof setPose&&setPose("celebrate");else{var d=Math.max(2,Math.floor(o/3));"function"==typeof awardPoints&&awardPoints(d,"🧠 Nice try!"),s.innerHTML+='
    ❌ Not quite'+c+"! The answer was "+String.fromCharCode(65+t)+". +"+d+" pts for trying! 📚
    ","function"==typeof setPose&&setPose("love")}s.innerHTML+='',s.innerHTML+=''},window.getNachoFriendship=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?{level:5,name:"Best Buds",emoji:"💛"}:e>=350?{level:4,name:"Close Friends",emoji:"🧡"}:e>=100?{level:3,name:"Good Friends",emoji:"😊"}:e>=10?{level:2,name:"Getting Acquainted",emoji:"👋"}:e>=1?{level:1,name:"Just Met",emoji:"🦌"}:{level:0,name:"Strangers",emoji:"❓"}},window.trackNachoInteraction=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0")+1;if(localStorage.setItem("btc_nacho_interactions",e.toString()),window._nachoLastInteraction=Date.now(),void 0!==db&&void 0!==auth&&auth.currentUser){var t=parseInt(localStorage.getItem("btc_nacho_questions")||"0");try{db.collection("users").doc(auth.currentUser.uid).update({nachoInteractions:e,nachoQuestions:t})}catch(e){}}"function"==typeof renderProgressRings&&renderProgressRings()};const i={mining:["How does the difficulty adjustment work?","What is a halving?","Is mining bad for the environment?","What is a nonce?","Can I mine at home?","What is an ASIC?"],wallet:["What is a seed phrase?","What is self-custody?","What is a hardware wallet?","How do I back up my wallet?","What is multisig?","Which wallet is best for beginners?"],lightning:["How fast is Lightning?","What are sats?","How do I get a Lightning Address?","What is a payment channel?","What is LNURL?","Can I tip people with Lightning?"],halving:["What is the block reward?","When is the next halving?","Why does the price go up after halving?","How many halvings are left?","What happens when all Bitcoin are mined?"],price:["Is it too late to buy?","What is DCA?","Why is Bitcoin volatile?","How high can Bitcoin go?","What is stock-to-flow?"],"self-custody":["What is a seed phrase?","What wallets do you recommend?","What does HODL mean?","What is cold storage?","What is a passphrase?"],privacy:["What is CoinJoin?","What is non-KYC Bitcoin?","Is Bitcoin anonymous?","What are silent payments?","What is Nostr?"],basics:["How does mining work?","What is the Lightning Network?","Who created Bitcoin?","What is a sat?","Why is there only 21 million?"],fud:["Is Bitcoin bad for the environment?","Can Bitcoin be hacked?","Will governments ban Bitcoin?","What about quantum computers?","Is Bitcoin a Ponzi scheme?"],node:["Why should I run a node?","What is a full node?","How does consensus work?","What is Nakamoto Consensus?"],taproot:["What is Schnorr?","What are covenants?","What is MuSig2?","What is OP_CAT?"],security:["What is a 51% attack?","How secure is Bitcoin?","What is proof of work?","Can Bitcoin be hacked?"],scarcity:["Why only 21 million?","What makes Bitcoin scarce?","What is inflation?","Bitcoin vs gold?"],layer:["What is Lightning Network?","What are sidechains?","What is the Liquid Network?","What are channel factories?"],economics:["What is sound money?","What is the Cantillon Effect?","What is time preference?","Why is fiat bad?"],satoshi:["Why did Satoshi disappear?","Who is Hal Finney?","What is the Genesis Block?","Is Craig Wright Satoshi?"],nostr:["What is Nostr?","How do I use Nostr?","What are Nostr relays?","Can I sign in with Nostr?"],regulation:["Can Bitcoin be banned?","What happened when China banned Bitcoin?","Is Bitcoin legal?","What about the SEC?"],altcoin:["Why is Bitcoin different from altcoins?","What about Ethereum?","Are meme coins worth it?","Why Bitcoin only?"],invest:["What is DCA?","How much should I invest?","Is now a good time to buy?","What is HODL?"],history:["What is Pizza Day?","What are the blocksize wars?","When was the first transaction?","What is the Genesis Block?"],energy:["Does Bitcoin waste energy?","How much energy does mining use?","Is Bitcoin green?","What is stranded energy?"]};var a=[];window.nachoFollowUps=function(e){if(!e)return[];var t=e.toLowerCase(),o=[];for(var n in i)t.includes(n)&&(o=o.concat(i[n]));0===o.length&&(o=["What is Bitcoin?","How do I get started?","What is the Lightning Network?","Who created Bitcoin?","Why is there only 21 million?","What is self-custody?"]);var r=window._nachoAskedQuestions||[],s=o.filter(function(e){return-1===a.indexOf(e)&&-1===r.indexOf(e.toLowerCase())});s.length<3&&(a=[],s=o.filter(function(e){return-1===r.indexOf(e.toLowerCase())})),0===s.length&&(s=o),s.sort(function(){return Math.random()-.5});var l=Math.min(Math.max(3,s.length),5),c=s.slice(0,l);return(a=a.concat(c)).length>30&&(a=a.slice(-15)),c},window.trackNachoQuestion=function(e,t){try{var o=JSON.parse(localStorage.getItem("btc_nacho_analytics")||"[]");o.push({q:e.substring(0,100),matched:t,t:Date.now()}),o.length>100&&(o=o.slice(-100)),localStorage.setItem("btc_nacho_analytics",JSON.stringify(o))}catch(e){}};let r="false"!==localStorage.getItem("btc_nacho_sound");window.nachoPlaySound=function(e){if(("function"!=typeof canPlaySound||canPlaySound())&&r)try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();if(o.connect(n),n.connect(t.destination),n.gain.value=.08,"pop"===e)o.frequency.value=800,o.type="sine",n.gain.setValueAtTime(.08,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.15),o.start(t.currentTime),o.stop(t.currentTime+.15);else if("coin"===e){o.frequency.value=1200,o.type="sine",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.3),o.start(t.currentTime),o.stop(t.currentTime+.3);var i=t.createOscillator();i.connect(n),i.frequency.value=1600,i.type="sine",i.start(t.currentTime+.1),i.stop(t.currentTime+.3)}else"click"===e?(o.frequency.value=600,o.type="triangle",n.gain.setValueAtTime(.05,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.08),o.start(t.currentTime),o.stop(t.currentTime+.08)):"tctv-beep"===e&&(o.frequency.value=2400,o.type="square",n.gain.setValueAtTime(.03,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.06),o.start(t.currentTime),o.stop(t.currentTime+.06))}catch(e){}},window.toggleNachoSound=function(){return r=!r,localStorage.setItem("btc_nacho_sound",r.toString()),r};let s=[];window.nachoAddContext=function(e){s.push(e),s.length>5&&s.shift()},window.nachoGetContext=function(){return s},setTimeout(function(){if("1"!==localStorage.getItem("btc_ln_prompt_dismissed")){var e=void 0!==currentUser?currentUser:null;if(e&&e.username&&!e.lightning&&!e.lightningAddress){var t=[];try{t=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}t.length<5||"function"==typeof forceShowBubble&&(forceShowBubble("⚡ Hey "+(e.username||"friend")+"! Connect a Lightning wallet to tip other users and receive tips! Tap me to learn how. 🦌",function(){go("lightning")}),localStorage.setItem("btc_ln_prompt_dismissed","1"))}}},3e4),function(){var e="btc_smart_nudges";function t(){try{return JSON.parse(localStorage.getItem(e)||"{}")}catch(e){return{}}}function o(e){var o=t();return!o[e]||Date.now()-o[e]>864e5}function n(){if("function"==typeof forceShowBubble&&!(Date.now()-(window._sessionStart||Date.now())<3e4)){var n=document.getElementById("nacho-bubble");if(!(n&&n.classList.contains("show")||window._nachoBusy)){var i,a,r=[];if(void 0!==BADGE_DEFS&&void 0!==earnedBadges){var s=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length;!earnedBadges.has("explorer_10")&&s>=7&&o("near_explorer_10")&&r.push({id:"near_explorer_10",text:"You've visited "+s+" topics — just "+(10-s)+" more to earn the Explorer badge! 🧭 Keep exploring!"}),!earnedBadges.has("explorer_25")&&s>=20&&s<25&&o("near_explorer_25")&&r.push({id:"near_explorer_25",text:"Only "+(25-s)+" more topics to unlock Trailblazer! 🗺️ You're so close!"});var l=void 0!==currentUser&¤tUser&¤tUser.streak||0;!earnedBadges.has("streak_7")&&l>=5&&l<7&&o("near_streak_7")&&r.push({id:"near_streak_7",text:l+"-day streak! 🔥 Just "+(7-l)+" more days for the Week Warrior badge! Don't break it!"}),!earnedBadges.has("streak_30")&&l>=25&&l<30&&o("near_streak_30")&&r.push({id:"near_streak_30",text:l+"-day streak! 💪 "+(30-l)+" more days to Monthly Maxi! That's legendary dedication!"}),!earnedBadges.has("streak_100")&&l>=90&&l<100&&o("near_streak_100")&&r.push({id:"near_streak_100",text:l+"-day streak! 💎 "+(100-l)+" days from Diamond Hands! You're in the top tier!"});var c=parseInt(localStorage.getItem("btc_chat_msgs")||"0");!earnedBadges.has("chat_50")&&c>=40&&c<50&&o("near_chat_50")&&r.push({id:"near_chat_50",text:c+" chat messages! Just "+(50-c)+" more to become a Conversationalist! 🎤 Head to Global Chat!"});var d=parseInt(localStorage.getItem("btc_pvp_wins")||"0");!earnedBadges.has("pvp_5")&&d>=3&&d<5&&o("near_pvp_5")&&r.push({id:"near_pvp_5",text:d+" PVP wins! ⚔️ "+(5-d)+" more to unlock Contender! Ready for a battle?"});var u=void 0!==completedQuests&&completedQuests.size||0;!earnedBadges.has("quest_3")&&u>=2&&u<3&&o("near_quest_3")&&r.push({id:"near_quest_3",text:"You've completed "+u+" quests! One more for the Quest Master badge! ⚔️ Try a quest after reading!"});var p=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0");!earnedBadges.has("tctv_couch_potato")&&p>=45&&p<60&&o("near_tctv_60")&&r.push({id:"near_tctv_60",text:p+" minutes of Timechain TV! 📺 Just "+(60-p)+" more for Couch Potato! Grab some popcorn! 🍿"}),localStorage.getItem("btc_last_spin_date")!==(new Date).toDateString()&&o("daily_spin")&&r.push({id:"daily_spin",text:"You haven't spun the daily wheel yet! 🎡 Free tickets and prizes await!"})}if(r.length>0){var m=r[Math.floor(Math.random()*r.length)];i=m.id,(a=t())[i]=Date.now(),localStorage.setItem(e,JSON.stringify(a)),forceShowBubble(m.text)}}}}setTimeout(function(){n(),setInterval(n,3e5)},12e4),window.checkSmartNudges=n}()}(),window.nachoNickname=function(){return localStorage.getItem("btc_nacho_nickname")||"Nacho"},function(){const e=[{id:"orange_scarf",category:"shirt",name:"Bitcoin Scarf",emoji:"🧣",desc:"A cozy orange scarf with the ₿ symbol.",level:1,overlay:{top:"68%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"sunglasses",category:"glasses",name:"Cool Shades",emoji:"🕶️",desc:"Sunglasses so cool, even the blockchain can't see through them.",level:1,overlay:{top:"43%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"bowtie",category:"shirt",name:"Fancy Bowtie",emoji:"🎀",desc:"A dapper bowtie for a distinguished buck. Class and sats.",level:1,overlay:{top:"64%",left:"50%",transform:"translateX(-50%)",fontSize:"1.3em"},hidden:!1,colorable:!0},{id:"mining_helmet",category:"hat",name:"Mining Helmet",emoji:"⛑️",desc:"A safety helmet for a hardworking miner. Ready to find the next block!",level:2,overlay:{top:"5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"lightning_chain",category:"glasses",name:"Lightning Chain",emoji:"⚡",desc:"A chain necklace with a Lightning bolt pendant.",level:2,overlay:{top:"65%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"party_hat",category:"hat",name:"Party Hat",emoji:"🎉",desc:"Every day is a party when you're stacking sats!",level:2,overlay:{top:"2%",left:"58%",transform:"translateX(-50%) rotate(15deg)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"hodl_hoodie",category:"shirt",name:"HODL Hoodie",emoji:"🧥",desc:"A hoodie that says HODL on the back. For diamond-handed deer.",level:3,overlay:{top:"72%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1,colorable:!0},{id:"laser_eyes",category:"glasses",name:"Laser Eyes",emoji:"🔴",desc:"The legendary Bitcoin laser eyes. Number go up!",level:3,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"0.9em",custom:"🔴 🔴"},hidden:!1,colorable:!0},{id:"wizard_hat",category:"hat",name:"Wizard Hat",emoji:"🪄",desc:"A mystical wizard hat. Nacho casts spells of financial sovereignty!",level:3,overlay:{top:"-5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!1,colorable:!0},{id:"crown",category:"hat",name:"Royal Crown",emoji:"👑",desc:"Fit for the king of cryptocurrency. There is no second best!",level:3,overlay:{top:"3%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"steak",category:"glasses",name:"Proof of Steak",emoji:"🥩",desc:"A juicy steak for a hardworking buck. Proof of Steak > Proof of Stake!",level:4,overlay:{top:"58%",right:"-18%",fontSize:"1.8em",transform:"rotate(20deg)"},hidden:!1},{id:"diamond_hooves",category:"glasses",name:"Diamond Hooves",emoji:"💎",desc:"Diamond hooves for a deer with diamond hands. Never selling!",level:4,overlay:{bottom:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em",custom:"💎💎"},hidden:!1},{id:"astronaut",category:"hat",name:"Moon Helmet",emoji:"🪖",desc:"To the moon! A space helmet for the ultimate HODLer.",level:4,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1},{id:"cape_permanent",category:"shirt",name:"Hero Cape",emoji:"🦸",desc:"A permanent cape for a Bitcoin hero. Earned, not given!",level:4,overlay:{top:"55%",right:"-15%",fontSize:"2.4em",transform:"rotate(-12deg)"},hidden:!1,colorable:!0},{id:"golden_antlers",category:"hat",name:"???",emoji:"✨",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"0.5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Golden Antlers",revealEmoji:"✨",revealDesc:"Antlers plated in pure gold. Only the closest friends get to see these shine!"},{id:"satoshi_cloak",category:"shirt",name:"???",emoji:"🧥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"68%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Satoshi's Cloak",revealEmoji:"🧥",revealDesc:"A mysterious cloak worn by Satoshi himself. Legend says it grants anonymity to any deer who wears it."},{id:"flame_aura",category:"glasses",name:"???",emoji:"🔥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"25%",left:"50%",transform:"translateX(-50%)",fontSize:"3.5em"},hidden:!0,revealName:"Flame Aura",revealEmoji:"🔥",revealDesc:"A blazing aura of pure Bitcoin energy. The ultimate flex for Nacho's best friend!"},{id:"rainbow_antlers",category:"hat",name:"???",emoji:"🌈",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!0,revealName:"Rainbow Antlers",revealEmoji:"🌈",revealDesc:"Prismatic rainbow antlers that shimmer in every color. Legendary!"},{id:"bitcoin_eyes",category:"glasses",name:"???",emoji:"₿",desc:"How do you find this one?",level:1,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.2em",custom:"₿ ₿"},hidden:!0,revealName:"Bitcoin Eyes",revealEmoji:"₿",revealDesc:"Eyes made of pure Bitcoin. You found the secret! Nacho sees everything in sats now."},{id:"santa_hat",category:"hat",name:"Santa Hat",emoji:"🎅",desc:"Ho ho HODL! A festive Santa hat for the holiday season.",level:1,overlay:{top:"1%",left:"54%",transform:"translateX(-50%) rotate(15deg)",fontSize:"2.2em"},hidden:!1,seasonal:"december"},{id:"pumpkin",category:"hat",name:"Pumpkin Head",emoji:"🎃",desc:"Spooky season! A jack-o-lantern for Halloween.",level:1,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1,seasonal:"october"},{id:"halving_pickaxe",category:"glasses",name:"Golden Pickaxe",emoji:"⛏️",desc:"A golden pickaxe to celebrate the halving! Limited edition.",level:1,overlay:{top:"22%",right:"-15%",fontSize:"2.2em",transform:"rotate(30deg)"},hidden:!1,seasonal:"april"}];var t=document.createElement("style");function o(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?5:e>=350?4:e>=100?3:e>=10?2:e>=1?1:0}t.textContent="\n @keyframes nachoEquipPop {\n 0% { transform: scale(0) rotate(-45deg); opacity: 0; }\n 50% { transform: scale(1.5) rotate(10deg); opacity: 1; }\n 70% { transform: scale(0.9) rotate(-5deg); }\n 100% { transform: scale(1) rotate(0deg); opacity: 1; }\n }\n @keyframes nachoEquipGlow {\n 0% { filter: drop-shadow(0 0 0px transparent); }\n 30% { filter: drop-shadow(0 0 12px rgba(247,147,26,0.8)); }\n 100% { filter: drop-shadow(0 0 4px rgba(247,147,26,0.3)); }\n }\n @keyframes nachoUnequip {\n 0% { transform: scale(1); opacity: 1; }\n 40% { transform: scale(1.3) rotate(15deg); opacity: 0.8; }\n 100% { transform: scale(0) rotate(-30deg); opacity: 0; }\n }\n @keyframes nachoItemFloat {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-3px); }\n }\n @keyframes nachoLaserPulse {\n 0%, 100% { opacity: 0.8; filter: drop-shadow(0 0 4px #ff0000); }\n 50% { opacity: 1; filter: drop-shadow(0 0 10px #ff0000) drop-shadow(0 0 20px #ff3300); }\n }\n @keyframes nachoSparkle {\n 0%, 100% { filter: drop-shadow(0 0 4px rgba(255,215,0,0.3)); }\n 50% { filter: drop-shadow(0 0 10px rgba(255,215,0,0.8)) drop-shadow(0 0 20px rgba(255,215,0,0.4)); }\n }\n @keyframes nachoCloakWave {\n 0%, 100% { transform: translateX(-50%) rotate(-2deg); }\n 50% { transform: translateX(-50%) rotate(2deg); }\n }\n .nacho-overlay-item {\n position: absolute;\n pointer-events: none;\n z-index: 3;\n }\n .nacho-overlay-item.equipping {\n animation: nachoEquipPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards,\n nachoEquipGlow 0.8s ease-out forwards;\n }\n .nacho-overlay-item.unequipping {\n animation: nachoUnequip 0.35s ease-in forwards;\n }\n .nacho-overlay-item.idle-float {\n animation: nachoItemFloat 3s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-laser {\n animation: nachoLaserPulse 1.5s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-sparkle {\n animation: nachoSparkle 2s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-wave {\n animation: nachoCloakWave 4s ease-in-out infinite;\n }\n",document.head.appendChild(t),window.equipNachoItem=function(t){if(!t)return localStorage.removeItem("btc_nacho_equipped_multi"),void renderNachoOverlay();var n=o(),i=e.find(function(e){return e.id===t}),a=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]");if(i&&i.level>n&&-1===a.indexOf(t))showToast("🔒 Need a higher friendship level to wear this!");else{var r=getEquippedItems(),s=i&&i.category||"misc";r[s]===t?(delete r[s],"function"==typeof forceShowBubble&&forceShowBubble("Back to natural in the "+s+" department! 🦌")):(r[s]=t,"function"==typeof forceShowBubble&&forceShowBubble({orange_scarf:"Looking cozy! This scarf really brings out my orange. 🧣🦌",mining_helmet:"Safety first! Time to mine some blocks! ⛑️⛏️",lightning_chain:"Bling bling! Fast as Lightning! ⚡🦌",hodl_hoodie:"HODL gang! This hoodie makes me feel unstoppable! 🧥💎",laser_eyes:"LASER EYES ACTIVATED! Number go up! 🔴🔴🚀",steak:"Mmm, Proof of Steak! Way better than Proof of Stake! 🥩😋",golden_antlers:"These golden antlers are MAGNIFICENT! Only for my best friends! 👑✨",satoshi_cloak:"Who am I? Nobody knows... I am Satoshi Nachoamoto! 🧙🦌"}[t]||"Looking fresh with my "+(i.hidden?i.revealName:i.name)+"! 🦌")),localStorage.setItem("btc_nacho_equipped_multi",JSON.stringify(r)),renderNachoOverlay(!0),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),document.getElementById("nachoClosetGrid")&&renderNachoClosetUI(document.getElementById("nachoClosetGrid").parentElement)}},window.renderNachoOverlay=function(t){document.querySelectorAll(".nacho-overlay-item").forEach(e=>e.remove());var o=getEquippedItems(),n=document.getElementById("nacho-avatar");n&&(Object.values(o).forEach(function(o){var i=e.find(function(e){return e.id===o});if(i){var a=i.hidden?i.revealEmoji:i.emoji,r=function(e){switch(e){case"laser_eyes":return"idle-laser";case"golden_antlers":case"diamond_hooves":return"idle-sparkle";case"satoshi_cloak":return"idle-wave";default:return"idle-float"}}(i.id),s=document.createElement("span");for(var l in s.className="nacho-overlay-item"+(t?" equipping":" "+r),s.id="nacho-overlay-"+i.id,s.textContent=i.overlay.custom||a,i.overlay.custom&&(s.style.letterSpacing="-0.1em",s.style.whiteSpace="nowrap"),i.overlay)"filter"!==l&&"custom"!==l&&(s.style[l]=i.overlay[l]);if(i.colorable){var c=localStorage.getItem("btc_closet_color_"+i.id);c&&"0deg"!==c&&(s.style.filter="hue-rotate("+c+")")}t&&s.addEventListener("animationend",function e(){s.classList.remove("equipping"),s.classList.add(r),s.removeEventListener("animationend",e)},{once:!0}),n.appendChild(s)}}),t&&function(e){for(var t=e.getBoundingClientRect(),o=["✨","⭐","💫","🌟"],n=0;n<6;n++)(function(e){setTimeout(function(){var n=document.createElement("div");n.className="nacho-trail",n.textContent=o[e%o.length],n.style.left=t.left+Math.random()*t.width+"px",n.style.top=t.top+Math.random()*t.height+"px",n.style.fontSize=.8+.8*Math.random()+"rem",document.body.appendChild(n),setTimeout(function(){n.parentNode&&n.remove()},800)},80*e)})(n)}(n))},window.getNachoFriendship=function(){const e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[{name:"Stranger",emoji:"🦌",min:0},{name:"Acquaintance",emoji:"🤝",min:10},{name:"Pleb Friend",emoji:"🧡",min:50},{name:"HODL Buddy",emoji:"💎",min:150},{name:"Maxi Mentor",emoji:"👑",min:500}];let o=t[0];for(const n of t)e>=n.min&&(o=n);return o},window.renderNachoClosetUI=function(t){for(var n=o(),i=getEquippedItems(),a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r="function"==typeof getNachoFriendship?getNachoFriendship():{level:0,name:"Strangers",emoji:"❓"},s=[1,10,100,350,750],l="",c=0;cNext level in '+(s[c]-a)+" more interactions";break}var d="",u=[];Object.values(i).forEach(function(t){var o=e.find(function(e){return e.id===t});if(o){var n=o.hidden?o.revealEmoji:o.emoji;o.overlay.custom&&(n=o.overlay.custom);var i="position:absolute;font-size:"+(o.overlay.fontSize||"1.5rem")+";";if(o.overlay.top&&(i+="top:"+o.overlay.top+";"),o.overlay.bottom&&(i+="bottom:"+o.overlay.bottom+";"),o.overlay.left&&(i+="left:"+o.overlay.left+";"),o.overlay.right&&(i+="right:"+o.overlay.right+";"),o.overlay.transform&&(i+="transform:"+o.overlay.transform+";"),i+="z-index:5;pointer-events:none;",o.colorable){var a=localStorage.getItem("btc_closet_color_"+o.id);a&&"0deg"!==a&&(i+="filter:hue-rotate("+a+");")}d+=''+n+"",u.push(o.hidden?o.revealName:o.name)}});var p="function"==typeof nachoNickname?nachoNickname():"Nacho",m='
    🦌 '+escapeHtml(p)+"'s Closet
    ";m+='
    Nacho'+d+'
    '+(u.length>0?'✨ Wearing: '+u.join(", ")+"":"No item equipped — tap one below!")+"
    ",m+='
    Friendship: '+r.emoji+" "+r.name+''+a+" interactions
    "+l,m+='
    ',m+='
    ';for(var h=(new Date).toLocaleString("en",{month:"long"}).toLowerCase(),g=0;g
    '+x+'
    '+w+"
    "+(b?'
    ✓ EQUIPPED
    ':"")+(b&&f.colorable?"
    🎨 Color
    ':"")+(y||v?"":'
    Lvl '+f.level+"
    ")+(v?'
    🔒
    ':"")+(f.seasonal?'
    🗓️ '+f.seasonal+"
    ":"")+"
    "}}m+="",m+='
    '+(Object.keys(i).length>0?function(){var t=e.find(function(e){return e.id===Object.values(i)[0]});if(!t)return"Tap an item to equip it on "+escapeHtml(p)+"!";var o=t.hidden?t.revealDesc:t.desc;return''+(t.hidden?t.revealName:t.name)+": "+o}():"Tap an unlocked item to equip it on "+escapeHtml(p)+"!
    Tap again to unequip.")+"
    ",t.innerHTML=m};var n="function"==typeof nachoNickname?nachoNickname():"Nacho";window.NACHO_CLOSET_TIPS=[{pose:"cool",text:"Did you know I have a whole closet of outfits, {name}? Check Settings → Stats → "+escapeHtml(n)+"'s Closet to dress me up! 👔🦌"},{pose:"celebrate",text:"The more we interact, the more items you unlock for me to wear! Check my closet in Settings! 🧣⚡"},{pose:"eyes",text:"I heard there are some mystery items in my closet that only my closest friends get to see... 👀🔒"},{pose:"fire",text:"Proof of Steak > Proof of Stake. Ask me about it... or better yet, unlock it in my closet! 🥩🦌"},{pose:"cheese",text:"Fashion tip from a deer: orange goes with everything. Especially Bitcoin orange. Check my closet in Settings! 🟠"}],window.checkNachoNewItems=function(){var t=o(),n=JSON.parse(localStorage.getItem("btc_nacho_items_notified")||"[]"),i=e.filter(function(e){return e.level<=t&&!n.includes(e.id)});if(i.length>0){for(var a=0;a
    '+(a?a.name:"Item")+'
    Choose a color
    ';[{name:"Default",hue:"0deg",color:"#f7931a"},{name:"Bitcoin Orange",hue:"25deg",color:"#ff8c00"},{name:"Crimson",hue:"340deg",color:"#dc2626"},{name:"Royal Purple",hue:"270deg",color:"#7c3aed"},{name:"Ocean Blue",hue:"200deg",color:"#0ea5e9"},{name:"Forest Green",hue:"120deg",color:"#16a34a"},{name:"Gold",hue:"45deg",color:"#eab308"},{name:"Hot Pink",hue:"310deg",color:"#ec4899"},{name:"Cyan",hue:"175deg",color:"#06b6d4"},{name:"Lime",hue:"90deg",color:"#84cc16"}].forEach(function(t){var n=o===t.hue;r+=""}),r+='
    ',i.innerHTML=r,n.appendChild(i),document.body.appendChild(n)},window._applyClosetColor=function(e,t){localStorage.setItem("btc_closet_color_"+e,t);var o=document.querySelector("#nacho-overlay");if(o&&(o.style.filter="0deg"===t?"none":"hue-rotate("+t+")"),"function"==typeof showColorPicker&&showColorPicker(e),"function"==typeof renderNachoClosetUI){var n=document.getElementById("nachoClosetContainer");n&&renderNachoClosetUI(n)}};const QUESTION_BANK={whitepaper:[{q:"When was the Bitcoin Whitepaper published?",a:"October 31, 2008",wrong:["January 3, 2009","March 15, 2007","December 25, 2010"]},{q:"How many pages of text is the Bitcoin Whitepaper?",a:"8 pages",wrong:["20 pages","50 pages","2 pages"]},{q:"The Whitepaper was published on:",a:"A cryptography mailing list",wrong:["Twitter","A Bitcoin forum","The New York Times"]},{q:"What is the title of the Bitcoin Whitepaper?",a:"Bitcoin: A Peer-to-Peer Electronic Cash System",wrong:["Digital Gold: The Future","How to Mine Cryptocurrency","The Blockchain Revolution"]},{q:"The Whitepaper proposed a solution to:",a:"The double-spending problem",wrong:["Climate change","Internet speed","Social media addiction"]}],whitepaper_pt2:[{q:"Who is credited as the author of the Whitepaper?",a:"Satoshi Nakamoto",wrong:["Vitalik Buterin","Elon Musk","Hal Finney"]},{q:"The Whitepaper describes Bitcoin as:",a:"A peer-to-peer electronic cash system",wrong:["A stock trading platform","A social network","A video game currency"]},{q:"What concept does the Whitepaper use to timestamp transactions?",a:"A chain of hashed blocks",wrong:["A central database","Email timestamps","GPS coordinates"]},{q:"The Bitcoin whitepaper solved what previously unsolvable problem?",a:"Digital scarcity without a trusted third party",wrong:["Faster internet speeds","Quantum-proof encryption","Free worldwide communication"]},{q:"What did Satoshi embed in the Genesis Block's coinbase transaction?",a:"A newspaper headline about bank bailouts",wrong:["Their real name","A mathematical formula","Instructions for miners"]}],decentralized:[{q:'How many people are "in charge" of Bitcoin?',a:"No one",wrong:["Satoshi Nakamoto","A board of directors","The Bitcoin Foundation"]},{q:"What is needed for code updates to Bitcoin?",a:"Deep consensus from the network",wrong:["A CEO decision","A government vote","Permission from miners only"]},{q:"Bitcoin is described as:",a:"A protocol, not a company",wrong:["A company based in Japan","A government project","A bank product"]},{q:"Bitcoin nodes are run by:",a:"Anyone who wants to, worldwide",wrong:["Only by miners","Only in the United States","Only by approved operators"]},{q:"If one country shuts down all Bitcoin mining:",a:"The network continues in other countries",wrong:["Bitcoin dies","All coins are lost","The price goes to zero permanently"]}],decentralized_pt2:[{q:"Bitcoin has no:",a:"Central point of failure",wrong:["Users","Transactions","Value"]},{q:"Decentralization means:",a:"No single entity controls the network",wrong:["One company runs everything","The government manages it","Only banks can use it"]},{q:"What happens to Bitcoin if one country bans it?",a:"The network continues operating globally since no single country controls it",wrong:["Bitcoin shuts down in that country","All nodes worldwide go offline","Miners must relocate to that country"]},{q:"How many Bitcoin full nodes are estimated to run worldwide?",a:"Tens of thousands across dozens of countries",wrong:["About 100 in the United States","One per continent","Only miners run nodes"]},{q:"Why is geographic distribution of nodes important?",a:"It prevents any single jurisdiction from shutting down the network",wrong:["It makes Bitcoin faster","It reduces electricity costs","It increases the block size"]}],scarce:[{q:"What is the maximum supply of Bitcoin?",a:"21 million",wrong:["100 million","1 billion","Unlimited"]},{q:"How many Bitcoin are estimated to be lost forever?",a:"2-3 million",wrong:["None","10 million","100,000"]},{q:"Bitcoin's code is:",a:"Open source and auditable by anyone",wrong:["Private and closed","Only visible to developers","Controlled by a company"]},{q:"What event cuts Bitcoin's new supply in half?",a:"The halving",wrong:["The merge","The split","The fork"]},{q:"How often does the halving occur?",a:"Approximately every 4 years",wrong:["Every year","Every 10 years","Every month"]}],scarce_pt2:[{q:"Bitcoin is often compared to which precious metal?",a:"Gold",wrong:["Silver","Platinum","Copper"]},{q:"The last Bitcoin will be mined around the year:",a:"2140",wrong:["2030","2050","2025"]},{q:"Bitcoin scarcity is enforced by:",a:"Math and code",wrong:["Government regulations","A central bank","Mining companies"]},{q:"What is the smallest unit of Bitcoin called?",a:"A satoshi (0.00000001 BTC)",wrong:["A bit (0.01 BTC)","A wei","A gwei"]},{q:"How does Bitcoin's stock-to-flow ratio compare to gold after the 2024 halving?",a:"Bitcoin's stock-to-flow surpassed gold's",wrong:["Gold's is still much higher","They are identical","Stock-to-flow doesn't apply to Bitcoin"]}],secure:[{q:"Bitcoin has been under attack since gaining significant value around:",a:"2013",wrong:["2020","2009","2017"]},{q:"How many potential Bitcoin wallets exist?",a:"2^160",wrong:["21 million","A few billion","2^16"]},{q:"Bitcoin's monetary policy is:",a:"Set in stone and immutable",wrong:["Changed annually","Decided by miners","Flexible based on market"]},{q:"A 51% attack would require:",a:"More computing power than the rest of the network combined",wrong:["A password","Government approval","Hacking one computer"]},{q:"Bitcoin has experienced how many hours of downtime since 2013?",a:"Zero",wrong:["Hundreds","A few days each year","One week"]}],secure_pt2:[{q:"Bitcoin uses which hashing algorithm?",a:"SHA-256",wrong:["MD5","RSA","AES"]},{q:"The cost to attack Bitcoin's network is:",a:"Billions of dollars",wrong:["A few hundred dollars","Free","A few thousand dollars"]},{q:"What is Bitcoin's uptime percentage since launch in 2009?",a:"Over 99.98% - virtually no downtime",wrong:["About 95%","Around 80% due to attacks","100% with zero interruptions"]},{q:"Why does higher hashrate make Bitcoin more secure?",a:"More computational power means an attacker needs proportionally more resources to overpower the network",wrong:["Higher hashrate makes transactions free","It allows more coins to be mined","It reduces the block time to seconds"]},{q:"What makes a 51% attack on Bitcoin impractical?",a:"The enormous cost of acquiring more mining power than all honest miners combined",wrong:["The government protects Bitcoin","Satoshi can reverse any attack","Bitcoin uses a firewall"]}],money:[{q:"How many satoshis are in one Bitcoin?",a:"100,000,000",wrong:["1,000,000","1,000","10,000"]},{q:"Bitcoin payments are compared to:",a:"Email - anyone with your address can send",wrong:["Fax machines","Phone calls","Physical mail"]},{q:"Bitcoin's distribution was fair because:",a:"There was no premine",wrong:["A company sold coins early","The government distributed it","Only miners got coins"]},{q:"A satoshi is named after:",a:"Bitcoin's creator, Satoshi Nakamoto",wrong:["A Japanese emperor","A type of sushi","A programming language"]},{q:"Bitcoin is divisible to how many decimal places?",a:"8",wrong:["2","4","16"]}],money_pt2:[{q:"Bitcoin can function as:",a:"A store of value, medium of exchange, and unit of account",wrong:["Only a store of value","Only for payments","Only for speculation"]},{q:'What makes Bitcoin "sound money"?',a:"Fixed supply and predictable issuance",wrong:["Government backing","Bank guarantees","Corporate ownership"]},{q:"Which property of money does Bitcoin's 21 million cap satisfy?",a:"Scarcity - it cannot be inflated or debased",wrong:["Acceptability - everyone must use it","Portability - it weighs nothing","Cognizability - it looks like gold"]},{q:"Why are satoshis important for Bitcoin as money?",a:"They allow micropayments and make Bitcoin divisible enough for everyday transactions",wrong:["They increase the total supply","They are a separate cryptocurrency","They can only be used on Lightning"]},{q:"What gives Bitcoin its monetary value according to Austrian economics?",a:"Subjective value from its useful properties: scarcity, portability, divisibility, and censorship resistance",wrong:["Government decree","Gold backing","The electricity used to mine it"]}],peaceful:[{q:"When China banned Bitcoin:",a:"Bitcoin just moved and kept going",wrong:["Bitcoin shut down","The price went to zero","The code was deleted"]},{q:"What happened to Bitcoin transactions during the 2021 China mining ban?",a:"The network kept running - hash rate dipped then recovered within months",wrong:["Transactions slowed severely as hash rate took over a year to fully recover","The difficulty adjustment failed and blocks stopped confirming for several weeks","The network split into two chains — one with and one without Chinese nodes"]},{q:"Bitcoin enables protest by:",a:"Allowing people to transact without government permission",wrong:["Sending angry emails","Blocking websites","Hacking banks"]},{q:'Bitcoin is called "peaceful" because:',a:"It opts out of the existing system without force",wrong:["It prevents all crime","It eliminates wars","It makes everyone rich"]},{q:"Bitcoin helps people in authoritarian regimes by:",a:"Providing censorship-resistant money",wrong:["Overthrowing governments","Hacking military systems","Printing local currency"]}],peaceful_pt2:[{q:"Bitcoin adoption is described as:",a:"Voluntary and organic",wrong:["Mandatory and forced","Government-mandated","Corporate-controlled"]},{q:"How does Bitcoin function as a peaceful protest tool?",a:"It allows people to opt out of inflationary monetary systems without violence",wrong:["It funds protest organizations","It blocks government websites","It replaces voting systems"]},{q:'Why is Bitcoin described as "opt-in" money?',a:"Nobody is forced to use it - participation is entirely voluntary",wrong:["You must opt in through a bank","Governments assign Bitcoin to citizens","Mining is mandatory for users"]},{q:"How did Bitcoin help protestors in authoritarian regimes?",a:"It allowed them to receive donations that could not be frozen by the government",wrong:["It gave them free internet access","It replaced their national ID systems","It provided encrypted phone calls"]},{q:'What makes Bitcoin "permissionless"?',a:"Anyone can send, receive, or hold Bitcoin without needing approval from any authority",wrong:["You need a license to own it","Only approved wallets can transact","Miners must approve each transaction manually"]}],dominant:[{q:"∞/21M means:",a:"All world wealth funneling into 21 million coins",wrong:["Bitcoin is infinite","There are infinite users","21 million blockchains"]},{q:"Bitcoin's growth pattern resembles:",a:"A J-shaped curve",wrong:["A straight line","A bell curve","A flat line"]},{q:"Bitcoin is said to change you by:",a:"Lowering your time preference",wrong:["Making you rich instantly","Increasing spending","Nothing changes"]},{q:"Bitcoin's market dominance refers to:",a:"Its share of total cryptocurrency market cap",wrong:["How many users it has","Its mining speed","Its block size"]},{q:"Bitcoin's ∞/21M meme represents:",a:"All the world's wealth eventually stored in a 21M coin supply",wrong:["Bitcoin has infinite users","Mining never ends","There are infinite blockchains"]}],dominant_pt2:[{q:"Bitcoin is considered dominant because:",a:"It has the strongest network effect and security",wrong:["It was the cheapest","A government chose it","It has the most features"]},{q:'What is the "Lindy effect" as applied to Bitcoin\'s dominance?',a:"The longer Bitcoin survives and grows, the more likely it is to continue dominating",wrong:["Old technology always fails eventually","Bitcoin dominance decreases with age","Lindy only applies to physical goods"]},{q:"Why do network effects favor Bitcoin over altcoins?",a:"More users, miners, developers, and infrastructure create a self-reinforcing cycle that's hard for competitors to match",wrong:["Bitcoin has the best marketing team","Altcoins are illegal","Network effects only apply to social media"]},{q:'What does Bitcoin\'s "dominance" metric measure?',a:"Bitcoin's share of total cryptocurrency market capitalization",wrong:["The number of Bitcoin nodes vs altcoin nodes","Bitcoin's hash rate compared to all others","The percentage of merchants accepting Bitcoin"]},{q:"Why has no altcoin overtaken Bitcoin despite thousands of attempts?",a:"Bitcoin's first-mover advantage, network effects, decentralization, and brand recognition create an insurmountable moat",wrong:["The government protects Bitcoin specifically","Altcoins are all scams with no technology","Satoshi prevents forks from succeeding"]}],"use-cases":[{q:"Bitcoin is described as better than gold because:",a:"It can be sent across the planet instantly",wrong:["It's heavier","It's shinier","It's backed by gold"]},{q:"How do Bitcoin remittance fees compare to Western Union?",a:"Much cheaper, nearly free",wrong:["About the same","More expensive","Double the cost"]},{q:"Credit card merchants pay about what fee?",a:"3%",wrong:["0%","10%","25%"]},{q:"Bitcoin can help the unbanked because:",a:"You only need a phone and internet to use it",wrong:["Banks distribute it","The government gives it away","You need a credit score"]},{q:"Bitcoin as a hedge against inflation means:",a:"Its fixed supply protects purchasing power",wrong:["It always goes up","The government guarantees its value","It pays interest"]}],"use-cases_pt2":[{q:"Micropayments on Bitcoin are possible through:",a:"The Lightning Network",wrong:["Visa","PayPal","Wire transfer"]},{q:"Bitcoin enables financial sovereignty by:",a:"Letting you be your own bank",wrong:["Requiring a bank account","Needing government ID","Using credit scores"]},{q:"Why is Bitcoin especially valuable for international remittances?",a:"It settles in minutes with low fees compared to days and high fees with traditional wire transfers",wrong:["It automatically converts to local currency","Banks process Bitcoin remittances for free","It requires no internet connection"]},{q:'How does Bitcoin serve as a "savings technology"?',a:"Its fixed supply and deflationary nature preserve purchasing power over time",wrong:["It pays interest like a savings account","Banks guarantee Bitcoin deposits","It automatically grows by 10% annually"]},{q:"What makes Bitcoin useful for micropayments via Lightning?",a:"Sub-penny transaction fees and instant settlement enable payments too small for traditional systems",wrong:["Lightning removes the need for Bitcoin","Micropayments require on-chain transactions","Only amounts over $1 can be sent"]}],mining:[{q:"What do miners do?",a:"Secure the network and process transactions",wrong:["Create Bitcoin from nothing","Print digital money","Delete old transactions"]},{q:"Miners are paid in:",a:"New Bitcoin and transaction fees",wrong:["US dollars","Ethereum","Company stock"]},{q:"Mining difficulty adjusts approximately every:",a:"2 weeks (2016 blocks)",wrong:["Every day","Every hour","Never"]},{q:"A mining pool is:",a:"A group of miners combining computing power",wrong:["A swimming pool for tech workers","A single powerful computer","A government facility"]},{q:"The mining reward after the 2024 halving is:",a:"3.125 BTC per block",wrong:["6.25 BTC","50 BTC","12.5 BTC"]}],mining_pt2:[{q:"ASIC miners are:",a:"Specialized hardware designed only for mining",wrong:["Regular laptops","Gaming consoles","Smart phones"]},{q:"What prevents miners from cheating?",a:"Other nodes verify their work",wrong:["The honor system","Government oversight","Nothing"]},{q:"What milestone did Bitcoin hash rate reach in September 2025?",a:"1 Zettahash per second",wrong:["500 Exahash","10 Petahash","100 Terahash"]},{q:"Pleb Pool and Atlas Pool are examples of:",a:"Solo Bitcoin mining pools",wrong:["Lightning wallets","Bitcoin exchanges","Hardware wallets"]},{q:"D-Central Technologies specializes in:",a:"Home mining equipment and support",wrong:["Bitcoin trading","Lightning channels","Cold storage"]}],mining_pt3:[{q:"Constellation Heating combines mining with:",a:"Heating swimming pools",wrong:["Cooling data centers","Wind power","Solar panels"]},{q:'What is a "nonce" in Bitcoin mining?',a:'A "number used once" that miners change to find a valid hash',wrong:["A type of mining hardware","A fee paid to nodes","The total number of Bitcoins"]},{q:"Mining pools allow small miners to:",a:"Receive more frequent, smaller payouts",wrong:["Control the entire network","Mine without using electricity","Change the supply of Bitcoin"]},{q:"Bitcoin difficulty adjusts every how many blocks?",a:"2,016 blocks (roughly 2 weeks)",wrong:["210,000 blocks","Only during halvings","Every single block"]},{q:"Bitcoin mining is best described as:",a:"A brute-force lottery of guessing nonces until a valid hash is found",wrong:["Solving complex mathematical equations","Running an algorithm that factors large prime numbers","Decrypting encrypted transaction data"]}],mining_pt4:[{q:"What happens when a miner finds a valid block hash?",a:"They broadcast the block to the network, collect the block reward and transaction fees",wrong:["They must wait for government approval before adding it","The block is sent to Satoshi for verification","All other miners must restart their hardware"]},{q:"Why does Bitcoin mining use so much energy?",a:"Energy expenditure is what gives Bitcoin its security - it makes attacks prohibitively expensive",wrong:["The code is poorly optimized","Miners are required to run 24/7 by law","Each transaction requires its own mining operation"]},{q:'What is "hash rate" in Bitcoin mining?',a:"The total computational power being used to process transactions and secure the network",wrong:["The speed at which new coins are printed","The rate at which transactions are deleted","The number of miners currently online"]},{q:'What is "stranded energy" and why do Bitcoin miners seek it?',a:"Energy produced in remote locations with no local demand - miners can monetize it at low cost",wrong:["Energy that has been stored in batteries","Solar power generated at night","Electricity from decommissioned plants only"]},{q:'What is a mining "share" in a pool?',a:"Proof that a miner contributed valid work toward finding a block, used to split rewards proportionally",wrong:["A stock in the mining company","A partial Bitcoin sent to the miner","A vote on which transactions to include"]}],nodes:[{q:"Running a node lets you:",a:"Verify transactions independently",wrong:["Mine Bitcoin","Print money","Control the network"]},{q:'What does it mean to say Bitcoin has "no leader"?',a:"No single person or organization controls the protocol rules",wrong:["Satoshi still runs it anonymously","The Bitcoin Foundation is in charge","Core developers vote on all changes"]},{q:"A full node stores:",a:"The entire blockchain history",wrong:["Only your transactions","Just the latest block","Nothing"]},{q:"How many Bitcoin nodes exist approximately?",a:"Tens of thousands worldwide",wrong:["Only 5","Exactly 21 million","One per country"]},{q:"Running a node requires:",a:"A regular computer with enough storage",wrong:["A supercomputer","Government permission","A mining rig"]}],nodes_pt2:[{q:"Nodes enforce:",a:"The consensus rules of Bitcoin",wrong:["Government laws","Company policies","Social media rules"]},{q:"Clark Moody dashboard is useful for tracking:",a:"Bitcoin network stats and Knots adoption",wrong:["Altcoin prices","Social media followers","Email subscribers"]},{q:"Matt Hill is the founder and CEO of:",a:"Start9 (node-in-a-box solution)",wrong:["Bitcoin Magazine","Coinbase","Blockstream"]},{q:"The Bitcoin Commons governance model proposes:",a:"Coordination without authority for Bitcoin implementations",wrong:["Central planning of upgrades","Voting on block size","Government oversight"]},{q:"A pruned node saves space by:",a:"Deleting old block data after validating it",wrong:["Only downloading headers","Charging other nodes for storage","Reducing the frequency of blocks"]}],nodes_pt3:[{q:"A full node is different from a miner because:",a:"It enforces all rules but doesn't create new blocks",wrong:["It is faster than a miner","It requires more electricity","It is only for experts"]},{q:"How does your node know if a transaction is valid?",a:"It checks the signatures and inputs against the consensus rules",wrong:["It asks a central server","It votes with other nodes","It waits for a tweet from Satoshi"]},{q:"What is the main benefit of running your own Bitcoin node?",a:"You verify all transactions and blocks yourself without trusting any third party",wrong:["You earn Bitcoin rewards for running it","You can mine Bitcoin more efficiently","You get faster transaction speeds"]},{q:'What does "initial block download" (IBD) mean?',a:"The process of downloading and validating the entire blockchain when first setting up a node",wrong:["The time it takes to mine the first block","Downloading the Bitcoin software installer","Syncing your wallet with an exchange"]},{q:"How does a Bitcoin node protect you from accepting fake transactions?",a:"It independently validates every transaction against consensus rules before accepting it",wrong:["It contacts Satoshi for verification","It checks with three other nodes and takes a vote","It uses AI to detect fraud patterns"]}],"pow-vs-pos":[{q:"Bitcoin uses which consensus mechanism?",a:"Proof of Work",wrong:["Proof of Stake","Proof of Authority","Proof of Space"]},{q:"In Proof of Work, security comes from:",a:"Computational work and electricity",wrong:["Staking coins","Voting","Government approval"]},{q:"Proof of Stake has been criticized for:",a:"Favoring wealthy holders (the rich get richer)",wrong:["Using too much energy","Being too decentralized","Being too slow"]},{q:"Proof of Work connects Bitcoin to:",a:"The physical world through energy expenditure",wrong:["The stock market","Social media","Government databases"]},{q:"In PoW, you can't fake:",a:"The energy spent to mine a block",wrong:["Your username","Your IP address","The current time"]}],"pow-vs-pos_pt2":[{q:"Proof of Work was chosen because:",a:"It provides unforgeable costliness",wrong:["It was the cheapest option","Satoshi had no other ideas","The government required it"]},{q:"What real-world resource does Proof of Work consume that Proof of Stake does not?",a:"Energy (electricity used for computation)",wrong:["Hard drive space","Internet bandwidth","RAM memory"]},{q:'What is the "nothing at stake" problem in Proof of Stake?',a:"Validators can sign multiple competing chain forks at no cost, weakening consensus",wrong:["Stakers lose all their tokens if they validate","There is no block reward in PoS","Validators must buy mining hardware"]},{q:"Why do PoW proponents argue it provides stronger security guarantees?",a:"Attacking PoW requires massive ongoing real-world energy expenditure that can't be faked",wrong:["PoW has more developers working on it","PoW chains are always faster","PoW was invented first so it must be better"]},{q:"How does Proof of Stake differ from Proof of Work in block producer selection?",a:"PoS selects validators based on the amount of coins they lock up, while PoW requires solving computational puzzles",wrong:["PoS uses random lottery tickets purchased with fiat","PoW lets the richest miner always win","There is no difference in selection mechanism"]}],"layer-2-lightning":[{q:"Lightning is which layer of Bitcoin?",a:"Layer 2",wrong:["Layer 1","Layer 3","Layer 0"]},{q:"Lightning uses what for privacy?",a:"Onion routing",wrong:["GPS tracking","Public ledger","Email verification"]},{q:"Opening a Lightning channel is like:",a:"Opening a bar tab",wrong:["Buying a car","Getting a loan","Opening a bank account"]},{q:"Lightning transactions are:",a:"Nearly instant and very cheap",wrong:["Slow and expensive","Free but take hours","Only for large amounts"]},{q:"Lightning channels are settled on:",a:"The Bitcoin base layer",wrong:["Ethereum","A separate blockchain","A bank ledger"]}],"layer-2-lightning_pt2":[{q:"Lightning enables:",a:"Micropayments as small as 1 satoshi",wrong:["Only large transactions","Only fiat payments","Only international transfers"]},{q:"Lightning capacity refers to:",a:"The total Bitcoin locked in payment channels",wrong:["Internet bandwidth","Mining power","Number of nodes"]},{q:"Satogram allows you to:",a:"Send messages across the Lightning network",wrong:["Mine Bitcoin","Create NFTs","Swap altcoins"]},{q:"Lightning Cats and Lightning Goats let you:",a:"Feed real animals using Lightning payments",wrong:["Trade animal NFTs","Mine with animal power","Buy pets with Bitcoin"]},{q:"Pay With Flash is a service for:",a:"Businesses to accept Bitcoin payments",wrong:["Mining Bitcoin","Cold storage","Coin mixing"]}],"layer-2-lightning_pt3":[{q:"LNgigs is a Bitcoin-powered:",a:"Freelance marketplace",wrong:["Mining pool","Exchange","Hardware wallet"]},{q:"The Lightning Network whitepaper was written by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto","Vitalik Buterin","Adam Back"]},{q:"Lightning Network payment channels work by:",a:"Opening a channel with an on-chain transaction, then transacting off-chain instantly",wrong:["Creating a separate blockchain for each payment","Sending Bitcoin through email servers","Using proof of stake instead of proof of work"]},{q:"Why is Lightning considered a Layer 2 solution?",a:"It builds on top of Bitcoin's base layer without changing the protocol",wrong:["Because it is the second cryptocurrency ever created","Because it requires two confirmations per transaction","Because only two people can use it at a time"]},{q:"A Lightning invoice is:",a:"A payment request containing the amount, destination, and expiry time",wrong:["A monthly bill for using the Lightning Network","A receipt showing your mining rewards","A document required by tax authorities"]}],"self-custody":[{q:'"Not your keys, not your..."',a:"Bitcoin",wrong:["Wallet","Password","Account"]},{q:"The most secure long-term storage is:",a:"Hardware wallet",wrong:["Exchange account","Phone app","Email attachment"]},{q:"A seed phrase is typically:",a:"12 or 24 words that recover your wallet",wrong:["Your email password","A website URL","A phone number"]},{q:"You should store your seed phrase:",a:"On paper or metal in a secure location",wrong:["In a screenshot on your phone","In your email drafts","On social media"]},{q:"Multi-sig means:",a:"Multiple keys required to authorize a transaction",wrong:["Multiple Bitcoin addresses","Multiple blockchains","Multiple exchanges"]}],"self-custody_pt2":[{q:"When an exchange holds your Bitcoin:",a:"You have an IOU, not actual Bitcoin",wrong:["It's completely safe","You own it fully","The government insures it"]},{q:"Cold storage means:",a:"Keeping keys offline, disconnected from the internet",wrong:["Storing Bitcoin in a freezer","A cold climate mining facility","An inactive exchange account"]},{q:"A hardware wallet provides security by:",a:"Keeping private keys on a dedicated device that never exposes them to the internet",wrong:["Storing Bitcoin inside the physical device","Encrypting the blockchain so only you can read it","Requiring government approval for each transaction"]},{q:"If you lose your hardware wallet but have your seed phrase, you can:",a:"Recover all your Bitcoin on a new wallet using the seed phrase",wrong:["Nothing - the Bitcoin is permanently lost","Contact the wallet manufacturer for a replacement","File a claim with Bitcoin insurance"]},{q:"Multisig (multi-signature) wallets require:",a:"Multiple keys to authorize a transaction (e.g., 2-of-3)",wrong:["Multiple Bitcoin addresses to send from","Multiple confirmations from the same key","Multiple mining pools to verify"]}],"privacy-nonkyc":[{q:"KYC stands for:",a:"Know Your Customer",wrong:["Keep Your Coins","Keys You Control","Knowledge Yields Crypto"]},{q:"CoinJoin is used for:",a:"Mixing transactions for privacy",wrong:["Joining mining pools","Merging blockchains","Creating altcoins"]},{q:"Non-KYC Bitcoin means:",a:"Bitcoin acquired without identity verification",wrong:["Stolen Bitcoin","Fake Bitcoin","Government Bitcoin"]},{q:"Bitcoin's blockchain is:",a:"Public - anyone can see transactions",wrong:["Completely private","Only visible to miners","Encrypted and hidden"]},{q:"Why do some people prefer non-KYC Bitcoin?",a:"To maintain financial privacy",wrong:["To pay lower fees","To mine faster","To get a better price"]}],"privacy-nonkyc_pt2":[{q:"A Bitcoin address should ideally be:",a:"Used only once for privacy",wrong:["Shared with everyone","Used for all transactions","Posted on social media"]},{q:"The first recorded address poisoning attack on Bitcoin happened in:",a:"2025",wrong:["2021","2013","2009"]},{q:"Shielded CSV on Bitcoin promises:",a:"Better than Zcash-level privacy as an L1.5",wrong:["Faster mining","Bigger blocks","More altcoins"]},{q:"Briar messenger is engineered for:",a:"Privacy in hostile environments using Tor",wrong:["Fast video calls","Social media sharing","Cloud storage"]},{q:'What is a "Dust Attack"?',a:"Tiny amounts of BTC sent to addresses to track the owner's movement",wrong:["A network overload","A type of mining hardware failure","Deleting your private keys by accident"]}],"privacy-nonkyc_pt3":[{q:'"WabiSabi" and "Whirlpool" are types of:',a:"CoinJoin coordination protocols",wrong:["Mining hardware","Wallet brand names","Bitcoin address formats"]},{q:"KYC (Know Your Customer) in Bitcoin refers to:",a:"Identity verification required by regulated exchanges",wrong:["A type of encryption algorithm","A consensus mechanism used by altcoins","The name of a Bitcoin wallet"]},{q:"Why do some Bitcoiners prefer non-KYC acquisition?",a:"To protect financial privacy and avoid linking identity to Bitcoin holdings",wrong:["Because it is cheaper than using exchanges","Because KYC Bitcoin is worth less","Because non-KYC Bitcoin mines faster"]},{q:'What is "address reuse" and why is it a privacy concern?',a:"Using the same Bitcoin address multiple times lets observers link all those transactions to one entity",wrong:["It causes transactions to fail","It increases mining fees","It violates Bitcoin consensus rules"]},{q:'What does "non-KYC Bitcoin" mean?',a:"Bitcoin acquired without providing identity documents, such as through peer-to-peer trades or mining",wrong:["Bitcoin that has never been in a wallet","Bitcoin mined before 2013","Bitcoin stored on a hardware wallet"]}],"problems-of-money":[{q:'Why is inflation described as a "hidden tax"?',a:"It silently erodes the purchasing power of savings without a formal vote",wrong:["It is an unofficial surcharge added by central banks on top of existing income taxes","Banks secretly deposit hidden service fees into government accounts disguised as price rises","Only people in the highest tax bracket are actually subject to the effects of inflation"]},{q:"Fractional reserve banking means:",a:"Banks hold only a fraction of deposits",wrong:["Banks hold all deposits","Bitcoin is fractional","Miners keep fractions"]},{q:"Inflation is often called:",a:"A hidden tax on savings",wrong:["A bonus for savers","A mining reward","A blockchain feature"]},{q:"Fiat currency is backed by:",a:"Government decree and trust",wrong:["Gold reserves","Bitcoin","Real estate"]},{q:"The US dollar has lost what percentage of purchasing power since 1913?",a:"Over 96%",wrong:["About 10%","None","About 50%"]}],"problems-of-money_pt2":[{q:"Money printing causes:",a:"Devaluation of existing currency",wrong:["Deflation","Higher savings rates","Stronger currency"]},{q:"Sound money historically meant:",a:"Money that couldn't be easily debased",wrong:["Money that makes noise","Digital currency","Credit cards"]},{q:"The Cantillon Effect describes how:",a:"Those closest to new money benefit most from inflation",wrong:["Bitcoin mining gets harder","Banks lose money","Gold prices drop"]},{q:"ShadowStats.com tracks:",a:"Real inflation rates vs official government numbers",wrong:["Bitcoin mining difficulty","Lightning channel capacity","Altcoin prices"]},{q:'"The Four Horsemen" documentary (2013) exposes:',a:"The fiat monetary system scam",wrong:["Bitcoin mining farms","Social media dangers","Space exploration"]}],"problems-of-money_pt3":[{q:'"Nixon Shock" in 1971 refers to:',a:"The US ending the dollar's convertibility into gold",wrong:["The launch of Bitcoin","A global stock market crash","The creation of the first bank"]},{q:"Gresham's Law states that:",a:'"Bad money drives out good money"',wrong:['"Bitcoin will replace fiat"','"Gold is always better than silver"','"Taxes are voluntary"']},{q:"What happened in 1971?",a:"Nixon ended the gold standard, allowing unlimited fiat money printing",wrong:["Bitcoin was invented","The first digital computer was built","The Euro was introduced"]},{q:'Inflation is often called a "hidden tax" because:',a:"It silently erodes the purchasing power of your savings",wrong:["The IRS taxes Bitcoin gains at a hidden rate","Banks charge fees that are not disclosed","Governments print money in secret locations"]},{q:"What is seigniorage?",a:"The profit a government makes by issuing currency that costs less to produce than its face value",wrong:["A tax on gold mining","Interest earned on savings accounts","The fee banks charge for wire transfers"]}],"investment-strategy":[{q:"DCA stands for:",a:"Dollar Cost Averaging",wrong:["Digital Currency Account","Decentralized Crypto Asset","Direct Coin Access"]},{q:"A common Bitcoin investment strategy is:",a:"Buy regularly and hold long-term",wrong:["Day trade constantly","Sell every week","Only buy at the top"]},{q:"HODL originated from:",a:'A misspelled forum post saying "I AM HODLING"',wrong:["A financial textbook","A government document","A bank term"]},{q:"Bitcoin's 4-year cycle is often tied to:",a:"The halving events",wrong:["US elections","Solar cycles","Stock market seasons"]},{q:"The best time to buy Bitcoin according to Bitcoiners is:",a:"Always - time in the market beats timing the market",wrong:["Only at all-time highs","Only on Mondays","Only in December"]}],"investment-strategy_pt2":[{q:"Stacking sats means:",a:"Accumulating small amounts of Bitcoin over time",wrong:["Building satellite dishes","Stacking physical coins","Creating smart contracts"]},{q:"The biggest drawdown in Bitcoin history was:",a:"94% decline from $32 to $2 in July 2011",wrong:["50% in 2018","70% in 2022","80% in 2014"]},{q:"MNAV.com tracks:",a:"Bitcoin treasury companies and their metrics",wrong:["Lightning channels","Mining pools","Altcoin prices"]},{q:"Lump-sum investing means:",a:"Buying a large amount of Bitcoin all at once",wrong:["Buying a fixed amount every week","Selling all your holdings","Trading only on weekends"]},{q:"Dollar Cost Averaging (DCA) means:",a:"Buying a fixed amount of Bitcoin at regular intervals regardless of price",wrong:["Only buying when the price drops below a target","Investing your entire savings at once","Selling Bitcoin every time it rises 10%"]}],"investment-strategy_pt3":[{q:'The Bitcoin phrase "zoom out" means:',a:"Look at the long-term price trend instead of daily volatility",wrong:["Reduce your Bitcoin position size","Use a magnifying glass to read the whitepaper","Exit the market during a downturn"]},{q:'What does "stacking sats" mean in Bitcoin culture?',a:"Regularly accumulating small amounts of Bitcoin (satoshis) over time",wrong:["Building a stack of physical Bitcoin coins","Storing Bitcoin on multiple exchanges","Running multiple mining rigs simultaneously"]},{q:'Why do Bitcoiners say "time in the market beats timing the market"?',a:"Long-term holders historically outperform those trying to buy dips and sell tops",wrong:["Because Bitcoin's price never goes down","Because exchanges charge timing fees","Because mining rewards increase over time"]},{q:'What is the "HODL" strategy?',a:"Buying Bitcoin and holding it long-term regardless of short-term price volatility",wrong:["A day-trading technique for quick profits","An automated trading bot strategy","Holding exactly 1 Bitcoin at all times"]},{q:"Why is cold storage recommended for long-term Bitcoin holdings?",a:"Keeping private keys offline eliminates the risk of remote hacking or exchange failure",wrong:["Cold storage earns interest on your Bitcoin","It makes transactions faster","Cold wallets automatically back up to the cloud"]}],cryptography:[{q:"Bitcoin uses cryptography that has been:",a:"Used for decades in other applications",wrong:["Invented specifically for Bitcoin","Never tested before","Made by AI"]},{q:"A private key is:",a:"A secret number that controls your Bitcoin",wrong:["Your email password","A physical key","Your bank PIN"]},{q:"A public key is derived from:",a:"The private key using one-way math",wrong:["Your name","Random chance","The blockchain"]},{q:"Digital signatures prove:",a:"You own the private key without revealing it",wrong:["Your identity","Your location","Your bank balance"]},{q:"Hashing is:",a:"Converting data into a fixed-length fingerprint",wrong:["Deleting data","Encrypting emails","Mining Bitcoin"]}],cryptography_pt2:[{q:"Elliptic curve cryptography is used for:",a:"Generating Bitcoin key pairs",wrong:["Mining blocks","Sending emails","Browsing the web"]},{q:"What type of cryptography does Bitcoin use for digital signatures?",a:"Elliptic Curve Digital Signature Algorithm (ECDSA) on the secp256k1 curve",wrong:["RSA 2048-bit encryption","AES-256 symmetric encryption","Triple DES block cipher"]},{q:"What is a hash function's role in Bitcoin?",a:"It creates a fixed-size, unique digital fingerprint of any input data, used for block headers, addresses, and mining",wrong:["It encrypts all Bitcoin transactions end-to-end","It compresses the blockchain to save space","It converts Bitcoin to other cryptocurrencies"]},{q:"Why can't you derive a private key from a public key?",a:"Elliptic curve math is a one-way function - easy to compute forward, computationally infeasible to reverse",wrong:["Because private keys are longer than public keys","Because the blockchain deletes private keys","Because Satoshi encrypted all key pairs"]},{q:"What does SHA-256 stand for and where is it used in Bitcoin?",a:"Secure Hash Algorithm 256-bit - used in mining (proof of work) and creating transaction IDs",wrong:["Super Hash Accelerator - used in wallet encryption only","Satoshi Hash Algorithm - used in signature verification","Shared Hash Array - used in peer-to-peer networking"]}],regulation:[{q:"Bitcoin's response to bans has been:",a:"Moving to friendlier jurisdictions",wrong:["Shutting down","Complying immediately","Becoming illegal forever"]},{q:"El Salvador made Bitcoin:",a:"Legal tender in 2021",wrong:["Illegal in 2020","A national secret","Only for tourists"]},{q:"Bitcoin regulation varies by:",a:"Country - each has different rules",wrong:["There are no rules anywhere","One global law covers it","Bitcoin regulates itself"]},{q:"A Bitcoin ETF allows:",a:"Traditional investors to get Bitcoin exposure through stock markets",wrong:["Free Bitcoin for everyone","Government-controlled mining","Printing new Bitcoin"]},{q:"The SEC has classified Bitcoin as:",a:"A commodity, not a security",wrong:["A security","A currency","Illegal"]}],regulation_pt2:[{q:'What is a "Self-Custody" regulation attempt?',a:"Rules that try to force users to use custodial services",wrong:["Laws that guarantee free Bitcoin","Mining equipment safety standards","Bitcoin price caps"]},{q:"Can a government effectively ban Bitcoin?",a:"They can restrict fiat on-ramps but cannot stop peer-to-peer transactions",wrong:["Yes - turning off the internet kills Bitcoin permanently","Yes - all nodes can be identified and shut down simultaneously","No bans have ever been attempted by any country"]},{q:"China has banned Bitcoin mining multiple times, yet:",a:"Miners relocated and the network hash rate recovered within months",wrong:["Bitcoin permanently lost 50% of its value","All Chinese Bitcoin was confiscated","The Bitcoin network was offline for weeks"]},{q:"How is Bitcoin classified for tax purposes in most jurisdictions?",a:"As property or a capital asset, meaning gains are subject to capital gains tax",wrong:["As currency, exempt from all taxes","As a commodity with no reporting requirements","As digital cash with no tax implications"]},{q:'What does the "Travel Rule" require for crypto transactions?',a:"Regulated exchanges must share sender and receiver identity information for transfers above a threshold",wrong:["Users must physically travel to an exchange to withdraw","Bitcoin can only be sent within your home country","Miners must verify passport numbers for each block"]}],energy:[{q:"Bitcoin mining and energy:",a:"Promotes renewable energy and uses wasted energy",wrong:["Only uses coal","Wastes all energy","Uses no energy"]},{q:"Stranded energy refers to:",a:"Energy produced in remote locations with no buyers",wrong:["Electricity outages","Solar panels at night","Wind on calm days"]},{q:"Bitcoin miners often locate near:",a:"Cheap renewable energy sources",wrong:["Shopping malls","Government buildings","Residential areas"]},{q:"Bitcoin mining can help stabilize:",a:"Electrical grids by acting as a flexible load",wrong:["The stock market","Internet speeds","Political systems"]},{q:"Compared to traditional banking, Bitcoin's energy use is:",a:"Debatable but often comparable or less",wrong:["1000x more","Zero","Exactly the same"]}],energy_pt2:[{q:"Methane flaring and Bitcoin mining:",a:"Miners can capture and use flared gas productively",wrong:["They are unrelated","Mining increases flaring","Flaring powers all mining"]},{q:"Bitcoin mining primarily uses which type of energy?",a:"Over 50% renewable - often stranded or wasted energy",wrong:["100% coal and natural gas","Nuclear power exclusively","Solar panels attached to mining rigs"]},{q:"Bitcoin mining can actually help the environment by:",a:"Monetizing flared methane that would otherwise be released into the atmosphere",wrong:["Reducing the total electricity consumed worldwide","Creating new renewable energy out of thin air","Cooling the planet through heat dissipation"]},{q:"How do Bitcoin miners contribute to grid stability?",a:"They can instantly power down during peak demand, acting as flexible load that balances the grid",wrong:["They generate excess electricity for the grid","They replace power plants entirely","They only mine during off-peak hours by law"]},{q:"What percentage of Bitcoin mining uses renewable energy sources according to recent estimates?",a:"Over 50% and growing, driven by miners seeking the cheapest energy",wrong:["Less than 5%","Exactly 100% - all mining is renewable","About 10%, mostly nuclear"]}],"core-source-code":[{q:"Changes to Bitcoin Core require:",a:"Careful testing and peer review",wrong:["One person's approval","A company decision","Government permission"]},{q:"What is a Bitcoin Improvement Proposal (BIP)?",a:"A formal document proposing changes or standards for the Bitcoin protocol",wrong:["A mandatory software update all Bitcoin nodes must immediately install","A formal funding request submitted by miners to the Bitcoin Foundation","A signed petition from major exchanges required before protocol changes occur"]},{q:"Anyone can:",a:"Read, review, and propose changes to Bitcoin's code",wrong:["Change Bitcoin without review","Delete the blockchain","Add more coins"]},{q:"A BIP is:",a:"A Bitcoin Improvement Proposal",wrong:["A Bitcoin Investment Plan","A Block Information Protocol","A Banking Integration Process"]},{q:"Bitcoin's code repository is hosted on:",a:"GitHub",wrong:["Facebook","A secret server","The dark web"]}],"blockchain-timechain":[{q:"A new Bitcoin block is produced approximately every:",a:"10 minutes",wrong:["1 second","1 hour","1 day"]},{q:"Each block contains:",a:"A list of transactions and a reference to the previous block",wrong:["Just one transaction","Pictures","Email addresses"]},{q:"The blockchain is often called:",a:"An immutable ledger",wrong:["A cloud server","A website","A database that can be edited"]},{q:"Satoshi originally called it:",a:"A timechain",wrong:["A blockchain","A datachain","A coinchain"]},{q:"The Genesis Block contains a message about:",a:"A newspaper headline about bank bailouts",wrong:["A recipe","A love letter","A stock tip"]}],"blockchain-timechain_pt2":[{q:"Block height refers to:",a:"The sequential number of a block in the chain",wrong:["How tall a server rack is","The size of the block","Mining difficulty"]},{q:"Satoshi originally called the blockchain the:",a:"Timechain",wrong:["Hashchain","Blockweb","Cryptoledger"]},{q:"Each Bitcoin block contains a reference to:",a:"The hash of the previous block, creating an unbreakable chain",wrong:["The next block that will be mined","All future transactions that will occur","A backup of the entire blockchain"]},{q:"The mempool is:",a:"A waiting area where unconfirmed transactions sit until miners include them in a block",wrong:["A type of Bitcoin storage device","The total amount of memory used by Bitcoin nodes","A pool of memory shared between mining hardware"]},{q:'Why did Satoshi originally call it a "timechain" rather than "blockchain"?',a:"Because each block timestamps transactions in chronological order, creating a chain of time-stamped records",wrong:["Because blocks are mined at exactly 10-minute intervals","Because it tracks time zones for each transaction",'Because the name "blockchain" was already trademarked']}],analogies:[{q:"In the airport analogy, Lightning is like:",a:"A bicycle courier in the terminal",wrong:["The runway","A cargo plane","Air traffic control"]},{q:"Bitcoin is often compared to:",a:"Digital gold",wrong:["Digital silver","Digital stocks","Digital bonds"]},{q:"The Bitcoin network is sometimes compared to:",a:"The internet protocol (TCP/IP)",wrong:["A single website","A phone call","A TV channel"]},{q:"Holding Bitcoin is compared to:",a:"Holding property in cyberspace",wrong:["Renting a movie","Subscribing to a service","Opening a bank account"]},{q:"Nick Szabo's pre-Bitcoin proposal for digital scarce money was called:",a:"Bit Gold",wrong:["Digital Cash","E-Gold","Digi-Buck"]}],byzantine_generals__problem:[{q:"The Byzantine Generals Problem is about:",a:"Reaching agreement when some participants may be dishonest",wrong:["Building castles","Trading gold","Sending emails"]},{q:"Bitcoin solved the Byzantine Generals Problem using:",a:"Proof of Work consensus",wrong:["A voting system","A trusted mediator","Encryption alone"]},{q:"In the analogy, the generals need to:",a:"Coordinate an attack without a trusted messenger",wrong:["Build a wall","Trade horses","Sign a peace treaty"]},{q:"Before Bitcoin, the Byzantine Generals Problem was considered:",a:"Unsolvable in a trustless digital environment",wrong:["Easy to solve","Irrelevant","Already solved by banks"]},{q:"The Byzantine Generals Problem asks how dispersed parties can reach consensus without trusting each other. What mechanism did Bitcoin invent to solve this?",a:"Nakamoto Consensus (proof-of-work + longest chain)",wrong:["Voting by validator nodes","Centralized coordinator server","Proof of stake randomization"]}],game_theory:[{q:"Bitcoin's incentive structure uses:",a:"Game theory to align participants",wrong:["Threats of punishment","Legal contracts","Trust alone"]},{q:"Miners are incentivized to be honest because:",a:"Cheating costs more than playing by the rules",wrong:["They sign contracts","The government watches them","There are no incentives"]},{q:"Nash Equilibrium in Bitcoin means:",a:"No participant benefits from changing their strategy alone",wrong:["Everyone mines equally","Prices never change","All nodes are identical"]},{q:"The prisoner's dilemma relates to Bitcoin because:",a:"Cooperation is more profitable than defection",wrong:["Miners are in prison","Bitcoin is illegal","Users are trapped"]},{q:"What game theory concept explains why Bitcoin miners are incentivized to stay honest rather than attack the network?",a:"Nash equilibrium - attacking costs more than honest mining",wrong:["Prisoner\\'s dilemma","Zero-sum game","Pareto inefficiency"]}],elevator_pitches:[{q:"A good Bitcoin elevator pitch should be:",a:"Simple and compelling in under a minute",wrong:["A 2-hour lecture","Only about price","As technical as possible"]},{q:"When explaining Bitcoin to beginners, start with:",a:"The problem it solves (broken money)",wrong:["Mining algorithms","Cryptographic proofs","Exchange trading"]},{q:"The simplest Bitcoin pitch is often:",a:"Digital money that no one can print or confiscate",wrong:["A get-rich-quick scheme","Internet points","A new bank"]},{q:"How would you explain Bitcoin to a complete newcomer in one sentence?",a:"A digital form of money that no government or company can print, freeze, or control",wrong:["A speculative investment to get rich quick","A credit card for online shopping","A bank account with higher interest"]},{q:"What is the most important feature for Bitcoin newcomers to understand first?",a:"Nobody can confiscate or freeze your bitcoin if you hold your own keys",wrong:["The price will always go up","It\\'s anonymous like cash","Transactions are free"]}],taproot:[{q:"Taproot is a Bitcoin:",a:"Upgrade that improves privacy and smart contracts",wrong:["New cryptocurrency","Mining algorithm","Exchange platform"]},{q:"Taproot was activated in:",a:"November 2021",wrong:["January 2009","March 2015","June 2023"]},{q:"Taproot uses Schnorr signatures which:",a:"Make multi-sig transactions look like regular ones",wrong:["Speed up mining","Create new coins","Delete old blocks"]},{q:"Taproot improves:",a:"Privacy, efficiency, and smart contract capabilities",wrong:["Mining speed only","Block size only","Transaction fees only"]},{q:"What type of signature scheme did Taproot introduce to Bitcoin?",a:"Schnorr signatures",wrong:["RSA signatures","Ring signatures","Lamport signatures"]}],taproot_pt2:[{q:"Taproot improves Bitcoin by:",a:"Enhancing privacy, efficiency, and smart contract capabilities using Schnorr signatures",wrong:["Increasing the total supply above 21 million","Removing the need for mining","Making all transactions completely anonymous"]},{q:"When was the Taproot upgrade activated on Bitcoin?",a:"November 2021 at block 709,632",wrong:["August 2017 with SegWit","January 2009 at genesis","June 2023 with Ordinals"]},{q:"What is MAST (Merkelized Abstract Syntax Trees) in Taproot?",a:"A structure that reveals only the executed spending condition, hiding unused conditions for privacy",wrong:["A new mining algorithm that replaces SHA-256","A type of Lightning channel","A database for storing smart contract state"]},{q:"How does Taproot improve multi-signature transactions?",a:"Schnorr signatures allow multiple signers to produce a single compact signature indistinguishable from a regular one",wrong:["It removes the need for multiple signatures entirely","It stores each signature in a separate block","It requires all signers to be online simultaneously"]},{q:"What is Tapscript?",a:"An updated version of Bitcoin Script that enables new opcodes and improved scripting with Taproot",wrong:["A programming language for building altcoins","A tool for writing Bitcoin Core patches","The scripting language used in Lightning Network"]}],scalability:[{q:"Bitcoin base layer processes roughly:",a:"7 transactions per second",wrong:["7 million per second","1 per minute","100,000 per second"]},{q:"Bitcoin scales primarily through:",a:"Layer 2 solutions like Lightning",wrong:["Making blocks bigger forever","Removing the block limit","Using faster internet"]},{q:"The block size limit exists to:",a:"Keep node requirements low and maintain decentralization",wrong:["Slow down transactions","Limit Bitcoin's value","Help miners make more money"]},{q:"The Blocksize Wars were about:",a:"Whether to increase block size or use Layer 2",wrong:["Mining profitability","Bitcoin's name","Which exchange to use"]},{q:"Bitcoin's block size is limited to approximately:",a:"1-4 MB (with SegWit)",wrong:["100 MB","Unlimited - it grows with demand","1 KB"]}],scalability_pt2:[{q:"What did SegWit (Segregated Witness) do for Bitcoin scalability?",a:"Separated signature data from transaction data, effectively increasing block capacity to ~2 MB equivalent",wrong:["Doubled the block size to 2 MB","Removed the block size limit entirely","Moved all transactions to a sidechain"]},{q:"What is transaction batching?",a:"Combining multiple payments into a single on-chain transaction to save block space and fees",wrong:["Sending the same transaction multiple times for reliability","Grouping transactions by sender country","Waiting until a block is full before broadcasting"]},{q:"Why did the Bitcoin community reject simply raising the block size limit?",a:"Larger blocks increase node operating costs, risking centralization and reducing censorship resistance",wrong:["Larger blocks would break all existing wallets","Satoshi explicitly forbade any block size changes","Larger blocks would reduce the total Bitcoin supply"]},{q:"How does the Lightning Network improve Bitcoin's throughput?",a:"By processing millions of transactions off-chain and only settling final balances on the Bitcoin blockchain",wrong:["By replacing Bitcoin's blockchain with a faster one","By increasing the block size to 100 MB","By reducing the time between blocks to 1 second"]},{q:"What is payment channel batching on Lightning?",a:"Opening or closing multiple channels in a single on-chain transaction to save fees and block space",wrong:["Sending the same payment to multiple recipients","Mining multiple blocks at once","Compressing transaction data for faster processing"]}],utxos:[{q:"UTXO stands for:",a:"Unspent Transaction Output",wrong:["Universal Token Exchange Order","Unified Transaction eXecution Object","Ultra-fast Transfer of eXchange Operations"]},{q:"A UTXO is like:",a:"A specific bill in your wallet that you spend whole",wrong:["A bank balance","A credit limit","An account number"]},{q:"When you spend a UTXO:",a:"It's consumed entirely and change is returned as a new UTXO",wrong:["Part of it disappears","It stays in your wallet","It's deleted from the blockchain"]},{q:"UTXO management matters for:",a:"Privacy and minimizing future transaction fees",wrong:["Mining speed","Block creation","Node operation"]},{q:"What is a UTXO in Bitcoin?",a:"Unspent Transaction Output - the amount of bitcoin remaining after a transaction",wrong:["A type of digital signature","A mining reward token","A user transaction ID"]}],dust:[{q:'Bitcoin "dust" is:',a:"An amount too small to spend because the fee exceeds the value",wrong:["Deleted Bitcoin","A type of mining waste","A security attack"]},{q:"Dust attacks are used to:",a:"Track and deanonymize wallet owners",wrong:["Steal Bitcoin directly","Mine faster","Create new blocks"]},{q:"To avoid dust issues:",a:"Consolidate small UTXOs when fees are low",wrong:["Delete your wallet","Stop using Bitcoin","Only use exchanges"]},{q:'What is a "dust attack" in Bitcoin?',a:"Sending tiny amounts of bitcoin to wallets to track and de-anonymize users",wrong:["Overloading the network with large transactions","Physical dirt damaging mining hardware","A bug in the Bitcoin software"]},{q:"Why should users consolidate small UTXOs when fees are low?",a:"To reduce future transaction costs, as each UTXO adds to transaction size",wrong:["To increase bitcoin value","To improve privacy","To earn mining rewards"]}],rbf:[{q:"RBF stands for:",a:"Replace-By-Fee",wrong:["Really Big Fee","Rapid Block Finality","Return Bitcoin Fast"]},{q:"RBF allows you to:",a:"Bump a stuck transaction's fee to speed confirmation",wrong:["Cancel any transaction","Send Bitcoin for free","Mine your own block"]},{q:"RBF is useful when:",a:"Your transaction is stuck because the fee was too low",wrong:["You want to mine","You need a new wallet","You want to buy altcoins"]},{q:"What does RBF (Replace-by-Fee) allow users to do?",a:"Replace an unconfirmed transaction with a higher-fee version",wrong:["Reverse a confirmed transaction","Increase their total bitcoin balance","Prevent double spending"]},{q:"What is CPFP (Child Pays for Parent) used for?",a:"Accelerating confirmation by spending an unconfirmed output with a high-fee transaction",wrong:["Splitting bitcoin for children","Creating child wallets","Reducing transaction size"]}],time_preference:[{q:"Low time preference means:",a:"Saving for the future instead of spending now",wrong:["Spending everything today","Not caring about money","Only day trading"]},{q:"Bitcoin encourages low time preference because:",a:"Its value tends to increase over time due to scarcity",wrong:["It loses value quickly","It pays interest","The government mandates savings"]},{q:"High time preference leads to:",a:"Overconsumption and debt",wrong:["Wealth building","Better savings","Financial freedom"]},{q:"Fiat currency encourages:",a:"Spending now because money loses value over time",wrong:["Long-term saving","Low time preference","Financial responsibility"]},{q:'What is "low time preference" in Bitcoin culture?',a:"Prioritizing long-term saving over short-term spending",wrong:["Trading Bitcoin frequently for quick profits","Spending all your Bitcoin before the next halving","Checking the price every 5 minutes"]}],time_preference_pt2:[{q:"A Bitcoin standard encourages low time preference because:",a:"Saving is rewarded since the money appreciates over time",wrong:["Bitcoin transactions are extremely slow","The government mandates holding periods","You can only sell Bitcoin once per year"]},{q:'What does "low time preference" mean in the context of Bitcoin?',a:"Prioritizing long-term value and future rewards over immediate gratification",wrong:["Preferring to spend Bitcoin quickly before it loses value","Setting a time limit on how long you hold Bitcoin","Trading Bitcoin on short timeframes"]},{q:"How does fiat money encourage high time preference?",a:"Inflation erodes purchasing power, incentivizing spending now rather than saving for later",wrong:["Fiat money expires after a certain date","Banks charge fees for holding money too long","Governments tax savings but not spending"]},{q:'Why do Bitcoiners say Bitcoin "fixes" time preference?',a:"A deflationary hard money incentivizes saving and long-term thinking since purchasing power increases over time",wrong:["Bitcoin automatically invests your savings","Bitcoin transactions are slower, forcing patience","Bitcoin wallets lock funds for a minimum of one year"]},{q:"How does time preference relate to civilization building?",a:"Lower time preference leads to more capital accumulation, investment, and long-term infrastructure development",wrong:["Higher time preference builds civilizations faster","Time preference has no relationship to economic development","Only governments can lower society's time preference"]}],soft_vs_hard_forks:[{q:"A soft fork is:",a:"Backward-compatible upgrade",wrong:["A completely new blockchain","Deleting Bitcoin","A type of altcoin"]},{q:"A hard fork creates:",a:"A permanent chain split if not everyone upgrades",wrong:["A temporary pause","More Bitcoin","A faster network"]},{q:"Bitcoin Cash was created by:",a:"A hard fork of Bitcoin in 2017",wrong:["Satoshi Nakamoto in 2009","The US government","Ethereum developers"]},{q:"SegWit was activated as:",a:"A soft fork",wrong:["A hard fork","A new blockchain","An altcoin"]},{q:"The key difference between a soft fork and a hard fork is:",a:"Soft forks are backwards-compatible; hard forks are not",wrong:["Soft forks are temporary; hard forks are permanent","Soft forks require less code; hard forks need more","Soft forks are approved by vote; hard forks by mining"]}],soft_vs_hard_forks_pt2:[{q:"The Blocksize Wars resulted in:",a:"Bitcoin Cash splitting off as a hard fork while Bitcoin kept small blocks + SegWit",wrong:["Bitcoin doubling its block size to 2 MB","All miners switching to Bitcoin Cash","The creation of Ethereum"]},{q:"What is a soft fork in Bitcoin?",a:"A backward-compatible protocol upgrade where old nodes still accept new blocks",wrong:["A complete restart of the blockchain","A split that creates a new cryptocurrency","An update that requires all nodes to upgrade immediately"]},{q:"What is a hard fork?",a:"A non-backward-compatible change that requires all nodes to upgrade or they'll follow a different chain",wrong:["A bug fix that doesn't change consensus rules","A minor update to wallet software","A temporary network outage"]},{q:"What was the Bitcoin Cash (BCH) hard fork about?",a:"A disagreement over scaling - BCH proponents wanted larger blocks while Bitcoin kept the 1 MB base limit with SegWit",wrong:["A dispute over who created Bitcoin","A fix for a critical security bug","A change to Bitcoin's monetary policy"]},{q:"Why are soft forks generally preferred over hard forks for Bitcoin upgrades?",a:"They maintain backward compatibility, don't force upgrades, and don't risk splitting the network",wrong:["They are faster to implement","They don't require any code changes","Hard forks are illegal in most countries"]}],fedimints:[{q:"Fedimint helps with:",a:"Community custody with privacy",wrong:["Solo mining","Creating altcoins","Government reporting"]},{q:"A Fedimint uses:",a:"Federated guardians who jointly custody Bitcoin",wrong:["A single custodian","Government vaults","Exchange accounts"]},{q:"Fedimint provides privacy through:",a:"Chaumian eCash tokens",wrong:["Public blockchain","KYC verification","IP tracking"]},{q:"Fedimints are designed for:",a:"Communities that trust each other but want privacy",wrong:["Individual use only","Government agencies","Large corporations"]},{q:"A Fedimint (Federated Mint) provides:",a:"Community-custodial privacy through Chaumian ecash on Bitcoin",wrong:["A new type of Bitcoin mining pool","A government-approved Bitcoin exchange","A way to increase Bitcoin's supply above 21 million"]}],fedimints_pt2:[{q:"Fedimints improve Bitcoin privacy by:",a:"Using blinded signatures so the mint cannot link deposits to withdrawals",wrong:["Deleting transaction data from the blockchain","Requiring all users to share their identity","Converting Bitcoin into a different cryptocurrency"]},{q:"What is a Fedimint?",a:"A federated Chaumian eCash mint where a group of guardians custody Bitcoin and issue private eCash tokens",wrong:["A government-run Bitcoin exchange","A type of Bitcoin mining pool","A centralized bank built on Lightning"]},{q:"How do Fedimints provide privacy?",a:"Using blind signatures so the mint cannot link who deposited Bitcoin with who redeems eCash tokens",wrong:["By encrypting the blockchain","By hiding all transactions from the public","By requiring users to use VPNs"]},{q:"What is the trust model of a Fedimint?",a:"Users trust a federation of guardians (e.g., 3-of-5 multisig) rather than a single custodian",wrong:["Completely trustless like on-chain Bitcoin","Users trust a single company","The government guarantees deposits"]},{q:"How do Fedimints interact with the Lightning Network?",a:"They can send and receive Lightning payments, allowing private transactions with the broader Bitcoin network",wrong:["They replace Lightning entirely","Lightning cannot connect to Fedimints","Fedimints require their own separate payment network"]}],books:[{q:"The Bitcoin Standard is a popular book about:",a:"Sound money and Bitcoin economics",wrong:["Bitcoin mining hardware","How to day trade","Building websites"]},{q:"Mastering Bitcoin by Andreas Antonopoulos is:",a:"A technical deep-dive into how Bitcoin works",wrong:["A children's book","A cookbook","A fitness guide"]},{q:"The Sovereign Individual predicted:",a:"Digital money and the decline of nation-states",wrong:["Social media","Electric cars","Space travel"]},{q:"21 Lessons by Gigi explores:",a:"Philosophical lessons learned from going down the Bitcoin rabbit hole",wrong:["21 mining techniques","21 trading strategies","21 altcoins to buy"]},{q:'"The Bitcoin Standard" by Saifedean Ammous primarily argues:',a:"Bitcoin is the hardest money ever invented and will replace fiat",wrong:["Bitcoin is a useful technology but too volatile to be money","Gold is still superior to Bitcoin as a store of value","Central banks should adopt Bitcoin as a reserve currency"]}],books_pt2:[{q:'Gigi\'s "21 Lessons" is structured around:',a:"21 philosophical, economic, and technical lessons learned from Bitcoin",wrong:["A 21-day guide to becoming a Bitcoin trader","The 21 richest Bitcoin holders and their strategies","The history of 21 failed cryptocurrencies"]},{q:'Who wrote "The Bitcoin Standard"?',a:"Saifedean Ammous",wrong:["Andreas Antonopoulos","Satoshi Nakamoto","Michael Saylor"]},{q:"What book by Jimmy Song teaches Bitcoin programming and development?",a:"Programming Bitcoin",wrong:["The Bitcoin Standard","Digital Gold","Cryptoassets"]},{q:"What book by Lyn Alden provides a broad investment perspective including Bitcoin?",a:"Broken Money",wrong:["The Bitcoin Standard","Digital Gold","The Internet of Money"]},{q:'What is "The Blocksize War" by Jonathan Bier about?',a:"The history of Bitcoin's scaling debate, SegWit activation, and the BCH fork",wrong:["How to increase your Bitcoin block rewards","A fiction novel about cryptocurrency battles","Military applications of blockchain technology"]}],"misconceptions-fud":[{q:"FUD stands for:",a:"Fear, Uncertainty, and Doubt",wrong:["Fully Unified Database","First User Downloaded","Financial Update Daily"]},{q:'"Bitcoin is used by criminals" ignores that:',a:"Cash is used far more for crime and Bitcoin is traceable",wrong:["Bitcoin is untraceable","There are no criminals","Crime doesn't exist"]},{q:'"Bitcoin has no intrinsic value" ignores:',a:"Its network security, scarcity, and utility",wrong:["Its physical weight","Its smell","Its color"]},{q:'"Bitcoin is too volatile" ignores:',a:"Its long-term upward trend and decreasing volatility over time",wrong:["That it never moves","That it only goes down","Government price controls"]},{q:'"Bitcoin wastes energy" ignores:',a:"Its use of stranded/renewable energy and the value it secures",wrong:["That it uses no energy","Solar panels","Wind turbines only"]}],"satoshi-nakamoto":[{q:"Satoshi Nakamoto:",a:"Stepped down and disappeared",wrong:["Is currently the CEO of Bitcoin","Was arrested","Sold all Bitcoin"]},{q:"Satoshi's last known communication was around:",a:"2011",wrong:["2020","2015","2009"]},{q:"Satoshi's Bitcoin holdings are estimated at:",a:"About 1 million BTC that have never moved",wrong:["Zero","100 BTC","All 21 million"]},{q:"Satoshi's disappearance is seen as:",a:"A feature - it made Bitcoin truly decentralized",wrong:["A bug","A crime","A marketing strategy"]},{q:"Satoshi's true identity is:",a:"Unknown - it could be one person or a group",wrong:["Confirmed to be Elon Musk","A CIA agent","The President"]}],"satoshi-nakamoto_pt2":[{q:"Why is it important that Satoshi Nakamoto disappeared?",a:"Bitcoin has no leader who can be arrested, corrupted, or pressured",wrong:["Because they were wanted by law enforcement","So they could secretly accumulate more Bitcoin","Because the code was finished and needed no more work"]},{q:"What evidence suggests Satoshi Nakamoto was likely one person rather than a team?",a:"Consistent writing style, coding patterns, and posting times across years of activity",wrong:["A signed confession published on the Bitcoin Talk forum","DNA evidence found on the original Bitcoin server hardware","A government investigation that confirmed a single identity"]},{q:"When did Satoshi Nakamoto stop posting publicly?",a:"Around December 2010, with a final known post in April 2011",wrong:["January 2009 right after launching Bitcoin","They never stopped and still post today","In 2015 during the block size debate"]},{q:"How many Bitcoin did Satoshi Nakamoto reportedly mine?",a:"Approximately 1 million BTC based on analysis of early mining patterns",wrong:["Exactly 21 million (the entire supply)","Zero - Satoshi never mined","About 100 BTC from the genesis block only"]},{q:"What famous message did Satoshi embed in the Bitcoin genesis block?",a:'"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"',wrong:['"Hello World - Bitcoin is born"','"In code we trust"','"The revolution will not be centralized"']}],history:[{q:"The Bitcoin Genesis Block was mined in:",a:"January 2009",wrong:["October 2008","June 2010","December 2007"]},{q:"The first real-world Bitcoin transaction was:",a:"10,000 BTC for two pizzas",wrong:["1 BTC for a car","100 BTC for a house","1 BTC for a coffee"]},{q:"Bitcoin Pizza Day is celebrated on:",a:"May 22",wrong:["January 3","October 31","December 25"]},{q:"Mt. Gox was:",a:"An early Bitcoin exchange that was hacked and collapsed",wrong:["A mining company","A Bitcoin wallet","A government agency"]},{q:"The first Bitcoin block is called:",a:"The Genesis Block (Block 0)",wrong:["The Alpha Block","Block One","The Origin Block"]}],history_pt2:[{q:"Hal Finney received:",a:"The first Bitcoin transaction from Satoshi",wrong:["The last Bitcoin ever","A medal from the government","The Bitcoin trademark"]},{q:"Laszlo's famous pizza order was called from:",a:"London (Laszlo was in Florida)",wrong:["New York","San Francisco","Tokyo"]},{q:"The Bitcoin Wiki has been online since:",a:"2010",wrong:["2015","2009","2013"]},{q:"Tim Draper is known in Bitcoin for:",a:"Buying seized Silk Road Bitcoin at US Marshals auction",wrong:["Creating the Lightning Network","Writing the whitepaper","Mining the genesis block"]},{q:'The "Lightning Torch" was:',a:"A Lightning payment passed between notable Bitcoiners",wrong:["A mining competition","A hardware wallet","A documentary"]}],_general:[{q:"One Bitcoin equals how many satoshis?",a:"100,000,000 (one hundred million)",wrong:["1,000,000 (one million)","10,000,000 (ten million)","1,000,000,000 (one billion)"]},{q:"Bitcoin was launched in which year?",a:"2009",wrong:["2008","2010","2012"]},{q:"Bitcoin transactions are recorded on:",a:"A public distributed ledger",wrong:["A private server","A bank database","An email chain"]},{q:"Who can send you Bitcoin?",a:"Anyone who knows your address",wrong:["Only your bank","Only verified users","Only people in your country"]},{q:"Bitcoin operates on:",a:"24/7, 365 days a year",wrong:["Banking hours only","Weekdays only","It shuts down for maintenance"]},{q:"The total number of Bitcoins that will ever exist is:",a:"Exactly 21 million",wrong:["Unlimited","100 million","It changes yearly"]},{q:"Bitcoin is often abbreviated as:",a:"BTC",wrong:["BTN","BCN","BIT"]},{q:"A Bitcoin wallet stores:",a:"Private keys, not actual Bitcoin",wrong:["Physical coins","Digital files of Bitcoin","Pictures of Bitcoin"]},{q:"To receive Bitcoin you need:",a:"A Bitcoin address",wrong:["A bank account","A social security number","A credit card"]},{q:"The Bitcoin network is maintained by:",a:"Thousands of volunteers running nodes worldwide",wrong:["A company in California","The United Nations","A single supercomputer"]},{q:"Bitcoin confirmation time depends on:",a:"Network congestion and fee paid",wrong:["Time of day","Your internet speed","Which country you are in"]},{q:"A mempool is:",a:"Where unconfirmed transactions wait to be included in a block",wrong:["A mining pool","A type of wallet","A cryptocurrency exchange"]},{q:"Bitcoin difficulty adjustment ensures:",a:"Blocks are found roughly every 10 minutes regardless of hash power",wrong:["Prices stay stable","Miners earn the same amount","Transactions are free"]},{q:"SegWit stands for:",a:"Segregated Witness",wrong:["Secure Widget","Sequential Witness","Segment Width"]},{q:"A Bitcoin address starts with:",a:"1, 3, or bc1",wrong:["0x","BTC","Any letter"]},{q:"The Lightning Network whitepaper was published by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto","Vitalik Buterin","Elon Musk"]},{q:"Bitcoin hash rate measures:",a:"The total computing power securing the network",wrong:["Transaction speed","Number of users","Price changes"]},{q:"A nonce in mining is:",a:"A number miners change to find a valid block hash",wrong:["A type of fee","A wallet address","A block reward"]},{q:'The term "NGMI" in Bitcoin culture means:',a:"Not Gonna Make It",wrong:["New Global Money Index","Next Generation Mining Interface","Network Growth Metric Indicator"]},{q:"Hyperbitcoinization refers to:",a:"Mass voluntary adoption of Bitcoin as money",wrong:["A Bitcoin price crash","A mining difficulty spike","A new altcoin launch"]},{q:"Strike, Cash App, and River are all:",a:"Apps that let you buy Bitcoin",wrong:["Mining pools","Altcoins","Bitcoin forks"]},{q:"Nostr is:",a:"A decentralized social protocol popular in the Bitcoin community",wrong:["A mining algorithm","A Bitcoin fork","An exchange"]},{q:'The phrase "fix the money, fix the world" means:',a:"Sound money leads to better societal outcomes",wrong:["Print more money","Ban all currencies","Use only credit cards"]},{q:"A timelock in Bitcoin allows:",a:"Locking funds until a specific block height or time",wrong:["Freezing the blockchain","Stopping mining","Deleting transactions"]},{q:"Block reward plus transaction fees equals:",a:"The total miner revenue per block",wrong:["The Bitcoin price","The network speed","The difficulty level"]},{q:"Ordinals on Bitcoin are:",a:"A way to inscribe data on individual satoshis",wrong:["A ranking system for miners","A type of wallet","A government regulation"]},{q:"A paper wallet is:",a:"A printed private key for cold storage",wrong:["A paper receipt from an ATM","A bank statement","A type of fiat currency"]},{q:"The Lightning Network can theoretically handle:",a:"Millions of transactions per second",wrong:["7 per second","100 per second","1 per minute"]},{q:"A watch-only wallet lets you:",a:"Monitor a balance without being able to spend",wrong:["Mine Bitcoin","Create new coins","Edit the blockchain"]},{q:"Pleb is a term of endearment in Bitcoin meaning:",a:"An everyday Bitcoiner, not wealthy but committed",wrong:["A professional trader","A mining executive","A government official"]},{q:"What is the total number of satoshis that will ever exist?",a:"2.1 quadrillion (2,100,000,000,000,000)",wrong:["21 million","100 billion","21 quadrillion"]},{q:"Bitcoin's first confirmed exchange rate (in 2010) was roughly:",a:"1,309 BTC per US dollar",wrong:["1 BTC per US dollar","100 BTC per US dollar","0.01 BTC per US dollar"]},{q:"The first Bitcoin exchange rate was established at approximately:",a:"$0.00099 per BTC (less than one penny)",wrong:["$1.00 per BTC","$0.10 per BTC","$100 per BTC"]},{q:"Dollar-cost averaging (DCA) into Bitcoin means:",a:"Buying a fixed amount regularly regardless of price",wrong:["Borrowing dollars to buy Bitcoin all at once","Selling Bitcoin when the dollar strengthens","Converting Bitcoin profits back into dollars"]},{q:'The phrase "Not your keys, not your coins" warns against:',a:"Keeping Bitcoin on exchanges where you don't control the private keys",wrong:["Using physical Bitcoin coins instead of digital","Sharing your public key with other people","Using hardware wallets instead of software"]}],risks__threats__attack_vectors__weaknes:[{q:"Which Bitcoin address type is better for quantum resistance?",a:"SegWit (bc1q) because Taproot exposes the public key",wrong:["Taproot (bc1p)","Legacy (1...)","All are equally vulnerable"]},{q:"BIP 360 proposes:",a:"Pay to Quantum Resistant Hash",wrong:["Bigger blocks","Faster mining","New altcoin support"]},{q:"Why is a 51% attack economically irrational against Bitcoin?",a:"The cost of acquiring that hash rate would far exceed any attainable reward",wrong:["Because Bitcoin's code blocks it automatically","Because Satoshi holds 51% of hash rate as a safeguard","Because 51% of miners have agreed never to attack"]},{q:"What can a successful 51% attacker actually do to Bitcoin?",a:"Double-spend their own recent transactions and block some new transactions",wrong:["Create new Bitcoin out of thin air beyond the 21M cap","Steal coins from other users' wallets","Delete the entire blockchain history"]},{q:"Quantum computing threatens Bitcoin by potentially:",a:"Breaking ECDSA signatures used to authorize spending",wrong:["Mining all remaining Bitcoin in seconds","Deleting the entire blockchain","Creating unlimited new Bitcoin addresses"]}],"evidence-against-alts":[{q:"Ethereum's original sale page reveals that ETH was:",a:"Pre-sold as a security to fund development",wrong:["Mined fairly like Bitcoin","Distributed equally","Created by Satoshi"]},{q:"What fundamental difference exists between Bitcoin and altcoins regarding decentralization?",a:"Altcoin founders often hold large pre-mines or centralized control",wrong:["Altcoins are too cheap","Bitcoin has better marketing","Altcoins use different blockchains"]},{q:'Why do Bitcoiners say "there is no second best"?',a:"No other crypto achieves Bitcoin's decentralization, security, and immutability",wrong:["Bitcoin was the first, so it automatically wins","The SEC has declared all other cryptos illegal","Satoshi patented the blockchain concept"]},{q:'What is a "pre-mine" and why is it concerning?',a:"Founders allocate coins to themselves before public launch - unfair distribution",wrong:["A technique to speed up transaction processing","A security measure that protects the network","A method of testing the blockchain before launch"]},{q:"Most altcoins are considered securities because:",a:"They have identifiable teams profiting from token sales with promises of returns",wrong:["They use the same code as Bitcoin","The SEC approves them as securities automatically","They are traded on stock exchanges"]}],"smart-contracts":[{q:"Bitcoin's scripting language has supported smart contracts:",a:"Since the beginning - Bitcoin always had them",wrong:["Only after Taproot in 2021","Only after SegWit in 2017","Never - only Ethereum has them"]},{q:"OP_RETURN is used in Bitcoin to:",a:"Embed small amounts of data in transactions",wrong:["Return sent Bitcoin","Cancel transactions","Mine faster"]},{q:"What is Bitcoin\\'s native scripting language called?",a:"Bitcoin Script",wrong:["Solidity","Python Script","JavaScript"]},{q:"What does OP_RETURN allow users to do on Bitcoin?",a:"Embed up to 80 bytes of arbitrary data in a transaction",wrong:["Execute Ethereum-style smart contracts","Change transaction amounts","Create new bitcoins"]},{q:"What are DLCs (Discreet Log Contracts) on Bitcoin?",a:"Smart contracts that settle based on external oracle data without revealing details",wrong:["Private keys stored in logs","Debug contracts for developers","Decentralized lending contracts on Ethereum"]}],"chaumian-mints":[{q:"Cashu is an implementation of:",a:"Chaumian ecash on Bitcoin/Lightning",wrong:["A new blockchain","An altcoin","A mining algorithm"]},{q:"Who invented the blind signature technology used in Chaumian eCash?",a:"David Chaum in 1982",wrong:["Satoshi Nakamoto in 2008","Adam Back in 1997","Hal Finney in 2004"]},{q:"What modern Bitcoin layer implements Chaumian eCash for minting privacy-preserving tokens?",a:"Cashu and Fedimint protocols",wrong:["Lightning Network","Liquid Network","Ethereum ERC-20"]},{q:"Cashu is:",a:"An ecash protocol built on Bitcoin using Chaumian blind signatures",wrong:["A competing cryptocurrency to Bitcoin","A hardware wallet manufacturer","A type of Bitcoin mining software"]},{q:'What are "blind signatures" in ecash?',a:"The mint signs tokens without knowing which user they belong to",wrong:["Signatures that expire after 24 hours","A way to sign transactions without a private key","Signatures that can only be verified by the government"]}],"swag-merch":[{q:"BTCAccepted.org helps you find:",a:"Businesses that accept Bitcoin payments",wrong:["Mining pools","Lightning nodes","Altcoin exchanges"]},{q:"Sats.host offers:",a:"Bitcoin-powered static website hosting",wrong:["Mining services","Cold storage","KYC verification"]},{q:'What annual Bitcoin conference is often called "the Super Bowl of Bitcoin"?',a:"Bitcoin Conference (formerly Miami/Bitcoin 2021)",wrong:["Consensus","DevCon","ETHDenver"]},{q:"What is the significance of wearing an orange pill at Bitcoin conferences?",a:'Signifies being "orange pilled" - awakened to Bitcoin\\\'s importance',wrong:["Medical supplement promotion","Conference staff identifier","VIP pass indicator"]},{q:"What popular Bitcoin merchandise item satirizes central banking?",a:'"End the Fed" t-shirts and posters',wrong:["Bitcoin gaming chairs","Satoshi action figures","Mining rig keychains"]}],"apps-tools":[{q:"PPQ.ai lets you use AI models and pay with:",a:"Bitcoin per prompt - no subscription needed",wrong:["Monthly credit card subscription","Ethereum gas fees","Free but with ads"]},{q:"Angor is a platform for:",a:"Non-custodial Bitcoin crowdfunding",wrong:["Bitcoin mining","Coin mixing","Hardware wallets"]},{q:"What website provides real-time visualization of the Bitcoin mempool?",a:"mempool.space",wrong:["blockchain.com","coinmarketcap.com","bitcoincharts.com"]},{q:"What popular hardware wallet supports both Bitcoin and Lightning?",a:"Coldcard and BitBox02",wrong:["PayPal Card","Venmo Wallet","Apple Pay"]},{q:"What full node implementation is the most widely used for running Bitcoin?",a:"Bitcoin Core",wrong:["Bitcoin Cash","Ethereum Classic","Ripple Node"]}],games:[{q:"Timechain Arcade offers:",a:"Free Bitcoin-themed video games",wrong:["Mining services","Trading tools","Hardware wallets"]},{q:"CanYouBeatBitcoin.com is:",a:"An investing simulator comparing your picks to Bitcoin",wrong:["A mining difficulty calculator","A Bitcoin wallet","A trading bot"]},{q:"What type of Bitcoin games reward players with satoshis?",a:"Play-to-earn Lightning games",wrong:["Casino-style gambling","Console RPGs","Mobile ad games"]},{q:"What popular Bitcoin trivia app lets users earn sats for answering questions?",a:"THNDR Games (like Bitcoin Bounce, Bitcoin Bay)",wrong:["Fortnite","Candy Crush","Minecraft"]},{q:"What is Zebedee known for in the Bitcoin gaming space?",a:"A platform enabling Lightning payments in games",wrong:["Hardware mining rigs","Altcoin exchange","NFT marketplace"]}],"difficulty-adjustment":[{q:"How often does Bitcoin's difficulty adjustment occur?",a:"Every 2,016 blocks (approximately 2 weeks)",wrong:["Every 1,000 blocks","Every month","Every day"]},{q:"What does the difficulty adjustment ensure?",a:"Blocks are found roughly every 10 minutes regardless of hash power changes",wrong:["Transaction fees stay constant","Mining rewards increase","Block size adjusts automatically"]},{q:"Bitcoin's difficulty adjusts every:",a:"2,016 blocks (roughly every 2 weeks)",wrong:["Every single block","Once per year","Every 210,000 blocks (at each halving)"]},{q:"If miners leave the network, difficulty adjustment:",a:"Lowers the difficulty so blocks are found at the target rate",wrong:["Increases difficulty to punish remaining miners","Has no effect - blocks just take longer forever","Automatically doubles the block reward"]},{q:"The target time between Bitcoin blocks is approximately:",a:"10 minutes",wrong:["1 minute","1 hour","30 seconds"]}],nostr:[{q:"What does the Nostr acronym stand for?",a:"Notes and Other Stuff Transmitted by Relays",wrong:["Network of Secured Transactions and Relays","New Open Source Transaction Relay","Node-Operated Social Trust Registry"]},{q:"What makes Nostr unique from typical social media?",a:"Your identity is uncensorable and no single entity controls the platform",wrong:["It automatically pays users in Bitcoin proportional to the engagement they receive","It functions exclusively on mobile devices with no desktop interface available","It requires government-issued identity verification before any content can be published"]},{q:"What is a NIP in the Nostr ecosystem?",a:"A Nostr Implementation Possibility - a protocol specification for how clients and relays behave",wrong:["A Nostr Identity Protocol mapping public keys to verified human-readable usernames","A standardised encryption layer securing private direct messages between Nostr users","A subscription fee structure charged by premium relay operators for event publishing"]},{q:"Nostr uses cryptographic keys to:",a:"Allow users to own their identity without a central authority",wrong:["Mine new coins on the Nostr blockchain","Encrypt all messages so no one can read them","Create smart contracts between users"]},{q:"How is Nostr connected to Bitcoin?",a:"Many clients integrate Lightning for tips and payments",wrong:["Nostr runs on the Bitcoin blockchain directly","You must own Bitcoin to create a Nostr account","Nostr mining validates Bitcoin transactions"]}],network_effects:[{q:"Bitcoin's network effect means:",a:"Each new user increases the value and utility for all existing users",wrong:["The internet gets faster","Mining gets easier","Fees decrease to zero"]},{q:"Why is Bitcoin's network effect considered a strong moat?",a:"It creates a self-reinforcing cycle of liquidity, security, and adoption that competitors cannot easily replicate",wrong:["Because Bitcoin has patents","Because the government protects it","Because the code is encrypted"]},{q:"What economic principle explains Bitcoin\\'s value increasing as more people use it?",a:"Metcalfe\\'s Law - network value proportional to connected users squared",wrong:["Moore\\'s Law","Murphy\\'s Law","Pareto Principle"]},{q:"Metcalfe's Law applied to Bitcoin suggests:",a:"Its value grows proportionally to the square of its users",wrong:["The price will always increase linearly","Only the first users receive any benefit","Network effects only apply to social media"]},{q:"What is the flywheel effect in Bitcoin adoption?",a:"More users attract more developers, merchants, and infrastructure, which attracts even more users",wrong:["Mining gets easier as more people join","Transaction fees decrease as the network grows","Bitcoin price always goes up with more users"]}],governance:[{q:"Bitcoin governance is best described as:",a:"Rough consensus among users, developers, miners, and node operators",wrong:["A CEO makes all decisions","Miners vote on everything","A foundation sets the rules"]},{q:"The Blocksize Wars demonstrated that:",a:"Users and node operators ultimately control Bitcoin's rules, not miners alone",wrong:["Miners have absolute power","Developers can force any change","Bitcoin cannot be upgraded"]},{q:"What is the BIP process in Bitcoin?",a:"Bitcoin Improvement Proposals for suggesting protocol changes",wrong:["Bitcoin Investment Plan","Blockchain IP Protection","Banking Integration Protocol"]},{q:"How is Bitcoin governed?",a:"Through rough consensus among users, developers, miners, and node operators",wrong:["By a board of directors at the Bitcoin Foundation","Through shareholder voting like a corporation","By whoever owns the most Bitcoin"]},{q:"A BIP (Bitcoin Improvement Proposal) is:",a:"A formal document proposing changes to Bitcoin's protocol or processes",wrong:["A mandatory update that all nodes must accept","A financial investment in Bitcoin development","A bug report filed to the Bitcoin support team"]}],human_rights__social_justice_and_freedo:[{q:"Bitcoin supports human rights by:",a:"Providing censorship-resistant money that cannot be confiscated by authoritarian regimes",wrong:["Replacing all governments","Eliminating all poverty instantly","Being controlled by the UN"]},{q:"Alex Gladstein advocates for Bitcoin because:",a:"It empowers people living under authoritarian regimes with financial freedom",wrong:["It makes trading stocks easier","It replaces the need for banks in wealthy countries","It was designed as a protest tool"]},{q:"How has Bitcoin helped activists in authoritarian regimes?",a:"By enabling uncensorable fundraising and protecting wealth from seizure",wrong:["By hiding their identity completely","By earning interest from banks","By creating new currencies"]},{q:"How does Bitcoin help people under authoritarian regimes?",a:"It provides censorship-resistant money that governments cannot freeze",wrong:["It automatically reports suspicious activity to authorities","It requires government ID to transact","It only works in democratic countries"]},{q:"Alex Gladstein of the Human Rights Foundation argues that:",a:"Bitcoin is the most important tool for financial freedom globally",wrong:["Only wealthy nations benefit from Bitcoin","Bitcoin should be controlled by human rights organizations","Proof of Stake is better for human rights than Proof of Work"]}],market_cap:[{q:"Bitcoin's market cap is calculated by:",a:"Current price multiplied by total coins in circulation",wrong:["Total transaction volume per day","Number of wallets times average balance","Mining revenue times block height"]},{q:"Why can Bitcoin's market cap potentially exceed gold's?",a:"Bitcoin is more portable, divisible, verifiable, and scarce than gold",wrong:["Because governments will mandate it","Because gold will be banned","Because Bitcoin mining produces gold"]},{q:"What metric compares Bitcoin\\'s market value to all other cryptocurrencies combined?",a:"Bitcoin Dominance Index",wrong:["Coin Market Gap","Crypto Index Fund","Volatility Ratio"]},{q:"Bitcoin's market capitalization represents:",a:"The total value of all existing Bitcoin at the current price",wrong:["The maximum number of coins that can ever exist","The amount of money invested in Bitcoin mining","The total transaction volume over the past year"]},{q:"If Bitcoin captured gold's market cap, each coin would be worth approximately:",a:"Over $500,000",wrong:["$100,000","$50,000","$10,000"]}],the_future:[{q:'What hypothetical event do Bitcoiners call "hyperbitcoinization"?',a:"A voluntary tipping point where Bitcoin displaces fiat as the world's dominant money",wrong:["A coordinated government transition where nations simultaneously adopt a Bitcoin standard","A planned protocol upgrade that makes Bitcoin the only globally compatible payment rail","A forced redenomination where central banks exchange fiat reserves for Bitcoin at par"]},{q:"Bitcoin is described as 'generational wealth' because:",a:"Its fixed supply and growing adoption may increase its value over decades",wrong:["Only family members can legally inherit and access a deceased holder's Bitcoin wallet","Bitcoin wallets automatically expire and reset to zero after 25 years of inactivity","Central banks officially guarantee Bitcoin's face value for 100 years as a reserve asset"]},{q:'What is the "digital scarcity" argument for Bitcoin\'s long-term value?',a:"Unlike any prior asset, Bitcoin's supply cap is enforced by math rather than human institutions",wrong:["Scarcity is irrelevant because Bitcoin can be subdivided infinitely","Bitcoin's value comes from government backing similar to gold reserves","Digital files can always be copied so Bitcoin cannot truly be scarce"]},{q:"What happens when the last Bitcoin is mined (~2140)?",a:"Miners will be compensated solely through transaction fees",wrong:["The network will shut down permanently","A new supply of 21 million coins will be created","Mining will become free with no reward"]},{q:'Who coined the term "hyperbitcoinization"?',a:"Daniel Krawisz in a 2014 Nakamoto Institute essay",wrong:["Satoshi Nakamoto in the Bitcoin whitepaper","Michael Saylor during a 2020 conference","Andreas Antonopoulos in Mastering Bitcoin"]}],"orange-pilling":[{q:"'Orange-pilling' someone means:",a:"Convincing them to understand and adopt Bitcoin",wrong:["Selling them altcoins","Giving them free Bitcoin","Signing them up for an exchange"]},{q:"The most effective way to orange-pill someone is often:",a:"Starting with the problem Bitcoin solves (broken money) rather than technical details",wrong:["Showing them price charts","Explaining SHA-256 hashing","Telling them to buy immediately"]},{q:'What does "orange pilling" someone mean?',a:"Educating them about Bitcoin until they understand its importance",wrong:["Giving them actual pills","Selling them mining equipment","Creating a Bitcoin wallet for them"]},{q:"What is the best approach when orange-pilling a skeptic?",a:"Start with their specific pain point (inflation, remittances, censorship) rather than technical details",wrong:["Show them price charts and promise guaranteed returns","Pressure them into buying immediately before the next halving","Explain the full UTXO model and Merkle trees first"]},{q:"The most effective orange-pilling strategy is:",a:"Meeting people where they are and addressing their specific concerns",wrong:["Posting price predictions on social media","Telling people they are stupid for not buying","Promising guaranteed financial returns"]}],maximalism:[{q:"Bitcoin maximalism is the belief that:",a:"Bitcoin is the only cryptocurrency that truly matters as sound money",wrong:["You should invest everything in Bitcoin","Bitcoin should replace all technology","Only developers should use Bitcoin"]},{q:"Maximalists argue altcoins are unnecessary because:",a:"Bitcoin's base layer plus additional protocol layers can serve all use cases",wrong:["Because altcoins are illegal","Because Satoshi said so","Because there can only be one blockchain"]},{q:"What is Bitcoin maximalism?",a:"The belief that Bitcoin will be the only cryptocurrency to achieve long-term dominance",wrong:["Investing only in altcoins","Maximizing one\\'s bitcoin holdings at all costs","Running multiple full nodes"]},{q:"Why do deep Bitcoin researchers tend to become maximalists?",a:"They realize no other project achieves true decentralization and immutability",wrong:["They are paid by Bitcoin companies to promote it","They lack knowledge of other technologies","It is required to participate in the Bitcoin community"]},{q:"What is the core argument of Bitcoin maximalists?",a:"Only Bitcoin achieves true decentralization and sound money; altcoins compromise on critical aspects",wrong:["Bitcoin should be the only legal currency","All other technology besides Bitcoin is useless","Maximalists refuse to use the internet"]}],developers:[{q:"Bitcoin Core is primarily written in:",a:"C++",wrong:["Python","JavaScript","Rust"]},{q:"Contributing to Bitcoin open source requires:",a:"Anyone can propose changes - no permission needed",wrong:["A computer science degree","Approval from the Bitcoin Foundation","Purchasing a developer license"]},{q:"Who is considered Bitcoin\\'s lead maintainer as of recent years?",a:"There is no formal leader; Bitcoin Core has multiple maintainers",wrong:["Satoshi Nakamoto","Vitalik Buterin","Elon Musk"]},{q:"What organization has historically funded Bitcoin Core development?",a:"MIT Digital Currency Initiative, Chaincode Labs, Brink, Spiral",wrong:["World Bank","Federal Reserve","Goldman Sachs"]},{q:"Which version control system hosts Bitcoin Core's source code?",a:"Git",wrong:["SVN","Mercurial","Bazaar"]}],ham_radio:[{q:"Bitcoin transactions can be sent via ham radio, which means:",a:"Bitcoin can work without an internet connection",wrong:["Bitcoin requires satellite dishes","Only miners can use radio","Radio transactions are free"]},{q:"How can Bitcoin transactions be sent without internet?",a:"Via ham radio operators broadcasting signed transactions",wrong:["Via postal mail","Via telephone calls","Via satellite TV only"]},{q:"What mesh network protocol has been used to broadcast Bitcoin transactions?",a:"Blockstream Satellite and goTenna mesh networks",wrong:["Bluetooth Classic","NFC payments","Zigbee home network"]},{q:"What is the benefit of Bitcoin over ham radio?",a:"Censorship resistance even when governments shut down internet",wrong:["Faster than fiber internet","Lower transaction fees","Better for large file transfers"]},{q:"Who demonstrated sending Bitcoin via ham radio in 2019?",a:"Rodolfo Novak co-founder of Coinkite",wrong:["Elon Musk","Jack Dorsey","Andreas Antonopoulos"]}],lightning_node:[{q:"Running a Lightning node allows you to:",a:"Route payments and earn fees while supporting the network",wrong:["Mine Bitcoin faster","Create new Bitcoin","Access the dark web"]},{q:"What is a Lightning node?",a:"Software that routes payments on the Lightning Network using payment channels",wrong:["A physical Bitcoin ATM","A mining rig","A Bitcoin exchange server"]},{q:"What do node operators lock up to open payment channels?",a:"Bitcoin as liquidity for routing payments",wrong:["Ethereum tokens","Fiat currency","Computing power"]},{q:"What fee do Lightning routing nodes typically charge?",a:"Routing fees measured in milli-satoshis (very small fraction of a cent)",wrong:["1% of transaction amount","$5 per payment","No fees allowed"]},{q:"What is inbound liquidity for a Lightning node?",a:"The ability to receive payments based on funds others have locked with you",wrong:["Money coming from bank deposits","Mining rewards","Exchange trading profits"]}],stablecoins:[{q:"Stablecoins in the Bitcoin ecosystem are typically:",a:"Tokens pegged to fiat currency values, sometimes built on Bitcoin layers",wrong:["A type of mining reward","Bitcoins that never change price","Government-issued digital dollars"]},{q:"What backs the majority of USDT (Tether)?",a:"Commercial paper, cash equivalents, and other reserves (historically controversial)",wrong:["100% US dollars in bank","Gold reserves","Bitcoin collateral"]},{q:"What major risk do centralized stablecoins pose?",a:"Issuer can freeze funds or fail to maintain peg",wrong:["They mine too slowly","High transaction fees","Private key loss"]},{q:"What caused USDC to depeg temporarily in March 2023?",a:"Exposure to failed Silicon Valley Bank",wrong:["Bitcoin price crash","Lightning Network bug","Satoshi selling coins"]},{q:"Stablecoins are NOT a threat to Bitcoin because:",a:"They are centralized IOUs that can be frozen, while Bitcoin is permissionless",wrong:["Stablecoins use the same technology as Bitcoin","Bitcoin automatically converts to stablecoins during crashes","Stablecoins have a higher market cap than Bitcoin"]}],consensus:[{q:"Bitcoin consensus means:",a:"All nodes agree on the state of the blockchain without a central authority",wrong:["Everyone votes on transactions","Miners decide which transactions are valid alone","The government approves each block"]},{q:"What is Nakamoto Consensus?",a:"The combination of proof-of-work, longest chain rule, and economic incentives",wrong:["Voting by coin holders","Consensus by the Bitcoin Foundation","Agreement between exchanges"]},{q:"Why does Bitcoin use the longest chain as the valid chain?",a:"Most proof-of-work indicates most energy/computational investment",wrong:["Random selection","Shortest chains are invalid","User voting"]},{q:"Nakamoto Consensus achieves agreement by:",a:"Having nodes follow the longest valid proof-of-work chain",wrong:["Requiring all nodes to vote on each transaction","Letting the wealthiest node decide which blocks are valid","Using a central server to broadcast the correct chain"]},{q:"What happens if two miners find a valid block at nearly the same time?",a:"A temporary fork occurs and resolves when the next block is found",wrong:["Both blocks are permanently added to the chain","The network shuts down until the conflict is resolved","The older miner's block always wins"]}],open_source:[{q:"Bitcoin being open source means:",a:"Anyone can read, audit, and propose changes to the code",wrong:["The code is secret but free to use","Only approved developers can view it","It costs nothing to mine"]},{q:"What license is Bitcoin Core released under?",a:"MIT License (open source)",wrong:["Proprietary commercial license","GPL v3 only","Patent-encumbered license"]},{q:"How can anyone contribute to Bitcoin Core?",a:"Submit pull requests on GitHub after code review",wrong:["Pay a developer fee","Get hired by a bank","Apply for a license"]},{q:"What is the purpose of code review in Bitcoin development?",a:"To catch bugs and security issues before deployment",wrong:["To slow down development","To charge developers money","To keep the code secret"]},{q:"Why is peer review critical in Bitcoin Core development?",a:"It catches bugs and vulnerabilities before they reach production, since changes affect billions in value",wrong:["It is just a formality required by the MIT license","Only one reviewer is needed for minor patches","Peer review slows down development unnecessarily"]}],coin_mixing_coinjoin_coin_control_utxo:[{q:"CoinJoin improves privacy by:",a:"Combining multiple users' transactions so individual spending is hard to trace",wrong:["Encrypting the blockchain","Deleting transaction history","Creating fake transactions"]},{q:"What is CoinJoin?",a:"A privacy technique combining multiple users\\' transactions to break heuristics",wrong:["A cryptocurrency mixer token","A type of hardware wallet","An exchange withdrawal method"]},{q:"What does coin control allow Bitcoin users to do?",a:"Manually select which UTXOs to spend in a transaction",wrong:["Control the price of bitcoin","Limit mining difficulty","Set transaction speed"]},{q:"What privacy benefit does proper UTXO management provide?",a:"Preventing address clustering and transaction graph analysis",wrong:["Increasing mining rewards","Reducing transaction fees","Speeding up confirmations"]},{q:'What is "coin control" in a Bitcoin wallet?',a:"The ability to manually select which UTXOs to spend in a transaction for better privacy",wrong:["A government program to regulate Bitcoin spending","Software that limits how much Bitcoin you can buy","A mining feature that controls block production"]}],environment___energy:[{q:"Bitcoin mining's relationship with renewable energy is:",a:"Miners actively seek cheap renewable and stranded energy, incentivizing green energy development",wrong:["Mining only uses coal","Renewable energy cannot power mining","Mining has no relationship with energy markets"]},{q:"What percentage of Bitcoin mining comes from renewable energy (estimates)?",a:"Estimates range from 50-60% using renewable or stranded energy",wrong:["0% - all coal","100% renewable","Less than 10%"]},{q:'What is "stranded energy" in Bitcoin mining?',a:"Energy that would otherwise go to waste due to lack of transmission infrastructure",wrong:["Energy from broken solar panels","Leftover battery power","Natural gas used for heating"]},{q:"How does Bitcoin mining help stabilize electrical grids?",a:"Miners can rapidly reduce load during peak demand (demand response)",wrong:["By storing electricity in batteries","By donating profits to utilities","By building more coal plants"]},{q:"What common criticism about Bitcoin energy use is often misrepresented?",a:"Per-transaction energy cost (Bitcoin uses same energy regardless of transaction count)",wrong:["It uses no energy at all","All energy comes from coal","Mining makes computers explode"]}],austrian_school_of_economics:[{q:"The Austrian School of Economics relates to Bitcoin because:",a:"It advocates for sound money with limited supply, which Bitcoin embodies",wrong:["It was founded by Satoshi Nakamoto","It requires government-controlled currency","It predicts Bitcoin will fail"]},{q:"Which Austrian economist emphasized the importance of sound money and criticized fiat?",a:"Ludwig von Mises and Friedrich Hayek",wrong:["John Maynard Keynes","Karl Marx","Milton Friedman"]},{q:"The Austrian School of Economics emphasizes:",a:"Sound money, free markets, and the dangers of central banking",wrong:["Government control of all monetary systems","That inflation is beneficial for economic growth","That central banks should print unlimited money"]},{q:'Who wrote "The Theory of Money and Credit"?',a:"Ludwig von Mises",wrong:["John Maynard Keynes","Paul Krugman","Adam Smith"]},{q:'Saifedean Ammous\' book "The Bitcoin Standard" argues that Bitcoin is the best form of money because:',a:"It is the hardest money ever created — no authority can inflate its supply",wrong:["It provides higher investment returns than gold over any comparable 10-year period","It is the only payment network capable of achieving true instant global settlement","A global coalition of central banks has adopted it as their primary reserve asset"]}],lindy_effect:[{q:'The term "Lindy Effect" was coined and popularized in its modern form by:',a:"Nassim Nicholas Taleb in his 2012 book Antifragile",wrong:["Satoshi Nakamoto in the Bitcoin whitepaper","Albert Goldman originally in 1964","Benoît Mandelbrot in The Fractal Geometry of Nature"]},{q:"What is the Lindy Effect?",a:"The longer something survives, the longer its remaining life expectancy",wrong:["A statistical model measuring how quickly Bitcoin mining difficulty adjusts to hash rate","A type of cryptographic hash function used to verify Bitcoin block headers on-chain","An industry certification that labels hardware wallet firmware as officially secure"]},{q:"The Lindy Effect applies to non-perishable things. Which of these would it NOT apply to?",a:"A human being - biological organisms have decreasing life expectancy with age",wrong:["Bitcoin, which has survived and strengthened over 15+ years of relentless stress-testing","The concept of sound money, which has persisted across thousands of years of civilisation","The C++ programming language, widely used on critical systems since the early 1980s"]},{q:"What concept is closely related to Lindy Effect in Bitcoin?",a:"Antifragility - stress makes the system stronger",wrong:["Inflation targeting","Proof of stake","Central banking"]},{q:"Why is Bitcoin's 15+ year survival significant for the Lindy Effect?",a:"Demonstrates resilience to attacks, bugs, and regulatory pressure",wrong:["Proves the codebase is now too rigid and entrenched to accept meaningful future upgrades","Makes it technically obsolete compared to newer blockchain protocols built after 2018","Shows that its energy consumption has compounded past any level that society can sustain"]}],softwar:[{q:"Jason Lowery's Softwar thesis argues that:",a:"Proof-of-work is a form of digital power projection analogous to military power in the physical world",wrong:["Bitcoin is a weapon system","Software replaces all hardware","Bitcoin was created by the military"]},{q:'Who authored the "Softwar" thesis about Bitcoin?',a:"Major Jason Lowery of the US Space Force",wrong:["Michael Saylor","Nick Szabo","Elizabeth Warren"]},{q:"What is the core argument of the Softwar thesis?",a:"Proof-of-work is a form of kinetic power projection for cyberspace",wrong:["Bitcoin should be banned","Proof of stake is superior","Bitcoin is a company"]},{q:"What does Softwar compare Bitcoin\\'s hash rate to?",a:"Physical military power projection and deterrence",wrong:["Social media likes","Stock market volume","Bank transaction counts"]},{q:"How does the Softwar thesis view Bitcoin mining in terms of national security?",a:"As a strategic asset that projects power in cyberspace, similar to how militaries project power in physical space",wrong:["As a threat to national security that should be banned","As purely an economic activity with no geopolitical significance","As a replacement for nuclear deterrence"]}],sidechains:[{q:"A Bitcoin sidechain is:",a:"A separate blockchain that is pegged to Bitcoin, enabling additional features while settling back to the main chain",wrong:["A backup copy of the Bitcoin blockchain","A faster version of Bitcoin Core","An altcoin that replaced Bitcoin"]},{q:"What is the Liquid Network?",a:"A federated sidechain enabling faster confidential Bitcoin transactions",wrong:["An Ethereum scaling solution","A mining pool","A hardware wallet"]},{q:"What is RSK (Rootstock)?",a:"A Bitcoin sidechain supporting smart contracts with merged mining",wrong:["A Russian Bitcoin exchange","A hardware wallet brand","A Lightning wallet"]},{q:"How are assets secured when moving to a sidechain?",a:"Through a federated peg locking bitcoin on mainchain",wrong:["By burning bitcoin permanently","By trusting a single company","No security is provided"]},{q:"What is a downside of federated sidechains compared to Bitcoin mainchain?",a:"Less decentralization due to reliance on federation members",wrong:["Higher transaction fees","Slower block times","No programming capabilities"]}],submarine_swap:[{q:"A submarine swap allows you to:",a:"Exchange on-chain Bitcoin for Lightning Bitcoin (or vice versa) trustlessly",wrong:["Mine Bitcoin using specialised deep-sea cooling rigs for better thermal efficiency","Send Bitcoin transactions without the internet using a mesh radio relay network","Convert Bitcoin into Ethereum through a cross-chain atomic bridge smart contract"]},{q:'Why is it called a "submarine" swap?',a:'On-chain is "above water" and Lightning off-chain is "below water" - you swap between the two',wrong:["The swap conceals funds below the blockchain visible layer before resurfacing on-chain","On-chain funds are submerged in a time-locked escrow vault beneath the mempool layer","The name comes from the HTLC diving beneath regular channel capacity during the swap"]},{q:"What enables submarine swaps to be trustless?",a:"HTLCs (Hash Time Locked Contracts)",wrong:["Centralized exchange custody","Bank wire confirmation","Social media verification"]},{q:"What problem do submarine swaps solve?",a:"Moving funds between on-chain and Lightning without closing channels",wrong:["Automatically rebalancing mining pool difficulty when large hash rate enters or exits","Stabilising the exchange rate between on-chain BTC and Lightning-denominated sats","Recovering wallet access when a user loses their hardware device or written seed phrase"]},{q:"Alex Bosworth and Olaoluwa Osuntokun created submarine swaps while at which company?",a:"Lightning Labs",wrong:["Blockstream","Chaincode Labs","River Financial"]}],supranational:[{q:'What does "supranational" mean in the context of Bitcoin?',a:"It transcends national borders and governments",wrong:["It is backed by the United Nations","It requires international approval to use","It can only be used between countries"]},{q:'What does it mean that Bitcoin is "supranational" money?',a:"It operates beyond any single nation's jurisdiction or control",wrong:["It is owned by the United Nations","Only governments can use it","It requires international banking licenses"]},{q:"Bitcoin settlement finality means:",a:"Once confirmed, transactions cannot be reversed",wrong:["Transactions can be disputed within 30 days","A central authority must approve each transaction","Only miners can verify if a transaction is final"]},{q:"Which of these best demonstrates Bitcoin's supranational nature?",a:"A citizen of any country can hold Bitcoin without a bank or government permission",wrong:["The UN officially recognized Bitcoin as legal tender in 2021","Bitcoin miners must register with their national government","Cross-border Bitcoin payments require a SWIFT code"]},{q:"What makes Bitcoin different from national currencies like the dollar or euro?",a:"No central bank can print more or manipulate its supply",wrong:["It is backed by gold reserves","It requires government approval","It only works online"]}],organic:[{q:"Bitcoin grew organically because:",a:"It had no pre-mine, no ICO, and no marketing budget",wrong:["A major corporation funded its development","Governments agreed to adopt it simultaneously","Social media algorithms promoted it automatically"]},{q:"What makes Bitcoin's distribution unique among cryptocurrencies?",a:"Fair launch - no coins were pre-allocated to founders",wrong:["Satoshi kept 50% of all coins before launch","Venture capitalists funded the initial distribution","Coins were distributed based on national GDP"]},{q:"How has Bitcoin grown without traditional marketing?",a:"Through grassroots adoption and word-of-mouth from users",wrong:["Massive advertising budgets","Celebrity endorsements","Government subsidies"]},{q:"What drives Bitcoin\\'s organic adoption in developing countries?",a:"Real need for inflation protection and remittance savings",wrong:["Central bank mandates","Corporate marketing campaigns","Mandatory school education"]},{q:"What is the role of Bitcoin\\'s open source community?",a:"Volunteer developers contribute code without corporate hierarchy",wrong:["They control Bitcoin Foundation","They receive government salaries","They own all bitcoins"]}],programmable:[{q:"Bitcoin Script is intentionally limited because:",a:"Simplicity reduces attack surface and increases security",wrong:["Satoshi was not a skilled programmer","The blockchain cannot process complex instructions","It was a temporary design meant to be upgraded"]},{q:'What does "Turing-incomplete" mean for Bitcoin Script?',a:"It cannot run arbitrary programs or infinite loops",wrong:["It cannot process any transactions at all","It requires a separate computer to verify","It can only handle one transaction per block"]},{q:"What makes Bitcoin programmable money?",a:"Bitcoin Script enables conditional spending and smart contracts",wrong:["Only banks can program it","It runs Python code directly","Central programmers control all transactions"]},{q:"What are timelocks in Bitcoin?",a:"Conditions preventing spending until a specific time or block height",wrong:["Physical locks on hardware wallets","Password requirements","Banking hours restrictions"]},{q:"What is a multisig (multi-signature) transaction?",a:"Requires multiple private keys to authorize spending",wrong:["Multiple transactions combined","Multiple miners confirming","Multiple exchanges involved"]}],ordinals:[{q:"Bitcoin Ordinals allow:",a:"Inscribing data (images, text) directly on individual satoshis",wrong:["Creating new tokens on the Bitcoin network","Speeding up transaction confirmation times","Reducing the total supply of Bitcoin"]},{q:"Why are Ordinals controversial in the Bitcoin community?",a:"They increase block space demand and fees for financial transactions",wrong:["They change the 21 million supply cap","They require a hard fork to implement","They give miners control over which transactions are valid"]},{q:"What are Bitcoin Ordinals?",a:"A numbering system for satoshis enabling inscription of arbitrary data",wrong:["A type of altcoin token","A mining algorithm","A Lightning channel type"]},{q:"What controversial use case emerged from Ordinals?",a:"BRC-20 tokens creating fungible tokens on Bitcoin",wrong:["Instant payment settlement","Hardware wallet security","Private key encryption"]},{q:"What is the debate around Ordinals inscriptions?",a:"They use block space, potentially raising fees for regular transactions",wrong:["They steal bitcoin from wallets","They hack the blockchain","They prevent mining from working"]}],geopolitics___macroeconomics:[{q:"Why is Bitcoin relevant to geopolitics?",a:"It provides a neutral monetary system outside any nation's control",wrong:["Major governments collectively control Bitcoin's code","Bitcoin mining is only legal in 5 countries","The UN regulates Bitcoin's international transfers"]},{q:'What is the "petrodollar" system?',a:"Oil is priced in US dollars, forcing global demand for the dollar",wrong:["A cryptocurrency backed by oil reserves","A Bitcoin mining technique using petroleum","A tax imposed on Bitcoin by oil-producing nations"]},{q:"Which country was the first to adopt Bitcoin as legal tender?",a:"El Salvador in September 2021",wrong:["United States","Japan","Germany"]},{q:"How do sanctions-evading nations view Bitcoin?",a:"As a way to circumvent SWIFT restrictions and frozen reserves",wrong:["As a threat to their currencies","As a US surveillance tool","As illegal everywhere"]},{q:"What macro trend drives Bitcoin adoption during inflation?",a:"Currency debasement making bitcoin\\'s fixed supply attractive",wrong:["Lower interest rates on bitcoin","Government bitcoin subsidies","Bank account requirements"]}],"op-codes":[{q:"Bitcoin OP_CODES are:",a:"Instructions in Bitcoin's scripting language that define spending conditions",wrong:["Error codes returned when a transaction fails","Codes used to communicate between mining pools","Secret backdoor commands for Bitcoin developers"]},{q:"OP_RETURN allows:",a:"Embedding small amounts of arbitrary data in the blockchain",wrong:["Reversing a confirmed transaction","Returning stolen Bitcoin to its owner","Increasing the block size limit"]},{q:"What is OP_CHECKSIG in Bitcoin Script?",a:"Verifies a digital signature against a public key",wrong:["Creates new bitcoins","Encrypts transaction data","Connects to mining pools"]},{q:"What was the OP_RETURN controversy?",a:"Its limit was reduced to prevent blockchain bloat from non-financial data",wrong:["It was used to hack exchanges","It created unlimited bitcoins","It stopped all transactions"]},{q:"What did Taproot enable for Bitcoin opcodes?",a:"More flexible scripting through Schnorr signatures and Merkle branches",wrong:["Removal of all previous scripts","Conversion to Ethereum compatibility","Centralized script approval"]}],public_key_vs_private_key:[{q:"Your Bitcoin public key is like:",a:"Your email address - you share it so people can send you Bitcoin",wrong:["Your password - never share it with anyone","Your bank PIN number - used to authorize spending","Your social security number - it proves your identity"]},{q:"If someone has your private key, they can:",a:"Spend all the Bitcoin controlled by that key",wrong:["Only view your transaction history","Reset your password and lock you out","Create new Bitcoin out of thin air"]},{q:"What is the relationship between private and public keys?",a:"Public keys are derived from private keys via one-way cryptographic function",wrong:["Private keys are given to everyone","Public keys encrypt private keys","They are identical numbers"]},{q:"What should you do with your private keys?",a:"Keep them secret and secure, never share with anyone",wrong:["Publish them online","Email them to exchanges","Print them on merchandise"]},{q:"What is the purpose of a public key?",a:"To receive bitcoin and verify signatures without revealing the private key",wrong:["To spend bitcoin alone","To mine new blocks","To create private keys"]}],transaction_fees:[{q:"Bitcoin transaction fees are determined by:",a:"The size of the transaction in bytes and current network demand",wrong:["A fixed percentage of the transaction amount","The number of Bitcoin being sent","The geographic distance between sender and receiver"]},{q:"When the mempool is full:",a:"Transactions with higher fees get confirmed first",wrong:["All transactions are rejected until it clears","The block size automatically increases","Transaction fees are refunded to senders"]},{q:"What determines Bitcoin transaction fees?",a:"Transaction size in bytes and current network demand (mempool congestion)",wrong:["Transaction amount in bitcoin","Sender\\'s reputation","Government regulation"]},{q:"What is the mempool?",a:"A waiting area for unconfirmed transactions held by nodes",wrong:["A mining hardware pool","A cryptocurrency exchange","A type of Bitcoin wallet"]},{q:"Why do fees spike during network congestion?",a:"Users compete for limited block space by bidding higher fees",wrong:["Miners arbitrarily raise prices","Exchanges charge extra","Bitcoin supply decreases"]}],philosophy:[{q:'"Don\'t trust, verify" means:',a:"Run your own node to independently verify all Bitcoin rules",wrong:["Never use Bitcoin because it cannot be trusted","Only trust exchanges that are government-regulated","Verify your identity before making transactions"]},{q:'The concept "Bitcoin is Time" by Gigi suggests:',a:"Bitcoin creates a decentralized clock through proof of work",wrong:["Bitcoin transactions can travel back in time","Bitcoin was invented to save people time","Bitcoin mining uses atomic clocks"]},{q:"What is the cypherpunk movement that birthed Bitcoin?",a:"Advocates for privacy through cryptography and code over trust",wrong:["Bankers wanting digital currency","Gamers creating virtual money","Governments tracking transactions"]},{q:'What does it mean that Bitcoin had a "fair launch"?',a:"No pre-mine, no ICO - anyone could mine from day one on equal terms",wrong:["The government approved it before launch","Satoshi distributed coins equally to all users","A committee reviewed and certified the genesis block"]},{q:'What does Bitcoin\\\'s "monetary policy" refer to?',a:"Fixed supply schedule with predictable issuance rate until 21 million",wrong:["Central bank interest rates","Government fiscal policy","Investment fund strategies"]}],halving:[{q:"The Bitcoin halving occurs every:",a:"210,000 blocks (approximately every 4 years)",wrong:["Every calendar year on January 3","Every 100,000 blocks","Whenever the price doubles"]},{q:"After the 2024 halving, the block reward is:",a:"3.125 BTC per block",wrong:["6.25 BTC per block","1.5625 BTC per block","50 BTC per block"]},{q:"The halving is significant because it:",a:"Mathematically enforces Bitcoin's decreasing supply issuance",wrong:["Doubles the total supply of Bitcoin","Reduces the number of active miners by half","Changes Bitcoin's consensus mechanism"]},{q:"What happens during a Bitcoin halving?",a:"Block reward paid to miners is cut in half",wrong:["Transaction fees double","Bitcoin supply doubles","Mining difficulty halves"]},{q:"When will the final bitcoin be mined?",a:"Around year 2140 when all 21 million are issued",wrong:["2025","2040","Never - mining continues forever"]}],bitcoin_vs_real_estate:[{q:"What key property rights advantage does Bitcoin have over real estate?",a:"It cannot be seized, taxed annually, or confiscated via eminent domain",wrong:["Real estate has stronger rights because it is protected by law","Bitcoin and real estate have identical property rights protections","Bitcoin ownership is not recognized by any major legal system"]},{q:"How do maintenance costs compare between Bitcoin and real estate?",a:"Bitcoin has near-zero costs; real estate requires taxes, insurance, and repairs",wrong:["Bitcoin requires expensive monthly server fees to maintain ownership","Real estate has no maintenance costs once the mortgage is paid off","Both assets have roughly equivalent ongoing maintenance expenses"]},{q:"Why is Bitcoin considered superior to real estate in terms of portability?",a:"A seed phrase can be memorized and carried across any border instantly",wrong:["Real estate deeds can be memorized and are just as portable","Bitcoin is less portable because it always requires internet access","Portability is irrelevant when comparing long-term stores of value"]},{q:"How does Bitcoin's divisibility compare to real estate?",a:"Bitcoin divides into 100 million satoshis; real estate cannot be micro-divided",wrong:["Real estate is more divisible because you can rent individual rooms","Bitcoin cannot be divided at all - you must buy a whole coin","Both assets offer identical divisibility through financial derivatives"]},{q:"What risk does real estate face that Bitcoin does not, related to government power?",a:"Eminent domain seizure, property tax liens, and government confiscation",wrong:["Governments can easily confiscate Bitcoin but not real estate","Neither asset faces any confiscation risk in democratic nations","Bitcoin faces greater government risk because it can be fully banned"]}],bitvm:[{q:"What does BitVM enable on Bitcoin without requiring a protocol change?",a:"Arbitrary computation verification through fraud proofs",wrong:["Turing-complete smart contracts executed by miners","On-chain virtual machine execution like the EVM","Zero-knowledge proof generation inside Bitcoin Script"]},{q:"BitVM uses which computational model to verify off-chain computation?",a:"An optimistic model with prover claims and verifier challenges",wrong:["A zero-knowledge model where proofs are posted each block","A consensus model where all nodes re-execute computation","A federated model where trusted signers attest to results"]},{q:"In BitVM, what is the fundamental logic gate used to represent any computable function?",a:"NAND gates",wrong:["AND gates","XOR gates","NOR gates"]},{q:"Who proposed the original BitVM whitepaper?",a:"Robin Linus",wrong:["Peter Todd","Jeremy Rubin","Andrew Poelstra"]},{q:"How does BitVM2 improve upon the original BitVM design?",a:"It reduces on-chain transactions needed for dispute resolution",wrong:["It adds Turing-complete execution directly on base layer","It eliminates the need for a verifier role entirely","It requires a soft fork to enable several new opcodes"]}],"block_time-block-size":[{q:"Why did Satoshi choose approximately 10 minutes for Bitcoin's target block time?",a:"It balances throughput with time needed for global block propagation",wrong:["It was arbitrary with no real technical justification behind it","Faster blocks would make mining unprofitable due to power costs","It matches the average time needed for international wire transfers"]},{q:"What is the difference between block weight and block size in Bitcoin?",a:"Weight counts witness bytes at a discount versus non-witness bytes",wrong:["Block weight and block size are identical with different names","Block weight measures computational effort to validate a block","Block weight only applies to Lightning Network transactions"]},{q:"What is the maximum block weight allowed by Bitcoin's consensus rules?",a:"4 million weight units (4 MWU)",wrong:["1 megabyte of raw data","8 million weight units (8 MWU)","2 million weight units (2 MWU)"]},{q:"Why does SegWit give witness data a discount in the block weight calculation?",a:"Witness data costs less for nodes to process, incentivizing adoption",wrong:["Witness data is encrypted and takes up less physical storage","The discount was a political compromise with no technical basis","Witness data is stored temporarily then deleted after 100 blocks"]},{q:'What is "blockspace economics" in Bitcoin?',a:"The fee market where users bid for limited space in each block",wrong:["A government program subsidizing mining in renewable energy zones","The cost of running a full node in electricity and bandwidth","A pricing model used for Lightning Network channel capacity"]}],burn_bitcoin:[{q:"What is the maximum amount of data that can be stored in an OP_RETURN output?",a:"80 bytes",wrong:["40 bytes","160 bytes","1000 bytes"]},{q:"What does it mean for Bitcoin to be provably unspendable through OP_RETURN?",a:"The output has no valid script path to spend it",wrong:["It requires a special private key to spend","It can only be spent after 100 confirmations","It is temporarily locked until a timelock expires"]},{q:"Roughly how many Bitcoin are estimated to be permanently lost or burned?",a:"Between 3-4 million BTC",wrong:["Less than 1 million BTC","Over 10 million BTC","Exactly 1 million BTC"]},{q:"What type of Bitcoin address output is provably unspendable with no script?",a:"Bare multisig with invalid pubkeys",wrong:["Standard P2PKH addresses","Wrapped P2SH addresses","Native P2WPKH addresses"]},{q:"What is proof of burn in the context of cryptocurrency?",a:"Demonstrating coins were sent to an unspendable address",wrong:["Mining blocks without ever receiving any block rewards","Permanently deleting the private keys to a wallet","Sending coins to a wallet whose owner has died"]}],consensus_pt2:[{q:"What does finality mean in Nakamoto Consensus?",a:"Reversals become exponentially harder with each confirmation",wrong:["Transactions are instantly and permanently irreversible","Miners hold a formal vote on transaction validity","The longest chain is always guaranteed to be correct"]},{q:"What are orphan blocks in Bitcoin?",a:"Valid blocks not included in the main chain",wrong:["Invalid blocks rejected by network nodes","Blocks that contain zero transactions inside","Alternative variants of the genesis block"]},{q:"What is selfish mining in Bitcoin?",a:"Withholding found blocks to gain unfair advantage",wrong:["Mining solo without joining any mining pool","Using only renewable energy sources for mining","Deliberately refusing to validate any transactions"]},{q:"What is the typical Bitcoin block propagation time?",a:"1-10 seconds globally",wrong:["About 60 seconds on average","Nearly instantaneous at all times","Approximately 10 full minutes"]},{q:"What was the FIBRE network designed to improve?",a:"Block propagation speed between miners",wrong:["Lightning Network payment routing","Wallet synchronization with nodes","Mining difficulty adjustment calculations"]}],cryptography_pt3:[{q:"What advantage do Schnorr signatures provide over ECDSA in Bitcoin?",a:"Key aggregation for efficient multi-signature transactions",wrong:["Quantum resistance that ECDSA fundamentally lacks","Smaller size in all cases regardless of signers","Available since day one but never actually used"]},{q:"What is MuSig2 in Bitcoin?",a:"A Schnorr-based multi-sig scheme producing one standard-looking signature",wrong:["A second version of the Bitcoin music streaming protocol","A next-generation mining algorithm replacing SHA-256 hashing","A Lightning Network routing protocol for two-hop payments"]},{q:"What are adaptor signatures used for in Bitcoin?",a:"Conditional payments where signing reveals a secret value",wrong:["Converting old formats to be Taproot-compatible ones","Signing transactions using multiple keys simultaneously","Adapting Script to support Turing-complete contracts"]},{q:"What is a Pedersen commitment?",a:"A commitment that hides a value while allowing math verification",wrong:["A legal agreement between developers to maintain the protocol","A type of fee commitment that is included in every block","A signed pledge by miners to always follow consensus rules"]},{q:"What is the current status of zero-knowledge proofs on Bitcoin?",a:"Being explored via projects like BitVM and validity rollups",wrong:["Fully implemented in Bitcoin Core since the Taproot upgrade","Impossible on Bitcoin due to fundamental Script limitations","Removed from Bitcoin in 2015 due to critical security risks"]}],"ctv-covenants":[{q:"What does BIP-119 (CheckTemplateVerify) allow a Bitcoin output to do?",a:"Commit to a specific future transaction template for spending",wrong:["Execute arbitrary smart contract code when it is spent","Lock funds until a specific block height has been reached","Require multiple signatures from different keys to spend"]},{q:'What is a "covenant" in the context of Bitcoin?',a:"A restriction on how a UTXO can be spent in the future",wrong:["A multisig arrangement between federation member nodes","A legal agreement between Lightning channel counterparties","A time-locked contract that expires after a set period"]},{q:'What Bitcoin use case does CTV enable through "congestion control"?',a:"Batching many payments into one transaction claimable later",wrong:["Auto-adjusting fees based on current mempool congestion","Throttling transactions a wallet can send within a block","Limiting block size during periods of high network load"]},{q:"What is OP_VAULT designed to provide using covenants?",a:"Time-delayed withdrawals with an emergency clawback option",wrong:["A decentralized exchange built for trustless atomic swaps","Cold storage that auto-moves funds to hardware wallets","Multi-party escrow designed for marketplace transactions"]},{q:"Why are covenants considered controversial by some Bitcoiners?",a:"They could enable coin censorship or spending blacklists",wrong:["They require a hard fork that would split the network","They make all transactions public and remove user privacy","They increase block size beyond what nodes can handle"]}],cycles:[{q:"What drives Bitcoin's historically observed ~4-year market cycle?",a:"The halving, which cuts new supply in half every ~4 years",wrong:["Government regulations that shift with 4-year election cycles","A scheduled software update that resets the network state","Random market psychology with no underlying structural driver"]},{q:"How does the Gartner Hype Cycle apply to each Bitcoin halving era?",a:"Each cycle shows trigger, peak hype, disillusionment, then recovery to a plateau",wrong:["Bitcoin skips disillusionment because the price only goes up long-term","The Gartner Hype Cycle only applies to new tech products, not currencies","Each Bitcoin cycle follows the exact same price pattern as the last one"]},{q:'What is the "lengthening cycles" debate in Bitcoin?',a:"The theory that each bull run takes longer to peak with smaller percentage gains",wrong:["The theory that mining cycles get shorter as hardware gets faster","A proposal to extend the halving interval from four years to eight","The idea that transaction confirmation times increase every year"]},{q:"Which on-chain metrics are commonly used to analyze Bitcoin market cycles?",a:"MVRV, NUPL, and the Pi Cycle Top indicator",wrong:["GDP growth, unemployment, and consumer price index","Twitter followers, Google Trends, and Reddit subs","Block size, node count, and developer commit stats"]},{q:'What is the "diminishing returns" theory in Bitcoin cycles?',a:"Each cycle's percentage gain shrinks, though absolute highs keep rising",wrong:["Returns are accelerating each cycle with larger percentage gains","Bitcoin will eventually produce negative returns in every cycle","It refers to decreasing energy efficiency of mining each cycle"]}],derivation_path:[{q:"What does a BIP-32 HD (Hierarchical Deterministic) wallet allow you to do?",a:"Generate unlimited key pairs from a single master seed",wrong:["Store multiple cryptocurrencies in one single private key","Recover funds without a seed phrase using only email","Connect directly to the network without running a node"]},{q:"In the derivation path m/84'/0'/0'/0/0, what does the \"84\" represent?",a:"BIP-84, the Native SegWit (bech32) address standard",wrong:["The year 1984 when public key crypto was standardized","The 84th account stored inside this particular wallet","The total number of addresses that can be derived"]},{q:"Which BIP defines the derivation path standard for Taproot (bc1p) addresses?",a:"BIP-86",wrong:["BIP-84","BIP-49","BIP-44"]},{q:"Why is sharing an xpub (extended public key) a privacy concern?",a:"It lets anyone see all addresses and balances from that account",wrong:["It allows someone to spend your Bitcoin without the private key","It broadcasts your seed phrase to every node on the network","It reveals your real-world name and identity on the blockchain"]},{q:'What is the "gap limit" in HD wallet address discovery?',a:"How many consecutive unused addresses are checked before stopping",wrong:["The maximum number of addresses a wallet can generate total","The time delay required between generating new addresses","The minimum spacing between two UTXOs in a transaction"]}],"difficulty-adjustment_pt2":[{q:"What algorithm does Bitcoin use for difficulty adjustment?",a:"Direct calculation based on actual vs target time",wrong:["PID controller algorithm with feedback loops","Neural network prediction of future hash rate","Moving average of recent hash rate samples"]},{q:"How many blocks is the difficulty retarget period?",a:"2,016 blocks",wrong:["1,008 blocks","4,032 blocks","10,080 blocks"]},{q:"What causes hash rate oscillation between mining pools?",a:"Miners chasing short-term luck variance",wrong:["Scheduled Bitcoin Core software update cycles","Daily difficulty adjustment recalculations","Network communication delays between nodes"]},{q:"What variance measure describes pool mining luck?",a:"Statistical variance around expected block discovery",wrong:["Fixed reward percentage distributed to miners","Difficulty share ratio across pool participants","Network propagation delay between peer nodes"]},{q:"How long does a difficulty epoch typically last?",a:"Approximately 2 weeks",wrong:["Exactly 1 week","About 1 month","Approximately 4 days"]}],dlcs:[{q:"In a Discreet Log Contract (DLC), what role does an oracle play?",a:"It signs a real-world outcome that determines how the contract pays out",wrong:["It holds the funds in escrow until both parties agree on the result","It executes smart contract code on a sidechain to settle the bet","It mines the specific transaction that settles the contract on-chain"]},{q:'What cryptographic technique makes DLCs "discreet" - invisible to the oracle?',a:"Adaptor signatures that use the oracle's attestation privately",wrong:["Zero-knowledge proofs that hide the contract from participants","Ring signatures that mix the contract with unrelated transactions","Homomorphic encryption that processes data without decrypting it"]},{q:"What is a common real-world use case for Discreet Log Contracts?",a:"Financial derivatives and betting settled by price or event data",wrong:["Decentralized file storage using the Bitcoin network as a backend","Privacy-preserving identity verification on the Bitcoin blockchain","Automated market making for Lightning Network liquidity pools"]},{q:"Why is the oracle in a DLC considered more trustworthy than traditional smart contract oracles?",a:"The oracle doesn't know the contract exists or what depends on it",wrong:["The oracle stakes Bitcoin collateral that is slashed if it lies","Multiple oracles must all agree before any payout can occur","The oracle runs inside a trusted execution environment on-chain"]},{q:"DLC.Link enables Discreet Log Contracts to be used primarily for what purpose?",a:"Bridging Bitcoin as collateral into DeFi without giving up custody",wrong:["Mining pool payout distribution based on individual hash rate","Decentralized DNS registration on the Bitcoin base layer","Cross-chain atomic swaps between Bitcoin and Ethereum directly"]}],"dollar-bitcoin_milkshake_theory":[{q:'Who originated the "Dollar Milkshake Theory"?',a:"Brent Johnson of Santiago Capital",wrong:["Ray Dalio of Bridgewater Associates","Michael Saylor of MicroStrategy","Saifedean Ammous of The Bitcoin Standard"]},{q:"What is the core thesis of the Dollar Milkshake Theory?",a:"The dollar strengthens by sucking up global liquidity while other fiat currencies weaken",wrong:["All fiat currencies collapse simultaneously and get replaced by Bitcoin","The dollar weakens as other currencies collectively strengthen against it","Central banks coordinate to create and adopt a single global currency"]},{q:'What is the "dollar strength paradox" in the Milkshake Theory?',a:"The dollar gets stronger vs other currencies while losing purchasing power vs hard assets",wrong:["A strong dollar always means the Bitcoin price will go down in tandem","Dollar strength is a reliable signal that the US economy is healthy","Nobody wants dollars but everyone needs them to service their debts"]},{q:"How does Bitcoin fit into the Dollar Milkshake Theory's endgame?",a:"After the dollar absorbs global liquidity, Bitcoin becomes the ultimate fiat exit",wrong:["Bitcoin is irrelevant to the theory because it isn't a fiat currency","Bitcoin collapses alongside other currencies during the dollar's rise","The theory predicts Bitcoin gets banned and replaced by state CBDCs"]},{q:"Why does global dollar demand play a central role in the Milkshake Theory?",a:"Trillions in dollar-denominated debt forces nations to buy dollars, strengthening it",wrong:["Global dollar demand is declining rapidly as nations actively de-dollarize","Dollar demand only matters for US domestic transactions and trade","The theory says dollar demand is irrelevant - only money supply matters"]}],"el-salvador":[{q:"What was the Chivo wallet in El Salvador's Bitcoin adoption?",a:"A government-issued Lightning wallet that gave citizens $30 in Bitcoin",wrong:["A private hardware wallet manufactured locally in El Salvador","An exchange platform where Salvadorans could trade altcoins","A banking app that only supported US dollar-based transactions"]},{q:'What is "Bitcoin Beach" and why is it significant to El Salvador\'s Bitcoin story?',a:"El Zonte - a village that built a grassroots Bitcoin economy before the national law",wrong:["A luxury resort in San Salvador that exclusively accepts Bitcoin payments","A government-built tourist attraction designed to promote Bitcoin adoption","A cryptocurrency exchange headquartered on the Salvadoran coastal region"]},{q:"What was President Bukele's core strategy behind making Bitcoin legal tender?",a:"Financial inclusion for the unbanked, foreign investment, and cheaper remittances",wrong:["Replacing the US dollar entirely with Bitcoin as the sole currency","Mining Bitcoin profitably using El Salvador's untapped oil reserves","Creating a government-controlled cryptocurrency to replace Bitcoin"]},{q:"How did the World Bank and IMF respond to El Salvador's Bitcoin law?",a:"They pushed back - the World Bank refused help and the IMF warned of risks",wrong:["Both organizations fully endorsed and helped fund the entire initiative","The IMF designed and helped build the Chivo wallet infrastructure","The World Bank provided a $500 million loan specifically for adoption"]},{q:"How did Lightning Network adoption benefit El Salvador's economy?",a:"It enabled fast, near-free payments and remittances, cutting out costly services",wrong:["Lightning was not used - only on-chain Bitcoin transactions were supported","Lightning made transactions faster but significantly more expensive overall","El Salvador banned Lightning in favor of on-chain-only Bitcoin payments"]}],"evidence-against-alts_pt2":[{q:'What is a "premine" and why is it a red flag for altcoins?',a:"Founders create and keep tokens before public launch, giving insiders an unfair edge",wrong:["A premine is a security feature that helps blockchains launch more quickly","A premine means the coin was tested before release, which is good practice","A premine is when miners validate the genesis block without earning fees"]},{q:"Why are many altcoin tokens considered securities under US law?",a:"They pass the Howey Test - buyers expect profits from a centralized team's efforts",wrong:["The SEC automatically classifies every digital asset as a regulated security","Any token traded on a cryptocurrency exchange is legally a security by default","Only tokens with market caps above $1 billion can qualify as securities"]},{q:'What is "VC token dumping" in the altcoin market?',a:"VCs invest early at a discount, then sell their tokens on retail investors at launch",wrong:["VCs donate their discounted tokens to charity projects after launch","VCs permanently lock their tokens to show support for the project","VCs use their tokens to fund open-source Bitcoin core development"]},{q:'Why do Bitcoiners argue that "decentralized governance tokens" are an oxymoron?',a:"Token voting concentrates power with whales and VCs, recreating inequality",wrong:["Governance tokens are too technically complex to ever implement properly","Bitcoin already uses governance tokens internally for protocol upgrades","Governance tokens have been declared illegal in every jurisdiction"]},{q:"What key evidence do Bitcoiners cite about Ethereum's centralization?",a:"A massive premine to insiders, repeated monetary policy changes, and known leadership",wrong:["Ethereum runs on a single server that is controlled by Vitalik Buterin","Ethereum transactions require explicit government approval before processing","Ethereum has fewer active nodes than a typical corporate cloud database"]}],"extension-blocks":[{q:"What are extension blocks in Bitcoin?",a:"Additional block space running alongside the main chain without changing it",wrong:["Larger blocks created by increasing the block size limit via a hard fork","Blocks reserved exclusively for Lightning Network channel operations","Compressed blocks that store only transaction hashes to save space"]},{q:"How do extension blocks differ from a traditional soft fork upgrade?",a:'Old nodes see extension transactions as "anyone-can-spend" outputs',wrong:["Extension blocks require all nodes to upgrade or be forked off the network","Extension blocks reduce the block size to improve network decentralization","Extension blocks are identical to soft forks but use a different label"]},{q:'What is the "space chain" concept related to extension blocks?',a:"A separate chain whose block space is auctioned via the main chain",wrong:["A satellite network that broadcasts Bitcoin blocks from orbit","A virtual reality environment where Bitcoin nodes operate in 3D","A specialized blockchain optimized for storing files over 4MB"]},{q:"What is a key trade-off of extension blocks?",a:"Non-upgraded nodes cannot fully validate extension block transactions",wrong:["All miners must upgrade their hardware simultaneously to participate","The main block size permanently increases for all future blocks","Lightning Network channels become incompatible with the base layer"]},{q:"Why have extension block proposals historically been controversial in Bitcoin development?",a:"They risk creating a second-class zone that weakens full node security",wrong:["They were proposed by altcoin developers trying to undermine Bitcoin","They would eliminate the need for the Lightning Network entirely","They require replacing SHA-256 with a completely different hash algorithm"]}],feedback_loops:[{q:"What is the price-hashrate-security feedback loop in Bitcoin?",a:"Higher price attracts miners, boosting hashrate, security, and confidence in a rising cycle",wrong:["Higher price causes miners to shut down, reducing hashrate and network security","Hashrate and price are completely independent with no meaningful connection","Security drops as price rises because more hackers are attracted to attack"]},{q:"How does the adoption-liquidity-utility feedback loop work in Bitcoin?",a:"More users deepen liquidity, making Bitcoin more useful, which attracts even more users",wrong:["More users raise fees, which drives away users and decreases overall liquidity","Liquidity falls as adoption grows because the total supply is permanently fixed","Adoption and liquidity have an inverse relationship in the Bitcoin network"]},{q:"How does the Lindy Effect create a reinforcing feedback loop for Bitcoin?",a:"Each day Bitcoin survives boosts confidence in its longevity, drawing more adoption",wrong:["The Lindy Effect means Bitcoin gets less reliable as its codebase ages","Older technology always gets replaced, so the Lindy Effect hurts Bitcoin","The Lindy Effect only applies to physical objects, not digital protocols"]},{q:"What is reflexivity in the context of Bitcoin market cycles?",a:"Perceptions influence fundamentals, which reinforce perceptions, creating self-amplifying cycles",wrong:["Reflexivity means Bitcoin's price always reflects its true fundamental value","It describes the tendency of Bitcoin to always revert to the same price","Reflexivity is a mining technique that increases block production speed"]},{q:"Why are Bitcoin's feedback loops considered among the most powerful in economics?",a:"Multiple self-reinforcing loops in price, hashrate, adoption, and security amplify together",wrong:["Bitcoin has only one feedback loop but it happens to be extremely strong","Bitcoin's feedback loops are actually weak compared to traditional market loops","Feedback loops only work in bull markets and reverse completely in bear runs"]}],first_principles:[{q:'What does "first principles thinking" mean when applied to Bitcoin?',a:"Breaking money down to fundamental properties and reasoning up from there",wrong:["Copying the design of existing currencies and then improving them","Following the majority opinion of mainstream economists on money","Starting with government approval and working backward from there"]},{q:"Which philosopher is most associated with the first principles method of reasoning from fundamental truths?",a:"Aristotle",wrong:["Plato","Socrates","Descartes"]},{q:"When reasoning from first principles about what makes good money, which set of properties matters most?",a:"Scarcity, portability, durability, divisibility, and fungibility",wrong:["Government backing, legal enforcement, and central bank control","Physical weight, aesthetic beauty, and historical tradition","Ease of printing, widespread banking, and inflation targeting"]},{q:"First principles thinking reveals what fundamental connection between energy and money?",a:"Money should represent stored energy - unforgeable costliness gives it value",wrong:["Money has no relationship to energy since it is purely a social construct","Only physical commodities can serve as money because they contain atoms","Energy is irrelevant to money if a government declares it legal tender"]},{q:"Why does first principles reasoning tend to lead people toward Bitcoin rather than altcoins?",a:"Bitcoin best satisfies the fundamental properties of sound money from first principles",wrong:["Bitcoin was the first cryptocurrency so it wins by default over altcoins","Altcoins are illegal in most countries so Bitcoin is the only legal option","Bitcoin has the best marketing team and strongest brand awareness overall"]}],foss:[{q:"What type of software license does Bitcoin Core use?",a:"MIT License",wrong:["GPL v3","Apache License 2.0","Creative Commons"]},{q:"Why is it important that Bitcoin Core is free and open-source software (FOSS)?",a:"Anyone can audit the code to verify no backdoors or hidden rules exist",wrong:["It makes Bitcoin free to use with zero transaction fees for users","It allows developers to create unlimited Bitcoin through the code","It means no one actually needs to run the Bitcoin software"]},{q:"What is the Guix build system used for in Bitcoin Core?",a:"Producing reproducible, auditable binaries so anyone can verify the software",wrong:["Automatically deploying Bitcoin Core updates to all nodes across the network","Managing the peer-review and merge workflow for Bitcoin Core pull requests","Cross-compiling Bitcoin Core binaries optimised for different CPU architectures"]},{q:'"Linus\'s Law" states that "given enough eyeballs, all bugs are shallow." How does this apply to Bitcoin?',a:"Thousands of developers review Bitcoin's code, so vulnerabilities get found and fixed faster",wrong:["Linux servers are the only machines capable of running Bitcoin full nodes properly","Linus Torvalds personally reviews and audits every Bitcoin Core release himself","Bitcoin can only run on open-source operating systems like Linux and FreeBSD"]},{q:"Why does open-source matter specifically for money/monetary software like Bitcoin?",a:"Users must verify the rules of their money - no hidden inflation or secret changes",wrong:["Open-source software is always faster and more efficient than proprietary code","It allows banks to freely copy Bitcoin and make their own branded version","It makes Bitcoin significantly easier for governments to regulate and control"]}],geopolitics___macroeconomics_pt2:[{q:"What is the BRICS de-dollarization movement and how does it relate to Bitcoin?",a:"BRICS nations are reducing dollar dependence, creating demand for neutral reserves like Bitcoin",wrong:["BRICS is a Bitcoin mining pool that is jointly operated by five nations","BRICS nations have collectively banned Bitcoin to protect local currencies","BRICS de-dollarization means these countries adopted Bitcoin as legal tender"]},{q:'What is the "strategic Bitcoin reserve" concept that multiple nations are exploring?',a:"Nations accumulating Bitcoin as a reserve asset alongside gold for its scarcity and hedge value",wrong:["A requirement for all nations to back their fiat currency reserves with Bitcoin","A UN mandate requiring every country to hold at least one thousand Bitcoin","A program where central banks replace all existing gold reserves with Bitcoin"]},{q:'What is the "nation-state game theory" argument for Bitcoin adoption?',a:"Early adopter nations gain a massive strategic edge, pressuring others to follow or fall behind",wrong:["Nations banning Bitcoin grow stronger because they fully control their money supply","Game theory proves that no nation will ever voluntarily adopt Bitcoin as a reserve","Nation-state game theory only applies to countries that possess nuclear weapons"]},{q:"How do proponents respond to critics who say Bitcoin is used for sanctions evasion?",a:"Bitcoin's transparent public ledger makes transactions easier to trace than physical cash",wrong:["Bitcoin supporters agree that sanctions evasion is its primary real-world use case","Bitcoin transactions are completely invisible and undetectable to all governments","Sanctions don't apply to digital assets under any current international law"]},{q:"How do institutions like the IMF and World Bank view Bitcoin?",a:"Generally hostile - they've pressured nations like El Salvador to drop Bitcoin legal tender status",wrong:["The IMF and World Bank are actually the largest institutional Bitcoin holders today","Both organizations have publicly endorsed Bitcoin as the future of global finance","The IMF created Bitcoin as a planned replacement for Special Drawing Rights"]}],governance_pt2:[{q:"Who can submit a Bitcoin Improvement Proposal (BIP)?",a:"Anyone in the Bitcoin community",wrong:["Only Bitcoin Core maintainers","Only miners with enough hash rate","Only officially registered developers"]},{q:"What activation method does BIP 9 use?",a:"Miner signaling with version bits during a defined window",wrong:["Node operators vote directly without miner input","Core developers set a flag day with no miner input","Miners and the SEC jointly approve the activation"]},{q:"BIP 8 improves on BIP 9 by adding what option?",a:'A "lock-in on timeout" (LOT=true) that forces activation even without miner majority',wrong:["A mandatory 95% node upgrade threshold that must be met before version bit signaling","An emergency pause mechanism letting any single mining pool block the activation","A two-thirds supermajority developer vote required before version bit signaling begins"]},{q:"What does UASF stand for?",a:"User-Activated Soft Fork",wrong:["Unified Active Soft Fork","Universal Auto Soft Fork","User Approval Soft Fork"]},{q:"What was Speedy Trial used for in Bitcoin?",a:"Taproot activation with a shortened signaling period",wrong:["SegWit activation with extended miner coordination","Lightning Network deployment across mainnet nodes","Difficulty adjustment algorithm changes and updates"]}],hardware:[{q:"What makes the Coldcard hardware wallet stand out among Bitcoin hardware wallets?",a:"It's air-gapped, Bitcoin-only, and supports NFC signing",wrong:["It supports thousands of altcoins and NFTs","It connects directly to the internet for speed","It's the cheapest hardware wallet available"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction) and why is it important for hardware wallets?",a:"A format for building transactions on one device and signing on another",wrong:["A Bitcoin address type exclusive to hardware wallets","A protocol for sending Bitcoin over Bluetooth","A backup format for storing seed phrases digitally"]},{q:"What is SeedSigner?",a:"A DIY, open-source, air-gapped wallet built on a Raspberry Pi",wrong:["A cloud service that generates seed phrases for you","A proprietary hardware wallet made by Ledger","An app that signs transactions via phone fingerprint"]},{q:'What is a "secure element" chip in hardware wallets?',a:"A tamper-resistant chip that stores keys and blocks extraction",wrong:["A chip that connects the wallet to Wi-Fi securely","A component that speeds up transaction processing","A GPS module that tracks the wallet for recovery"]},{q:'What does "air-gapped" mean when describing a hardware wallet like Coldcard or Foundation Passport?',a:"It never connects to internet - data moves via SD card, QR, or NFC",wrong:["The wallet is sealed in a vacuum to prevent tampering","The wallet uses satellite connections instead of Wi-Fi","The wallet can only be used outdoors for security"]}],history_pt3:[{q:"Approximately how many BTC did Mt. Gox lose in its collapse?",a:"850,000 BTC",wrong:["100,000 BTC","2 million BTC","50,000 BTC"]},{q:"What year did the Silk Road marketplace get seized?",a:"2013",wrong:["2011","2015","2017"]},{q:"How many Bitcoins were exchanged for two pizzas on Bitcoin Pizza Day?",a:"10,000 BTC",wrong:["1,000 BTC","100,000 BTC","1,000,000 BTC"]},{q:"What was the main conflict of the Blocksize War?",a:"Whether to increase block size limit",wrong:["Changing Bitcoin to proof of stake","Adding privacy features to Bitcoin","Changing the halving schedule"]},{q:"What was SegWit2x?",a:"Failed agreement to double block size after SegWit",wrong:["Successful hard fork increasing block size","A new proof-of-work mining algorithm","A second layer scaling protocol"]}],improved_incentive_structure:[{q:'How does Bitcoin "fix broken incentives" in the current monetary system?',a:"By removing money printing, it forces honest accounting and ends inflation of debt",wrong:["It gives governments better tools to manage the economy","It doesn't change incentives - just moves them to digital","It fixes incentives by making all transactions government-traceable"]},{q:'What does "low time preference society" mean in the context of a Bitcoin standard?',a:"People plan long-term and save more because their money gains value over time",wrong:["A society that doesn't care about time and works fewer hours","A society where transactions must complete within strict time limits","A society that only uses Bitcoin for short-term speculation"]},{q:'Why is proof of work considered a "fair distribution" mechanism for new Bitcoin?',a:"Anyone can mine by spending real energy - no pre-mines or insider allocations",wrong:["Proof of work gives equal Bitcoin to every person on Earth","Early miners got special privileges that later miners don't","Proof of work distributes Bitcoin based on geographic location"]},{q:"How does sound money (like Bitcoin) change savings and investment behavior?",a:"People save more and only invest in projects with real returns above deflation",wrong:["Sound money discourages saving because money becomes too valuable","Investment behavior stays the same regardless of monetary system","Sound money causes everyone to hoard and collapse the economy"]},{q:"What broken incentive does fiat money create that Bitcoin eliminates?",a:"Fiat rewards borrowing over saving because inflation erodes purchasing power",wrong:["Fiat incentivizes too much saving, which Bitcoin fixes","Fiat money has no broken incentives - it works as designed","Bitcoin creates the same borrow incentive since rates exist"]}],"investment-strategy_pt4":[{q:"What is UTXO management for tax optimization?",a:"Choosing specific UTXOs with known cost bases to minimize capital gains taxes",wrong:["Automatically hiding Bitcoin transactions from the IRS","Converting all UTXOs to altcoins before tax season","Splitting Bitcoin into $600 transactions to avoid reporting"]},{q:'What does "step-up in cost basis" mean for inherited Bitcoin?',a:"Cost basis resets to market price at owner's death, erasing prior gains",wrong:["Inherited Bitcoin is always taxed at the original purchase price","There is no tax on inherited Bitcoin in any jurisdiction","The cost basis doubles each year after inheritance"]},{q:"What is a Bitcoin IRA?",a:"A self-directed retirement account holding Bitcoin with tax advantages",wrong:["A government program that pays retirees in Bitcoin","An insurance policy replacing lost or stolen Bitcoin","A bank savings account that earns interest in Bitcoin"]},{q:"Why do experienced Bitcoiners warn against lending out your Bitcoin?",a:"Lending platforms like Celsius and BlockFi collapsed, losing depositor funds",wrong:["Bitcoin code prevents any form of lending or borrowing","Lending Bitcoin causes the network to slow down significantly","Bitcoin interest rates are always negative so you lose money"]},{q:"Why is cost basis tracking important for Bitcoin investors?",a:"Each purchase creates a separate tax lot needed for capital gains calculations",wrong:["Cost basis tracking is only needed for exchange-held Bitcoin","The IRS uses a flat tax rate on all Bitcoin regardless of price","Cost basis is irrelevant since Bitcoin is classified as currency"]}],laws_of_thermodynamics:[{q:"How does the First Law of Thermodynamics (conservation of energy) relate to Bitcoin mining?",a:"Miners convert electricity into computational work securing the ledger",wrong:["Bitcoin mining creates energy from nothing to power the network","The First Law means Bitcoin can only exist in cold climates","Energy is destroyed during mining, explaining the high usage"]},{q:'What does "unforgeable costliness" mean in Bitcoin\'s thermodynamic context?',a:"Real energy must be spent to produce Bitcoin and this cost can't be faked",wrong:["Bitcoin transactions are free because the network is decentralized","The cost of mining is purely artificial with no security purpose","Unforgeable costliness means Bitcoin wallets cannot be hacked"]},{q:"How does the Second Law of Thermodynamics (entropy always increases) connect to Bitcoin?",a:"Proof of work creates order in the ledger by increasing entropy via energy use",wrong:["Bitcoin violates the Second Law by creating value from nothing","Entropy has no connection to digital systems like Bitcoin","The Second Law means Bitcoin will eventually stop working"]},{q:'Why do some physicists describe proof of work as "thermodynamic security"?',a:"Reversing the chain would require re-spending all the energy that built it",wrong:["Because Bitcoin mining rigs get very hot during operation","Because proof of work requires cooling systems to function","Because thermodynamic equations are used to set transaction fees"]},{q:'What is the "Maxwell\'s Demon" analogy sometimes applied to Bitcoin?',a:"You can't sort molecules or secure a ledger without real energy expenditure",wrong:["Maxwell's Demon is the name of the first Bitcoin mining software","It describes a theoretical AI attack that takes over the network","It refers to Bitcoin price randomness being like particle motion"]}],"layer-2-lightning_pt4":[{q:"What does Lightning Labs' Loop service do?",a:"It moves funds between on-chain and Lightning using submarine swaps",wrong:["It mines Bitcoin directly from a Lightning node","It converts Bitcoin to altcoins through atomic swaps","It syncs the Lightning channel graph to the Bitcoin timechain"]},{q:"What is Multi-Path Payments (MPP) on Lightning?",a:"Splitting a payment across multiple routes to exceed single-channel limits",wrong:["Making multiple payments to different recipients simultaneously","A backup payment method used only if Lightning is offline","Sending the same payment through multiple channels for redundancy"]},{q:"What privacy advantage does AMP have over basic MPP on Lightning?",a:"Each shard has a different payment hash, making it harder for routing nodes to link shards",wrong:["AMP wraps each shard in an extra onion layer completely invisible to intermediate nodes","AMP routes every shard through Tor by default, concealing the sender's network identity","AMP uses zero-knowledge proofs so routing nodes cannot observe any payment metadata"]},{q:"What is trampoline routing on the Lightning Network?",a:"Delegating route calculation to intermediate nodes for lighter clients",wrong:["Bouncing payments off satellites for wider global coverage area","A routing method that always prioritizes the fastest available path","A security protocol that encrypts all payment amounts in transit"]},{q:"What are channel factories in the Lightning Network?",a:"Opening many channels among multiple parties in one on-chain transaction",wrong:["Physical facilities where Lightning network nodes are manufactured","Automated systems that create channels based on user demand levels","Software that converts on-chain wallets into Lightning-ready wallets"]}],"layer-2-lightning_pt5":[{q:"What is liquidity management on the Lightning Network?",a:"Balancing inbound and outbound capacity to reliably route payments",wrong:["Converting Lightning Bitcoin back to regular on-chain Bitcoin","Managing the total circulating supply of Bitcoin on Lightning","Keeping Lightning nodes continuously connected to the internet"]},{q:"What is channel rebalancing on Lightning?",a:"Moving funds between your own channels to redistribute liquidity",wrong:["Closing and reopening channels with updated funding parameters","Resetting all channel state back to the initial funding amount","Transferring full channel ownership to a different Lightning node"]},{q:"What is a Lightning Service Provider (LSP)?",a:"A service offering liquidity and channel management for easy onboarding",wrong:["An internet service provider that specializes in Bitcoin traffic","A government-licensed operator required to run Lightning nodes","A cloud service that mines Bitcoin using collected Lightning fees"]},{q:"What are zero-conf channels on Lightning?",a:"Channels usable immediately without waiting for on-chain confirmation",wrong:["Channels that require zero Bitcoin as a deposit to open them","Channels that provide completely zero-fee routing for payments","Channels that are permanent and cannot be closed once opened"]},{q:"How do Lightning routing nodes earn revenue?",a:"By charging small fees for forwarding payments through their channels",wrong:["By mining new Bitcoin on the Lightning Network second layer","By collecting a percentage of all Lightning transactions globally","By selling their channel and routing data to analytics companies"]}],"layer-3-sidechains":[{q:"How does the Liquid Network secure its two-way peg to Bitcoin?",a:"Through a federation of functionaries managing the peg via multisig",wrong:["Through merge-mining where Bitcoin miners also validate Liquid","Through a trustless smart contract deployed on Bitcoin's base layer","Through proof-of-stake consensus among Liquid token holder nodes"]},{q:"How does RSK (Rootstock) secure its sidechain?",a:"Through merge-mining where Bitcoin miners also validate RSK blocks",wrong:["Through a federation of trusted companies that collectively sign","Through proof-of-stake where RSK token holders vote on blocks","Through BitVM fraud proofs posted to Bitcoin's main base layer"]},{q:"What consensus mechanism does Stacks use to connect to Bitcoin?",a:"Proof of Transfer (PoX), where miners spend BTC to produce blocks",wrong:["Proof of Work using the same SHA-256 algorithm as Bitcoin mining","Delegated Proof of Stake with community-elected block producers","Proof of Authority using a fixed and permissioned validator set"]},{q:"What are drivechains (BIP-300) designed to enable?",a:"Permissionless sidechains with miner-voted withdrawals to mainchain",wrong:["Faster block times on Bitcoin by reducing difficulty adjustment","A new Lightning channel type that skips on-chain funding steps","Decentralized mining pools that auto-distribute block rewards"]},{q:"What is the primary security concern with federated sidechains like Liquid?",a:"Users must trust federation members not to collude and steal funds",wrong:["The sidechain can reverse Bitcoin base layer transactions at will","Federated sidechains consume more energy than Bitcoin's proof-of-work","The federation has the power to change Bitcoin's 21 million cap"]}],maximalism_pt2:[{q:'What do Bitcoiners mean when they call "toxic maximalism" an immune response?',a:"Aggressive pushback against scams protects newcomers like an immune system",wrong:["Maximalists spread computer viruses to attack competing altcoin networks","Toxic maximalism is a disease Bitcoin developers are actively trying to cure","It means Bitcoin's code automatically rejects transactions from altcoins"]},{q:'What is the "altcoin opportunity cost" argument made by Bitcoin maximalists?',a:"Money spent on altcoins could have gone to Bitcoin, which outperforms long-term",wrong:["Altcoins are free to create so there is no real opportunity cost at all","Bitcoin maximalists believe altcoin trading increases Bitcoin's overall value","Opportunity cost is a fiat concept that does not apply to digital assets"]},{q:"Why do Bitcoin-only companies (like Swan, River, and Unchained) choose not to support altcoins?",a:"They see promoting altcoins as ethically wrong since most will fail and harm users",wrong:["They lack the technical capability needed to support other cryptocurrency tokens","Government regulations currently prohibit companies from offering multiple cryptos","Supporting altcoins would make their exchange and wallet software too slow"]},{q:'What is the "ethical case" for Bitcoin maximalism?',a:"Promoting risky altcoins to unsophisticated investors causes real financial harm",wrong:["Bitcoin maximalists believe they have a religious duty to spread adoption","Ethics demand that all financial technologies be treated equally by default","The ethical case is that Bitcoin miners deserve all cryptocurrency profits"]},{q:'How does Gresham\'s Law ("bad money drives out good") apply to the Bitcoin maximalism argument?',a:"People spend weak fiat and altcoins while hoarding Bitcoin as the hardest money",wrong:["Gresham's Law proves that cheaper altcoins will eventually replace Bitcoin","It means governments will ultimately force citizens to use Bitcoin only","Gresham's Law only applies to physical coins and not digital currencies"]}],mining_pt5:[{q:"What does Stratum V2 allow individual miners to do that Stratum V1 does not?",a:"Choose their own transactions for block templates",wrong:["Mine without needing any internet connection","Bypass the network difficulty adjustment algorithm","Mine multiple different coins at the same time"]},{q:"What is a block template in Bitcoin mining?",a:"A candidate block with selected transactions awaiting a valid hash",wrong:["A design blueprint for building new ASIC mining hardware","A backup copy of the entire Bitcoin blockchain ledger","A reusable template for creating new cryptocurrency mining pools"]},{q:"What is a selfish mining attack?",a:"Withholding discovered blocks to gain an unfair chain advantage",wrong:["Refusing to share mining profits with other pool members","Mining only low-fee transactions for the miner's personal gain","Using stolen electricity to illegally power Bitcoin mining rigs"]},{q:"What is ASICBoost?",a:"A technique that optimizes SHA-256 to reduce energy per hash",wrong:["A specific brand of mining hardware manufactured by Bitmain","A firmware update that automatically doubles any miner's hashrate","A method to cool ASIC miners using advanced liquid nitrogen"]},{q:"What is the difference between overt and covert ASICBoost?",a:"Overt is visible in block headers; covert is hidden from view",wrong:["Overt is legal in all jurisdictions while covert is illegal","Overt uses significantly more energy per hash than covert does","Overt works on any ASIC while covert is Bitmain hardware only"]}],mining_pt6:[{q:'What is "hash price" in Bitcoin mining economics?',a:"Revenue earned per unit of hash rate per day",wrong:["Cost to purchase a single ASIC miner","Bitcoin's price divided by total hash rate","Electricity cost per hash computation"]},{q:"What typically happens to less efficient miners shortly after a Bitcoin halving?",a:"They become unprofitable and may shut down",wrong:["They automatically receive double the reward","Their hash rate doubles to compensate","They permanently switch to mining altcoins"]},{q:"What is the typical operational lifespan of an ASIC miner before it becomes obsolete?",a:"Approximately 3 to 5 years",wrong:["About 6 months on average","Over 20 years with maintenance","Exactly one halving cycle"]},{q:"What is the breakeven electricity cost for Bitcoin mining?",a:"The kWh price where revenue equals costs",wrong:["A fixed rate set by Bitcoin developers","The average electricity cost worldwide","The minimum power to run one ASIC"]},{q:"As block subsidies decrease over time, what must replace them to incentivize miners?",a:"Transaction fees paid by users",wrong:["Government subsidies for miners","Increased mining difficulty","New coins from hard forks"]}],"misconceptions-fud_pt2":[{q:'How do Bitcoiners respond to "Bitcoin is too volatile to be money"?',a:"Every 4-year period has been profitable and volatility decreases over time",wrong:["They agree volatility makes Bitcoin unsuitable as money","They say volatility doesn't exist if you ignore the price","They claim Bitcoin's price is actually fixed by miners"]},{q:'Why is the claim "quantum computers will break Bitcoin" misleading?',a:"Such computers don't exist yet and Bitcoin can upgrade before they do",wrong:["Bitcoin already uses quantum-resistant encryption algorithms","Quantum computers actually strengthen Bitcoin's security","Satoshi designed Bitcoin to be immune to all future computing"]},{q:'What is the rebuttal to "Tether (USDT) props up Bitcoin\'s price"?',a:"Bitcoin grew for years before Tether and kept rising through its controversies",wrong:["Tether holds 100% of its reserves in Bitcoin directly","Bitcoin's price is determined solely by mining costs","Tether was created by Satoshi as part of Bitcoin's design"]},{q:'Why is "Bitcoin is a pyramid scheme" factually wrong?',a:"It has no company, no CEO, no return promises, and no recruitment profits",wrong:["Because early adopters are guaranteed profits by the protocol","Because Satoshi Nakamoto still runs the company behind Bitcoin","Because the Bitcoin protocol pays dividends to long-term holders"]},{q:'What is the strongest argument against "governments will ban Bitcoin"?',a:"China banned it multiple times yet it kept growing, and the US approved ETFs",wrong:["Governments lack the technology to detect Bitcoin transactions","International law prevents any country from banning crypto","Bitcoin automatically shuts down in countries where it's banned"]}],nodes_pt4:[{q:"What is the key difference between a pruned node and an archival (full) node?",a:"A pruned node deletes old block data after verifying it",wrong:["A pruned node skips transaction verification entirely","An archival node only stores the UTXO set","A pruned node cannot validate new transactions"]},{q:"What does BIP 152 (Compact Block Relay) do?",a:"Sends short transaction IDs instead of full transactions",wrong:["Compresses the entire blockchain into smaller files","Allows nodes to skip blocks during initial sync","Encrypts block data for privacy between nodes"]},{q:"What is the Erlay protocol designed to improve?",a:"Transaction relay efficiency between nodes",wrong:["Block mining speed via nonce optimization","Lightning Network channel capacity","Wallet synchronization for mobile devices"]},{q:"What is the UTXO set and why does its size matter for nodes?",a:"All unspent outputs nodes must keep in memory for validation",wrong:["A list of all transactions ever made on Bitcoin","A record of all mining rewards ever distributed","A backup of private keys stored across the network"]},{q:"What is a major concern about running a Bitcoin full node related to bandwidth?",a:"Relaying transactions and blocks uses significant upload bandwidth",wrong:["Nodes must pay per-megabyte fees to the network","Bandwidth usage is zero after initial block download","Only mining nodes consume significant bandwidth"]}],nodes_pt5:[{q:"What programming language is Bitcoin Core primarily written in?",a:"C++",wrong:["Rust","Python","Java"]},{q:"What is btcd?",a:"An alternative Bitcoin full node written in Go",wrong:["A Bitcoin wallet for desktop computers","A command-line tool for Bitcoin mining","A testing framework for Bitcoin Core"]},{q:"What are reproducible builds in the context of Bitcoin Core?",a:"Anyone can compile source and get an identical binary",wrong:["A system where Bitcoin Core auto-updates itself","A method to restore a node from a backup","A way to compile Bitcoin Core faster on CPUs"]},{q:"What is Guix used for in Bitcoin Core development?",a:"A build system for reproducible, verifiable builds",wrong:["A graphical interface for running a Bitcoin node","A security scanner for checking vulnerabilities","A package manager for installing Bitcoin wallets"]},{q:"Why is it important to be able to build Bitcoin Core from source?",a:"To verify the code and ensure your binary matches it",wrong:["Because pre-built binaries aren't available","To get access to hidden developer features","Because source builds make the node faster"]}],"op-codes_pt2":[{q:"What would OP_CAT enable if re-enabled?",a:"Concatenation of data values in script",wrong:["Comparison of timestamp values","Multiplication of numeric values","Direct verification of signatures"]},{q:"What does OP_CHECKSIGFROMSTACK verify?",a:"Arbitrary message signatures on the stack",wrong:["Only standard transaction signatures","Block signatures submitted by miners","Lightning Network commitment signatures"]},{q:"What is Simplicity designed for in Bitcoin?",a:"Formal verification of smart contracts",wrong:["Faster transaction processing speeds","Simplified wallet address formats","Reduced overall block sizes"]},{q:"What is a major limitation of Bitcoin Script?",a:"No loops or complex control flow",wrong:["Maximum of 100 opcodes per script","Cannot handle any signatures","Requires active internet access"]},{q:"Which script type was introduced with Taproot?",a:"P2TR (Pay to Taproot)",wrong:["P2SH (Pay to Script Hash)","P2WSH (Pay to Witness Script)","P2PKH (Pay to Pub Key Hash)"]}],"orange-pilling_pt2":[{q:'What is the "Socratic method" approach to orange-pilling someone about Bitcoin?',a:"Asking questions that lead them to discover Bitcoin's value themselves",wrong:["Quoting ancient Greek philosophers who predicted digital money","Having the person read the Bitcoin whitepaper out loud to you","Debating them aggressively until they agree Bitcoin is good"]},{q:'What is "progressive disclosure" when introducing someone to Bitcoin?',a:"Starting with simple concepts they care about, then going deeper",wrong:["Showing them Bitcoin's full transaction history from genesis","Revealing your entire Bitcoin portfolio to build their trust","Disclosing all of Bitcoin's technical flaws upfront to seem honest"]},{q:"When orange-pilling family members, what is generally the most effective approach?",a:"Focus on what they care about - savings, retirement, their future",wrong:["Send them a 3-hour technical podcast about mining and hashing","Buy them Bitcoin without asking and surprise them with it later","Bring it up at every family dinner until they finally agree"]},{q:"What is one of the biggest mistakes people make when trying to orange-pill someone?",a:"Information overload - dumping too much detail at once",wrong:["Being too patient and waiting for them to ask questions","Starting with how Bitcoin helps people in other countries","Recommending they read a book about the history of money"]},{q:"Which book is widely considered the best starting point for orange-pilling someone interested in economics and sound money?",a:"The Bitcoin Standard by Saifedean Ammous",wrong:["Mastering Bitcoin by Andreas Antonopoulos","Programming Bitcoin by Jimmy Song","The Blocksize War by Jonathan Bier"]}],ordinals_inscriptions:[{q:"Who proposed the Ordinal Theory for Bitcoin?",a:"Casey Rodarmor",wrong:["Adam Back","Pieter Wuille","Satoshi Nakamoto"]},{q:"How are individual satoshis numbered in Ordinal Theory?",a:"Sequentially based on mining order",wrong:["Randomly assigned by the network","By their transaction ID hash","By the receiving wallet address"]},{q:"What do inscriptions attach to specific satoshis?",a:"Arbitrary data like images or text",wrong:["Private keys for spending them","Their full transaction history","Multisig spending conditions"]},{q:"What token standard emerged from Ordinals functionality?",a:"BRC-20",wrong:["ERC-20","RGB","Omni Layer"]},{q:"What was a major criticism of Ordinals regarding block space?",a:"They use limited block space for non-monetary data",wrong:["They significantly reduce mining reward amounts","They break Bitcoin's core consensus rules","They allow theft of other users' funds"]}],philosophy_pt2:[{q:"Who wrote the Cypherpunk Manifesto?",a:"Eric Hughes",wrong:["Timothy May","Julian Assange","Nick Szabo"]},{q:"What concept did Timothy May advocate for in the Crypto-Anarchist Manifesto?",a:"Using cryptography to protect individual privacy",wrong:["Building centralized digital currency systems","Government regulation of all encryption tools","Corporate ownership of communication networks"]},{q:"What was Nick Szabo's Bit Gold concept?",a:"A digital collectible using proof of work",wrong:["A stablecoin backed by physical gold","A centralized government digital currency","A Lightning-style payment channel design"]},{q:"What did Wei Dai propose with b-money?",a:"Anonymous digital cash with decentralized minting",wrong:["A blockchain with standard mining rewards","A central bank controlled digital currency","A system of gold-backed certificates"]},{q:"What was Hal Finney's famous contribution to Bitcoin?",a:"Received the first Bitcoin transaction from Satoshi",wrong:["Wrote the original Bitcoin whitepaper himself","Created the SHA-256 based mining algorithm","Founded the first Bitcoin trading exchange"]}],"privacy-nonkyc_pt4":[{q:"What is a PayJoin (P2EP) transaction?",a:"Both sender and receiver contribute inputs, obscuring who paid whom",wrong:["A payment split equally between two participating parties","A transaction requiring two separate network confirmations","A joint mining operation shared between two mining pools"]},{q:"What are Silent Payments (BIP 352)?",a:"One static address generates a unique on-chain address per payment",wrong:["Transactions that are hidden from the public mempool entirely","Payments delayed until network activity drops to low levels","A method to send Bitcoin without paying any transaction fees"]},{q:"What is the Boltzmann entropy score used for in Bitcoin privacy?",a:"Measuring ambiguity of a transaction's input-output linkages",wrong:["Calculating the thermodynamic energy cost of a transaction","Rating the randomness quality of a wallet's seed phrase","Scoring how quickly a transaction will get confirmed"]},{q:"What does Whirlpool do for Bitcoin privacy?",a:"Mixes UTXOs via CoinJoin to break transaction history links",wrong:["Provides a VPN service designed specifically for Bitcoin nodes","Encrypts Bitcoin transactions end-to-end before broadcast","Runs a privacy coin layer on top of the Bitcoin blockchain"]},{q:"What is CoinSwap and how does it differ from CoinJoin?",a:"Uses atomic swaps so mixing is invisible on-chain, unlike CoinJoin",wrong:["Converts Bitcoin to privacy coins and back for mixing purposes","Is faster but provides less privacy protection than CoinJoin","Requires a trusted third party while CoinJoin does not need one"]}],"problems-of-money_pt4":[{q:"The Cantillon Effect describes how newly printed money benefits those closest to its creation. Who benefits MOST from money printing?",a:"Banks and the politically connected who receive new money first",wrong:["Average workers who receive higher wages from inflation","Retirees on fixed incomes who get cost-of-living adjustments","Small business owners who can raise their prices immediately"]},{q:"What is Quantitative Easing (QE)?",a:"A central bank creating new money to buy bonds, expanding supply",wrong:["A method of reducing government debt by printing less money","A technique for making international trade easier between nations","A system where banks lend to each other at zero percent interest"]},{q:'What is the "repo market" and why does it matter for understanding fiat fragility?',a:"Overnight lending market using bonds as collateral - its 2019 crisis exposed systemic fragility",wrong:["A marketplace where banks sell repossessed homes and vehicles for profit","A government repository that stores and audits physical gold reserves","A database where central banks track and monitor all global transfers"]},{q:'What is the "Eurodollar system"?',a:"US dollars held and created by banks outside the US, forming a shadow system",wrong:["The system that converts Euros to Dollars at European exchange desks","A European Central Bank program to replace the Dollar with the Euro","A cryptocurrency project backed equally by both Euros and US Dollars"]},{q:'What does the decline of the "petrodollar" system mean for global finance?',a:"Oil nations moving away from dollar pricing weakens its reserve status",wrong:["Oil companies are switching from drilling to mining Bitcoin instead","The petrodollar decline means that oil is becoming nearly worthless","European nations are being forced to buy all their oil with gold"]}],regulation_pt3:[{q:"In the US, what is the key difference between SEC and CFTC jurisdiction over digital assets?",a:"SEC regulates securities (most altcoins); CFTC regulates Bitcoin as a commodity",wrong:["SEC handles Bitcoin while CFTC handles all altcoins separately","Both agencies share identical authority over all digital assets","CFTC only regulates physical commodities, not any digital assets"]},{q:"What is the Howey Test and how does it apply to Bitcoin?",a:"A legal test for securities - Bitcoin fails to qualify since it has no central enterprise",wrong:["A technical test that measures a blockchain's degree of decentralization","Bitcoin fails the Howey Test, making it an SEC-regulated security asset","A test that determines the appropriate tax rate on crypto investments"]},{q:'What is the "Travel Rule" in cryptocurrency regulation?',a:"A FATF rule requiring institutions to share sender/receiver identity above a threshold",wrong:["A regulation that limits Bitcoin transfers to within a single country","A requirement for Bitcoin miners to register their physical locations","A law that bans carrying hardware wallets across international borders"]},{q:"What is the FATF and why is it significant for Bitcoin privacy?",a:"An international body pushing KYC/AML standards that threaten self-custodial privacy",wrong:["A global mining consortium that coordinates difficulty adjustment levels","A nonprofit organization promoting Bitcoin adoption in developing nations","A technology standard designed for faster Bitcoin transaction processing"]},{q:"How have US states approached Bitcoin regulation differently from the federal government?",a:"Several states passed pro-Bitcoin laws like reserve bills and transmitter exemptions",wrong:["All 50 states enforce identical cryptocurrency regulations matching federal law","States are constitutionally prohibited from creating crypto-related legislation","Most states have banned Bitcoin mining operations due to energy concerns"]}],rollups:[{q:"What is a validity rollup on Bitcoin?",a:"A system that bundles off-chain transactions and posts a ZK proof to Bitcoin",wrong:["A sidechain that copies Bitcoin's consensus rules exactly as written","A Lightning Network channel that batches together multiple payments","A mining pool feature that combines block templates from miners"]},{q:"How do sovereign rollups differ from validity rollups?",a:"Users verify rollup state themselves rather than relying on the base layer",wrong:["Sovereign rollups use a central authority; validity rollups are decentralized","Sovereign rollups use proof-of-stake; validity rollups use proof-of-work","Sovereign rollups are limited to only seven transactions per second"]},{q:"How could BitVM enable rollups on Bitcoin?",a:"By allowing fraud proofs to verify rollup state without needing new opcodes",wrong:["By adding a Turing-complete VM directly into Bitcoin's consensus layer","By creating a dedicated sidechain specifically for validating rollup data","By replacing Bitcoin's existing Script language with Solidity contracts"]},{q:"How do Bitcoin rollups differ from sidechains?",a:"Rollups post proofs or data to Bitcoin, inheriting its security guarantees",wrong:["Rollups use a separate token for gas while sidechains use native BTC","Rollups need a federation of signers while sidechains are fully trustless","Rollups are faster than sidechains but limited to simple transfers only"]},{q:"What is the main trust assumption difference between a validity rollup and an optimistic rollup?",a:"Validity rollups prove correctness upfront; optimistic rollups assume it until challenged",wrong:["Validity rollups trust a federation of signers; optimistic rollups trust miners","Validity rollups need a soft fork to work; optimistic rollups work on Bitcoin today","Validity rollups are run centrally; optimistic rollups are always fully decentralized"]}],"self-custody_pt3":[{q:"What is Sparrow Wallet known for in multisig coordination?",a:"Deep UTXO management and easy multisig setup with hardware signers",wrong:["A mobile-only wallet with cloud-based multisig coordination","A hardware wallet that stores multiple seed phrases internally","A browser extension designed primarily for Lightning payments"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction)?",a:"A standard format letting a transaction be built and signed by multiple parties",wrong:["A special Bitcoin transaction type that only sends partial amounts","A privacy protocol that hides the identity of a transaction sender","A transaction format exclusively used by mining pool operators"]},{q:"What are output descriptors in Bitcoin?",a:"A standard way to describe how a wallet derives addresses for reliable recovery",wrong:["Labels attached to individual transaction outputs for bookkeeping purposes","A complete list of all outputs ever created on the Bitcoin blockchain","Metadata that mining pools attach to the transactions they broadcast"]},{q:"Why is multisig generally preferred over Shamir Secret Sharing (SSS) for Bitcoin custody?",a:"Multisig never reconstructs the full private key in one place; SSS does when signing",wrong:["Multisig transactions cost significantly less in fees than SSS schemes","SSS requires more hardware devices to operate than multisig setups","Multisig predates SSS and has substantially better documentation available"]},{q:"What is Nunchuk known for in the Bitcoin wallet space?",a:"Easy collaborative multisig setup and built-in inheritance planning",wrong:["Being the first wallet to natively support Lightning payments","A hardware-only wallet designed exclusively for cold storage use","A privacy wallet that uses CoinJoin mixing transactions by default"]}],"self-custody_pt4":[{q:"Why is titanium preferred over stainless steel for seed phrase backup plates?",a:"Higher melting point and better corrosion resistance in extreme conditions",wrong:["Titanium is significantly cheaper and more widely available worldwide","Titanium plates can fit more seed words than steel backup plates","Titanium is the only metal undetectable by standard metal detectors"]},{q:"What is a passphrase (25th word) in Bitcoin seed phrase security?",a:"An extra user-chosen word that generates an entirely different wallet",wrong:["The password you enter to unlock your hardware wallet device","A recovery phrase issued to you by the wallet manufacturer","An encryption key used to protect the local blockchain data"]},{q:"Why is geographic distribution important for Bitcoin seed phrase storage?",a:"It protects against localized disasters destroying all backup copies at once",wrong:["It speeds up the wallet by routing through the nearest Bitcoin nodes","It is a legal requirement enforced in most regulatory jurisdictions","It mathematically increases the entropy of the generated seed phrase"]},{q:"What is a dead man's switch in Bitcoin inheritance planning?",a:"A mechanism that triggers key release if the owner fails to check in",wrong:["A physical switch on hardware wallets that wipes them if tampered","A transaction that auto-sends all Bitcoin to a burn address on a timer","A self-destruct feature built directly into the Bitcoin Core software"]},{q:"What is the biggest risk of not having a Bitcoin inheritance plan?",a:"Your Bitcoin could be permanently lost since no one else has the keys",wrong:["The government will automatically seize all of your Bitcoin holdings","Your Bitcoin gets redistributed among other active network participants","Your Bitcoin will steadily lose value without an actively managed wallet"]}],softwar_pt2:[{q:"What military rank is Jason Lowery?",a:"Major",wrong:["Colonel","Lieutenant","Captain"]},{q:"What university did Jason Lowery work with on his thesis?",a:"MIT",wrong:["Harvard","Stanford","Caltech"]},{q:"According to Softwar, what does proof of work project?",a:"Physical power through cyberspace",wrong:["Financial return on investment","Social consensus via voting","Network speed and throughput"]},{q:"How does Softwar view Bitcoin for nation-states?",a:"A strategic defense technology",wrong:["A replacement for fiat currency","A consumer payment system","An unregulated security asset"]},{q:"What energy concept is central to the Softwar thesis?",a:"Using energy to secure cyberspace property",wrong:["Reducing global carbon emissions","Accelerating solar power adoption","Profiting from energy arbitrage"]}],spv:[{q:"What does SPV (Simplified Payment Verification) allow a lightweight client to do?",a:"Verify transaction inclusion using block headers and Merkle proofs",wrong:["Mine Bitcoin blocks using minimal computing power","Send transactions without paying any network fees","Run a full node on a mobile phone with limited storage"]},{q:"What privacy problem did the original SPV bloom filters (BIP-37) have?",a:"They leaked which addresses the wallet cared about to the server",wrong:["They revealed the user's IP address to every network node","They broadcast the user's seed phrase as part of filter data","They required users to share real names with node operators"]},{q:"What do BIP-157 and BIP-158 (compact block filters) improve over bloom filters?",a:"Clients download pre-computed filters without revealing their addresses",wrong:["They compress the entire blockchain into a single downloadable file","They allow nodes to verify transactions without any network access","They replace Merkle proofs with zero-knowledge proofs for speed"]},{q:"What is Neutrino in the context of Bitcoin light clients?",a:"A light client protocol using BIP-157/158 compact block filters",wrong:["A privacy coin built as a Bitcoin sidechain project","A mining algorithm designed for mobile phone hardware","A wallet that runs a full node in the cloud for you"]},{q:"What is the main security tradeoff of SPV compared to running a full node?",a:"SPV clients trust miners produce valid blocks without full verification",wrong:["SPV clients cannot receive Bitcoin, they can only send it","SPV clients must pay higher transaction fees than full nodes","SPV clients can only connect to one peer node at a time"]}],submarine_swap_pt2:[{q:"What is a Loop Out in Lightning?",a:"Moving funds from Lightning back to on-chain",wrong:["Opening a new payment channel","Receiving inbound Lightning payments","Closing all channels at once"]},{q:"What is Boltz Exchange known for?",a:"Trustless on-chain and Lightning swaps",wrong:["Running a Bitcoin mining pool","Operating a centralized exchange","Selling Bitcoin hardware wallets"]},{q:"What makes submarine swaps trustless?",a:"Atomic hash time-locked contracts",wrong:["Multi-signature escrow wallets","Trusted third-party verification","Proof of stake consensus rules"]},{q:"How do submarine swaps differ from atomic swaps?",a:"They move between layers of the same chain",wrong:["Submarine swaps always require trust","Atomic swaps are significantly faster","Submarine swaps use different coins"]},{q:"What enables cross-chain atomic swaps without intermediaries?",a:"HTLCs combining hashlock and timelock",wrong:["Trusted custodial escrow services","Centralized exchange order books","Smart contract platforms only"]}],tail_emission:[{q:'What is "tail emission" in the context of cryptocurrency monetary policy?',a:"A small perpetual block reward ensuring miners always get some subsidy",wrong:["The final Bitcoin expected to be mined around the year 2140","The process of burning unsold Bitcoin to reduce total supply","A mechanism that increases block rewards over time for miners"]},{q:"Which major cryptocurrency implements tail emission as part of its monetary policy?",a:"Monero, with a permanent minimum reward of 0.6 XMR per block",wrong:["Bitcoin, which added tail emission in the Taproot upgrade","Ethereum, which introduced it during the merge to proof of stake","Litecoin, which activated it after its third halving event"]},{q:"What concern about Bitcoin's long-term security does the tail emission debate address?",a:"Whether fees alone can incentivize miners after block rewards end",wrong:["Whether Bitcoin's encryption can withstand quantum computers","Whether the 21 million supply cap should be raised over time","Whether nodes will have enough storage for the growing chain"]},{q:"What is the main argument AGAINST adding tail emission to Bitcoin?",a:"It would break the 21 million cap and destroy sound money credibility",wrong:["Tail emission would make mining too profitable and attract too many","It would speed up transaction confirmation times excessively","Tail emission is technically impossible to implement on Bitcoin"]},{q:'What is the "fee market sufficiency" argument against the need for tail emission?',a:"Growing adoption and scarce block space will naturally raise fee revenue",wrong:["Miners will voluntarily work for free because they believe in Bitcoin","The government will subsidize mining to keep the network running","New Bitcoin will be discovered on the network like finding new gold"]}],time_preference_pt3:[{q:'According to Saifedean Ammous in "The Bitcoin Standard," what is the relationship between sound money and time preference?',a:"Sound money lowers time preference, encouraging saving and long-term investment",wrong:["Sound money raises time preference because people rush to spend currency","There is no meaningful relationship between money type and time preference","Sound money eliminates time preference, making people totally indifferent"]},{q:"How does Ammous argue that low time preference connects to civilization building?",a:"People invest in long-term projects when money reliably holds its value",wrong:["Civilizations advance fastest when people spend money as quickly as possible","Low time preference leads to stagnation because nobody takes any risks","Civilization building is completely unrelated to the monetary system"]},{q:"What behavioral effect does fiat money have on time preference according to the Austrian economics perspective?",a:"Fiat raises time preference - inflation punishes savers and rewards debtors",wrong:["Fiat lowers time preference because stable inflation aids long-term planning","Fiat has no effect on time preference, which is determined by culture","Fiat encourages saving because interest rates compensate for inflation"]},{q:"How does the concept of delayed gratification relate to Bitcoin and sound money?",a:"Sound money rewards patience by preserving purchasing power over time",wrong:["Delayed gratification is irrelevant to any monetary system design","Bitcoin punishes patience because its price is far too volatile","Sound money discourages waiting by making everything too expensive"]},{q:"What is the key difference between how fiat and Bitcoin influence personal financial behavior?",a:"Fiat incentivizes consumption and debt; Bitcoin incentivizes saving",wrong:["Both systems produce identical behavior - spending stays the same","Bitcoin makes people spend more as they feel wealthy from gains","Fiat encourages saving; Bitcoin encourages spending due to deflation"]}],vbyte:[{q:"What is a virtual byte (vbyte) in Bitcoin?",a:"A unit where 1 vbyte equals 4 weight units, used for fee calculation",wrong:["A compressed byte format that reduces transaction size by 75%","The amount of data a Bitcoin node can process per second","A unit measuring the electricity cost of validating transactions"]},{q:"How did SegWit change the way Bitcoin transaction fees are calculated?",a:"Fees use weight units or vbytes, giving witness data a discount",wrong:["SegWit made all transactions free for the first year after launch","SegWit replaced fee priority with a first-come-first-served queue","SegWit doubled the base fee rate for all transaction types"]},{q:"What is the witness discount ratio in SegWit?",a:"Witness data costs 1 weight unit per byte; non-witness costs 4",wrong:["Witness data is free; non-witness data costs 2 weight units","Both witness and non-witness data cost 2 weight units per byte","Witness data costs 3 weight units; non-witness data costs 4"]},{q:"Why is understanding vbytes important for optimizing Bitcoin transaction costs?",a:"Using SegWit addresses moves data into the discounted witness section",wrong:["Vbytes determine how many confirmations a transaction needs","Using fewer vbytes increases the mining reward for the block","Transactions with more vbytes get higher priority in mempool"]},{q:"A typical single-input, single-output SegWit transaction is approximately how many vbytes?",a:"About 110 vbytes",wrong:["About 500 vbytes","About 10 vbytes","About 1,000 vbytes"]}],blockchain_timechain:[{q:'Why do some Bitcoiners prefer the term "timechain" over "blockchain"?',a:"It emphasizes chronological ordering — each block is permanently anchored in time, not merely linked by shared data hashes",wrong:['It was Satoshi\'s original preferred name in the whitepaper before "blockchain" became the mainstream term later',"It highlights that Bitcoin blocks have timestamps while most other blockchains completely omit block time information","It refers to the fixed 10-minute block interval creating a reliable and predictable sequence of time-indexed records"]},{q:"What date was the Bitcoin genesis block mined, and what was embedded in it as proof-of-time?",a:'January 3, 2009; the Times headline "Chancellor on brink of second bailout for banks" proving no coins predate that block',wrong:['October 31, 2008; the text "Bitcoin: A Peer-to-Peer Electronic Cash System" matching the title of the whitepaper exactly','January 9, 2009; the headline "US Federal Reserve cuts interest rates to near zero" referencing the ongoing financial crisis','November 1, 2008; the phrase "The Times 01/Nov/2008 Global markets near total collapse" embedded as political commentary']},{q:"How does Bitcoin track ownership differently from a traditional bank account?",a:"Bitcoin uses UTXOs (Unspent Transaction Outputs) — discrete coin-like objects — rather than maintaining a running account balance",wrong:["Bitcoin maintains a shared ledger of named accounts with balances updated atomically by each confirmed transaction on the chain","Bitcoin stores ownership in a global identity table where each public key maps to a single cumulative spendable balance amount","Bitcoin assigns each wallet address a unique balance field that miners update when new blocks are added to the chain"]},{q:"What role do Merkle trees play in Bitcoin's design?",a:"They allow SPV wallets to verify a transaction exists in a block without downloading the entire blockchain at all",wrong:["They compress raw transaction bytes so each block can store more transactions within the standard 1 MB block size limit","They link blocks together unforgeable by hashing all transactions directly into the previous block's header field","They prevent double-spending by organizing transactions into a sorted tree that all miners must validate on confirmation"]},{q:"What happens when two miners simultaneously find valid blocks at the same block height?",a:"Both are briefly valid; this is called an orphan or stale block situation — only one survives once the chain extends further",wrong:["Both blocks are merged by the network into a combined super-block containing all transactions from each competing version","The network pauses for 10 minutes and nodes vote on which block to accept based on total transaction fees included","Both miners split the block reward equally and every node permanently accepts whichever block it received first"]},{q:"Which six fields appear in a standard Bitcoin block header?",a:"Version, previous block hash, Merkle root, timestamp, nBits difficulty target, and nonce — the six canonical header fields",wrong:["Version, miner address, transaction count, Merkle root, timestamp, and block height as specified in the protocol spec","Previous block hash, coinbase reward amount, timestamp, nBits target, nonce, and the winning miner's signature field","Block height, previous hash, Merkle root, transaction list hash, nonce, and the miner's public key identifier field"]},{q:'How does Bitcoin settlement compare to the "instant" transfers promoted by retail banking?',a:"Bank transfers are IOUs between institutions; Bitcoin achieves irreversible on-chain settlement in roughly 10 minutes",wrong:["Both achieve true final settlement instantly; the only difference is Bitcoin's settlement is public while bank transfers are private","Bitcoin settlement takes 3–5 business days like wire transfers; the 10-minute block time is only for initial confirmation","Fiat transfers settle on delivery while Bitcoin requires a 72-hour grace period for large transactions over 1 BTC value"]},{q:"What is the Bitcoin mempool and how do miners interact with it?",a:"It's the waiting room for unconfirmed transactions; miners select from it and prioritize higher-fee transactions for inclusion",wrong:["It's a permanent archive of all confirmed transactions that nodes must query to validate each new incoming spending attempt","It's a shared pool where miners deposit newly minted coins before distributing them back to senders as transaction change","It's a registry of known peer node addresses used to discover and connect to other participants on the Bitcoin network"]},{q:"How does Bitcoin's transaction finality compare to SWIFT international bank transfers?",a:"Bitcoin reaches practical finality in about 1 hour (6 confirmations); SWIFT international transfers take 1–5 business days",wrong:["Bitcoin finality takes 24 hours for large transactions; SWIFT now settles in under 2 hours for standard bank-to-bank wires","Both systems achieve finality in roughly the same timeframe; the meaningful difference is in cost rather than settlement speed","Bitcoin reaches finality in under 1 minute with Taproot active; SWIFT settles same-day under the ISO 20022 standard"]},{q:"Why is altering a historical Bitcoin block effectively impossible once buried under sufficient work?",a:"Changing any block invalidates every subsequent block's hash, forcing an attacker to redo all downstream proof-of-work",wrong:["Changing a block triggers a cryptographic alarm that immediately alerts all nodes causing automatic rejection of the edit","Each block is countersigned by a quorum of miners who must all re-sign any proposed modifications to historical records","Historical blocks are stored in read-only memory on every Bitcoin node, making any write operation physically impossible"]}],layer_2_lightning:[{q:"What is the fundamental on-chain mechanism that makes Lightning Network payment channels possible?",a:"Two parties lock funds in a 2-of-2 multisig UTXO on-chain, then exchange signed balance updates off-chain without broadcasting",wrong:["Two parties create a shared custodial wallet hosted by a Lightning Service Provider who settles batches periodically on-chain","Two parties send micropayments through a trusted routing hub that accumulates them and settles on-chain once per day","Two parties lock funds with a single-signature escrow contract and route payments outward through Lightning Service Providers"]},{q:"What cryptographic primitive enables trustless multi-hop routing through intermediate Lightning Network nodes?",a:"HTLCs (Hash Time-Locked Contracts): payment releases when the recipient reveals a preimage, or refunds after a timeout expires",wrong:["Schnorr threshold signatures: three-of-five quorums authorize each hop and prevent intermediate nodes from stealing funds","Zero-knowledge proofs: each routing node proves it forwarded funds without learning the source or destination of the payment","Pedersen commitments: each hop commits to the forwarded amount and reveals it only after the full route successfully completes"]},{q:"What information does a standard Lightning Network BOLT11 invoice contain?",a:"Payment amount, payment hash, expiry time, and destination public key — all encoded in a compact BOLT11 string format",wrong:["Sender's node ID, payment amount, full routing path, and a cryptographic commitment to the sender's current channel balance","Recipient's Bitcoin address, invoice amount, expiry time, and an ordered list of acceptable intermediate routing node IDs","Payment hash, a UTXO reference, expiry time, and the maximum routing fee the payer will accept per hop along the route"]},{q:'What is "inbound liquidity" on the Lightning Network and why is it required to receive payments?',a:"It's capacity to receive funds; someone else must open and fund a channel directed toward your node before you can receive",wrong:["It's the total BTC you have locked across all outgoing channels; more inbound capacity increases your maximum outgoing send limit","It's a routing score assigned by the network based on how reliably your node has historically forwarded other people's payments","It's the reserved on-chain balance your Lightning wallet holds as collateral before you can open any new payment channel"]},{q:"How are routing fees structured on the Lightning Network?",a:"A flat base fee in satoshis per payment plus a proportional fee rate charged in parts per million of the payment amount",wrong:["A uniform percentage fee set globally by the Bitcoin protocol and charged identically by every node along every payment route","Fees equal the hop count multiplied by the node operator's published hourly rate, capped at 0.5% of total payment value","Routing fees are negotiated bilaterally between each pair of nodes before every payment using a real-time fee auction system"]},{q:'What key advantage do BOLT12 "offers" provide over standard BOLT11 Lightning invoices?',a:"Offers are static reusable payment codes; unlike BOLT11 single-use invoices, the same offer can be paid repeatedly by anyone",wrong:["Offers include mandatory KYC fields that make Lightning payments compliant with financial regulations in regulated jurisdictions","Offers embed a complete routing path to the recipient, eliminating pathfinding work in the sender's wallet software entirely","Offers encode pre-negotiated channel paths that bypass normal routing, making payments confirm faster than standard BOLT11 invoices"]},{q:"What is LNURL and what categories of interaction does it enable in Lightning wallets?",a:"LNURL is a set of HTTP-based protocols enabling QR-driven Lightning interactions: pay-to-link, withdraw, and auth flows",wrong:["LNURL is a Bitcoin Improvement Proposal defining a universal address format for cross-chain Lightning payment routing globally","LNURL is a routing protocol that enables Lightning nodes to discover the lowest-fee multi-hop path to any global destination","LNURL is a Lightning wallet sync standard that replicates channel states across multiple devices belonging to one user"]},{q:'What is a Lightning Network "force-close" and what protection exists against fraud after one is broadcast?',a:"A unilateral broadcast of the last signed channel state; a CSV timelock gives the counterparty time to contest any cheating attempt",wrong:["A force-close is a cooperative mutual settlement where both parties co-sign an on-chain transaction dividing the balance evenly","A force-close triggers automatic reimbursement to both parties from the Lightning Service Provider's dedicated insurance fund","A force-close broadcasts a penalty transaction that burns the cheating party's funds and credits the honest party in full"]},{q:"How does Lightning Network improve payment privacy compared to base-layer Bitcoin transactions?",a:"Lightning payments are not recorded on-chain at all; only channel open and close transactions appear in the public ledger",wrong:["Lightning uses stealth addresses so each payment routes to a freshly generated one-time destination hiding the recipient identity","Lightning payments are logged on a private sidechain visible only to the two channel partners and their direct routing nodes","Lightning improves privacy because routing nodes are legally required to delete all payment records within 24 hours of routing"]},{q:"How does Lightning Network's theoretical transaction throughput compare to Bitcoin's base layer?",a:"Lightning can theoretically handle millions of transactions per second at near-zero cost; base layer manages only about 7 TPS",wrong:["Lightning handles up to 1,000 TPS with current node software; the base layer handles ~7 TPS but provides stronger settlement finality","Lightning doubles effective base-layer capacity to about 14 TPS; the primary advantage is lower fees rather than raw throughput","Lightning processes up to 100,000 TPS in ideal conditions with capacity bounded by the weakest routing node's available bandwidth"]}],pow_vs_pos:[{q:"Why do Bitcoin advocates argue Proof-of-Work is a stronger security foundation than Proof-of-Stake?",a:"PoW links digital security to real-world energy expenditure — you cannot fake or virtualize the physical cost of mining blocks",wrong:["PoW uses more electricity, which signals that all participants are financially committed to the network's long-term success","PoW produces a public record of miner identities so the community can penalize dishonest participants after any attack occurs","PoW requires specialized hardware purchases that effectively deanonymize miners, creating legal accountability for any attack"]},{q:"How are validators selected to produce blocks in a Proof-of-Stake system?",a:"Validators are chosen based on the size of their token stake; those with more tokens staked gain proportionally more block rights",wrong:["Validators are elected by token-holder votes each epoch and then share block rewards equally with their supporting voters","Validators are selected by a verifiable random function with absolutely no weighting by stake size or prior token holdings","Validators are chosen by a committee of existing validators who review each candidate's historical performance and uptime record"]},{q:'What is the "nothing at stake" problem that affects naive Proof-of-Stake designs?',a:"Validators can vote on multiple competing chain forks simultaneously at zero cost because no real resource is being consumed",wrong:["Validators can pledge the same tokens to multiple chains at once because there is no on-chain registry of all staked assets","Validators have no incentive to stay online because the penalty for downtime costs less than the reward for staying connected","New participants can't accumulate stake because established validators monopolize block production without expending any resources"]},{q:"When did Ethereum complete its switch from Proof-of-Work to Proof-of-Stake consensus?",a:'September 2022, in an event called "The Merge" that replaced Ethereum\'s PoW mining with a Proof-of-Stake validator set',wrong:["March 2021, when the Ethereum Foundation completed deployment of the Beacon Chain mainnet consensus upgrade on schedule","December 2023, when Ethereum's final sharding upgrade replaced the remaining PoW elements with Proof-of-Stake validation","June 2020, when Ethereum 2.0 Phase 0 launched and the Proof-of-Work chain was simultaneously deprecated in the upgrade"]},{q:"How do the thresholds for a successful attack differ between Bitcoin's PoW and a typical PoS network?",a:"A Bitcoin 51% attack requires over half of total global hashrate; a typical PoS attack requires acquiring over 33% of staked tokens",wrong:["A PoW attack requires 67% of mining power while PoS needs only 10% of staked capital, making PoS actually more attack-resistant","Both systems require exactly 51% of their respective resources; the cost difference depends solely on the current token price","PoW is attacked by controlling 25% of ASIC manufacturers; PoS requires 51% of staked tokens for an equivalent disruption"]},{q:"What did Saifedean Ammous write about Proof-of-Work's uniquely fair property in The Bitcoin Standard?",a:'"PoW is the only mechanism that does not confer explicit power on any subset of participants" — Saifedean Ammous, The Bitcoin Standard',wrong:['"PoW guarantees equal returns on investment for all miners regardless of pool size or geographic cost of electricity access"','"PoW creates a perfectly merit-based network where each participant\'s contribution is measured objectively by work performed"','"PoW eliminates all insider advantages by requiring every participant to solve the same cryptographic puzzle each block epoch"']},{q:"Does Proof-of-Stake slashing fully resolve the security weaknesses inherent in stake-based consensus?",a:"No — slashing punishes detectable misbehavior but cannot prevent long-range attacks where an attacker rewrites old chain history",wrong:["Yes — slashing penalizes all forms of validator dishonesty and provides demonstrably stronger security guarantees than PoW mining","Yes — slashing combined with finality gadgets eliminates all known attack vectors including long-range history rewriting attacks","No — slashing creates severe centralization pressure by making it prohibitively risky for small validators to run nodes at all"]},{q:"What was Bitcoin's approximate network hashrate in the 2024–2025 timeframe?",a:"Over 700 exahashes per second (EH/s), making a successful 51% attack require more hardware than currently exists on Earth",wrong:["Over 100 exahashes per second (EH/s), a figure comparable to Ethereum's peak PoW hashrate just before The Merge in 2022","Approximately 200 terahashes per second (TH/s), reflecting the dominance of next-generation 7nm ASIC mining hardware farms","Around 500 petahashes per second (PH/s), representing roughly 40% annual growth sustained since the May 2020 halving event"]},{q:"How does access to Bitcoin mining compare to participation in Proof-of-Stake validation?",a:"Anyone with hardware and cheap electricity can mine Bitcoin; PoS compounds advantages for those who already hold large wealth",wrong:["Bitcoin mining requires a license from the Bitcoin Foundation; PoS is fully open to anyone willing to make a small token deposit","Both systems offer equivalent access barriers; entry cost is roughly comparable between mining rigs and major PoS token deposits","PoS is far more accessible because anyone can stake tiny amounts; Bitcoin mining requires millions of dollars minimum investment"]},{q:"What is the fundamental difference in the nature of costs between PoW and PoS security models?",a:"PoW requires external real-world energy cost to attack; PoS only requires internal tokens the attacker may already own and hold",wrong:["PoW security comes from miner coordination costs; PoS security relies on smart contract audits and formal verification proofs","PoW security depends on hardware scarcity; PoS security relies entirely on the irreversibility of slashing penalties post-attack","PoW costs are paid by miners and passed to users through fees; PoS costs are socialized across all token holders proportionally"]}],evidence_against_alts:[{q:"How was Ethereum's initial token supply structured at its 2014 crowdsale?",a:"About 72 million ETH were pre-mined; roughly 70% of the initial supply was allocated to founders and early insiders",wrong:["All 72 million ETH were sold in a fully public fair launch with zero allocation reserved for the founding team or investors","Roughly 20 million ETH were pre-mined with the remainder distributed through a public sale open to any retail investor globally","100 million ETH were created and divided equally: one third to founders, one third to an R&D reserve, one third to the public"]},{q:"What does research reveal about the infrastructure running Ethereum's validator nodes?",a:"About 61% of Ethereum nodes run in cloud data centers; AWS alone hosts roughly 25% making centralization a severe concern",wrong:["Only about 15% of Ethereum nodes run in the cloud; the vast majority are home validators run by individual stakers globally","Nearly 95% of Ethereum nodes run on dedicated bare-metal servers; cloud hosting is actively discouraged by the foundation","Roughly 40% of nodes are cloud-hosted, a level considered acceptable within Ethereum's published decentralization targets"]},{q:"What action did Ethereum take after the DAO hack in 2016, and what principle did it violate?",a:'Ethereum rolled back its blockchain to reverse the hack, proving its "code is law" and immutability claims were overrideable',wrong:["Ethereum implemented a smart contract patch to freeze hacker funds without altering any already-confirmed on-chain state","Ethereum hard forked to add new security rules but preserved all historical transactions, maintaining full ledger immutability","Ethereum's core developers sued the attacker in Swiss court and recovered the funds without touching or altering the chain"]},{q:"What are the key concerns about XRP's token distribution and Ripple's legal status?",a:"Ripple pre-created ~100 billion XRP, controls its scheduled release, and was sued by the SEC for an unregistered securities offering",wrong:["XRP has a capped supply of 21 million tokens like Bitcoin, but Ripple Labs retains permanent veto power over all protocol upgrades","Ripple distributed XRP through open mining but faces legal challenges because its founders hold United States banking licenses","XRP has no maximum supply cap and Ripple can mint new tokens freely; the SEC sued over undisclosed token minting activities"]},{q:"What is notable about Solana's track record of network availability since its mainnet launch?",a:"Solana has suffered over 10 major network outages since launch, including a single outage lasting approximately 17 hours",wrong:["Solana has maintained a perfect uptime record since launch thanks to its Proof-of-History consensus and strong validator incentives","Solana experienced one brief 2-hour outage in 2021 that was rapidly resolved via a coordinated validator restart procedure","Solana's network undergoes scheduled maintenance windows twice per year, which critics sometimes mischaracterize as full outages"]},{q:"Why can't a competing cryptocurrency simply copy Bitcoin's open-source code and achieve equivalent security and value?",a:"Code is easily copied but network effects are not: Bitcoin's liquidity, hashrate security, deep trust, and developer talent are irreplaceable",wrong:["Bitcoin's source code is proprietary and protected under copyright law, making direct copies illegal in most global jurisdictions","Bitcoin's cryptographic algorithms are patented by the Satoshi Nakamoto estate, blocking forks from using the same security scheme","Bitcoin's code can be copied but all forks share the UTXO set, preventing any fork from maintaining independent ownership records"]},{q:"What has happened to nearly all altcoins throughout Bitcoin's history when evaluated in BTC-denominated terms?",a:"Over 99% of altcoins ever launched have declined toward zero when priced against Bitcoin, regardless of their initial hype cycles",wrong:["About 50% of altcoins outperform Bitcoin over five-year windows; the rest decline, making broad diversification a rational strategy","Altcoins have collectively outperformed Bitcoin since 2017 on a volume-weighted basis when adjusted for total market capitalization","Roughly 30% of altcoins launched before 2018 still trade above their original ICO price when measured in BTC-denominated terms"]},{q:'What happened to major corporate "blockchain not Bitcoin" initiatives at firms like JPMorgan, IBM, and Maersk?',a:"JPMorgan, IBM, and Maersk all launched enterprise blockchain projects with great fanfare and then quietly abandoned each of them",wrong:["JPMorgan's blockchain now processes $10 trillion daily and IBM's Food Trust actively tracks 25 billion food supply chain records","The corporate blockchain era succeeded in creating interoperable networks that now settle cross-border payments in real time","IBM and JPMorgan merged their blockchain platforms into a single enterprise network now operating across 500 Fortune 500 companies"]},{q:"What makes Bitcoin's origin uniquely different from every other major cryptocurrency ever launched?",a:'Bitcoin has an "immaculate conception": no founder enrichment, no premine, no ICO, and an anonymous creator who then disappeared',wrong:["Bitcoin is unique because its consensus rules have never changed since genesis; no other network has achieved this full stability","Bitcoin's origin is unique because it was launched by a publicly known academic team who donated all profits back to a foundation","Bitcoin is the only cryptocurrency launched before 2015 that still runs its original completely unmodified consensus algorithm"]},{q:"Why does launching a new Proof-of-Work coin present a fundamental and unavoidable security problem?",a:"Any new PoW chain starts with near-zero hashrate, meaning an attacker with modest hardware could 51% attack it from day one",wrong:["New PoW coins are insecure because ASIC manufacturers refuse to supply hardware to chains below the 1 EH/s threshold hashrate","New PoW chains are vulnerable because they must use Bitcoin's SHA-256 algorithm, enabling cheap merged mining attack exploits","Launching a new PoW coin requires regulatory approval in most countries, creating legal barriers that deter legitimate honest miners"]}],cryptography:[{q:"Why did Satoshi choose the secp256k1 elliptic curve for Bitcoin instead of the more widely used NIST P-256?",a:"secp256k1's parameters have no known backdoor; NIST P-256's constants were generated through an opaque process lacking transparency",wrong:["secp256k1 produces shorter 48-byte signatures versus NIST P-256's 72-byte signatures, saving meaningful space per transaction","secp256k1 was the only elliptic curve with an existing open-source implementation available when Bitcoin was being actively developed","secp256k1 enables faster signature verification on commodity CPUs, which was critical for Satoshi's constrained 2009 launch timeline"]},{q:"Which digital signature algorithm did Bitcoin use to authorize transactions before the Taproot upgrade activated?",a:"ECDSA (Elliptic Curve Digital Signature Algorithm) was used to sign and authorize all Bitcoin transactions before Taproot activated",wrong:["EdDSA (Edwards-curve Digital Signature Algorithm), a Schnorr-based variant used widely across modern cryptography since the 1990s","RSA-2048, which was replaced by ECDSA in a 2012 BIP update to reduce transaction signature size and improve overall verification speed","DSA (Digital Signature Algorithm), the original NIST standard adapted for Bitcoin's secp256k1 elliptic curve in the genesis block"]},{q:"What is the key mathematical property of Schnorr signatures that makes them especially valuable for Bitcoin?",a:"Schnorr signatures are linear and additive — multiple parties' signatures can be aggregated into one compact signature via MuSig",wrong:["Schnorr signatures are 256 bytes shorter than equivalent ECDSA signatures, significantly reducing the on-chain footprint of all transactions","Schnorr signatures operate on a different elliptic curve that is provably harder to attack than the secp256k1 curve used by ECDSA","Schnorr signatures are non-deterministic by design, which prevents the timing-based side-channel attacks that can affect ECDSA"]},{q:"What are the key security properties of the SHA-256 hash function as used in Bitcoin?",a:"256-bit fixed output, deterministic, pre-image resistant, and avalanche effect: one changed input bit completely alters the output",wrong:["128-bit variable output, probabilistic, collision-resistant only, designed for high speed on the hardware-accelerated Bitcoin ASICs","512-bit fixed output, deterministic, fully reversible using the corresponding private key, and exhibits a strong avalanche effect","256-bit fixed output, non-deterministic due to an internal random salt, collision-resistant only, and tied to the secp256k1 curve"]},{q:"What is the step-by-step process for deriving a Bitcoin address from a public key?",a:"SHA-256 the public key, then RIPEMD-160 to get a 20-byte hash, then apply Base58Check encoding to produce the final address",wrong:["RIPEMD-160 the private key directly, then SHA-256 it twice, producing a 32-byte output encoded in hexadecimal as the address","SHA-512 the public key then truncate to 20 bytes, then apply Base64 encoding with a 4-byte checksum appended to the result","SHA-256 the compressed public key twice, take the final 20 bytes, then encode using standard Base64 plus a 4-byte checksum"]},{q:'Why are cryptographic hash functions described as "one-way" functions?',a:"Given hash output H(x), finding the original input x is computationally infeasible — you can compute forward but never reverse it",wrong:["Hash functions are one-way because they discard excess information via bitwise truncation performed during the internal hashing rounds","Hash functions are one-way by law only; reversing them without authorization qualifies as a federal computer intrusion crime globally","Hash functions are one-way in hardware only; software implementations of SHA-256 can theoretically be reversed with sufficient RAM"]},{q:"Why does Bitcoin's Base58Check encoding omit certain characters from its alphabet?",a:"It removes visually ambiguous characters — 0, O, I, and l — to prevent costly transcription errors when addresses are copied manually",wrong:["It removes alphabetically late characters x, y, and z to keep all encoded strings short enough to fit on a single paper backup","It excludes special symbols and all uppercase letters to ensure compatibility with every Unicode keyboard and QR code scanner","It removes vowels entirely to prevent encoded addresses from accidentally spelling dictionary words that users might confuse with keys"]},{q:"What is the discrete logarithm problem and how does it protect Bitcoin private keys?",a:"Given a public key (a curve point), deriving the private key (scalar multiplier) is computationally infeasible on the secp256k1 curve",wrong:["Given a private key expressed as a large prime, factoring it into two component primes is computationally infeasible on modern hardware","Given a hash of the public key, reversing SHA-256 to recover the original elliptic curve point is computationally infeasible always","Given an AES-encrypted wallet file, brute-forcing the decryption key is computationally infeasible without the user's original passphrase"]},{q:"How are cryptographic commitment schemes used within Lightning Network HTLCs?",a:"A hash of a secret preimage is shared first; the preimage is revealed upon payment, atomically unlocking funds across all hops",wrong:["A time-locked commitment to a routing fee is published on-chain first; revealing it later proves the payment was properly delivered","Each routing node commits to holding forwarded funds for a fixed timelock period and reveals its commitment to prevent double-spend","A cryptographic commitment to the exact payment amount is shared with all hops; revealing it triggers simultaneous on-chain settlement"]},{q:"What is P2PKH and what security advantage does it offer over the earlier Pay-to-Public-Key output type?",a:"P2PKH (Pay-to-Public-Key-Hash) hashes the public key before use, providing protection if ECDSA is ever weakened or compromised",wrong:["P2PKH locks outputs behind a 2-of-2 multisig requirement, making theft completely impossible without access to both signing keys","P2PKH encrypts the output script with the sender's public key so only the intended recipient can decode the locking conditions","P2PKH uses RIPEMD-256 instead of RIPEMD-160, producing a longer hash that offers significantly stronger collision-resistance guarantees"]}],austrian_economics:[{q:'What did Ludwig von Mises formalize in "Human Action" (1949)?',a:"Praxeology — the study of purposeful human action under scarcity, establishing economics as a deductive science of individual choice",wrong:["Econometrics — the statistical measurement of market outcomes using regression models and aggregate national income data","Macroeconomics — the study of unemployment, inflation, and national output using demand-side analytical frameworks and policy models","Behaviorism — the empirical study of how psychological biases cause individuals to systematically deviate from classically rational decision-making"]},{q:'What was Hayek\'s core argument in "The Use of Knowledge in Society" (1945)?',a:"Prices are decentralized information signals encoding dispersed local knowledge that no central planner could ever collect or replicate",wrong:["Wages are collective bargaining outcomes that government intervention can optimize to achieve full employment across all economic sectors","Capital is best allocated by expert technocrats who can model aggregate market behavior using national statistical databases","Markets fail to coordinate information efficiently whenever monopolies or asymmetric information distort the natural price discovery process"]},{q:'What did Hayek propose in "Denationalization of Money" (1976)?',a:"Competitive private currencies issued and managed entirely outside government control, a concept Bitcoin made real 35 years later",wrong:["A global reserve currency jointly managed by central banks under an international treaty with binding monetary supply rules","A commodity basket standard linking currency values to weighted indices of gold, silver, and key agricultural commodity prices","Full public ownership of the money supply administered by democratically elected monetary boards with transparent policy rules"]},{q:"According to Austrian Business Cycle Theory, what causes boom-bust cycles?",a:"Artificially low central bank interest rates that encourage malinvestment and unsustainable credit expansion, inevitably followed by a painful bust",wrong:["Excessive consumer spending fueled by rising wages that outpaces underlying productivity growth in the manufacturing and services sectors","Trade imbalances caused by currency manipulation that distort the natural flow of global capital across national borders and industries","Monopolistic corporate pricing that suppresses marketplace competition and prevents efficient capital reallocation across the broader economy"]},{q:"How does sound money affect time preference across society according to Austrian theory?",a:"Sound money lowers time preference, encouraging saving and long-term investment over immediate consumption and short-term debt-fueled spending",wrong:["Sound money raises time preference by making future purchasing power uncertain, discouraging multi-year planning among investors and consumers","Sound money has no measurable effect on time preference, which is entirely determined by individual psychology and genetic disposition","Sound money temporarily lowers time preference but eventually promotes excessive hoarding that collapses demand and deflates the broader economy"]},{q:"What is the Austrian subjective theory of value, in contrast to Marxist labor theory?",a:"Value is determined solely by individual actors based on personal preferences and scarcity, not by labor hours embedded in production",wrong:["Value is determined by the collective social utility of a good as measured through democratic consensus and community price-setting processes","Value is established at market equilibrium when aggregate supply matches aggregate demand at a mutually acceptable price level","Value is a function of raw material scarcity measured objectively by the replacement cost of producing the good under current market conditions"]},{q:"What is the Cantillon Effect in monetary economics?",a:"Newly created money benefits those who receive it first — banks and government contractors — before rising prices erode everyone else's purchasing power",wrong:["Currency devaluation benefits exporters first by making their goods cheaper abroad, before domestic wage growth fully catches up to new price levels","Tax cuts benefit large corporations first because they can immediately reinvest capital gains before smaller firms or wage earners see any benefit","Interest rate reductions benefit institutional borrowers first since they can refinance cheaply before retail lending rates are fully adjusted downward"]},{q:"How did Hayek and Keynes fundamentally disagree about recessions?",a:"Keynes argued government spending cures recessions; Hayek argued forced stimulus generates malinvestment that makes the inevitable correction far worse",wrong:["Keynes supported a gold-backed currency to anchor inflation expectations; Hayek argued fiat money was essential for flexible countercyclical policy","Keynes blamed monopolistic corporations for downturns; Hayek argued recessions stemmed purely from insufficient consumer spending and weak aggregate demand","Keynes viewed free markets as naturally self-correcting over time; Hayek argued central bank intervention was essential to stabilize employment and output"]},{q:'How did Saifedean Ammous connect Austrian economics to Bitcoin in "The Bitcoin Standard"?',a:"He applied Mises and Hayek's sound money theory directly to Bitcoin, arguing it restores low time preference and the hard money properties lost under fiat",wrong:["He applied Keynesian demand-side economics to argue Bitcoin's fixed supply would prevent deflationary spirals in modern post-industrial economies","He adapted Modern Monetary Theory to show Bitcoin's decentralized issuance could replace central bank open market operations in a digital economy","He combined behavioral economics with game theory to prove Bitcoin would inevitably displace fiat through pure network adoption incentives"]},{q:'What is "high time preference" in Austrian economic terms?',a:"A strong preference for present consumption over future saving, leading to debt-fueled spending, short-term thinking, and underinvestment in capital formation",wrong:["A preference for investments with rapid compounding returns rather than patient accumulation of slower long-term capital appreciation strategies","An economic condition where rising inflation expectations cause consumers to accelerate purchases before prices increase any further","A deliberate preference for holding liquid assets to preserve maximum optionality in periods of high economic and market uncertainty"]}],bitcoin_vs_real_estate:[{q:"What are the inflation-adjusted annual returns of US real estate over a full century?",a:"Approximately 0–2% real annual returns after accounting for inflation, far below the impressive nominal figures typically advertised by the industry",wrong:["Approximately 6–8% real annual returns after inflation, making residential property the most reliable long-term wealth preservation asset available","Approximately 4–5% real annual returns after inflation, driven primarily by land scarcity in growing metropolitan and coastal urban areas","Approximately 3–4% real annual returns after inflation, compounding consistently across all US regional markets over every significant historical period"]},{q:"What ongoing costs does real estate ownership typically impose on investors?",a:"1–4% of property value annually in maintenance costs alone, plus additional property taxes, insurance premiums, and management fees on top of that",wrong:["Less than 0.5% of property value annually, making residential real estate the most cost-efficient long-term store of value among all asset classes","Exactly 2% of property value annually, standardized by industry actuarial formulas and applied uniformly across all residential property types","5–10% of property value annually for commercial properties only; well-maintained residential homes carry negligible operating costs once fully paid off"]},{q:"How does Bitcoin's liquidity compare to real estate when investors need to exit a position?",a:"Bitcoin trades 24/7 globally with settlement in minutes; real estate typically requires 30–90 days to sell and incurs 5–10% in transaction costs",wrong:["Real estate sells faster than Bitcoin in most markets because institutional buyers routinely complete off-market transactions within 48 business hours","Both assets have similar liquidity profiles since Bitcoin's extreme volatility makes it practically impossible to exit large positions at fair market value","Bitcoin and real estate carry comparable transaction costs since major crypto exchanges charge 5–7% fees on high-value liquidation orders"]},{q:"How does real estate use leverage, and what risk does that introduce?",a:"Real estate commonly uses mortgage leverage to amplify gains, but this equally amplifies losses during price downturns and can wipe out equity entirely",wrong:["Real estate leverage is capped by regulation at 20% of property value, making catastrophic leveraged losses virtually impossible under normal conditions","Real estate leverage always benefits owners long-term because national property values have never declined over any rolling 10-year historical period","Leverage risk applies only to commercial real estate; owner-occupied residential mortgages are federally insured against any significant loss of principal"]},{q:"Can Bitcoin be transferred internationally as easily as real estate can be conveyed between parties?",a:"Bitcoin settles globally across borders in minutes with no intermediaries required; real estate is geographically immovable and cannot cross borders at all",wrong:["Both assets are equally difficult to transfer internationally due to strict capital controls and harmonized anti-money-laundering regulations worldwide","Real estate transfers more easily across some international jurisdictions because standardized legal frameworks exist under international property law treaties","Bitcoin international transfers face the same title verification and escrow delays as real estate due to mandatory blockchain finality confirmation periods"]},{q:"How does Bitcoin differ from real estate when it comes to government seizure risk?",a:"Property can be seized through eminent domain, tax liens, or civil forfeiture by governments; properly secured self-custodied Bitcoin cannot be confiscated",wrong:["Both assets are equally vulnerable to government seizure since courts can subpoena Bitcoin private keys the same way they can seize titled property","Real estate is better protected from seizure than Bitcoin because constitutional property rights provide stronger legal safeguards against government confiscation","Bitcoin is more vulnerable to seizure than real estate since regulated exchanges are required to freeze accounts and comply with government asset orders"]},{q:"How does Bitcoin's divisibility compare to real estate for investors with limited capital?",a:"Bitcoin is divisible down to 1 satoshi (0.00000001 BTC), allowing fractional purchases at any size; you cannot sell 0.01% of a house to raise cash",wrong:["Real estate through REITs is more divisible than Bitcoin, which enforces a minimum practical transaction size of 0.001 BTC on most networks","Both assets are equally accessible to small investors since modern fractional ownership platforms let people buy proportional shares of any property","Real estate is more accessible to capital-constrained investors because government programs allow property acquisition with as little as 1% down payment"]},{q:"How does Bitcoin's geographic risk profile differ from that of real estate?",a:"Real estate values depend entirely on local economies and geography; Bitcoin is a global asset uncorrelated with any specific regional market or jurisdiction",wrong:["Bitcoin and real estate are highly correlated hard assets that respond identically to global CPI inflation data and Federal Reserve policy changes","Bitcoin carries more geographic concentration risk than real estate because the majority of mining activity occurs in just two or three countries","Major global-city real estate is uncorrelated with local economic conditions and behaves identically to fully global assets like commodity futures"]},{q:"How has Bitcoin performed relative to real estate over any 4-year or longer holding period?",a:"Bitcoin has outperformed real estate by an enormous margin over every 4-year or longer holding period across its entire existence as an asset class",wrong:["Real estate has consistently outperformed Bitcoin on a risk-adjusted basis over 4-year holding periods due to its substantially lower price volatility","Bitcoin and real estate have delivered nearly identical total returns over 4-year periods once leverage, tax benefits, and rental income are properly included","Bitcoin has outperformed real estate only in exceptional bull market cycles; most 4-year holding period comparisons show highly mixed and inconclusive results"]},{q:"What happened to real estate values during hyperinflation in countries like Venezuela, Zimbabwe, and Lebanon?",a:"Real estate also lost value in hard money terms during hyperinflation across Venezuela, Zimbabwe, and Lebanon; Bitcoin preserved purchasing power for those who held it",wrong:["Real estate proved the most reliable inflation hedge in both Venezuela and Zimbabwe, outperforming gold, foreign currency, and all other asset classes","Real estate retained its full value in all documented hyperinflationary environments since physical property cannot be devalued by money printing alone","Real estate outperformed Bitcoin in hyperinflationary countries because local governments shut down cryptocurrency exchanges and banned digital asset transactions"]}],gold_standard_history:[{q:"What characterized the Classical Gold Standard era from roughly 1870 to 1914?",a:"44 years of remarkable price stability, subdued long-run inflation, and a long-term investment culture that financed and enabled the Industrial Revolution",wrong:["44 years of recurring deflationary collapses and economic stagnation caused by the rigid link between currency and a slowly growing physical gold supply","Frequent currency crises triggered by large gold discoveries in California and South Africa that constantly disrupted global price stability and trade","A period of rising inflation and sovereign debt caused by British imperial expansion and surging demand for commodities in colonial territories"]},{q:"What monetary system did the Bretton Woods agreement establish in 1944?",a:"The USD was pegged to gold at $35 per ounce and all other major currencies were pegged to the dollar, making it the world reserve currency",wrong:["All G7 currencies were simultaneously pegged directly to gold at individually negotiated rates, with no single national currency designated as reserve","A post-war trade liberalization treaty that created the WTO and established a system of managed floating exchange rates among Allied nations","The British pound replaced gold as the global reserve standard at a fixed rate of £1 to $4.03, with the US and UK serving as dual anchors"]},{q:'What was the "Nixon Shock" of August 15, 1971?',a:"Nixon unilaterally suspended the dollar's gold convertibility, ending Bretton Woods entirely and launching the global era of pure unbacked fiat currency",wrong:["Nixon imposed sweeping wage and price controls to combat inflation while simultaneously proposing a formal gold revaluation to $100 per ounce","Nixon signed legislation allowing foreign central banks to convert dollars to gold at a newly negotiated rate of $70 per ounce going forward","Nixon coordinated a multilateral agreement with G10 finance ministers to collectively devalue all major currencies against gold by 10 percent simultaneously"]},{q:"What did Executive Order 6102 of 1933 do, and what penalty did it carry?",a:"FDR's order made it illegal for Americans to own gold bullion, with penalties of up to 10 years in prison and a $10,000 fine for violations",wrong:["FDR's order nationalized the Federal Reserve System and established direct Treasury Department control over all money supply decisions nationwide","A 1933 executive order creating the gold exchange standard to formally replace the classical gold standard with a centrally managed currency regime","A 1933 banking regulation requiring all gold held by private commercial banks to be audited quarterly and insured by the federal government"]},{q:'What was gold\'s "fatal flaw" as a monetary standard, according to "The Fiat Standard"?',a:"Spatial salability — gold was too heavy and risky to transport globally, driving centralization into bank vaults and enabling gradual government seizure and control",wrong:["Temporal salability — gold's slowly growing supply made it deflationary over time, consistently discouraging consumption and causing recurring economic stagnation","Divisibility — gold could not be split into units small enough for everyday retail transactions without significantly debasing its purity and market value","Verifiability — gold could not be authenticated quickly enough in ordinary commerce, creating widespread fraud through counterfeit coins and debased alloys"]},{q:"What caused the Weimar Republic's catastrophic hyperinflation between 1921 and 1923?",a:"The German government printed money to pay WWI reparations demanded by the Allies, causing prices to double every few days at the peak of the crisis",wrong:["A speculative bubble in German industrial equities collapsed, triggering simultaneous bank runs and uncontrolled monetary expansion by the Reichsbank","The Allied naval blockade of German ports cut off essential imports, creating artificial commodity shortages that drove a runaway wage-price spiral","A series of devastating agricultural droughts in 1921 and 1922 destroyed food harvests, causing scarcity-driven price spikes that spiraled into full hyperinflation"]},{q:"How did the gold standard enable the large-scale infrastructure of the Industrial Revolution?",a:"Sound money preserved the value of savings over decades, allowing investors to patiently fund long-term projects like railroads, power grids, and telephone networks",wrong:["Gold-backed currency enabled colonial resource extraction that directly funded industrial projects in Britain through forced labor and administrative taxation systems","The gold standard had minimal direct impact on industrial investment, which was primarily financed through short-term commercial bank credit and trade finance","Industrial Revolution infrastructure was financed mainly through royal patronage and long-term government bonds rather than private savings kept in hard money"]},{q:"How does gold's stock-to-flow ratio compare with Bitcoin's as halvings continue?",a:"Gold's stock-to-flow is roughly 60 years; Bitcoin's surpasses gold after each halving and approaches infinity as block rewards eventually diminish to zero",wrong:["Gold's stock-to-flow of 60 years permanently exceeds Bitcoin's because Bitcoin's supply grows faster than newly mined gold production in absolute terms","Both gold and Bitcoin effectively share equivalent stock-to-flow ratios of around 50–60 years, making them equally scarce as long-term monetary commodities","Gold's stock-to-flow is actually only 20 years due to advances in deep-sea and asteroid mining technology; this makes direct comparison with Bitcoin impossible"]},{q:"How does Bitcoin's hard supply cap compare to gold's theoretical total supply?",a:"Gold's supply is theoretically unlimited through asteroid mining and new geological discoveries; Bitcoin is mathematically capped forever at exactly 21 million coins",wrong:["Gold's accessible supply is now effectively fixed because known economically viable deposits are nearly exhausted and new mining is no longer profitable","Both gold and Bitcoin have effectively unlimited supplies since gold recycling and Bitcoin's layer-2 solutions eliminate any meaningful long-term scarcity constraint","Bitcoin's supply is also theoretically unlimited because permanently lost coins reduce effective circulation, creating protocol pressure to eventually reissue them"]},{q:"Why did the US dollar become the global reserve currency at Bretton Woods in 1944?",a:"The US held the world's largest gold reserves in 1944, making the dollar the most credible currency to serve as the global gold-backed reserve anchor",wrong:["The dollar was chosen because the US had the largest economy and most liquid bond markets regardless of the size of its gold reserve holdings","The British pound was the initial reserve currency at Bretton Woods; the dollar only replaced it after the UK defaulted on its post-war Lend-Lease debts","The IMF selected the dollar through a competitive evaluation of Allied nations' monetary policy track records and fiscal discipline over the preceding decade"]}],cypherpunks:[{q:'What did Eric Hughes declare in "A Cypherpunk\'s Manifesto" (1993)?',a:'"Privacy is necessary for an open society in the electronic age... We must defend our own privacy if we expect to have any."',wrong:['"Encryption is a weapon of the people... The state\'s monopoly on surveillance must be broken by making cryptography universally available and free."','"Anonymity is the foundation of all digital freedom... Any government that surveils its citizens without consent has permanently forfeited its legitimacy."','"Code is the new law... Those who control cryptographic infrastructure ultimately control the rights and freedoms of citizens in the digital age."']},{q:"Where did Satoshi Nakamoto first publish the Bitcoin whitepaper on October 31, 2008?",a:"The Cypherpunks mailing list, the center of digital privacy and cryptographic activism since its founding in 1992 by Eric Hughes and John Gilmore",wrong:["The Bitcoin.org website, which Satoshi registered in August 2008 specifically to host the whitepaper and distribute the initial open-source software release","The SourceForge code repository, where Satoshi posted the whitepaper alongside the initial C++ source code for broad public review and comment","The Cryptography mailing list hosted at metzdowd.com, a separate but closely overlapping community focused primarily on academic cryptographic research"]},{q:"What was Adam Back's technical contribution that directly shaped Bitcoin's design?",a:"He invented Hashcash in 1997 — a proof-of-work system directly cited in the Bitcoin whitepaper that became the foundation of Bitcoin's mining mechanism",wrong:["He created the Merkle tree data structure in 1994 that Bitcoin uses to efficiently organize and cryptographically verify transaction data inside each block","He developed the elliptic curve digital signature algorithm that Bitcoin uses to cryptographically authenticate ownership and authorize every transaction","He invented the SHA-256 hashing algorithm in 1995 that Bitcoin relies on to secure its proof-of-work calculations and generate transaction identifiers"]},{q:"Who was Hal Finney and what was his historic role in Bitcoin's earliest days?",a:"He received the first Bitcoin transaction from Satoshi (block 170), ran the second node, created RPOW in 2004, and died of ALS in 2014 with his brain cryonically preserved",wrong:["He authored the cryptographic foundations of the original Bitcoin whitepaper before Satoshi transformed them into a fully operational peer-to-peer payment system","He mined the genesis block alongside Satoshi and ran Bitcoin's first public exchange, converting BTC into USD for the earliest adopters of the network","He ran Bitcoin's first currency exchange and facilitated the landmark pizza transaction, the first documented real-world commercial use of Bitcoin"]},{q:"Why do many researchers suspect Nick Szabo is Satoshi Nakamoto?",a:'He coined the term "smart contracts" in 1994 and created bit gold in 1998 — a Bitcoin direct predecessor featuring similar proof-of-work and digital scarcity mechanics',wrong:["He registered bitcoin.org before the whitepaper's release and was the only known cypherpunk with sufficient C++ expertise to write the original client","His writing style matched the Bitcoin whitepaper with 99% confidence according to multiple independent linguistic forensic analysis studies published in 2013",'He confirmed in a 2019 podcast interview that he was "deeply involved in Bitcoin\'s conceptual design" without explicitly claiming sole authorship of the protocol']},{q:"What was Wei Dai's contribution to digital cash, and how is he honored in crypto today?",a:'He created b-money in 1998, the first proposal for anonymous distributed electronic cash directly cited by Satoshi; Ethereum\'s smallest unit, the "wei," is named after him',wrong:['He invented the zero-knowledge proof protocol in 1992 underlying Ethereum\'s privacy layer; the "gwei" denomination honors his foundational cryptographic contribution',"He designed the distributed hash table architecture in 1997 that directly inspired Bitcoin's peer-to-peer network topology and decentralized node discovery protocol",'He created e-gold in 1996, the first operational digital gold currency system, and MakerDAO\'s "dai" stablecoin was named in honor of his legacy']},{q:'What did Timothy May argue in his "Crypto-Anarchist Manifesto" written in 1988?',a:"Cryptography would make governments unable to tax or regulate digital communications, enabling untraceable anonymous transactions and entirely new free markets",wrong:["Encryption would enable investigative journalists to safely transmit whistleblower documents across borders, fundamentally reforming government accountability worldwide","Public-key cryptography would make government-issued identity documents and passports completely obsolete within two decades of widespread civilian adoption","Digital cash systems would eliminate banking fees for ordinary citizens and redistribute trillions in financial industry profits directly to technology developers"]},{q:"What is Len Sassaman's unusual and permanent connection to the Bitcoin blockchain?",a:"He was a cypherpunk cryptographer who died in July 2011 shortly after Satoshi went dark; his obituary was permanently encoded into the Bitcoin blockchain as tribute",wrong:["He merged Satoshi's final code commits before the creator went dark in 2011, making him the last developer to interact officially with the original Bitcoin client","He operated the longest-running Bitcoin full node during the first year of the network, and his node identifier was encoded in the metadata of block 21,000","He contributed the peer-to-peer networking module to the original Bitcoin client, and his PGP public key is permanently embedded inside the genesis block's coinbase script"]},{q:"What legal precedent did Phil Zimmermann establish through his battles over PGP encryption?",a:'His US prosecution for "exporting munitions" when PGP spread abroad established the critical constitutional precedent that software source code is protected free speech',wrong:["His case established that no court could compel production of cryptographic keys as self-incriminating testimony, extending Fifth Amendment protections to encryption","His legal battle with RSA Security over patent licensing established the foundational principle that mathematical algorithms cannot be privately owned as intellectual property","His prosecution established that open-source cryptographic software cannot under any circumstances be classified as a weapon under the Arms Export Control Act"]},{q:"What was Julian Assange's connection to the cypherpunk movement and to Bitcoin's early adoption?",a:"Assange was a cypherpunk mailing list subscriber when Satoshi published the whitepaper in 2008; WikiLeaks later became one of Bitcoin's first major organizational adopters",wrong:["Assange personally corresponded with Satoshi throughout 2009 to coordinate WikiLeaks's launch of a dedicated anonymous Bitcoin donation infrastructure for sources",'Assange co-authored the "Cypherpunks" book with Jacob Appelbaum in 2012, which became a widely cited foundational text within the early Bitcoin community',"Assange was a contributing Bitcoin developer before founding WikiLeaks, writing the anonymous transaction routing code that appeared in client version 0.2"]}],satoshi_nakamoto_deep:[{q:"How many posts did Satoshi Nakamoto make on the BitcoinTalk forum before going silent?",a:"Exactly 575 documented posts on the BitcoinTalk forum before Satoshi went dark in late 2010 and early 2011, handing off to Gavin Andresen",wrong:["Approximately 3,200 posts across BitcoinTalk and the Cypherpunks mailing list before formally transferring all authority and repository access to Gavin Andresen","Around 1,100 public posts on BitcoinTalk, plus hundreds of private direct messages to core developers that were later partially leaked online","Fewer than 100 public posts total, since Satoshi strongly preferred communicating through private encrypted email rather than open public forum discussions"]},{q:"What is considered significant about Satoshi's self-reported birthday of April 5, 1975?",a:"April 5 is the date of FDR's 1933 Executive Order 6102 confiscating gold, and 1975 is the year Americans regained the legal right to own gold again",wrong:["April 5 is the date Satoshi registered bitcoin.org in 2008, and 1975 is the year Whitfield Diffie and Martin Hellman published the public-key cryptography paper","April 5 is the date of the first confirmed Bitcoin transaction in 2009, and 1975 marks the founding of the first academic digital money research consortium","April 5 was chosen as a random privacy-preserving date, and 1975 simply reflects the year the cypherpunk movement's core philosophical foundations were established"]},{q:"What is notable about how Satoshi Nakamoto managed Bitcoin addresses for privacy?",a:"Satoshi maintained over 22,000 documented unique addresses and reportedly never reused a single one, demonstrating perfect on-chain privacy hygiene throughout",wrong:["Satoshi used a single master address for all early mining rewards to simplify personal accounting, then rotated to new addresses only after 2010","Satoshi reused addresses intentionally to signal authenticity to early users, maintaining fewer than 50 documented unique addresses across all activity","Satoshi's addresses followed a deterministic pattern researchers cracked in 2013, successfully mapping every early mining reward back to a single master wallet"]},{q:"What did Satoshi write in his final known email to Gavin Andresen in April 2011?",a:'"I have moved on to other things. It is in good hands with Gavin and everyone."',wrong:['"The system is working as intended. Never add features without thorough peer review, and always keep the codebase minimal and fully auditable."','"Please do not attempt to contact me again. Bitcoin must stand entirely on its own without any individual being perceived as its leader."','"Protect the 21 million supply cap above all else. Any proposal to alter total issuance must be permanently and unconditionally rejected."']},{q:"What surprising feature was hidden inside Satoshi's original Bitcoin source code?",a:"The unfinished beginnings of an online poker game were embedded within the original approximately 31,000 lines of C++ source code",wrong:["A built-in decentralized exchange for direct peer-to-peer currency swaps without intermediaries, which was deliberately stripped out before the 2009 launch","An early DNS-based identity system allowing users to cryptographically link human-readable usernames to their Bitcoin addresses across the network","A complete payment channel prototype closely resembling the Lightning Network that Satoshi implemented fully but deliberately disabled before the January 2009 launch"]},{q:"What does Satoshi's registration of netcoin.org reveal about the project's late development?",a:"Satoshi registered netcoin.org one day before bitcoin.org, strongly suggesting the project's final name was still undecided until very late in development",wrong:["Satoshi registered netcoin.org as a deliberate decoy domain to mislead corporate legal teams that were monitoring digital currency development for patent filings","Netcoin.org was registered by Hal Finney on Satoshi's behalf as a geographic mirror for distributing the whitepaper outside of US legal jurisdiction","The netcoin.org registration proves Satoshi initially envisioned a narrower online payment network before expanding the scope to a full decentralized monetary system"]},{q:"How did the pre-launch Bitcoin parameters differ from the version released in January 2009?",a:"Pre-launch Bitcoin used 15-minute block times and 30-day difficulty adjustments; these were changed to 10-minute blocks and a 2-week difficulty window before launch",wrong:["Pre-launch Bitcoin used 1-minute block times and 24-hour difficulty adjustments; these were deliberately slowed to improve stability and prevent network spam","The original technical parameters matched the final launch version exactly; no substantive changes were made between the whitepaper publication and the software release","Pre-launch Bitcoin had no automatic difficulty adjustment at all; the 2-week adjustment period was proposed by Hal Finney and added during the first year of operation"]},{q:"What is notable about the approximately 1 million Bitcoin Satoshi mined in the early days?",a:"Satoshi mined roughly 1 million BTC using a deliberately limited single-threaded miner to avoid dominating the network, and none of these coins have ever moved",wrong:["Satoshi mined approximately 1 million BTC but transferred the majority to a multi-signature escrow wallet controlled by the Bitcoin Foundation before going dark in 2011","Satoshi mined approximately 1 million BTC and quietly liquidated about half of them during the 2013 bull run to fund ongoing anonymous development work","Satoshi's early mining totaled only around 50,000 BTC; the widely cited 1 million figure is a persistent myth based on demonstrably flawed blockchain analysis methods"]},{q:"What happens to Bitcoin that fans send to the original Genesis Block address as tribute?",a:"Over 68 BTC have been sent as tribute to the Genesis Block address, but they are permanently unspendable since the output carries no valid scriptPubKey to spend from",wrong:["Bitcoin sent to the Genesis Block address is automatically destroyed by the protocol itself, permanently reducing the circulating supply below 21 million coins","Genesis Block donations remain locked and are accessible only to whoever controls Satoshi's original private keys, creating an enduring cryptographic mystery","All Bitcoin sent to the Genesis Block address accumulates in a special reserve fund governed collectively by the Bitcoin Core development team and maintainers"]},{q:"What does the fact that only 0.06% of Bitcoin Core code remains from Satoshi's original suggest?",a:'The global community has rebuilt nearly everything from scratch, embodying the spirit that "we are all Satoshi" through decades of collective open-source maintainership',wrong:["Satoshi's original code was so poorly structured and buggy that developers had to replace it entirely, raising serious questions about Satoshi's actual programming expertise","The 0.06% figure proves Satoshi contributed only the whitepaper concept while the actual software was primarily written by Hal Finney and other early collaborators","Bitcoin Core has diverged so completely from Satoshi's original design that it should be treated as an entirely different protocol incompatible with the founding vision"]}],books_deep:[{q:"Which book did Michael Saylor credit as most impactful in MicroStrategy's decision to adopt Bitcoin?",a:"The Bitcoin Standard by Saifedean Ammous",wrong:["The Fiat Standard by Saifedean Ammous","Gradually Then Suddenly by Parker Lewis","Broken Money by Lyn Alden"]},{q:'In "The Bitcoin Standard," what economic concept measures the ratio of above-ground supply to annual production?',a:"Stock-to-Flow ratio",wrong:["Purchasing power parity index","Time preference discount rate","Monetary velocity multiplier"]},{q:'What is the subtitle of Saifedean Ammous\'s second book, "The Fiat Standard"?',a:"The Debt Slavery Alternative to Human Civilization",wrong:["The Hidden Tax on Every Holder of Currency","How Central Banks Destroyed the Modern World","A Monetary History of the Post-Gold Era"]},{q:"In \"21 Lessons,\" DerGigi describes Bitcoin's origin as having no founder still in control, no premine, and no ICO — he calls this Bitcoin's what?",a:"Immaculate conception",wrong:["Genesis paradox","Sovereign neutrality principle","Trustless bootstrap event"]},{q:'In "Gradually, Then Suddenly," Parker Lewis argues Bitcoin cannot be copied because of what, not because the code is proprietary?',a:"Bitcoin's network effects make a copy worthless from day one",wrong:["Bitcoin's mining hardware creates a prohibitive barrier to entry for copycats","Bitcoin's regulatory approval cannot be duplicated by any fork or altcoin","Bitcoin's cryptographic proof-of-work algorithm is patented and legally protected"]},{q:"Jason Lowery's \"Softwar\" was submitted as an MIT thesis. What novel claim does it make about Bitcoin's proof-of-work?",a:"PoW is a form of non-lethal power projection allowing nations to compete via hashrate instead of violence",wrong:["PoW is an energy accounting system that proves Bitcoin's value in physical thermodynamic terms","PoW functions as a diplomatic signaling mechanism that deters state-level cyberattacks on infrastructure","PoW creates a decentralized arms-control treaty enforced by thermodynamics rather than international law"]},{q:"According to Vijay Boyapati's \"The Bullish Case for Bitcoin,\" what is the correct order of Bitcoin's monetization stages?",a:"Collectible → store of value → medium of exchange → unit of account",wrong:["Store of value → collectible → medium of exchange → unit of account","Medium of exchange → store of value → unit of account → collectible","Collectible → medium of exchange → store of value → unit of account"]},{q:'Nik Bhatia\'s "Layered Money" argues that monetary layers built atop Bitcoin — like Lightning — are a natural evolution. What historical precedent does he trace this pattern through?',a:"The monetary hierarchy from gold to central bank notes to commercial bank deposits through history",wrong:["The progression from barter to commodity money to bills of exchange in medieval Europe","The development of the Federal Reserve system from private clearinghouses after the Panic of 1907","The transition from the classical gold standard to the Bretton Woods dollar-gold exchange system"]},{q:"Jonathan Bier's \"The Blocksize War\" documents the 2015–2017 governance battle. What broader lesson does it demonstrate about who ultimately controls Bitcoin's protocol?",a:"Economic nodes and users — not miners — hold final power over which consensus rules Bitcoin enforces",wrong:["Core developers hold final power because miners must adopt whatever client they release to the network","Miners hold final power because they can always reorganize the chain and override node-level rules","Large exchanges hold final power because they determine which version of Bitcoin earns the ticker symbol"]},{q:'Lyn Alden\'s "Broken Money" is primarily a macro case for Bitcoin. What does she identify as the core structural flaw in the current monetary system?',a:"The dollar-based reserve system built after 1971 creates persistent debt growth and destroys savings over time",wrong:["The Federal Reserve's dual mandate forces it to create inflation to meet employment targets indefinitely","Commercial banks' fractional reserve lending multiplies currency beyond any anchor to productive activity","Government deficit spending requires continuous monetization that no neutral reserve asset can currently absorb"]}],human_rights_deep:[{q:'Alex Gladstein of the Human Rights Foundation wrote "Check Your Financial Privilege." What percentage of people does he say live in liberal democracies with stable reserve currencies?',a:"Only about 13% of the global population",wrong:["Only about 28% of the global population","Roughly half — about 49% of the global population","Approximately 34% of the global population"]},{q:"When Nigeria's central bank banned banks from servicing crypto exchanges in 2021, what happened to peer-to-peer Bitcoin trading volumes?",a:"They surged to the highest levels in Africa as Nigerians routed around the ban",wrong:["They collapsed by over 80% as citizens feared criminal prosecution for trading","They remained flat because most Nigerians were unaware of hardware wallet alternatives","They shifted entirely to stablecoins, with Bitcoin trading volumes dropping to near zero"]},{q:"In Venezuela's hyperinflation crisis, what was the typical fee range that families lost when sending remittances through traditional wire and cash services?",a:"20–40% of the total transfer in fees and unfavorable exchange rates",wrong:["5–10% of the total transfer in fees and unfavorable exchange rates","50–70% of the total transfer in fees and currency conversion losses","10–15% of the total transfer in fees and exchange rate spreads"]},{q:"During the 2019–2020 Lebanese banking crisis, how did the situation differ for Bitcoin holders versus bank depositors?",a:"Banks froze depositor accounts entirely, while Bitcoin holders retained full, unobstructed access to their funds",wrong:["Bitcoin holders saw their funds seized by Lebanese authorities, while bank depositors received partial access","Both groups faced equal restrictions, as Lebanese courts extended banking freezes to crypto wallets","Bank depositors could withdraw up to $400 per week, while Bitcoin holders faced blockchain-level withdrawal limits"]},{q:"In Taliban-controlled Afghanistan, what specific financial freedom does Bitcoin on a mobile phone enable for women?",a:"Women legally barred from holding bank accounts can control their own money without requiring male permission or a bank",wrong:["Women can receive international aid disbursements that Taliban officials cannot intercept or redirect to male relatives","Women can pay for goods anonymously, preventing Taliban tracking of purchases deemed un-Islamic by local authorities","Women can earn wages in Bitcoin from foreign employers, bypassing Taliban labor laws restricting female employment"]},{q:"During the 2022 Canadian trucker convoy protests, what happened to the GoFundMe campaign, and how did the Bitcoin alternative compare in size?",a:"GoFundMe froze $10 million in donations; Bitcoin campaigns raised approximately $21 million which could not be frozen",wrong:["GoFundMe froze $3 million in donations; Bitcoin campaigns raised approximately $7 million which could not be frozen","GoFundMe froze $25 million in donations; Bitcoin campaigns raised approximately $4 million which could not be frozen","GoFundMe froze $10 million in donations; Bitcoin campaigns raised approximately $4 million which was later seized"]},{q:"In 2010, WikiLeaks was financially blockaded — Visa, Mastercard, and PayPal all cut off donations under US government pressure. What did this event demonstrate about Bitcoin?",a:"Bitcoin was completely immune to the blockade, allowing WikiLeaks to continue receiving donations without any payment processor",wrong:["Bitcoin donations to WikiLeaks were blocked by exchanges cooperating with US Treasury demands at the network layer","Bitcoin provided a brief alternative but was later traced by the NSA, leading to arrests of major WikiLeaks donors","Bitcoin exposure forced WikiLeaks to pause fundraising temporarily due to volatility making donation values unpredictable"]},{q:"How many adults worldwide are estimated to lack a bank account, and what does Bitcoin's mobile-first design offer them?",a:"About 1.4 billion unbanked adults can access Bitcoin-based financial services using only a mobile phone",wrong:["About 500 million unbanked adults can access Bitcoin-based financial services using only a mobile phone","About 3 billion unbanked adults can access Bitcoin-based financial services using only a mobile phone","About 800 million unbanked adults can access Bitcoin-based financial services using only a mobile phone"]},{q:"In Cuba, what financial problem does Bitcoin solve for diaspora families sending money home?",a:"It eliminates the 10%+ fees charged by Western Union and other remittance services for transfers to Cuba",wrong:["It bypasses the US embargo by routing transfers through Bitcoin exchanges outside Western financial networks","It prevents Cuban authorities from seizing transfers that exceed government-set remittance caps per household","It allows Cuban recipients to hold value that cannot be confiscated during government mandated currency conversions"]},{q:"Alex Gladstein argues that the global financial privilege gap is poorly understood by people in wealthy nations. What is the key stat that reframes the debate?",a:"87% of humanity lives under authoritarian or semi-authoritarian governments with weaker, less stable currencies",wrong:["65% of global GDP is produced in countries whose citizens cannot freely buy or sell foreign currencies","92% of global inflation occurs in the developing world, yet monetary reform debates are dominated by G7 economists","74% of the world's population has experienced at least one episode of government-imposed capital controls since 1970"]}],cbdc:[{q:"What does CBDC stand for, and what is its most fundamental difference from Bitcoin?",a:"Central Bank Digital Currency — it is centrally controlled by government, unlike Bitcoin which has no central issuer",wrong:["Crypto-Backed Digital Contract — it requires collateral backing unlike Bitcoin which is backed only by decentralized consensus","Cross-Border Digital Currency — it is designed for international trade unlike Bitcoin which was designed for domestic payments","Central Bank Distributed Coin — it uses distributed ledger technology unlike Bitcoin which uses a single-node blockchain"]},{q:"What is one programmability feature of CBDCs that no physical cash or Bitcoin can ever impose on a user?",a:"Expiry dates that cause the money to disappear from your account if not spent within a set time period",wrong:["Verification requirements that confirm every transaction is spent on government-approved goods and services only","Mandatory conversion into physical cash if not used for digital transactions within a quarterly spending window","Automatic tax withholding on all transactions above a threshold set by the treasury at the time of payment"]},{q:"China's digital yuan (e-CNY) is one of the most advanced CBDC deployments. How has it been distributed and monitored?",a:"It has been used in government benefit payments and all transactions are monitored in real time by Chinese authorities",wrong:["It has been distributed exclusively through commercial banks and monitored only for transactions exceeding 50,000 yuan","It runs on a private blockchain shared with approved banks, with full transaction privacy from government surveyors","It has been issued only to state employees as salary, with transaction data retained only for anti-fraud purposes"]},{q:"How could a CBDC theoretically implement negative interest rates in a way that physical cash makes impossible?",a:"The government could directly reduce account balances over time to penalize saving and force consumer spending",wrong:["The government could block transactions with foreign merchants to concentrate spending within the domestic economy","The government could require merchants to charge surcharges on CBDC payments relative to digital yuan alternatives","The government could convert idle CBDC balances into government bonds automatically after 90 days without spending"]},{q:'Privacy advocates have called CBDCs "panopticon money." What does this metaphor mean in practice?',a:"Every purchase is tracked and visible to authorities — no transaction can be anonymous like cash transactions currently are",wrong:["All financial data is visible to a network of multinational banks and corporations rather than just the government issuer","CBDC balances are displayed publicly on a blockchain explorer, removing all financial privacy from citizens","The government can see transaction patterns across all users but cannot identify specific individuals behind purchases"]},{q:"When Nigeria launched one of the world's first CBDCs — the eNaira in 2021 — what happened to public adoption?",a:"Adoption was extremely low, with citizens preferring cash and Bitcoin over the government's digital currency",wrong:["Adoption was very high in urban areas but failed in rural regions where smartphone penetration is below 20%","Adoption was forced above 60% when the government imposed penalties on businesses refusing eNaira payments","Adoption was moderate but froze after the central bank suspended the eNaira following a technical hack in 2022"]},{q:"How does a CBDC differ from ordinary digital bank money in terms of government control over individual accounts?",a:"With a CBDC the government controls the ledger directly, enabling confiscation without going through a bank as intermediary",wrong:["With a CBDC users earn interest set by the central bank directly, bypassing commercial bank interest rate decisions entirely","With a CBDC government transfers are instant and fee-free, but commercial transactions still pass through bank clearing systems","With a CBDC citizens interact with a public ledger they can audit, unlike traditional bank accounts that are privately held"]},{q:"How many central banks globally were actively researching or developing CBDC programs as of the mid-2020s?",a:"Over 130 central banks were actively exploring or developing CBDC programs",wrong:["About 40 central banks were actively exploring or developing CBDC programs","Over 200 central banks were actively exploring or developing CBDC programs","Approximately 80 central banks were actively exploring or developing CBDC programs"]},{q:"What is the key distinction between Bitcoin's permissionless access model and a CBDC's access model?",a:"Bitcoin allows anyone to participate without approval, while CBDC authorities decide who is permitted to use the system",wrong:["Bitcoin requires miners to validate identities before transactions confirm, while CBDCs use zero-knowledge proofs for privacy","Bitcoin charges higher fees than CBDCs because it lacks a central issuer to subsidize transaction processing costs","Bitcoin transactions are reversible within 24 hours, while CBDC transactions are irreversible from the moment of broadcast"]},{q:"What concern do economists raise about spending limits and category restrictions that CBDCs could technically enforce?",a:"Governments could block purchases of disfavored goods — fuel, firearms, political donations — at the payment protocol level",wrong:["Governments could restrict CBDC use to domestic merchants, effectively creating a new form of capital controls overnight","Economists worry CBDCs will displace commercial banks entirely by eliminating the need for deposit-taking institutions","Economists warn that real-time CBDC settlement will allow high-frequency traders to front-run ordinary consumer purchases"]}],block_size_wars:[{q:"What was the central technical debate in the Blocksize War of 2015–2017?",a:"Whether to increase Bitcoin's block size limit to fit more transactions per block for on-chain scaling",wrong:["Whether to replace Bitcoin's SHA-256 proof-of-work algorithm with a memory-hard alternative to reduce miner centralization","Whether to implement a second script language alongside Bitcoin Script to support smart contract functionality on-chain","Whether to increase the total Bitcoin supply cap from 21 million to accommodate growing global payment demand"]},{q:'What was the "big blocker" argument for raising the block size limit?',a:"Larger blocks would allow more on-chain transactions, keeping fees low and enabling Bitcoin to scale as a global payment system",wrong:["Larger blocks would make mining more profitable, incentivizing more miners and increasing Bitcoin's overall network security","Larger blocks would reduce orphan block rates, making the chain more stable and resistant to selfish mining attacks","Larger blocks would decrease blockchain download times by batching more data per round-trip during initial sync"]},{q:'What was the core "small blocker" concern about raising the block size limit?',a:"Larger blocks would make running a full node too expensive, concentrating Bitcoin verification among large miners and data centers",wrong:["Larger blocks would slow transaction propagation globally, allowing well-connected miners to dominate block production","Larger blocks would require a hard fork that could be exploited by adversarial states to attack Bitcoin's consensus layer","Larger blocks would reduce the fee market needed to sustain miners after the block subsidy eventually reaches zero"]},{q:"What was BIP148 (UASF) and why was it historically significant?",a:"It was a User-Activated Soft Fork where node operators threatened to reject non-SegWit blocks — users directly forced miners to comply",wrong:["It was a miner-activated upgrade proposal that required 95% hash power signaling before SegWit could activate on mainnet","It was a protocol patch that fixed the transaction malleability bug independently of SegWit, resolving the scaling debate peacefully","It was a compromise proposal combining a 2 MB block size increase with the SegWit witness discount in a single hard fork"]},{q:"What did SegWit (BIP141) actually do to Bitcoin's effective block capacity?",a:"It increased effective capacity to approximately 2–4 MB by applying a discount to signature (witness) data without a hard fork",wrong:["It increased effective capacity to exactly 8 MB by separating transaction data from signatures in a full hard fork upgrade","It doubled raw on-chain TPS by compressing transaction data with a new serialization format in a backward-compatible upgrade","It increased effective capacity to approximately 1.5 MB by removing redundant script opcodes from the transaction format"]},{q:"What was the New York Agreement (SegWit2x) and what happened to it?",a:"A 2017 deal between miners and businesses to activate SegWit then hard fork to 2 MB blocks — it was ultimately rejected and abandoned",wrong:["A 2016 deal between Core developers and exchanges to freeze block size at 1 MB permanently in exchange for Lightning funding","A 2017 proposal to move Bitcoin to a proof-of-stake system signed by major mining pools; it collapsed after a Chinese mining ban","A 2015 agreement between Blockstream and major miners to develop SegWit in exchange for their opposition to competing clients"]},{q:"Bitcoin Cash (BCH) was created on August 1, 2017. Who were the two most prominent figures leading the big-block faction that forked off?",a:'Roger Ver ("Bitcoin Jesus") and Jihan Wu of Bitmain, the dominant mining hardware manufacturer',wrong:["Gavin Andresen and Mike Hearn, the original Bitcoin Core developers who departed over the governance dispute","Charlie Lee and Craig Wright, who disagreed on block size before Craig later launched Bitcoin SV as a separate fork","Vitalik Buterin and Brian Armstrong, who favored higher-throughput chains compatible with Ethereum's transaction model"]},{q:"What did the outcome of the Blocksize War prove about the power structure in Bitcoin's governance?",a:"Miners cannot override the economic nodes — exchanges, businesses, and users running full nodes hold final authority over consensus rules",wrong:["Core developers hold veto power over any upgrade because miners must route block templates through their reference code","Large institutional holders effectively control protocol direction by threatening to sell if unfavorable forks succeed on the market","Mining pools hold governance power because they can reorganize the blockchain to reverse any soft fork that harms profitability"]},{q:"Which book is considered the definitive account of the Blocksize War and who wrote it?",a:'"The Blocksize War" by Jonathan Bier, which documents the full 2015–2017 governance battle in detail',wrong:['"Digital Gold" by Nathaniel Popper, which documents the governance battle alongside early Bitcoin adoption stories','"The Bitcoin Standard" by Saifedean Ammous, which includes a full chapter on the governance crisis and its resolution','"Cryptoassets" by Chris Burniske and Jack Tatar, which covers the fork wars across Bitcoin, Ethereum, and other protocols']},{q:"What is the broader lesson Bitcoin historians draw from the Blocksize War about contentious protocol changes?",a:"Bitcoin's governance is uniquely robust because controversial changes are extremely difficult to force through without broad consensus",wrong:["Bitcoin's governance is dangerously slow because improvements like SegWit took two years longer than technically necessary to deploy","Bitcoin's governance proves that miners always win long-term disputes because they control the hash power securing the chain","Bitcoin's governance shows that off-chain political agreements like the New York Agreement are the most effective scaling path"]}],mtgox:[{q:'What does the name "Mt. Gox" actually stand for, and what was the platform before it became a Bitcoin exchange?',a:"Magic: The Gathering Online Exchange — it was originally a card trading site repurposed for Bitcoin in 2010",wrong:["Mountain Gold Exchange — it was originally a commodity futures platform repurposed by Mark Karpeles in 2010","Monetary Transfer Global Operations Exchange — it was founded as a forex broker then pivoted to Bitcoin in 2011","Multiple Trading and Order Xchange — it was originally a stock options platform converted to Bitcoin trading in 2009"]},{q:"At its peak in 2013, what share of all global Bitcoin transactions passed through Mt. Gox?",a:"Over 70% of all global Bitcoin transactions were processed through Mt. Gox at its peak",wrong:["Over 90% of all global Bitcoin transactions were processed through Mt. Gox at its peak","Approximately 40% of all global Bitcoin transactions were processed through Mt. Gox at its peak","Roughly 55% of all global Bitcoin transactions were processed through Mt. Gox at its peak"]},{q:"When Mt. Gox collapsed in February 2014, how many BTC did it announce had been lost, and how many were later found internally?",a:"Mt. Gox reported ~850,000 BTC lost; approximately 200,000 BTC were later discovered in old wallets and recovered",wrong:["Mt. Gox reported ~650,000 BTC lost; approximately 150,000 BTC were later discovered in cold storage and recovered","Mt. Gox reported ~1.2 million BTC lost; approximately 350,000 BTC were later discovered during bankruptcy proceedings","Mt. Gox reported ~850,000 BTC lost; none were ever recovered as all coins were immediately laundered by the attackers"]},{q:"What were the two root causes that allowed Mt. Gox to be drained of Bitcoin over a period of years?",a:"Transaction malleability exploits combined with severe internal financial mismanagement and lack of auditing",wrong:["A private key leak on the public GitHub repository combined with a social engineering attack on the core server team","Insider theft by a rogue employee combined with a zero-day exploit in the OpenSSL library used for wallet encryption","A 51% attack on the Bitcoin network combined with poor hot wallet security that left most funds in an online server"]},{q:"What crime was Mt. Gox CEO Mark Karpeles ultimately convicted of in Japan?",a:"Data manipulation — he was convicted of falsifying electronic records, though embezzlement charges were dropped",wrong:["Theft and embezzlement — he was convicted of directly moving customer Bitcoin to personal wallets for his own enrichment","Securities fraud — he was convicted of issuing false statements about exchange reserves to prevent a bank run","Money laundering — he was convicted of funneling customer funds through shell companies registered in France and Japan"]},{q:"What phrase, now a cornerstone of Bitcoin culture, emerged directly from the lessons of the Mt. Gox collapse?",a:'"Not your keys, not your coins" — the principle that only self-custody guarantees ownership of your Bitcoin',wrong:['"Proof of reserves or proof of fraud" — the principle that exchanges must publish verifiable on-chain reserve attestations','"Run your own node, trust no one" — the principle that verifying the chain yourself is the only true form of sovereignty','"Cold storage or capitulation" — the principle that any Bitcoin left on an exchange is a loan you may never get back']},{q:"How long did Mt. Gox creditors wait for repayment, and what was notable about the form the repayment took?",a:"Creditors waited approximately 10 years; distributions began in 2024 and were paid in BTC worth far more in dollar terms than original claims",wrong:["Creditors waited approximately 5 years; distributions began in 2019 and were paid in Japanese yen at 2014 Bitcoin valuations","Creditors waited approximately 7 years; distributions began in 2021 and were partially repaid in BCH following the 2017 fork","Creditors waited approximately 10 years; distributions began in 2024 but were paid only in fiat at 2014 prices per court order"]},{q:"How did Bitcoin's price respond to the Mt. Gox collapse in early 2014, and how long did recovery take?",a:"Bitcoin dropped from roughly $800 to roughly $350 and took nearly 3 years to reclaim its pre-Mt. Gox price",wrong:["Bitcoin dropped from roughly $1,200 to roughly $150 and took nearly 5 years to reclaim its pre-Mt. Gox price","Bitcoin dropped from roughly $800 to roughly $600 and recovered within 6 months as markets shrugged off the exchange failure","Bitcoin dropped from roughly $500 to roughly $50 and took over 4 years to reclaim its pre-collapse all-time high"]},{q:"What lasting contribution to Bitcoin's security culture did the Mt. Gox failure accelerate?",a:"It drove rapid development of hardware wallets and normalized self-custody as the standard practice for holding Bitcoin",wrong:["It accelerated the development of proof-of-reserve auditing standards that all major exchanges now publish quarterly","It prompted the creation of the Bitcoin Foundation to lobby for exchange insurance requirements in major jurisdictions","It caused Bitcoin developers to implement mandatory withdrawal delays on-protocol to prevent rapid theft from online wallets"]},{q:"Despite being the largest exchange failure in crypto history, what did the Mt. Gox debacle definitively prove about the Bitcoin protocol itself?",a:"The Bitcoin protocol was never compromised — it was Mt. Gox's internal systems that were hacked, not the Bitcoin network",wrong:["The Bitcoin protocol's transaction malleability bug was the root cause, proving base layer security vulnerabilities are existential","The Bitcoin protocol survived only because developers issued an emergency patch within 48 hours of the malleability exploit","The Bitcoin protocol was briefly compromised but miners voluntarily reorganized the chain to restore 200,000 stolen coins"]}],mining_hardware:[{q:"What was the correct order of Bitcoin mining hardware evolution?",a:"CPU → GPU → FPGA → ASIC",wrong:["GPU → CPU → ASIC → FPGA","CPU → FPGA → GPU → ASIC","FPGA → GPU → CPU → ASIC"]},{q:"In what year did CPU mining of Bitcoin begin?",a:"2009",wrong:["2010","2011","2008"]},{q:"Who co-founded Bitmain, the dominant ASIC manufacturer?",a:"Jihan Wu and Micree Zhan",wrong:["Roger Ver and Charlie Lee","Adam Back and Greg Maxwell","Hal Finney and Nick Szabo"]},{q:"What is the efficiency metric used to measure ASIC mining performance?",a:"Joules per terahash (J/TH)",wrong:["Kilowatts per gigahash (kW/GH)","Watts per megahash (W/MH)","Terahash per kilowatt-hour (TH/kWh)"]},{q:"Approximately what hash rate does the open-source Bitaxe home miner achieve?",a:"About 3 TH/s",wrong:["About 30 TH/s","About 300 GH/s","About 0.3 PH/s"]},{q:"Why can ASICs not be repurposed once Bitcoin mining becomes unprofitable?",a:"They are application-specific and can only run the SHA-256 algorithm",wrong:["They require proprietary firmware that prevents other software from running","Their cooling systems are designed exclusively for Bitcoin network voltage requirements","They use encrypted memory modules that are locked to Bitcoin pool credentials"]},{q:"Which early Bitcoin miner was also known as a prolific GPU miner around 2010–2011?",a:"Laszlo Hanyecz (the Bitcoin Pizza guy)",wrong:["Hal Finney, who mined the first transaction from Satoshi","Roger Ver, who mined the first blocks on Bitcoin testnet","Nick Szabo, who later sold his GPU rigs to fund Bit Gold research"]},{q:"What milestone did the Bitcoin network hashrate reach in 2025?",a:"1 ZH/s (1 zettahash per second)",wrong:["1 EH/s (1 exahash per second)","1 PH/s (1 petahash per second)","100 EH/s (100 exahashes per second)"]},{q:"What notable event happened with a Bitaxe miner in July 2024?",a:"A Bitaxe solo-mined a valid Bitcoin block, beating billion-to-one odds",wrong:["A Bitaxe achieved a world record hash rate of 10 TH/s for a home device","A Bitaxe was the first open-source device submitted to a major mining pool","A Bitaxe operator won a class-action lawsuit against an ASIC manufacturer"]},{q:"How are some miners repurposing the waste heat from ASIC rigs?",a:"Heating homes, greenhouses, and swimming pools",wrong:["Powering adjacent data centers through thermoelectric generators","Generating steam to drive small turbines for on-site electricity recovery","Pre-heating industrial boilers to reduce natural gas consumption at factories"]}],mining_economics:[{q:"What is the current Bitcoin block subsidy after the April 2024 halving?",a:"3.125 BTC per block",wrong:["6.25 BTC per block","1.5625 BTC per block","2.5 BTC per block"]},{q:'What is "hashprice" in Bitcoin mining economics?',a:"Revenue earned per unit of hashrate per day, usually expressed in $/TH/day",wrong:["The market price of a new ASIC miner measured in USD per terahash of rated capacity","The electricity cost required to produce one terahash of mining output per hour","The break-even Bitcoin price at which a miner's marginal cost equals block reward value"]},{q:"What electricity cost range do large-scale miners typically target to remain competitive?",a:"$0.02–$0.05 per kWh",wrong:["$0.08–$0.12 per kWh","$0.10–$0.15 per kWh","$0.01–$0.02 per kWh"]},{q:"What percentage of a Bitcoin miner's operating costs does energy typically represent?",a:"60–80% of total operating costs",wrong:["20–35% of total operating costs","40–55% of total operating costs","85–95% of total operating costs"]},{q:'What is the "security budget" debate in Bitcoin mining?',a:"Whether transaction fees will be sufficient to incentivize miners after block subsidies approach zero",wrong:["Whether mining pool operators should be required to hold a reserve of BTC as collateral","Whether governments can legally tax mining revenue without undermining network security","Whether energy costs will eventually make proof-of-work mining economically impossible"]},{q:"What is the typical mining pool fee that pools charge for shared mining rewards?",a:"Around 1–2% of earned rewards",wrong:["Around 5–10% of earned rewards","Around 0.1–0.25% of earned rewards","Around 3–5% of earned rewards"]},{q:"How does Bitcoin's difficulty adjustment maintain the ~10-minute block time?",a:"It recalibrates every 2,016 blocks to keep average block time near 10 minutes regardless of hashrate changes",wrong:["It automatically throttles miners' submission rate if blocks are found faster than every 9 minutes","It uses a rolling 144-block average to smoothly adjust the proof-of-work target every day","It resets the target difficulty at each block based on the hash of the previous block header"]},{q:"Approximately how much energy does Bitcoin consume annually?",a:"About 150 TWh per year",wrong:["About 50 TWh per year","About 500 TWh per year","About 1,000 TWh per year"]},{q:"What proportion of Bitcoin mining is estimated to use renewable energy sources?",a:"Over 50% is estimated to come from renewable sources",wrong:["About 10–15% is estimated to come from renewable sources","About 25–30% is estimated to come from renewable sources","About 75–80% is estimated to come from renewable sources"]},{q:"Why do transaction fees become proportionally more important after each halving?",a:"The block subsidy is cut in half, so fees make up a larger share of total miner revenue",wrong:["More transactions are broadcast after each halving due to increased Bitcoin adoption and price","Mining difficulty resets after each halving, temporarily increasing the fee market competitiveness","ASIC efficiency improvements slow after halvings, raising the cost basis miners must recover"]}],taproot_assets:[{q:"What company developed the Taproot Assets protocol?",a:"Lightning Labs",wrong:["Blockstream","Spiral (formerly Square Crypto)","Chaincode Labs"]},{q:"What was the original name of the Taproot Assets protocol before it was renamed?",a:"Taro",wrong:["Omni","Fabric","Sapio"]},{q:"Where does the actual asset data live in the Taproot Assets protocol?",a:"Off-chain, with cryptographic proofs committed on-chain via Taproot",wrong:["Fully on-chain inside OP_RETURN outputs attached to each UTXO","In a federated sidechain pegged to the Bitcoin mainchain via a two-way peg","Distributed across Lightning Network gossip messages anchored by node signatures"]},{q:"What Bitcoin upgrade was a technical prerequisite for the Taproot Assets protocol?",a:"Taproot (BIP341/342), which introduced MAST and tapscript commitment structures",wrong:["SegWit (BIP141), which introduced the witness discount and fixed transaction malleability","CheckSequenceVerify (BIP112), which introduced relative timelocks for channel safety","P2SH (BIP16), which introduced hash-locked scripts and multi-signature spending conditions"]},{q:"What key benefit does Taproot Assets offer to users in high-inflation countries?",a:"They can hold USD-pegged stablecoins and transact over Lightning while inheriting Bitcoin's security",wrong:["They can convert local currency to BTC automatically at the best available exchange rate","They can access zero-fee remittance corridors by routing through sovereign node operators","They can participate in DeFi yield protocols without leaving the Bitcoin network stack"]},{q:"When did Taproot Assets launch on Bitcoin mainnet?",a:"Late 2023",wrong:["Early 2021, shortly after the Taproot soft fork activated","Mid 2022, following a year-long testnet deployment by Lightning Labs","Early 2024, alongside the Bitcoin halving block at height 840,000"]},{q:"How does edge routing work in a Taproot Assets Lightning payment?",a:"Intermediate routing nodes handle only BTC; the final recipient receives the Taproot Asset",wrong:["Every routing node must hold the specific Taproot Asset being transferred along the path","Taproot Asset payments are split into BTC-equivalent shards that each routing node recombines","The sender converts the asset to BTC at the first hop and the receiver converts back at the last hop"]},{q:"How does Taproot Assets differ from Ethereum ERC-20 tokens?",a:"Taproot Assets inherit Bitcoin's security and require no separate smart contract execution environment",wrong:["Taproot Assets use a layer-2 virtual machine that runs alongside the Bitcoin script interpreter","Taproot Assets require validator nodes to stake BTC as a bond to attest to correct asset issuance","Taproot Assets rely on zero-knowledge rollups posted to Bitcoin rather than on-chain contract state"]},{q:"What data structure does Taproot Assets use to commit asset state to Bitcoin?",a:"Merkle trees committed inside Taproot's MAST structure",wrong:["Verkle trees embedded in the SegWit witness field of Bitcoin transactions","Sparse Merkle tries anchored via OP_RETURN outputs to each Bitcoin block","Patricia tries stored in Lightning channel state and settled during channel closure"]},{q:"What type of assets can be issued using the Taproot Assets protocol?",a:"Fixed-supply tokens, reissuable stablecoins, and other custom asset types",wrong:["Only non-fungible tokens representing unique Bitcoin UTXOs with inscribed metadata","Only fiat-pegged stablecoins backed by proof-of-reserve attestations from custodians","Only wrapped versions of existing ERC-20 tokens bridged from Ethereum via atomic swaps"]}],op_codes_bitcoin:[{q:"What is the foundational opcode that verifies a digital signature in Bitcoin Script?",a:"OP_CHECKSIG",wrong:["OP_VERIFY","OP_EQUALVERIFY","OP_HASH160"]},{q:"What Bitcoin scripting language property prevents infinite loops and ensures termination?",a:"Bitcoin Script is non-Turing-complete with no loops or recursion",wrong:["Bitcoin Script has a hard gas limit that terminates execution after a fixed number of opcodes","Bitcoin Script requires all scripts to be pre-registered in a whitelist of approved templates","Bitcoin Script uses a time-boxed interpreter that terminates any script exceeding 10 milliseconds"]},{q:"What does OP_RETURN do in Bitcoin Script?",a:"Marks an output as permanently unspendable and allows arbitrary data to be embedded",wrong:["Returns the top stack value to the calling script as an exit code for conditional branches","Refunds the transaction fee to the sender if the script fails to execute successfully","Terminates script execution early and marks the transaction as valid without further checks"]},{q:"What is OP_CHECKLOCKTIMEVERIFY (CLTV) commonly used for?",a:"Locking coins until a specified block height or Unix timestamp, used in Lightning HTLCs",wrong:["Verifying that a transaction was signed before a certain block height to prevent replay attacks","Checking whether a block timestamp is within a valid range to prevent time-warp exploits","Requiring that spending transactions include a minimum number of confirmations before being valid"]},{q:"What is OP_CHECKSEQUENCEVERIFY (CSV) and how does it differ from CLTV?",a:"A relative timelock locking a coin for N blocks after the UTXO was created, unlike CLTV's absolute lock",wrong:["An absolute timelock identical to CLTV but measured in seconds rather than block heights","A relative fee check ensuring a transaction pays at least N satoshis per byte before being relayed","A sequence number validator that confirms inputs are signed with the correct nSequence bitmask"]},{q:"Why was OP_CAT originally disabled in Bitcoin Script?",a:"Satoshi disabled it as a precaution against potential vulnerabilities and memory exhaustion attacks",wrong:["Miners voted to disable it in 2011 to prevent concatenation-based denial-of-service on full nodes","The BIP process rejected OP_CAT because it duplicated functionality already covered by OP_SUBSTR","Core developers disabled it during the 2013 database fork to reduce script complexity mid-crisis"]},{q:"What capability would re-enabling OP_CAT provide to Bitcoin Script?",a:"Covenants, ZK proof verification on-chain, vaults, and expanded smart contract functionality",wrong:["Turing-complete execution, allowing arbitrary programs to run inside Bitcoin transactions","Native cross-chain atomic swaps without requiring hash time-locked contracts or pre-images","Dynamic fee adjustment inside scripts, allowing self-amending transactions based on mempool state"]},{q:"What is BitVM and who proposed it?",a:"A system by Robin Linus enabling Turing-complete computation via optimistic execution and fraud proofs",wrong:["A formal verification framework by Andrew Poelstra for proving Bitcoin script correctness at compile time","A proposed opcode suite by Jeremy Rubin enabling covenants and recursive transaction templates natively","A sidechain design by Adam Back using Bitcoin opcodes for confidential transaction verification"]},{q:"What does OP_VAULT (BIP345) enable for Bitcoin holders?",a:"Coin vaults with enforced withdrawal delays and a recovery path to thwart theft",wrong:["Multi-party time-locked escrow contracts that release funds based on external oracle attestations","Automatic re-locking of coins to a cold storage address if a spending transaction is unconfirmed","Covenant-based inheritance schemes where heirs receive coins after a fixed block height delay"]},{q:"What is the Simplicity language and who developed it?",a:"A formally verifiable smart contract language for Bitcoin developed by Andrew Poelstra at Blockstream",wrong:["A high-level scripting language for Bitcoin compiled to opcodes, developed by Robin Linus at BitVM Labs","A zero-knowledge proof system for Bitcoin scripts created by Pieter Wuille at Chaincode Labs","A stack-based Turing-complete language for Bitcoin sidechains designed by Gregory Maxwell at Blockstream"]}],bip_standards:[{q:"What does BIP stand for in Bitcoin development?",a:"Bitcoin Improvement Proposal",wrong:["Bitcoin Integration Protocol","Bitcoin Implementation Parameter","Bitcoin Infrastructure Patch"]},{q:"What does BIP32 define?",a:"Hierarchical deterministic (HD) wallets that generate a full key tree from one master seed",wrong:["The mnemonic seed phrase standard using a 2048-word wordlist for human-readable backups","The derivation path format m/purpose'/coin'/account'/change/index for wallet compatibility","The Pay-to-Script-Hash address format allowing complex redemption scripts to use short addresses"]},{q:"How many words are in a standard BIP39 mnemonic seed phrase?",a:"12 or 24 words drawn from a 2048-word wordlist",wrong:["8 or 16 words drawn from a 4096-word phonetically distinct wordlist","10 or 20 words drawn from a 1024-word wordlist filtered for international readability","6 or 12 words drawn from a 512-word wordlist designed for maximum memorability"]},{q:"What unique property do BIP39 words share that aids disambiguation?",a:"The first 4 letters of each word are unique across the entire 2048-word wordlist",wrong:["Each word contains exactly one vowel cluster, making audio transcription unambiguous","No two words share more than two consecutive letters, preventing handwriting confusion","Every word has a unique last two letters, enabling checksummed manual entry validation"]},{q:"What critical bug did BIP141 (SegWit) fix in the Bitcoin protocol?",a:"Transaction malleability, which had prevented safe construction of the Lightning Network",wrong:["The block size limit bug that allowed miners to produce blocks larger than 1 MB without penalty","The time-warp attack that allowed difficulty manipulation by lying about block timestamps","The inflation bug that briefly allowed miners to create more coinbase outputs than permitted"]},{q:"What three major improvements did BIP341/342 (Taproot) introduce?",a:"Schnorr signatures, MAST (Merkelized Abstract Syntax Trees), and Tapscript",wrong:["Bulletproofs, covenant opcodes, and cross-input signature aggregation for privacy","Confidential transactions, threshold signatures, and probabilistic payment channels","Adaptor signatures, recursive covenants, and scriptless script channel factories"]},{q:"What does BIP119 (CTV / CheckTemplateVerify) propose?",a:"A covenant opcode constraining how a coin can be spent to a set of pre-defined transaction templates",wrong:["A threshold signature scheme allowing n-of-m signers to collaboratively authorize transactions","A payment channel factory design enabling thousands of channels from a single on-chain transaction","A fee estimation algorithm that pre-commits to a fee rate before mining to reduce fee sniping"]},{q:"What privacy mechanism does BIP47 (PayNym) provide?",a:"Payment codes letting senders derive unique per-payment addresses via ECDH without address reuse",wrong:["CoinJoin coordination codes that allow trustless mixing of outputs across multiple participants","Stealth addresses generated per-block so receivers never publish a static on-chain identifier","Blind signature tokens allowing receivers to request payments without revealing their public key"]},{q:"How does BIP78 (PayJoin) disrupt blockchain surveillance?",a:"Sender and receiver both contribute inputs, breaking common chain analysis ownership heuristics",wrong:["It replaces transaction IDs with unlinkable blinded identifiers stored in the witness field","It batches multiple payments into one transaction with indistinguishable output values","It routes payments through an intermediary node that reassembles split UTXOs before broadcast"]},{q:"What is the derivation path structure defined by BIP44?",a:"m/purpose'/coin'/account'/change/index",wrong:["m/account'/coin'/purpose'/index/change","m/index/change/account'/coin'/purpose'","m/coin'/purpose'/change/account'/index"]}]},QUEST_TRIGGERS=[5,15,25,40,60,80,100];let currentQuest=null,isRetry=!1,completedQuests=new Set,weeklyCompleted=[],visitedForQuest=[],questCount=0;function _getCurrentWeekKey(){var e=new Date,t=new Date(e.getFullYear(),0,1),o=Math.floor((e-t)/864e5)+1,n=Math.ceil((o+t.getDay())/7);return e.getFullYear()+"-W"+n}function _loadWeeklyCompleted(){var e=safeJSON("btc_quest_week",{}),t=_getCurrentWeekKey();e.week!==t&&(e={week:t,completed:[]},localStorage.setItem("btc_quest_week",JSON.stringify(e))),weeklyCompleted=e.completed||[]}function _saveWeeklyCompleted(e){var t=safeJSON("btc_quest_week",{}),o=_getCurrentWeekKey();t.week!==o&&(t={week:o,completed:[]}),t.completed||(t.completed=[]),-1===t.completed.indexOf(e)&&t.completed.push(e),localStorage.setItem("btc_quest_week",JSON.stringify(t)),weeklyCompleted=t.completed}function initQuests(){safeJSON("btc_visited_channels",[]).forEach(e=>{visitedForQuest.includes(e)||visitedForQuest.push(e)}),void 0!==auth&&auth.currentUser?(loadCompletedQuests(auth.currentUser.uid),_loadWeeklyCompleted()):setTimeout(initQuests,2e3)}function _getDailyActivities(){var e=(new Date).toISOString().split("T")[0],t=safeJSON("btc_daily_activities",{});return t.date!==e&&(t={date:e,quiz:!1,trivia:!1,poll:!1,sfAwarded:!1}),t}function _markDailyActivity(e){var t=_getDailyActivities();t[e]=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(t))}function _checkDailyAllThree(){var e=_getDailyActivities();if(e.quiz&&e.trivia&&e.poll&&!e.sfAwarded){e.sfAwarded=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(e));var t=(new Date).toISOString().split("T")[0];void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({dailyAllThreeDate:t,dailyQuizDone:!0,dailyTriviaDone:!0,dailyPollDone:!0}).catch(function(){}),"function"==typeof window.contributeSatoshiFavor&&window.contributeSatoshiFavor("daily_all_three")}}async function loadCompletedQuests(e){if(db)try{const t=await db.collection("users").doc(e).get();t.exists&&t.data().completedQuests&&(t.data().completedQuests.forEach(e=>completedQuests.add(e)),questCount=completedQuests.size)}catch(e){}}function onChannelVisitForQuest(e){visitedForQuest.includes(e)||visitedForQuest.push(e);const t=visitedForQuest.length;for(const e of QUEST_TRIGGERS)if(t===e&&!currentQuest){setTimeout(()=>{"function"==typeof showToast&&showToast("⚡ You have explored "+e+" channels! A Quest is ready!"),setTimeout(()=>generateAndShowQuest(),3e3)},2e3);break}}function generateAndShowQuest(e,t,o){var n=(new Date).toISOString().split("T")[0],i=safeJSON("btc_quest_daily",{});if(i.date!==n&&(i={date:n,count:0}),i.count>=1&&!o)return void(e&&"function"==typeof showToast&&showToast("⏰ You've completed your daily quiz! Go to Quiz Quests to retake it for a perfect score."));const a=safeJSON("btc_asked_questions",[]);let r=[];if(t&&QUESTION_BANK[t]&&QUESTION_BANK[t].forEach(e=>r.push({...e,source:t})),!t){for(const e of visitedForQuest){const t=QUESTION_BANK[e];t&&t.forEach(t=>r.push({...t,source:e}))}if(QUESTION_BANK._general&&QUESTION_BANK._general.forEach(e=>r.push({...e,source:"_general"})),r.length<5)for(const[e,t]of Object.entries(QUESTION_BANK))if(t.forEach(t=>{r.some(e=>e.q===t.q)||r.push({...t,source:e})}),r.length>=10)break}var s=t?Math.min(3,r.length):5;if(r.length!a.includes(e.q));function c(e){for(var t=e.q.toLowerCase(),o=[[/nostr/i,"nostr"],[/lightning/i,"lightning"],[/halving/i,"halving"],[/mining/i,"mining"],[/node/i,"node"],[/wallet/i,"wallet"],[/seed.?phrase/i,"seed"],[/private.?key/i,"privkey"],[/satoshi/i,"satoshi"],[/block.?chain/i,"blockchain"],[/proof.?of.?work/i,"pow"],[/fud\b/i,"fud"],[/self.?custody/i,"custody"],[/etf/i,"etf"],[/taproot/i,"taproot"],[/difficulty/i,"difficulty"],[/mempool/i,"mempool"],[/hash.?rate/i,"hashrate"],[/white.?paper/i,"whitepaper"],[/21.?million/i,"21m"],[/inflation/i,"inflation"],[/kyc/i,"kyc"],[/privacy/i,"privacy"],[/multisig/i,"multisig"],[/dca|dollar.cost/i,"dca"],[/el.?salvador/i,"elsalvador"]],n=0;nMath.random()-.5);var d=t?Math.min(l.length,5):5,u=[],p={};if(t)for(var m=0;me.q)];localStorage.setItem("btc_asked_questions",JSON.stringify(y));const b=u.map(e=>{const t=[e.a,...e.wrong].sort(()=>Math.random()-.5),o=t.indexOf(e.a);return{q:e.q,options:t,answer:o}});currentQuest={id:f,topicKey:t||null,title:getQuestTitle(questCount,t),questions:b},window._currentQuestServerId=null,"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("startQuest")({questions:b.map(function(e){return{answer:e.answer}}),topicKey:t||null}).then(function(e){window._currentQuestServerId=e.data.questId}).catch(function(e){console.warn("Quest registration failed:",e)}),showQuest(currentQuest,!1)}function getQuestTitle(e,t){if(t&&"_general"!==t){var o={mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",energy:"🔋",cryptography:"🔐",consensus:"🤝",regulation:"⚖️",maximalism:"🔥","difficulty-adjustment":"🎯",books:"📚",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊","smart-contracts":"📝","blockchain-timechain":"⛓️","pow-vs-pos":"⚔️","evidence-against-alts":"⚠️",organic:"🌳",peaceful:"☮️",supranational:"🔔"},n=t.replace(/_pt\d+$/,""),i=o[t]||o[n]||"⚡",a=t.replace(/_pt(\d+)$/,"").replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),r=t.match(/_pt(\d+)$/);return r&&(a+=" (Part "+r[1]+")"),i+" "+a+" Quest"}const s=["₿ Bitcoin Basics Quest","⚡ Lightning Learner Quest","🔒 Security Scholar Quest","💰 Economics Expert Quest","⛓ Technical Titan Quest","🟠 Culture Connoisseur Quest","🛡️ Sovereignty Sage Quest","👑 Satoshi Scholar Quest"];return s[e%s.length]}function playWarriorDrum(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const t=new(window.AudioContext||window.webkitAudioContext),o="undefined"!=typeof audioVolume?audioVolume:.5,n=t.currentTime;function e(e){const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.type="sine",i.frequency.setValueAtTime(150,n+e),i.frequency.exponentialRampToValueAtTime(60,n+e+.15),a.gain.setValueAtTime(.7*o,n+e),a.gain.exponentialRampToValueAtTime(.001,n+e+.4),i.start(n+e),i.stop(n+e+.4);const r=t.createOscillator(),s=t.createGain();r.connect(s),s.connect(t.destination),r.type="sine",r.frequency.setValueAtTime(80,n+e),r.frequency.exponentialRampToValueAtTime(50,n+e+.3),s.gain.setValueAtTime(.5*o,n+e),s.gain.exponentialRampToValueAtTime(.001,n+e+.5),r.start(n+e),r.stop(n+e+.5);const l=Math.floor(.08*t.sampleRate),c=t.createBuffer(1,l,t.sampleRate),d=c.getChannelData(0);for(let e=0;e",i+="

    "+(t?"Retry! Get 3+ correct for 25 XP!":"Answer 5 questions. 3+ correct = 50 XP. All 5 = 100 XP!")+"

    ",i+="",i+='
    ',e.questions.forEach((e,t)=>{i+='
    ',i+='
    Question '+(t+1)+" of 5
    ",i+='
    '+e.q+"
    ",i+='
    ',e.options.forEach((e,o)=>{i+='"}),i+="
    "}),i+="
    ",i+='',i+='',n.innerHTML=i,o.classList.add("open"),window._questAnswers=new Array(5).fill(-1),window._questCorrect=e.questions.map(e=>e.answer)}function selectAnswer(e,t,o){e.parentElement.querySelectorAll(".quest-opt").forEach(e=>e.classList.remove("selected")),e.classList.add("selected"),window._questAnswers[t]=o,window._questAnswers.every(e=>e>=0)&&(document.getElementById("questSubmitBtn").disabled=!1)}async function submitQuest(){if(window._questSubmitted)return;window._questSubmitted=!0;var e=document.getElementById("questSubmitBtn");e&&(e.disabled=!0,e.style.opacity="0.5",e.textContent="Grading...");const t=window._questAnswers,o=window._questCorrect;let n=0,i=0;if(window._currentQuestServerId&&"undefined"!=typeof firebase&&firebase.functions)try{var a=await firebase.functions().httpsCallable("gradeQuest")({questId:window._currentQuestServerId,answers:t,isRetry:!!isRetry});n=a.data.score,i=a.data.pts}catch(e){console.error("Server quest grading failed, falling back:",e),t.forEach((e,t)=>{e===o[t]&&n++})}else t.forEach((e,t)=>{e===o[t]&&n++});document.querySelectorAll(".quest-q").forEach((e,n)=>{e.querySelectorAll(".quest-opt").forEach((e,i)=>{e.disabled=!0,i===o[n]&&e.classList.add("correct"),i===t[n]&&i!==o[n]&&e.classList.add("wrong")})});let r="";var s=5===n,l=!!currentQuest.topicKey;if(isRetry)n>=3?(i||(i=25),r="🎉 "+n+"/5 correct on retry! +"+i+" XP!",!s&&l||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 - Better luck next time! Keep reading and try again.";else if(s){if(i||(i=100),r="🏆 PERFECT! 5/5! +"+i+" XP!",completedQuests.add(currentQuest.id),questCount++,"function"==typeof window.nachoGlobalAnnounce&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var c=void 0!==currentUser&¤tUser&¤tUser.username||auth.currentUser.displayName||"A mystery Bitcoiner",d=currentQuest.title||"a Quiz Quest";window.nachoGlobalAnnounce("🏆 @"+c+" just aced "+d+" with a PERFECT 5/5! Think you can do the same? ➡️ [Quest Hub](#quests)",auth.currentUser.uid)}}else n>=3?(i||(i=50),r="🎉 "+n+"/5 correct! +"+i+" XP!",l||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 - You can retry for 25 XP!";if(i>0){"function"==typeof notifySelfQuest&¬ifySelfQuest(currentQuest.title),"function"==typeof notifySelfPoints&¬ifySelfPoints(i,"🏆 Quest: "+(currentQuest.title||"Quest")),"function"==typeof window._raidOnQuizComplete&&window._raidOnQuizComplete(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(i);var u=(new Date).toISOString().split("T")[0],p=safeJSON("btc_quest_daily",{});p.date!==u&&(p={date:u,count:0}),p.count++,p.lastScore=n,p.lastTopic=currentQuest.topicKey||null,p.lastTitle=currentQuest.title||null,localStorage.setItem("btc_quest_daily",JSON.stringify(p)),_markDailyActivity("quiz"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({questsCompletedToday:p.count||0,lastQuestDate:u}).catch(function(e){console.error("Quest sync failed:",e)})}try{completedQuests.has(currentQuest.id)&&void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&(await db.collection("users").doc(auth.currentUser.uid).update({completedQuests:firebase.firestore.FieldValue.arrayUnion(currentQuest.id)}),db.collection("stats").doc("global").set({questsCompleted:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){}))}catch(e){console.error("Quest completion sync failed:",e)}const m=document.getElementById("questSubmitBtn");m&&(m.style.display="none");const h=document.querySelector(".quest-skip");h&&(h.style.display="none"),window._questScore=n,window._questMsg=r,window._questPts=i;const g=document.querySelector(".quest-header");g&&(g.innerHTML='
    ⚡ QUEST COMPLETE

    '+currentQuest.title+'

    '+(5===n?"🏆":n>=3?"🎉":"😅")+'
    '+n+' / 5 Correct
    Review your answers below - green is correct, red is wrong
    ');const f=document.getElementById("questInner");f&&f.scrollTo({top:0,behavior:"smooth"}),"function"==typeof showToast&&showToast(r)}function playHooraySound(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const e=new(window.AudioContext||window.webkitAudioContext),t="undefined"!=typeof audioVolume?audioVolume:.5,o=e.currentTime;[523,659,784,1047].forEach((n,i)=>{const a=e.createOscillator(),r=e.createGain();a.connect(r),r.connect(e.destination),a.type="sine",a.frequency.value=n,r.gain.setValueAtTime(.15*t,o+.1*i),r.gain.exponentialRampToValueAtTime(.001,o+.1*i+.4),a.start(o+.1*i),a.stop(o+.1*i+.4);const s=e.createOscillator(),l=e.createGain();s.connect(l),l.connect(e.destination),s.type="triangle",s.frequency.value=2*n,l.gain.setValueAtTime(.06*t,o+.1*i),l.gain.exponentialRampToValueAtTime(.001,o+.1*i+.3),s.start(o+.1*i),s.stop(o+.1*i+.3)}),[1047,1319,1568].forEach(n=>{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.type="sine",i.frequency.value=n,a.gain.setValueAtTime(.12*t,o+.45),a.gain.linearRampToValueAtTime(.1*t,o+.7),a.gain.exponentialRampToValueAtTime(.001,o+1.3),i.start(o+.45),i.stop(o+1.3)})}catch(e){}}function _resolveQuestChannel(e){if(!e||void 0===CHANNELS)return null;if(CHANNELS[e])return e;var t=e.replace(/_pt\d+$/,"");if(CHANNELS[t])return t;var o={cycles:"cyles",dlcs:"discrete_log_contracts__dlcs",first_principles:"1_first_principles",foss:"free_and_open_source_software__foss",ordinals_inscriptions:"ordinals",spv:"simplified_payment_verification__spv",halving:"scarce","el-salvador":"regulation"};if(o[e]&&CHANNELS[o[e]])return o[e];if(o[t]&&CHANNELS[o[t]])return o[t];for(var n=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper"],i=0;i=3&&playHooraySound();const n=document.querySelector(".quest-questions");n&&(n.style.display="none");var i=_resolveQuestChannel(currentQuest?currentQuest.topicKey:null);if(!i&&void 0!==CHANNELS){var a=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper","cryptography","philosophy","energy","nodes"].filter(function(e){return!!CHANNELS[e]}).sort(function(){return Math.random()-.5});a.length&&(i=a[0])}var r="";if(i&&void 0!==CHANNELS&&CHANNELS[i]){var s=CHANNELS[i].title;r='
    '+(currentQuest&¤tQuest.topicKey&&_resolveQuestChannel(currentQuest.topicKey)?5===e?"📚 Keep learning":"📖 Study up on":"🔍 Explore next")+'
    '+s+" →
    "}const l=document.querySelector(".quest-header");l&&(l.innerHTML='
    ⚡ QUEST COMPLETE

    '+currentQuest.title+'

    '+(5===e?"🏆":e>=3?"🎉":"😅")+'
    '+e+' / 5 Correct
    '+t+"
    "+(o>0?'
    +'+o+" XP earned!
    ":"")+r+(e<5?'":"")+'');const c=document.getElementById("questInner");c&&(c.scrollTop=0)}function retryQuest(){currentQuest.questions.forEach(e=>{const t=e.options[e.answer];e.options.sort(()=>Math.random()-.5),e.answer=e.options.indexOf(t)}),showQuest(currentQuest,!0)}function startQuestManual(e){if(!currentQuest)if(e){if(generateAndShowQuest(!0,e),"function"==typeof isMobile&&isMobile()){const e=document.getElementById("sidebar");e&&e.classList.remove("open")}}else _showQuestTopicPicker()}function _getDailyRecommendedQuiz(e){if(!e||0===e.length)return null;for(var t=e.map(function(e){return e.key}).sort(),o=t.length,n=new Date("2026-01-01T00:00:00Z").getTime(),i=(new Date).toISOString().split("T")[0],a=new Date(i+"T00:00:00Z").getTime(),r=Math.floor((a-n)/864e5),s=r%o,l=Math.floor(r/o),c=t.slice(),d=7919*l+31337,u=c.length-1;u>0;u--){var p=(d=(16807*d+0)%2147483647)%(u+1),m=c[u];c[u]=c[p],c[p]=m}var h=c[s];return e.find(function(e){return e.key===h})||null}function _showQuestTopicPicker(){var e=[],t={_general:"🌐",mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜","satoshi-nakamoto":"🧩",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",philosophy:"🤔",energy:"🔋",cryptography:"🔐",consensus:"🤝",taproot:"🌳",regulation:"⚖️",maximalism:"🔥",utxos:"📦","difficulty-adjustment":"🎯",transaction_fees:"💳",game_theory:"♟️",books:"📚","orange-pilling":"🍊",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊",geopolitics___macroeconomics:"🌎",human_rights__social_justice_and_freedo:"✊","smart-contracts":"📝",sidechains:"🔗",stablecoins:"🏦",fedimints:"🏛️","pow-vs-pos":"⚔️","blockchain-timechain":"⛓️",softwar:"🪖",time_preference:"⏳",governance:"🏛️","apps-tools":"🧰","misconceptions-fud":"🚫",elevator_pitches:"🗣️"};for(var o in QUESTION_BANK)if("_general"!==o){var n=QUESTION_BANK[o];if(n&&!(n.length<3)){var i=o.replace(/_pt(\d+)$/,"").replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),a=o.match(/_pt(\d+)$/);a&&(i+=" (Part "+a[1]+")");var r=o.replace(/_pt\d+$/,""),s=t[o]||t[r]||"📖",l=completedQuests.has("quest_"+o)||completedQuests.has(o)||-1!==weeklyCompleted.indexOf(o);e.push({key:o,label:i,emoji:s,count:n.length,done:l})}}e.sort(function(e,t){return e.done!==t.done?e.done?1:-1:e.label.localeCompare(t.label)});var c=e.filter(function(e){return e.done}).length,d=document.getElementById("questModal");if(d){var u=document.getElementById("questInner");if(u){var p='

    Choose a Quest Topic

    Pick a Bitcoin topic to test your knowledge

    '+c+"/"+e.length+' topics completed
    ',m=_getDailyRecommendedQuiz(e);m&&(p+=""),p+='',p+='',p+='
    ',e.forEach(function(e){var t=e.done?"rgba(34,197,94,0.06)":"rgba(255,255,255,0.02)",o=e.done?"rgba(34,197,94,0.2)":"var(--border)",n=e.done?'':''+e.count+"Q";p+=""}),p+="
    ",p+='',u.innerHTML=p,setTimeout(function(){var e=document.querySelectorAll("#questTopicList button");e.forEach(function(e){var t=(e.getAttribute("onclick")||"").match(/_startQuestTopic\('([^']+)'\)/);t&&(e.dataset.key=t[1]),e.dataset.label=e.textContent.trim()});var t=document.getElementById("questSearch");t&&t.addEventListener("input",function(){var t=this.value.toLowerCase();e.forEach(function(e){var o=e.dataset.label.toLowerCase();e.style.display=o.includes(t)?"":"none"})})},0),d.classList.add("open")}}}function skipQuest(){closeQuest()}function closeQuest(){document.getElementById("questModal").classList.remove("open"),currentQuest=null,isRetry=!1}function _renderFavorTab(e){if(e){var t="function"==typeof window._resolveFavorState?window._resolveFavorState():null,o=t&&t.favorActive,n=t&&t.points||0,i=Math.min(100,n/21*100),a='
    ✨⛏️
    Satoshi\'s Favor
    Community mining when the community earns 21 points.
    Chance to win 21,000 sats! ⚡
    ';if(o){var r=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();a+='
    🎉 SATOSHI\'S FAVOR IS ACTIVE!
    '+Math.floor(r/6e4)+"m "+Math.floor(r%6e4/1e3)+'s
    Mine below 1,000 to win 21,000 sats!
    ',a+=''}else a+='
    '+n+'/21 points
    '+(21-n)+" more points to activate
    ";if(a+='
    ⚔️ Faction SF Competition
    🐝
    Cyber Hornets
    0
    SF points
    VS
    🦡
    Honey Badgers
    0
    SF points
    👤Unaffiliated - Choose a Faction!
    0pts
    ',a+='
    How it works:
    This is a community challenge - everyone\'s points combine!

    • Complete the daily Quiz Quest, Trivia & Poll = 1 point
    • Earn a badge = 1 point
    • Level up to Pleb/Stacker ranks = 1 point each
    • Level up to Maxi ranks = 5 points each
    • Level up to Papa John or higher = 10 points
    • At 21 points, a mining competition opens for 60 minutes
    • Extra points beyond 21 add +3 min each (even while active!)
    • 10 hashes max per minute per user (60 second cooldown)
    • Generate a random hash. Below 1,000 = win 21,000 sats!',a+='
    🏆 All-Time Lowest Hashes
    Loading...
    ',a+='
    ⭐ Your Personal Best
    Loading...
    ',a+="
    ",e.innerHTML=a,_startFactionScoreboardListener(),_loadFavorLeaderboards(),o){var s=document.getElementById("favorTabTimer");if(s)var l=setInterval(function(){if(s){if(!t||!t.favorActive)return s.textContent="EXPIRED",void clearInterval(l);var e=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();if(e<=0)s.textContent="00:00";else{var o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);s.textContent=o+"m "+n+"s"}}else clearInterval(l)},1e3)}}}function _startFactionScoreboardListener(){if(window._factionScoreUnsub&&(window._factionScoreUnsub(),window._factionScoreUnsub=null),void 0!==db){var e=db.collection("satoshiFavor").doc("factionTotals");window._factionScoreUnsub=e.onSnapshot(function(e){var t=e.exists?e.data():{cyber_hornets:0,honey_badgers:0,unaffiliated:0},o=t.cyber_hornets||0,n=t.honey_badgers||0,i=o+n,a=document.getElementById("sfScoreHornets"),r=document.getElementById("sfScoreBadgers"),s=document.getElementById("sfScoreUnaffiliated"),l=document.getElementById("sfScoreLeader"),c=document.getElementById("sfScoreBar"),d=document.getElementById("sfScoreBarFill"),u=document.getElementById("sfNoFactionNote"),p=t.unaffiliated||0;if(a&&(a.textContent=o.toLocaleString()),r&&(r.textContent=n.toLocaleString()),s&&(s.textContent=p.toLocaleString()),l&&(l.textContent=o>n?"🐝 Leading":n>o?"🦡 Leading":i>0?"Tied!":""),c&&d&&i>0){c.style.display="block";var m=Math.round(o/i*100);d.style.background="linear-gradient(90deg, #f7931a "+m+"%, #a855f7 "+m+"%)"}var h=void 0!==currentUser&¤tUser&¤tUser.faction||"";u&&(u.style.display=h?"none":"block");var g=document.getElementById("sfAdminBackfill");if(g){var f=void 0!==currentUser&¤tUser&&"needcreations@gmail.com"===currentUser.email;g.style.display=f?"block":"none"}var y=void 0!==currentUser&¤tUser&¤tUser.faction||"",b=document.getElementById("factionScoreboardInner");if(b&&y){var v=b.querySelectorAll('div[style*="flex:1"]');v[0]&&(v[0].style.borderWidth="cyber_hornets"===y?"3px":"2px"),v[1]&&(v[1].style.borderWidth="honey_badgers"===y?"3px":"2px")}},function(e){console.warn("[FACTION-SCORE] Listener error:",e)})}}window._retakeLastQuiz=function(){var e=safeJSON("btc_quest_daily",{}).lastTopic||null,t=document.getElementById("questHubOverlay");t&&t.remove(),setTimeout(function(){generateAndShowQuest(!0,e,!0)},200)},window._startQuestTopic=function(e){var t=document.getElementById("questModal");if(t&&t.classList.remove("open"),currentQuest=null,!e){var o=[];for(var n in QUESTION_BANK)"_general"!==n&&(QUESTION_BANK[n].length<3||completedQuests.has("quest_"+n)||completedQuests.has(n)||-1!==weeklyCompleted.indexOf(n)||o.push(n));if(o.length>0)e=o[Math.floor(Math.random()*o.length)];else{var i=Object.keys(QUESTION_BANK).filter(function(e){return"_general"!==e&&QUESTION_BANK[e].length>=3});e=i[Math.floor(Math.random()*i.length)]}}setTimeout(function(){generateAndShowQuest(!0,e)},200)},setTimeout(initQuests,3e3),window.closeQuestHubForFavor=function(){var e=document.getElementById("questHubOverlay");e&&e.remove(),window._cleanupRaidBoss&&window._cleanupRaidBoss(),window._factionScoreUnsub&&(window._factionScoreUnsub(),window._factionScoreUnsub=null)},window._runFactionBackfill=function(){if("undefined"!=typeof firebase){var e=document.querySelector("#sfAdminBackfill button");e&&(e.textContent="⏳ Running backfill...",e.disabled=!0),firebase.functions().httpsCallable("backfillFactionTotals")({}).then(function(t){var o=t.data;"function"==typeof showToast&&showToast("✅ Backfill done! 🐝 "+(o.totals&&o.totals.cyber_hornets||0)+" vs 🦡 "+(o.totals&&o.totals.honey_badgers||0)),e&&(e.textContent="✅ Done!")}).catch(function(t){"function"==typeof showToast&&showToast("❌ Backfill error: "+t.message),e&&(e.textContent="⚡ Backfill historical data (admin)",e.disabled=!1),console.error("[BACKFILL]",t)})}};var _favorTopHashesUnsub=null,_favorPBUnsub=null;function _renderTopHashesHTML(e){for(var t=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null,o="",n=0;n
    '+s+''+(c?"🏆 ":"")+l+(a?" (you)":"")+'
    '+i.value.toLocaleString()+"
    "}return o}function _renderPBHTML(e){var t=e<1e3;return'
    '+(t?"🏆 ":"")+e.toLocaleString()+'
    Your all-time lowest hash
    '}function _loadFavorLeaderboards(){if(void 0!==db){_favorTopHashesUnsub&&(_favorTopHashesUnsub(),_favorTopHashesUnsub=null),_favorPBUnsub&&(_favorPBUnsub(),_favorPBUnsub=null),_favorTopHashesUnsub=db.collection("satoshiFavor").doc("topHashes").onSnapshot(function(e){var t=document.getElementById("favorTopHashes");t&&(e.exists&&e.data().entries&&0!==e.data().entries.length?t.innerHTML=_renderTopHashesHTML(e.data().entries):t.innerHTML='
    No hashes yet. Be the first to mine!
    ')},function(){var e=document.getElementById("favorTopHashes");e&&(e.innerHTML='
    Could not load leaderboard
    ')});var e=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null;if(e){var t=!1;_favorPBUnsub=db.collection("satoshiFavor").doc("personalBests").collection("users").doc(e).onSnapshot(function(o){var n=document.getElementById("favorPersonalBest");n&&(o.exists?n.innerHTML=_renderPBHTML(o.data().value):t?n.innerHTML='
    No hashes yet. Start mining!
    ':(t=!0,db.collection("satoshiFavor").doc("personalBests").get().then(function(t){if(n=document.getElementById("favorPersonalBest"))if(t.exists){var o=(t.data().users||{})[e];n.innerHTML=o?_renderPBHTML(o.value):'
    No hashes yet. Start mining!
    '}else n.innerHTML='
    No hashes yet. Start mining!
    '}).catch(function(){})))},function(){var e=document.getElementById("favorPersonalBest");e&&(e.innerHTML='
    Could not load personal best
    ')})}else{var o=document.getElementById("favorPersonalBest");o&&(o.innerHTML='
    Sign in to track your personal best
    ')}}}function _renderQuestHubTab(){var e=window._questHubTab||"quiz";["Quiz","Trivia","Poll","Raid","Favor","Charity"].forEach(function(t){var o=document.getElementById("qhTab"+t);if(o){var n=e===t.toLowerCase(),i="Raid"===t&&n,a="Charity"===t&&n;o.style.background=i?"linear-gradient(135deg,#8b5cf6,#7c3aed)":a?"linear-gradient(135deg,#ef4444,#dc2626)":n?"var(--accent)":"none",o.style.color=n?"#fff":"var(--text-muted)",o.style.borderColor=i?"#8b5cf6":a?"#ef4444":n?"var(--accent)":"var(--border)"}});var t=document.getElementById("questHubBody");t&&("raid"!==e&&window._cleanupRaidBoss(),"quiz"===e?_renderQuizTab(t):"trivia"===e?_renderTriviaTab(t):"poll"===e?_renderPollTab(t):"raid"===e?_renderRaidTab(t):"favor"===e?_renderFavorTab(t):"charity"===e&&_renderCharityTab(t))}void 0!==startQuestManual&&(window.startQuestManual=startQuestManual),void 0!==selectAnswer&&(window.selectAnswer=selectAnswer),void 0!==submitQuest&&(window.submitQuest=submitQuest),void 0!==skipQuest&&(window.skipQuest=skipQuest),void 0!==closeQuest&&(window.closeQuest=closeQuest),void 0!==showQuest&&(window.showQuest=showQuest),void 0!==generateAndShowQuest&&(window.generateAndShowQuest=generateAndShowQuest),void 0!==_showQuestTopicPicker&&(window._showQuestTopicPicker=_showQuestTopicPicker),void 0!==showQuestFinalResults&&(window.showQuestFinalResults=showQuestFinalResults),void 0!==retryQuest&&(window.retryQuest=retryQuest),void 0!==_renderQuestHubTab&&(window._renderQuestHubTab=_renderQuestHubTab),window._questHubTab="quiz",window.showQuestHub=function(){window._chatOverlayOpen&&"function"==typeof toggleChatOverlay&&toggleChatOverlay();var e=document.getElementById("questHubOverlay");e&&e.remove();var t=document.createElement("div");t.id="questHubOverlay",t.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.88);z-index:100000;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(5px);padding:20px;animation:nachoPop 0.25s ease;",t.onclick=function(e){e.target===t&&(window._cleanupRaidBoss(),t.remove())};var o=document.createElement("div");o.style.cssText="background:var(--bg-side,#141425);border:1px solid var(--border);width:100%;max-width:520px;max-height:85vh;border-radius:24px;overflow:hidden;display:flex;flex-direction:column;position:relative;";var n=document.createElement("style");n.textContent='@media(min-width:600px){#questHubOverlay [style*="font-size:0.6"]{font-size:0.82rem!important}#questHubOverlay [style*="font-size:0.7"]{font-size:0.88rem!important}#questHubOverlay [style*="font-size:0.75"]{font-size:0.9rem!important}#questHubOverlay [style*="font-size:0.78"]{font-size:0.92rem!important}#questHubOverlay [style*="font-size:0.8"]{font-size:0.95rem!important}#questHubOverlay [style*="font-size:0.82"]{font-size:0.97rem!important}#questHubOverlay [style*="font-size:0.85"]{font-size:1rem!important}#questHubOverlay [style*="font-size:0.9"]{font-size:1.05rem!important}#questHubOverlay [style*="font-size:0.95"]{font-size:1.08rem!important}#questHubOverlay p,[id="questHubBody"] div{font-size:inherit}#questHubBody{font-size:1rem}#questHubTabs button{font-size:0.88rem!important;padding:12px 0!important}}',o.appendChild(n);var i=document.createElement("div");i.style.cssText="padding:20px 24px 0;flex-shrink:0;",i.innerHTML='

    ⚔️ Quest Hub

    Earn XP by testing your Bitcoin knowledge
    ';var a=document.createElement("div");a.id="questHubBody",a.style.cssText="padding:0 24px 24px;overflow-y:auto;flex:1;",o.appendChild(i),o.appendChild(a),t.appendChild(o),document.body.appendChild(t),_renderQuestHubTab()};var _charityStats=null,_charityRecent=[],_charityStatsLoaded=!1;function _loadCharityStats(e){if("undefined"==typeof firebase||!firebase.firestore)return e&&e();var t=firebase.firestore();Promise.all([t.collection("charity_stats").doc("global").get({source:"server"}),t.collection("charity_donations").orderBy("ts","desc").limit(10).get({source:"server"})]).then(function(t){var o=t[0],n=t[1];_charityStats=o.exists?o.data():{totalDonated:0,factionTotals:{}},_charityRecent=[],n.forEach(function(e){_charityRecent.push(e.data())}),_charityStatsLoaded=!0,e&&e()}).catch(function(){e&&e()})}function _renderCharityTab(e){e.innerHTML='
    Loading charity data...
    ',_loadCharityStats(function(){_renderCharityTabInner(e)})}function _renderCharityTabInner(e){var t="function"==typeof escapeHtml?escapeHtml:function(e){return String(e||"").replace(//g,">")},o=void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous,n=void 0!==currentUser&¤tUser&¤tUser.faction||"",i=void 0!==currentUser&¤tUser&¤tUser.points||0,a=void 0!==currentUser&¤tUser&¤tUser.pointsClaimed||0,r=void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,s=Math.max(0,i-a-r),l=_charityStats||{totalDonated:0,factionTotals:{}},c=l.totalDonated||0,d=l.factionTotals&&l.factionTotals.cyber_hornets||0,u=l.factionTotals&&l.factionTotals.honey_badgers||0,p="";p+='
    ❤️
    Donate XP for Charity
    1,000 XP = 1,000 sats donated - 10× more impact than redeeming for yourself
    ',p+='
    🌍 Community Pledge
    '+c.toLocaleString()+' sats pledged
    ('+c.toLocaleString()+" XP donated by the community)
    ";var m=d+u,h=m>0?Math.round(d/m*100):50,g=100-h;p+='
    ⚔️ Faction Giving
    🐝 Cyber Hornets🦡 Honey Badgers
    '+d.toLocaleString()+" XP ("+h+"%)"+u.toLocaleString()+" XP ("+g+"%)
    ",o?n?(p+='
    🎡 Your Donation
    Available to donate: '+s.toLocaleString()+" XP"+(r>0?' ('+r.toLocaleString()+" already donated)":"")+"
    ",p+='
    ',[5,10,25,50,100].forEach(function(e){var t=Math.floor(s*e/100);p+='"}),p+="
    ",p+='
    ',p+='
    ',p+='',p+="
    "):p+="
    ⚔️
    Choose Your Faction First
    Your faction's donation total is tracked for the community leaderboard. Join a side before you donate!
    ":p+='
    🔐 Sign in to donate XP for charity
    ',_charityRecent.length>0&&(p+='
    📜 Recent Donations
    ',_charityRecent.forEach(function(e){var o,n=e.anonymous||!e.uid||"Anonymous"===(e.username||""),i="cyber_hornets"===e.faction?'🐝':"honey_badgers"===e.faction?'🦡':"";o=n?"color:var(--text-muted);":"cyber_hornets"===e.faction?"color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,1px 1px 0 #000,-1px 1px 0 #000;font-weight:700;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;":"honey_badgers"===e.faction?"color:#e5e7eb;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,1px 1px 0 #000,-1px 1px 0 #000;font-weight:700;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;":"color:var(--text);font-weight:600;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;";var a=n?''+t(e.username||"Anonymous")+"":''+t(e.username||"Anonymous")+"";p+='
    '+i+" "+a+'+'+(e.amount||0).toLocaleString()+" XP
    "}),p+="
    "),p+='
    🗳️ Community Charity Vote
    Coming soon - the community will vote on which charities receive our pledged sats. Focused on Bitcoin education and adoption, but not limited to it.
    ',p+="

    Our community will vote on which charities our contributions go to. In Bitcoin, the charities will focus on Bitcoin education and adoption - but our donations are not limited to the Bitcoin ecosystem. We can find charities outside of Bitcoin that we want to support as a community.

    ⚠️ Donations are non-refundable. Donated XP cannot be reclaimed or reversed. Donations are a community pledge and are not tax-deductible. This is not a registered charitable organization and no tax receipts are issued.

    ",p+='
    🏅 Donation Badges
    ';var f="function"==typeof safeJSON?safeJSON("btc_hidden_badges",[]):[];[{id:"donor_100",emoji:"🫷",name:"Giving Pleb",thresh:"100 XP",reward:"50 XP"},{id:"donor_500",emoji:"💛",name:"Stack Sharer",thresh:"500 XP",reward:"150 XP"},{id:"donor_1000",emoji:"🧡",name:"Community Builder",thresh:"1,000 XP",reward:"300 XP"},{id:"donor_5000",emoji:"❤️",name:"Archive Patron",thresh:"5,000 XP",reward:"1,000 XP"},{id:"donor_10000",emoji:"🔥",name:"Sats Saint",thresh:"10,000 XP",reward:"2,000 XP"},{id:"donor_25000",emoji:"⚡",name:"Lightning Philanthropist",thresh:"25,000 XP",reward:"4,000 XP"},{id:"donor_50000",emoji:"🏆",name:"Satoshi's Steward",thresh:"50,000 XP",reward:"7,500 XP"},{id:"donor_100000",emoji:"👑",name:"Legend of the Archive",thresh:"100,000 XP",reward:"15,000 XP"}].forEach(function(e){var t=f.includes(e.id)||void 0!==currentUser&¤tUser&&Array.isArray(currentUser.donationBadges)&¤tUser.donationBadges.includes(e.id);p+='
    '+e.emoji+'
    '+e.name+'
    '+e.thresh+' donated
    +'+e.reward+" reward
    "}),p+="
    ",e.innerHTML=p,window._charitySetAmount=function(e){var t=document.getElementById("charityAmtInput");t&&(t.value=e>0?e:"")},window._submitCharityDonation=function(){if("undefined"!=typeof firebase&&firebase.functions){var e=document.getElementById("charityAmtInput"),t=parseInt(e?e.value:"")||0;if(!t||t<1)"function"==typeof showToast&&showToast("Enter a valid amount");else{var o=Math.max(0,void 0!==currentUser&¤tUser?(currentUser.points||0)-(currentUser.pointsClaimed||0)-(currentUser.pointsDonated||0):0);if(t>o)"function"==typeof showToast&&showToast("Not enough available XP. You have "+o.toLocaleString()+" pts available.");else{var n=!!document.getElementById("charityAnonToggle")&&document.getElementById("charityAnonToggle").checked,i=document.querySelector('[onclick="window._submitCharityDonation()"]');i&&(i.disabled=!0,i.textContent="Donating..."),firebase.functions().httpsCallable("donatePoints")({amount:t,anonymous:n}).then(function(e){void 0!==currentUser&¤tUser&&(currentUser.pointsDonated=(currentUser.pointsDonated||0)+t,e.data&&e.data.bonusPts&&(currentUser.points=(currentUser.points||0)+e.data.bonusPts));var o=e.data&&e.data.newBadges||[],n=o.length>0?" You earned "+o.length+" new badge"+(o.length>1?"s":"")+"!":"";if("function"==typeof showToast&&showToast("❤️ Thank you! "+t.toLocaleString()+" XP donated ("+t.toLocaleString()+" sats pledged to charity)."+n,5e3),window._charityThankYou(t,o,e.data&&e.data.bonusPts||0),o.length>0&&"function"==typeof window.contributeSatoshiFavor){var i={donor_100:{emoji:"🫷",name:"Giving Pleb"},donor_500:{emoji:"💛",name:"Stack Sharer"},donor_1000:{emoji:"🧡",name:"Community Builder"},donor_5000:{emoji:"❤️",name:"Archive Patron"},donor_10000:{emoji:"🔥",name:"Sats Saint"},donor_25000:{emoji:"⚡",name:"Lightning Philanthropist"},donor_50000:{emoji:"🏆",name:"Satoshi's Steward"},donor_100000:{emoji:"👑",name:"Legend of the Archive"}};o.forEach(function(e){var t=i[e];t&&window.contributeSatoshiFavor("badge_earned",t.emoji+" "+t.name).catch(function(){})})}_charityStatsLoaded=!1,_renderCharityTab(document.getElementById("questHubBody"))}).catch(function(e){i&&(i.disabled=!1,i.textContent="❤️ Donate XP for Charity"),"function"==typeof showToast&&showToast("❌ "+(e.message||"Donation failed. Try again."),4e3)})}}}else"function"==typeof showToast&&showToast("Firebase not ready")}}function _renderQuizTab(e){var t=(new Date).toISOString().split("T")[0],o=safeJSON("btc_quest_daily",{}),n=o.date===t?o.count:0,i=completedQuests?completedQuests.size:0,a=o.date===t&&n>=1&&o.lastScore&&o.lastScore<5,r="";if(a){o.lastTopic&&o.lastTopic.replace(/['\\]/g,"");var s=o.lastTitle||"your last quiz";r='
    🔄 You scored '+o.lastScore+"/5 on "+("function"==typeof escapeHtml?escapeHtml(s):s)+'
    Retake it to get a perfect score! +25 XP for improvement
    '}e.innerHTML='
    📝
    Quiz Quests
    1 daily quiz - retake until you ace it!
    '+n+'
    Today
    '+i+'
    All Time
    3+ correct = 50 XP
    Perfect = 100 XP
    '+r+"
    "}function _getTriviaToday(){if("undefined"==typeof TRIVIA_BANK||!TRIVIA_BANK||!TRIVIA_BANK.length)return null;var e=new Date,t=new Date(e.getFullYear(),0,0),o=(7*Math.floor((e-t)/864e5)+e.getFullYear())%TRIVIA_BANK.length;return{index:o,trivia:TRIVIA_BANK[o]}}function _getTriviaState(){try{return JSON.parse(localStorage.getItem("btc_trivia_state")||"{}")}catch(e){return{}}}function _setTriviaState(e){try{localStorage.setItem("btc_trivia_state",JSON.stringify(e))}catch(e){}}function _renderTriviaTab(e){var t=_getTriviaToday();if(t&&t.trivia){var o=_getTriviaState(),n=(new Date).toISOString().split("T")[0],i=o.date===n,a=t.trivia,r='
    🧠
    Trivia Quest
    1 new question every day
    +50 XP correct · +10 XP for trying
    ';r+='
    '+("function"==typeof escapeHtml?escapeHtml(a.q):a.q)+"
    ",r+='
    ';for(var s=0;s
    '+String.fromCharCode(65+s)+''+l+''+(p?''+p+"":"")+"
    "}else r+='"}r+="",i&&void 0!==db&&db.collection("trivia_stats").doc(n).get().then(function(e){var t=e.exists?e.data():{},o=t.total||0;if(!(o<1))for(var n=0;n
    💡 Explanation
    '+("function"==typeof escapeHtml?escapeHtml(a.explanation):a.explanation)+"
    ",r+='
    Come back tomorrow for a new trivia question! 🧠
    '),e.innerHTML=r}else e.innerHTML='
    Trivia questions loading...
    '}function _getPollToday(){if("undefined"==typeof POLL_BANK||!POLL_BANK||!POLL_BANK.length)return null;var e=new Date,t=new Date(e.getFullYear(),0,0),o=(13*Math.floor((e-t)/864e5)+e.getFullYear())%POLL_BANK.length;return{index:o,poll:POLL_BANK[o]}}function _getPollState(){try{return JSON.parse(localStorage.getItem("btc_poll_state")||"{}")}catch(e){return{}}}function _setPollState(e){try{localStorage.setItem("btc_poll_state",JSON.stringify(e))}catch(e){}}function _renderPollTab(e){var t=_getPollToday();if(t&&t.poll){var o=_getPollState(),n=(new Date).toISOString().split("T")[0],i=o.date===n&&"number"==typeof o.chosen,a=t.poll,r='
    📊
    Poll Quest
    Vote daily - see what the community thinks
    +50 XP for voting
    ';if(r+='
    '+("function"==typeof escapeHtml?escapeHtml(a.q):a.q)+"
    ",i)_renderPollResults(e,r,a,o,n);else{var s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null,l=a.id||"poll_day_"+n;s&&void 0!==db?db.collection("poll_votes").doc(l).get().then(function(i){if(i.exists&&i.data().voters&&-1!==i.data().voters.indexOf(s)){var l=o.chosen;_setPollState(o={date:n,index:t.index,chosen:"number"==typeof l?l:-1,pollId:a.id}),_renderPollResults(e,r,a,o,n)}else _showPollVoteButtons(e,r,a)}).catch(function(){_showPollVoteButtons(e,r,a)}):_showPollVoteButtons(e,r,a)}}else e.innerHTML='
    Polls loading...
    '}function _showPollVoteButtons(e,t,o){t+='
    ';for(var n=0;n'+String.fromCharCode(65+n)+""+i+""}t+="
    ",e.innerHTML=t}function _renderPollResults(e,t,o,n,i){var a=o.id||"poll_day_"+i;void 0!==db?db.collection("poll_votes").doc(a).get().then(function(i){var a=i.exists&&i.data().votes||[0,0,0,0],r=a.reduce(function(e,t){return e+t},0)||1;_drawPollResults(e,t,o,a,r,n.chosen)}).catch(function(){_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}):_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}function _drawPollResults(e,t,o,n,i,a){var r=t,s=["#f7931a","#3b82f6","#22c55e","#8b5cf6"];r+='
    ';for(var l=0;l
    '+(u?"✓":String.fromCharCode(65+l))+''+c+'
    '+d+"%
    "}r+="",r+='
    '+i+" total vote"+(1!==i?"s":"")+" · Come back tomorrow for a new poll!
    ",e.innerHTML=r}function _renderRaidTab(e){e.innerHTML='
    Loading Raid Boss...
    ',window._loadRaidBoss()}function _raidEmptyState(){return'
    ⚔️
    Raid Boss
    No active raid boss right now.
    Check back soon for community boss fights!
    '}function _raidVictoryBanner(e){var t="function"==typeof escapeHtml?escapeHtml(e.name||"Raid Boss"):e.name||"Raid Boss",o=_getRaidBossImage(e);return'
    '+(o?'
    '+t+'
    💀
    ':'
    💀
    ')+'
    BOSS DEFEATED! 🎉
    '+t+' has fallen!
    The community worked together and took it down! Great job everyone!
    🏆 Community reward unlocked!
    Extra orange ticket drawing for 21,000 sats - this Friday night!
    '}window._charityThankYou=function(e,t,o){var n=document.getElementById("charityThankYouOverlay");n&&n.remove();var i=document.createElement("div");i.id="charityThankYouOverlay",i.style.cssText="position:fixed;inset:0;z-index:300000;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;padding:20px;";var a=document.createElement("div");a.style.cssText="background:var(--card-bg);border:1px solid rgba(239,68,68,0.4);border-radius:20px;padding:28px 24px;max-width:360px;width:100%;text-align:center;position:relative;";var r='
    ❤️
    Thank You!
    You donated '+e.toLocaleString()+" XP - that's "+e.toLocaleString()+" sats pledged to charity.
    ";o>0&&(r+='
    +'+o.toLocaleString()+" bonus XP earned!
    "),t&&t.length>0&&(r+='
    🏼 New badge'+(t.length>1?"s":"")+" unlocked: "+t.join(", ")+"
    "),r+='
    The community will vote on which charities receive these sats.
    ',a.innerHTML=r,i.appendChild(a),i.addEventListener("click",function(e){e.target===i&&i.remove()}),document.body.appendChild(i)},window._renderCharityHome=function(){var e=document.getElementById("charityDonateHome");e&&"undefined"!=typeof firebase&&firebase.firestore&&firebase.firestore().collection("charity_stats").doc("global").get().then(function(t){var o=t.exists?t.data():{totalDonated:0,factionTotals:{}},n=o.totalDonated||0,i=o.factionTotals&&o.factionTotals.cyber_hornets||0,a=o.factionTotals&&o.factionTotals.honey_badgers||0;e.innerHTML='
    ❤️ Donate XP for Charity
    Tap to donate →
    '+n.toLocaleString()+' sats pledged
    🐝 '+i.toLocaleString()+' XP🦡 '+a.toLocaleString()+" XP
    "}).catch(function(){})},window.triviaAnswer=function(e){var t=_getTriviaToday();if(t&&t.trivia){var o=t.trivia,n=(new Date).toISOString().split("T")[0],i=_getTriviaState();if(i.date!==n){var a=e===o.answer,r=a?50:10;if(_setTriviaState(i={date:n,index:t.index,chosen:e,correct:a}),"function"==typeof awardPoints&&awardPoints(r,a?"🧠 Trivia Quest correct!":"🧠 Trivia Quest attempt"),a&&"function"==typeof window._raidOnTriviaCorrect&&window._raidOnTriviaCorrect(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(r),_markDailyActivity("trivia"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({lastTriviaDate:n,triviaAnswered:firebase.firestore.FieldValue.increment(1),triviaCorrect:firebase.firestore.FieldValue.increment(a?1:0)}).catch(function(){}),void 0!==db){var s={total:firebase.firestore.FieldValue.increment(1)};s["option_"+e]=firebase.firestore.FieldValue.increment(1),db.collection("trivia_stats").doc(n).set(s,{merge:!0}).catch(function(){})}var l=document.getElementById("questHubBody");l&&_renderTriviaTab(l),"function"==typeof showToast&&showToast(a?"✅ Correct! +50 XP 🧠":"❌ Wrong - +10 XP for trying!",3e3)}}},window.pollVote=function(e){var t=_getPollToday();if(t&&t.poll){var o=t.poll,n=(new Date).toISOString().split("T")[0],i=_getPollState();if(i.date!==n||"number"!=typeof i.chosen){var a=document.querySelectorAll("#pollOptions button");a.forEach(function(e){e.disabled=!0,e.style.opacity="0.5",e.style.cursor="default"});var r=o.id||"poll_day_"+n,s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null;if(void 0!==db&&s){var l=db.collection("poll_votes").doc(r);db.runTransaction(function(t){return t.get(l).then(function(n){var i=n.exists?n.data():{},a=i.voters||[];if(-1!==a.indexOf(s))return Promise.reject({code:"already-voted"});var c=i.votes||[0,0,0,0];c[e]=(c[e]||0)+1,a.push(s),t.set(l,{pollId:r,question:o.q,options:o.options,votes:c,voters:a,lastUpdated:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0})})}).then(function(){_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof awardPoints&&awardPoints(50,"📊 Poll Quest vote"),"function"==typeof window._raidOnPollVote&&window._raidOnPollVote(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(50),"function"==typeof showToast&&showToast("📊 Vote recorded! +50 XP",3e3),_markDailyActivity("poll"),_checkDailyAllThree(),auth.currentUser.isAnonymous||db.collection("users").doc(s).update({lastPollDate:n,pollsVoted:firebase.firestore.FieldValue.increment(1)}).catch(function(){});var a=document.getElementById("questHubBody");a&&_renderPollTab(a)}).catch(function(r){if(!r||"already-voted"!==r.code)return console.error("[POLL] Vote failed:",r),"function"==typeof showToast&&showToast("⚠️ Vote failed - try again",3e3),void a.forEach(function(e){e.disabled=!1,e.style.opacity="1",e.style.cursor="pointer"});_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("You already voted on this poll today!",3e3);var s=document.getElementById("questHubBody");s&&_renderPollTab(s)})}else{_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("📊 Vote recorded locally",3e3);var c=document.getElementById("questHubBody");c&&_renderPollTab(c)}}}},window._raidBossUnsub=null,window._raidParticipantsUnsub=null,window._raidTimerInterval=null,window._cleanupRaidBoss=function(){window._raidBossUnsub&&(window._raidBossUnsub(),window._raidBossUnsub=null),window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null),window._raidTimerInterval&&(clearInterval(window._raidTimerInterval),window._raidTimerInterval=null),window._raidDamageDealersOpen=!1},window._loadRaidBoss=function(){window._cleanupRaidBoss();var e=document.getElementById("raidBossContent");e&&(void 0!==db?window._raidBossUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.innerHTML=_raidEmptyState();else{var o=Date.now(),n=null,i=null,a=null;if(t.forEach(function(e){var t=e.data();t._id=e.id;var r=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,s=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime?i.startTime.toMillis?i.startTime.toMillis():i.startTime:0))&&(i=t):t.defeated&&(a||(a=t))}),a&&(i||n)&&!n){window._defeatedBossId=a._id;var r=_raidVictoryBanner(a);e.innerHTML=r;var s=document.createElement("div");return s.id="raidUpcomingSection",e.appendChild(s),window._currentRaidBoss=i||a,void _renderRaidBossCard(s,i)}var l=n||i||a;l?(window._currentRaidBoss=l,_renderRaidBossCard(e,l)):e.innerHTML=_raidEmptyState()}},function(t){console.error("[RAID] Boss listener error:",t),e.innerHTML='
    ⚠️ Failed to load raid boss
    '}):e.innerHTML='
    ⚠️ Database not available
    ')};var RAID_BOSS_IMAGES={"Channel-Crawler":"images/raid-bosses/channel-crawler.png","Quiz-Crusader":"images/raid-bosses/quiz-crusader.png","TV-Titan":"images/raid-bosses/tv-titan.png","Beats-Baron":"images/raid-bosses/beats-baron.png","Flash-Flash":"images/raid-bosses/flash-flash.png","XP-Hoarder":"images/raid-bosses/xp-hoarder.png","Poll-Patroller":"images/raid-bosses/poll-patroller.png","Chat-Charger":"images/raid-bosses/chat-charger.png","Badge-Builder":"images/raid-bosses/badge-builder.png","Streak-Sage":"images/raid-bosses/streak-sage.png","Topic-Explorer":"images/raid-bosses/topic-explorer.png","Lightning-Lancer":"images/raid-bosses/lightning-lancer.png","Forum-Forge":"images/raid-bosses/forum-forge.png","Trivia-Tactician":"images/raid-bosses/trivia-tactician.png","Content-Conqueror":"images/raid-bosses/content-conqueror.png"};function _getRaidBossImage(e){return e.image||RAID_BOSS_IMAGES[e.name]||""}function _renderRaidBossCard(e,t){Date.now();var o=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,n=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0,i=_getRaidBossImage(t);if(t.placeholder){var a=o?new Date(o):null,r=a?a.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"Soon",s=i?''+(t.name||':'
    ⚔️
    ';return e.innerHTML='
    '+s+'
    '+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
    '+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
    '+("function"==typeof escapeHtml?escapeHtml(r):r)+'
    Get ready to team up and take it down!
    🏆 Community Prize
    Defeat the boss = extra orange ticket giveaway for 21,000 sats!
    ',void _startRaidCountdown("raidCountdownPlaceholder",o)}if(t.defeated){var l=t.winners||[],c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null;if(c&&-1!==l.indexOf(c)&&localStorage.setItem("btc_raid_winner","true"),l.length>0)for(var d=0;d'+(t.name||
    💀
    ':'
    💀
    ';return e.innerHTML='
    '+u+'
    DEFEATED!
    '+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
    '+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
    🎉 Community reward unlocked!
    Extra orange ticket giveaway for 21,000 sats!
    ',void(window._defeatedBossId=t._id)}var p=void 0!==t.current?t.current:void 0!==t.currentHP?t.currentHP:0,m=t.target||t.targetHP||1,h=Math.min(100,Math.round(p/m*100)),g=Math.max(0,m-p),f=Math.max(0,100-h),y="function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss",b="function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"",v=i?''+y+'':'
    👹
    ';if(e.innerHTML='
    '+v+'
    '+y+'
    '+b+'
    ❤️ Boss Health'+g.toLocaleString()+" / "+m.toLocaleString()+' HP
    '+h+'% damage dealt
    ⏰ Time Remaining
    🏆 Community Prize
    Defeat the boss and the community earns an extra orange ticket giveaway for 21,000 sats!
    Loading...
    ',!document.getElementById("raidShimmerStyle")){var w=document.createElement("style");w.id="raidShimmerStyle",w.textContent="@keyframes raidShimmer{0%{transform:translateX(-100%)}100%{transform:translateX(100%)}}",document.head.appendChild(w)}_startRaidCountdown("raidTimer",n),window._raidActiveTab="current",window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),_listenRaidParticipants(t._id)}function _startRaidCountdown(e,t){function o(){var o=document.getElementById(e);if(!o)return clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var n=Math.max(0,t-Date.now());if(n<=0)return o.textContent="Time's up!",clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var i=Math.floor(n/864e5),a=Math.floor(n%864e5/36e5),r=Math.floor(n%36e5/6e4),s=Math.floor(n%6e4/1e3);o.textContent=(i>0?i+"d ":"")+(a>0?a+"h ":"")+(r<10?"0":"")+r+"m "+(s<10?"0":"")+s+"s"}window._raidTimerInterval&&clearInterval(window._raidTimerInterval),o(),window._raidTimerInterval=setInterval(o,1e3)}function _listenRaidParticipants(e){window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),void 0!==db&&(window._raidParticipantsUnsub=db.collection("raid_bosses").doc(e).collection("participants").orderBy("contributed","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t)if(e.empty)t.innerHTML='
    No raiders yet - be the first! ⚔️
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,l=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] Participants listener error:",e)}))}function _listenAllTimeRaiders(){window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),void 0!==db&&(window._raidAllTimeUnsub=db.collection("users").where("raidDamageAllTime",">",0).orderBy("raidDamageAllTime","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t&&"alltime"===window._raidActiveTab)if(e.empty)t.innerHTML='
    No all-time damage recorded yet.
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.raidDamageAllTime||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,l=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] All-time raiders listener error:",e);var t=document.getElementById("raidParticipants");t&&"alltime"===window._raidActiveTab&&(t.innerHTML='
    Could not load all-time data.
    ')}))}window._raidDamageDealersOpen=!1,window._raidDamageDealersUnsub=null,window._toggleRaidDamageDealers=function(){var e=document.getElementById("raidDamageDealers"),t=document.getElementById("raidDamageDealersBtn");if(e){if(window._raidDamageDealersOpen=!window._raidDamageDealersOpen,!window._raidDamageDealersOpen)return e.style.display="none",t&&(t.textContent="⚔️ Top Damage Dealers"),void(window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null));e.style.display="block",t&&(t.textContent="▲ Hide Damage Dealers"),e.innerHTML='
    Loading...
    ';var o=window._defeatedBossId||(window._currentRaidBoss&&window._currentRaidBoss._id?window._currentRaidBoss._id:null);o&&void 0!==db?window._raidDamageDealersUnsub=db.collection("raid_bosses").doc(o).collection("participants").orderBy("contributed","desc").limit(30).onSnapshot(function(e){var t=document.getElementById("raidDamageDealers");if(t)if(e.empty)t.innerHTML='
    No damage recorded for this boss.
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,l=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] Damage dealers listener error:",e);var t=document.getElementById("raidDamageDealers");t&&(t.innerHTML='
    Failed to load damage data.
    ')}):e.innerHTML='
    No damage data available.
    '}},window._raidActiveTab="current",window._raidAllTimeUnsub=null,window._switchRaidTab=function(e){if(e!==window._raidActiveTab){window._raidActiveTab=e;var t=document.getElementById("raidTabCurrent"),o=document.getElementById("raidTabAllTime");t&&(t.style.borderBottomColor="current"===e?"#8b5cf6":"transparent",t.style.color="current"===e?"#8b5cf6":"var(--text-faint)"),o&&(o.style.borderBottomColor="alltime"===e?"#8b5cf6":"transparent",o.style.color="alltime"===e?"#8b5cf6":"var(--text-faint)");var n=document.getElementById("raidParticipants");n&&(n.innerHTML='
    Loading...
    '),"current"===e?(window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._currentRaidBoss&&window._currentRaidBoss._id&&_listenRaidParticipants(window._currentRaidBoss._id)):(window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),_listenAllTimeRaiders())}};var RAID_GUIDANCE={uniqueUsers5Topics:{action:"Visit 5+ learning topics to deal damage!",nav:"home"},quizCompletions:{action:"Complete quiz quests to deal damage!",nav:"quests"},watchMinutes:{action:"Watch Timechain TV to deal damage!",nav:"tctv"},beatsMinutes:{action:"Listen to Bitcoin Beats to deal damage!",nav:"beats"},flashcardCompletions:{action:"Complete flashcard sets to deal damage!",nav:"quests"},totalXP:{action:"Earn XP from any activity to deal damage!",nav:"home"},pollVotes:{action:"Vote in Quest Hub polls to deal damage!",nav:"quests"},chatMessages:{action:"Send messages in Global Chat to deal damage!",nav:"chat"},badgesEarned:{action:"Earn badges to deal damage! Find them in the Leaderboard button 🏆",nav:"badges"},streakUsers:{action:"Maintain a 7-day daily visit streak to deal damage!",nav:"home"},uniqueTopicsVisited:{action:"Visit learning topics you haven't read yet!",nav:"home"},tipsSent:{action:"Send Lightning tips to deal damage!",nav:"home"},forumPosts:{action:"Create forum posts to deal damage!",nav:"forum"},triviaCorrect:{action:"Answer trivia correctly in Quest Hub to deal damage!",nav:"quests"},totalTopicReads:{action:"Read learning topics to deal damage!",nav:"home"}};window._contributeRaid=function(){var e=window._currentRaidBoss;if(e){var t=RAID_GUIDANCE[e.metric]||{action:"Complete activities on the site to deal damage!",nav:"home"};"function"==typeof showToast&&showToast("⚔️ "+t.action,3500);var o=document.getElementById("questHubOverlay");if(o&&o.remove(),"badges"===t.nav){if("function"==typeof toggleLeaderboard){var n=document.getElementById("leaderboard");if(n&&n.classList.contains("open")){n.classList.remove("open");var i=document.getElementById("lbFloatBtn");i&&(i.style.display="flex")}toggleLeaderboard(),setTimeout(function(){var e=document.getElementById("leaderboard");if(e)for(var t=e.querySelectorAll("h4"),o=0;o'+i.emoji+'
    '+i.title+'
    '+i.desc+"
    "}t+='',t+="";var a=document.createElement("div");a.id="forumRulesOverlay",a.innerHTML=t,document.body.appendChild(a)}window.acceptForumRules=function(){localStorage.setItem("btc_forum_rules_accepted","true");var e=document.getElementById("forumRulesOverlay");e&&e.remove()},window.showForumRulesBtn=function(){i()};var a=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","retard","nazi","hitler","kkk","porn","hentai","rape","pedo"];function r(e){for(var t=e.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/),o=0;o=4&&-1!==t[o].indexOf(a[n]))return!1}return!0}function s(e){return"function"==typeof escapeHtml?escapeHtml(e):String(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}window.forumBack=function(){history.back()};var l="recent",c=sessionStorage.getItem("btc_forum_category")||"all",d=null,u="discussions",p=["Bitcoin Basics","Lightning","Mining","Privacy","Self-Custody","Economics","Technical","Culture","Opinion","Tutorial","News Analysis"];function m(e,n){if(n)if(0!==e.length){var i="";e.forEach(function(e){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},a=o.find(function(t){return t.id===e.category}),r=a?a.emoji+" "+a.name:"",l=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),c=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid);i+='
    '+(e.upvotes||0)+'
    '+s(e.title)+"
    "+(e.body?'
    '+s(e.body).substring(0,120)+(e.body.length>120?"...":"")+"
    ":"")+"
    '+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'💬 '+(e.replyCount||0)+""+(r?''+r+"":"")+(l?"':"")+"
    "}),n.innerHTML=i}else n.innerHTML='
    🦌
    No posts yet. Be the first to start a discussion!
    '}async function h(e){var o=document.getElementById("forumReplies");if(o)try{var n=await db.collection("forum_replies").where("postId","==",e).orderBy("createdAt","asc").limit(100).get(),i=[];if(n.forEach(function(e){i.push({id:e.id,...e.data()})}),0===i.length)return void(o.innerHTML='
    No replies yet. Be the first!
    ');var a=[],r={};i.forEach(function(e){e.parentReplyId?(r[e.parentReplyId]||(r[e.parentReplyId]=[]),r[e.parentReplyId].push(e)):a.push(e)});var l='
    '+i.length+" "+(1===i.length?"reply":"replies")+"
    ";function c(e,o){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},i=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid),a=s(e.body).replace(/\n/g,"
    ");a=T(a=a.replace(/(https?:\/\/[^\s<]+)/g,'$1'));var r=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),l=auth&&auth.currentUser&&!auth.currentUser.isAnonymous;return'
    '+(e.parentAuthorName?'
    ↩ '+s(e.parentAuthorName)+"
    ":"")+'
    "+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'
    '+a+'
    "+(l?'':"")+(r?"':"")+"
    "}a.forEach(function(e){l+=c(e,!1),(r[e.id]||[]).forEach(function(e){l+=c(e,!0)})}),Object.keys(r).forEach(function(e){a.some(function(t){return t.id===e})||r[e].forEach(function(e){l+=c(e,!1)})}),o.innerHTML=l}catch(d){o.innerHTML='
    Error loading replies
    '}}window.renderForum=function(){var e=document.getElementById("forumContainer");if(e){e.innerHTML="";var t='
    ';if(t+='
    Home
    ',t+='

    🗣️ Pleb Talk

    Discuss Bitcoin with fellow learners
    ',t+='
    ',"stacker"===u){var n=window._snSearchQuery||"";t+='
    ',t+='',t+='',n&&(t+=''),t+="
    ";var a=window._snSub||"",r=[{id:"",label:"All"},{id:"bitcoin",label:"bitcoin"},{id:"lightning",label:"lightning"},{id:"nostr",label:"nostr"},{id:"privacy",label:"privacy"},{id:"tech",label:"tech"},{id:"meta",label:"meta"}];t+='
    ';for(var d=0;d'+S(p.label)+""}if(t+="
    ",n)t+='
    Search results for: '+S(n)+"
    ";else{var h=window._snSort||"top",g=window._snWhen||"day";t+='
    ';for(var f=[{id:"top",label:"🔥 Top"},{id:"recent",label:"🕐 Recent"},{id:"random",label:"🎲 Random"}],y=0;y'+b.label+""}if("top"===h){t+='"}t+='stacker.news ↗',t+="
    "}return t+='
    Loading Stacker News...
    ',t+="
    ",e.innerHTML=t,void(n?function(e){var t=document.getElementById("snFeed");if(t){var o="https://embed-proxy.needcreations.workers.dev/api/sn/search?q="+encodeURIComponent(e);fetch(o).then(function(e){return e.json()}).then(function(o){if(o&&o.data&&o.data.search&&o.data.search.items){var n=o.data.search.items;n.length?t.innerHTML=v(n):t.innerHTML='
    No results found for "'+S(e)+'"
    '}else t.innerHTML='
    No results found
    '}).catch(function(){t.innerHTML='
    Search failed.
    '})}}(n):loadStackerNewsFeed(window._snSort||"top",window._snWhen||"day",a))}"articles"!==u?(t+='
    ',["recent","top","discussed"].forEach(function(e){var o=l===e;t+=""}),t+='
    ",t+='
    Loading posts...
    ',t+="",e.innerHTML=t,document.getElementById("main").scrollTop=0,"true"!==localStorage.getItem("btc_forum_rules_accepted")&&i(),forumLoadPosts()):function(e,t){var o=e;o+='
    ',o+='
    ',["recent","top"].forEach(function(e){var t=l===e;o+=""}),o+="
    ",o+='
    Loading articles...
    ',o+="",t.innerHTML=o,document.getElementById("main").scrollTop=0,async function(){var e=document.getElementById("articlesList");if(e&&void 0!==db)try{var t="top"===l?"upvotes":"createdAt",o=await db.collection("articles").where("status","==","published").orderBy(t,"desc").limit(15).get(),n=[];if(o.forEach(function(e){n.push({id:e.id,...e.data()})}),0===n.length)return void(e.innerHTML='
    📝
    No articles yet
    Be the first to publish a Bitcoin article!
    ');var i="";n.forEach(function(e){var t="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},o=Math.max(1,Math.round((e.wordCount||500)/200)),n=e.createdAt&&e.createdAt.toDate?e.createdAt.toDate().toLocaleDateString():"",a=e.pinned?'📌 PINNED ':"";i+="
    ',e.coverUrl&&(i+='
    '),i+='
    ',i+=a+'

    '+s(e.title)+"

    ",e.subtitle&&(i+='
    '+s(e.subtitle)+"
    "),e.tags&&e.tags.length&&(i+='
    ',e.tags.forEach(function(e){i+=''+s(e)+""}),i+="
    "),i+='
    "+t.emoji+" "+s(e.authorName||"Anon")+"·"+o+" min read"+(n?"·"+n+"":"")+"
    ",i+='
    👍 '+(e.upvotes||0)+"💬 "+(e.replyCount||0)+""+(e.tipTotal?"⚡ "+e.tipTotal+" sats":"")+"
    ",i+="
    "}),e.innerHTML=i}catch(t){console.error("Articles load error:",t),e.innerHTML='
    Error loading articles
    '}}()}(t,e)}},window._forumUnsubscribe=null,window.forumLoadPosts=async function(){document.getElementById("forumPosts")&&void 0!==db&&(window._forumUnsubscribe&&(window._forumUnsubscribe(),window._forumUnsubscribe=null),async function(){var e=document.getElementById("forumPosts");if(e)try{var t="top"===l?"upvotes":"discussed"===l?"replyCount":"createdAt",o=c+"_"+l,n=Date.now();if(window._forumCache&&window._forumCache.key===o&&n-window._forumCache.time<12e4)return window._forumCache.posts,void m(window._forumCache.posts,e);var i="all"!==c?db.collection("forum_posts").where("category","==",c).orderBy(t,"desc").limit(50):db.collection("forum_posts").orderBy(t,"desc").limit(50),a=await i.get(),r=[];a.forEach(function(e){r.push({id:e.id,...e.data()})}),window._forumCache={key:o,time:Date.now(),posts:r},m(r,e)}catch(t){e.innerHTML='
    Error loading posts. Try refreshing.
    '}}())},window.forumSetSort=function(e){l=e,renderForum()},window.forumSetCategory=function(e){c=e,sessionStorage.setItem("btc_forum_category",e),renderForum()},window.forumViewPost=async function(e,o){var n=document.getElementById("forumContainer");if(n&&void 0!==db){o||history.pushState({channel:"forum",forumPost:e},"","#forum/post/"+e),n.innerHTML='
    ';try{var i=await db.collection("forum_posts").doc(e).get();if(!i.exists)return void renderForum();var a={id:i.id,...i.data()};d=a;var r="function"==typeof getLevel?getLevel(a.authorPoints||0):{emoji:"🟢"},l=a.voters&&auth&&auth.currentUser&&-1!==a.voters.indexOf(auth.currentUser.uid),c='
    ';if(c+='
    Home
    ',c+='',c+='

    '+s(a.title)+'

    "+r.emoji+" "+s(a.authorName||"Anon")+''+timeAgo(a.createdAt)+"
    ",a.body){var u=s(a.body).replace(/\n/g,"
    ").replace(/\*\*(.+?)\*\*/g,"$1");c+='
    '+(u=T(u=u.replace(/(https?:\/\/[^\s<]+)/g,'$1')))+"
    "}a.link&&(c+='🔗 '+s(a.link).substring(0,60)+(a.link.length>60?"...":"")+"
    ");var p=auth&&auth.currentUser&&a.authorId===auth.currentUser.uid||t();c+='
    💬 '+(a.replyCount||0)+" replies"+(p?"':"")+"
    ",c+="
    ",auth&&auth.currentUser&&!auth.currentUser.isAnonymous?c+='
    ':c+='
    🔒
    Want to join the conversation?
    ',c+='
    Loading replies...
    ',c+="
    ",n.innerHTML=c,document.getElementById("main").scrollTop=0,h(e)}catch(e){n.innerHTML='
    Error loading post
    '}}},window.forumNewPost=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){history.pushState({channel:"forum-new"},"","#forum");var e=document.getElementById("forumContainer");if(e){var t='
    ';t+='
    Home
    ',t+='',t+='

    📝 Create New Post

    ',t+='
    ';var n="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;";t+='",t+='',t+='',t+='',t+='
    ',t+='',t+='
    ',t+="
    ",window._forumFormOpenTime=Date.now(),e.innerHTML=t,document.getElementById("main").scrollTop=0}}else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
    🔒

    Registration Required

    Create a free account to post in the forum, join discussions, and earn XP! It only takes a few seconds.
    ')}};var g=0;function f(e){if(!e)return"";var t=s(e);return T(t='

    '+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,'$1')).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/(?$1')).replace(/^### (.+)$/gm,'

    $1

    ')).replace(/^## (.+)$/gm,'

    $1

    ')).replace(/^# (.+)$/gm,'

    $1

    ')).replace(/\*\*(.+?)\*\*/g,'$1')).replace(/\*(.+?)\*/g,"$1")).replace(/`(.+?)`/g,'$1')).replace(/^> (.+)$/gm,'
    $1
    ')).replace(/^- (.+)$/gm,'
  • $1
  • ')).replace(/^\d+\. (.+)$/gm,'
  • $1
  • ')).replace(/---/g,'
    ')).replace(/\n{2,}/g,'

    '))+"

    ")}window.forumSubmitPost=async function(){if(!window._forumSubmitting){var e=Date.now();if(e-g<3e4)"function"==typeof showToast&&showToast("⏳ Wait 30 seconds between posts");else{g=e,window._forumSubmitting=!0;var t=document.getElementById("forumPostStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o=document.getElementById("forumHoneypot");if(o&&o.value)t&&(t.innerHTML='Something went wrong. Please try again.');else if(window._forumFormOpenTime&&Date.now()-window._forumFormOpenTime<5e3)t&&(t.innerHTML='Please take a moment to write your post.');else{var n=(document.getElementById("forumNewTitle").value||"").trim(),i=(document.getElementById("forumNewBody").value||"").trim(),a=(document.getElementById("forumNewLink").value||"").trim(),l=document.getElementById("forumNewCat").value;if("function"==typeof sanitizeInput&&(n=sanitizeInput(n),i=sanitizeInput(i)),!n||n.length<5)t&&(t.innerHTML='Title must be at least 5 characters');else if(!r(n)||i&&!r(i))t&&(t.innerHTML='Post contains inappropriate language. Keep it clean!');else{a&&!/^https?:\/\//i.test(a)&&(a="https://"+a);var c=parseInt(localStorage.getItem("btc_forum_post_count")||"0"),d=localStorage.getItem("btc_forum_post_date")||"",u=(new Date).toISOString().split("T")[0];if(d!==u&&(c=0),c>=5)t&&(t.innerHTML='You\'ve reached the daily post limit (5). Try again tomorrow!');else{t&&(t.innerHTML='Posting...');try{var p=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",m=void 0!==currentUser&¤tUser&¤tUser.points||0,h=await db.collection("forum_posts").add({title:n,body:i.substring(0,2e3),link:a.substring(0,200)||null,category:l,authorId:auth.currentUser.uid,authorName:p,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:m,upvotes:0,voters:[],replyCount:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()});if(localStorage.setItem("btc_forum_post_count",(c+1).toString()),localStorage.setItem("btc_forum_post_date",u),"function"==typeof awardPoints&&awardPoints(10,"📝 Forum post"),"function"==typeof awardTickets&&awardTickets(5,"📝 Forum post"),forumNotifyMentions(i,"forum_post",h.id,n),db.collection("users").doc(auth.currentUser.uid).update({forumPosts:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumPosts=(currentUser.forumPosts||0)+1),"function"==typeof window._raidOnForumPost&&window._raidOnForumPost(),"function"==typeof window.nachoGlobalAnnounce){var f=s(n).substring(0,80),y=s(i).substring(0,120);window.nachoGlobalAnnounce("🗣️ New Forum Post: "+f+" by "+s(p)+": "+y+(i.length>120?"...":"")+" ➡️ [Open PlebTalk](#forum)")}forumBack()}catch(e){t&&(t.innerHTML='Error posting. Try again.')}}}}}else t&&(t.innerHTML='You must be signed in')}}},window._forumReplyingTo=null,window.forumReplyToReply=function(e,t){window._forumReplyingTo={replyId:e,authorName:t};var o=document.getElementById("forumReplyIndicator");o&&(o.style.display="flex",o.querySelector("span").textContent="↩ Replying to "+t);var n=document.getElementById("forumReplyInput");n&&(n.focus(),n.placeholder="Reply to "+t+"...")},window.forumCancelReplyTo=function(){window._forumReplyingTo=null;var e=document.getElementById("forumReplyIndicator");e&&(e.style.display="none");var t=document.getElementById("forumReplyInput");t&&(t.placeholder="Write a reply...")},window.forumSubmitReply=async function(e){if(!window._forumReplySubmitting){window._forumReplySubmitting=!0;var t=document.getElementById("forumReplyStatus"),o=document.getElementById("forumReplyInput");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&o){var n=o.value.trim();if(!n||n.length<2)return t&&(t.innerHTML='Reply is too short'),void(window._forumReplySubmitting=!1);if(!r(n))return t&&(t.innerHTML='Reply contains inappropriate language'),void(window._forumReplySubmitting=!1);t&&(t.innerHTML='Posting...');try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0,s={postId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:a,upvotes:0,voters:[],createdAt:firebase.firestore.FieldValue.serverTimestamp()},l=window._forumReplyingTo;l&&l.replyId&&(s.parentReplyId=l.replyId,s.parentAuthorName=l.authorName||""),await db.collection("forum_replies").add(s),await db.collection("forum_posts").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Forum reply");var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";if(l&&l.replyId){try{var u=await db.collection("forum_replies").doc(l.replyId).get();u.exists&&u.data().authorId&&"function"==typeof sendNotification&&sendNotification(u.data().authorId,"reply",c+' replied to your comment on "'+(d?(d.title||"").substring(0,40):"a post")+'"',"forum_post",e)}catch(e){}d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",c+' replied in your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e)}else d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",c+' replied to your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e);forumNotifyMentions(n,"forum_post",e,d?d.title:""),db.collection("users").doc(auth.currentUser.uid).update({forumReplies:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumReplies=(currentUser.forumReplies||0)+1),o.value="",window.forumCancelReplyTo(),t&&(t.innerHTML='✅ Reply posted!'),h(e)}catch(e){t&&(t.innerHTML='Error posting reply')}window._forumReplySubmitting=!1}else window._forumReplySubmitting=!1}},window.forumVotePost=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_posts").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your post "'+(a.title||"").substring(0,40)+'"',"forum_post",e)}}d&&d.id===e?forumViewPost(e):forumLoadPosts()}catch(e){}},window.forumVoteReply=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_replies").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;-1!==n.indexOf(i)?await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)}):await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)}),d&&h(d.id)}catch(e){}},window.forumDeletePost=async function(e){if(auth&&auth.currentUser){var o=t();if(confirm(o?"Admin: Delete this post and all its replies?":"Delete your post? This cannot be undone."))try{var n=await db.collection("forum_replies").where("postId","==",e).get(),i=db.batch();n.forEach(function(e){i.delete(e.ref)}),i.delete(db.collection("forum_posts").doc(e)),await i.commit(),"function"==typeof showToast&&showToast("🗑️ Post deleted"),forumBack()}catch(e){"function"==typeof showToast&&showToast("Error deleting post")}}},window.forumDeleteReply=async function(e,o){if(auth&&auth.currentUser){var n=t();if(confirm(n?"Admin: Delete this reply?":"Delete your reply? This cannot be undone."))try{await db.collection("forum_replies").doc(e).delete(),await db.collection("forum_posts").doc(o).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Reply deleted"),d&&h(o)}catch(e){"function"==typeof showToast&&showToast("Error deleting reply")}}},window.forumSwitchTab=function(e){u=e,renderForum()};var y=["Content must be Bitcoin-focused or Bitcoin-adjacent","Minimum 500 words, maximum 10,000 words","No promotion of altcoins, scams, or affiliate spam","Original content only — no plagiarism","No hate speech or personal attacks","Author grants the archive a non-exclusive license to display the content","Moderators may remove content that violates these guidelines"];async function b(e){var o=document.getElementById("articleReplies");if(o)try{var n=await db.collection("article_replies").where("articleId","==",e).orderBy("createdAt","asc").limit(50).get();if(n.empty)return void(o.innerHTML='
    No comments yet. Be the first!
    ');var i="";n.forEach(function(o){var n=o.data(),a="function"==typeof getLevel?getLevel(n.authorPoints||0):{emoji:"🟢"},r=n.createdAt&&n.createdAt.toDate?"function"==typeof timeAgo?timeAgo(n.createdAt.toDate()):n.createdAt.toDate().toLocaleDateString():"",l=auth&&auth.currentUser&&(auth.currentUser.uid===n.authorId||t());i+='
    "+a.emoji+" "+s(n.authorName||"Anon")+'· '+r+""+(l?"':"")+'
    '+T(s(n.body).replace(/\n/g,"
    ").replace(/(https?:\/\/[^\s<]+)/g,'$1'))+"
    "}),o.innerHTML=i}catch(e){o.innerHTML='
    Error loading comments
    '}}function v(e){for(var t="",o=0;o",t+='
    ',t+='
    ',t+='
    '+B(n.sats)+"
    ",t+='
    sats
    ',t+="
    ",t+='
    ',t+='
    '+S(n.title)+"
    ",t+='
    ',t+='@'+S(n.user.name)+"",t+="·",t+=""+i+"",n.ncomments>0&&(t+="·",t+="💬 "+n.ncomments+""),a&&(t+="·",t+=''+S(a)+""),r&&(t+=''+S(r)+""),t+="
    ",t+='',t+="
    "}return t}function w(e,t){for(var o="",n=0;n',o+='
    ',o+='@'+S(i.user.name)+"",o+="·",o+=""+k(i.createdAt)+"",i.sats>0&&(o+="·",o+='⚡ '+B(i.sats)+""),o+="
    ",i.text&&(o+='
    '+x(i.text)+"
    "),o+="",i.comments&&i.comments.comments&&i.comments.comments.length>0&&(o+=w(i.comments.comments,t+1))}return o}function x(e){if(!e)return"";var t=S(e);return'

    '+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/^#{3}\s+(.+)$/gm,'

    $1
    ')).replace(/^#{2}\s+(.+)$/gm,'
    $1
    ')).replace(/^#{1}\s+(.+)$/gm,'
    $1
    ')).replace(/\*\*\*(.+?)\*\*\*/g,"$1")).replace(/\*\*(.+?)\*\*/g,"$1")).replace(/\*(.+?)\*/g,"$1")).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/`([^`]+)`/g,'$1')).replace(/\n\n/g,'

    ')).replace(/\n/g,"
    "))+"

    "}function k(e){var t=Math.floor((Date.now()-new Date(e).getTime())/1e3);return t<60?"just now":t<3600?Math.floor(t/60)+"m ago":t<86400?Math.floor(t/3600)+"h ago":Math.floor(t/86400)+"d ago"}function B(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"k":String(e)}function S(e){return e?e.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""):""}function T(e){return e&&-1!==e.indexOf("@")?e.replace(/(<[^>]+>)|(@([a-zA-Z0-9_\-\.]{2,20}))/g,function(e,t,o,n){return t||'"+o+""}):e}window.articleNew=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void("function"==typeof showToast&&showToast("🔒 Sign in to write articles"));if((void 0!==currentUser&¤tUser&¤tUser.points||0)<100)"function"==typeof showToast&&showToast("📝 You need 100+ points to publish articles. Keep exploring!");else{var e=null;try{e=JSON.parse(localStorage.getItem("btc_article_draft"))}catch(e){}var t=document.getElementById("forumContainer");if(t){var o="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;",n='
    ';n+='',n+='

    ✍️ Write an Article

    ',n+='
    ',n+='',n+='',n+='
    ';var i=e&&e.tags?e.tags:[];p.forEach(function(e){var t=-1!==i.indexOf(e);n+=""}),n+="
    ",n+='
    ',n+='
    0 words · Min 500
    ',n+='',n+='
    📋 Content Guidelines
    ',y.forEach(function(e){n+='
    • '+e+"
    "}),n+='
    ',n+='
    ',n+='
    ',n+="
    ",t.innerHTML=n,document.getElementById("main").scrollTop=0;var a=document.getElementById("articleBody");a&&(a.addEventListener("input",function(){var e=this.value.trim().split(/\s+/).filter(function(e){return e.length>0}).length,t=document.getElementById("articleWordCount");t&&(t.textContent=e+" words · Min 500")}),window._articleAutoSave=setInterval(function(){articleSaveDraft(!0)},3e4))}}},window.toggleArticleTag=function(e,t){if(-1!==e.style.borderColor.indexOf("var(--accent)")||-1!==e.style.color.indexOf("var(--accent)"))e.style.border="1px solid var(--border)",e.style.background="none",e.style.color="var(--text-muted)";else{if(document.querySelectorAll('#articleTagsContainer button[style*="accent-bg"]').length>=3)return void("function"==typeof showToast&&showToast("Max 3 tags"));e.style.border="1px solid var(--accent)",e.style.background="var(--accent-bg)",e.style.color="var(--accent)"}},window.articleInsert=function(e,t,o){var n=document.getElementById("articleBody");if(n){n.focus();var i=n.selectionStart,a=n.selectionEnd,r=n.value.substring(i,a),s=r||o,l=e+s+t;n.setRangeText(l,i,a,"select"),r||(n.selectionStart=i+e.length,n.selectionEnd=i+e.length+s.length),n.dispatchEvent(new Event("input"))}},window.articleInsertLink=function(){var e=document.getElementById("articleBody");if(e){var t=e.value.substring(e.selectionStart,e.selectionEnd),o=document.getElementById("articleLinkDialog");o&&o.remove();var n=document.createElement("div");n.id="articleLinkDialog",n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",n.onclick=function(e){e.target===n&&n.remove()};var i="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";n.innerHTML='

    🔗 Insert Link

    ',document.body.appendChild(n),setTimeout(function(){document.getElementById("linkDialogUrl").focus()},100)}},window.articleDoInsertLink=function(){var e=(document.getElementById("linkDialogText").value||"").trim()||"link",t=(document.getElementById("linkDialogUrl").value||"").trim();if(t){t.match(/^https?:\/\//)||(t="https://"+t);var o=document.getElementById("articleBody");if(o){var n="["+e+"]("+t+")",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleLinkDialog").remove()}else"function"==typeof showToast&&showToast("Enter a URL")},window.articleInsertImage=function(){var e=document.getElementById("articleImageDialog");e&&e.remove();var t=document.createElement("div");t.id="articleImageDialog",t.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",t.onclick=function(e){e.target===t&&t.remove()};var o="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";t.innerHTML='

    🖼️ Insert Image

    Or upload from device:
    ',document.body.appendChild(t),setTimeout(function(){var e=document.getElementById("imageDialogFile");e&&e.addEventListener("change",function(){var e=this.files[0];if(e)if(e.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var t=document.getElementById("imageDialogPreview"),o=document.getElementById("imageDialogBtn");if(o&&(o.disabled=!0,o.textContent="Uploading..."),"undefined"!=typeof firebase&&firebase.storage&&void 0!==auth&&auth.currentUser)firebase.storage().ref("article-images/"+auth.currentUser.uid+"/"+Date.now()+"_"+e.name.replace(/[^a-zA-Z0-9._-]/g,"_")).put(e).then(function(e){return e.ref.getDownloadURL()}).then(function(e){document.getElementById("imageDialogUrl").value=e,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image"),"function"==typeof showToast&&showToast("✅ Image uploaded!")}).catch(function(e){"function"==typeof showToast&&showToast("Upload failed: "+(e.message||"Unknown error")),o&&(o.disabled=!1,o.textContent="Insert Image")});else{var n=new FileReader;n.onload=function(e){document.getElementById("imageDialogUrl").value=e.target.result,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image")},n.readAsDataURL(e)}}}),document.getElementById("imageDialogUrl").focus()},100)},window.articleDoInsertImage=function(){var e=(document.getElementById("imageDialogUrl").value||"").trim(),t=(document.getElementById("imageDialogAlt").value||"").trim()||"image";if(e){var o=document.getElementById("articleBody");if(o){var n="\n!["+t+"]("+e+")\n",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleImageDialog").remove()}else"function"==typeof showToast&&showToast("Enter an image URL or upload a file")},window.toggleArticlePreview=function(){var e=document.getElementById("articleBody"),t=document.getElementById("articlePreviewArea"),o=document.getElementById("articlePreviewBtn");e&&t&&("none"===t.style.display?(t.innerHTML=f(e.value),t.style.display="block",e.style.display="none",o.textContent="Edit"):(t.style.display="none",e.style.display="",o.textContent="Preview"))},window.articleSaveDraft=function(e){var t=(document.getElementById("articleTitle")||{}).value||"",o=(document.getElementById("articleSubtitle")||{}).value||"",n=(document.getElementById("articleBody")||{}).value||"",i=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&i.push(e.getAttribute("data-tag"))}),(t||n)&&(localStorage.setItem("btc_article_draft",JSON.stringify({title:t,subtitle:o,body:n,tags:i,savedAt:Date.now()})),e||"function"!=typeof showToast||showToast("💾 Draft saved!"))},window.articleSubmit=async function(){if(!window._articleSubmitting){var e=document.getElementById("articleStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var t=(document.getElementById("articleTitle").value||"").trim(),o=(document.getElementById("articleSubtitle").value||"").trim(),n=(document.getElementById("articleBody").value||"").trim(),i=document.getElementById("articleTerms");if(!t||t.length<10)e&&(e.innerHTML='Title must be at least 10 characters');else{var a=n.split(/\s+/).filter(function(e){return e.length>0}).length;if(a<500)e&&(e.innerHTML='Article must be at least 500 words (currently '+a+")");else if(a>1e4)e&&(e.innerHTML='Article must be under 10,000 words');else{var l=[];if(document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&l.push(e.getAttribute("data-tag"))}),l.length<1)e&&(e.innerHTML='Select at least 1 tag');else if(i&&i.checked)if(r(t)&&r(n)){window._articleSubmitting=!0,e&&(e.innerHTML='Publishing...');try{var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",d=void 0!==currentUser&¤tUser&¤tUser.points||0,p=void 0!==currentUser&¤tUser&¤tUser.profilePic?currentUser.profilePic:"",m="",h=document.getElementById("articleCover");if(h&&h.files&&h.files[0]){var g=h.files[0];if(g.size>3145728)return e&&(e.innerHTML='Cover image too large (max 3MB)'),void(window._articleSubmitting=!1);e&&(e.innerHTML='Uploading cover...');try{var f=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),y=await f.put(g);m=await y.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}e&&(e.innerHTML='Publishing article...');var b={title:t.substring(0,120),subtitle:o.substring(0,200),body:n.substring(0,5e4),tags:l.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),authorId:auth.currentUser.uid,authorName:c,authorPoints:d,authorPic:p,upvotes:0,voters:[],replyCount:0,tipTotal:0,status:"published",pinned:!1,agreedToTerms:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp(),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};m&&(b.coverUrl=m),await db.collection("articles").add(b),localStorage.removeItem("btc_article_draft"),window._articleAutoSave&&clearInterval(window._articleAutoSave),"function"==typeof awardPoints&&awardPoints(30,"📝 Article published"),"function"==typeof awardTickets&&awardTickets(20,"📝 Article published");var v=parseInt(localStorage.getItem("btc_articles_published")||"0");localStorage.setItem("btc_articles_published",String(v+1)),"function"==typeof showToast&&showToast("📝 Article published!"),u="articles",renderForum()}catch(t){console.error("Article submit error:",t),e&&(e.innerHTML='Error publishing: '+s(t.message)+"")}window._articleSubmitting=!1}else e&&(e.innerHTML='Content contains inappropriate language');else e&&(e.innerHTML='You must agree to the content guidelines')}}}else e&&(e.innerHTML='Sign in required')}},window.articleView=async function(e){var o=document.getElementById("forumContainer");if(o&&db){o.innerHTML='
    Loading article...
    ';try{var n=await db.collection("articles").doc(e).get();if(!n.exists)return void(o.innerHTML='
    Article not found
    ');var i=n.data();i.id=e;var a="function"==typeof getLevel?getLevel(i.authorPoints||0):{emoji:"🟢"},r=Math.max(1,Math.round((i.wordCount||500)/200)),l=i.createdAt&&i.createdAt.toDate?i.createdAt.toDate().toLocaleDateString():"",c=auth&&auth.currentUser&&auth.currentUser.uid===i.authorId,d=t(),u=auth&&auth.currentUser&&-1!==(i.voters||[]).indexOf(auth.currentUser.uid),p='
    ';if(p+='',i.coverUrl&&(p+='
    Cover
    '),p+='

    '+s(i.title)+"

    ",i.subtitle&&(p+='
    '+s(i.subtitle)+"
    "),p+='
    ',i.authorPic&&(p+=''),p+='
    "+a.emoji+" "+s(i.authorName||"Anon")+'
    '+l+" · "+r+" min read · "+(i.wordCount||0).toLocaleString()+" words
    ",c&&(p+="'),d&&(p+=""),p+="
    ",i.tags&&i.tags.length&&(p+='
    ',i.tags.forEach(function(e){p+=''+s(e)+""}),p+="
    "),p+='
    '+f(i.body)+"
    ",p+='
    ',p+="","function"==typeof tipButtonHtml&&(p+=tipButtonHtml({recipientName:i.authorName,recipientUid:i.authorId,context:"article",contextId:e,label:"⚡ Tip Author",size:"md"})),(c||d)&&(p+="'),p+="
    ",p+='

    💬 Comments

    ',p+='
    Loading comments...
    ',auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(p+='
    '),p+="
    ",o.innerHTML=p,document.getElementById("main").scrollTop=0,b(e),auth&&auth.currentUser){var m="btc_article_read_"+e;localStorage.getItem(m)||setTimeout(function(){document.getElementById("articleReplies")&&(localStorage.setItem(m,"1"),"function"==typeof awardPoints&&awardPoints(5,"📖 Read an article"),"function"==typeof showToast&&showToast("📖 +5 points for reading!"))},6e4)}}catch(e){console.error("Article view error:",e),o.innerHTML='
    Error loading article
    '}}},window.articleVote=async function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{var t=db.collection("articles").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your article "'+(a.title||"").substring(0,40)+'"',"article",e)}}articleView(e)}catch(e){}else"function"==typeof showToast&&showToast("🔒 Sign in to upvote")},window.articleSubmitReply=async function(e){var t=document.getElementById("articleReplyInput"),o=document.getElementById("articleReplyStatus");if(t&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var n=t.value.trim();if(!n||n.length<2)o&&(o.innerHTML='Comment too short');else if(r(n))try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0;await db.collection("article_replies").add({articleId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorPoints:a,createdAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("articles").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Article comment");try{var s=await db.collection("articles").doc(e).get();if(s.exists&&s.data().authorId&&"function"==typeof sendNotification){var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(s.data().authorId,"comment",l+' commented on your article "'+(s.data().title||"").substring(0,40)+'"',"article",e)}forumNotifyMentions(n,"article",e,s&&s.exists?s.data().title:"")}catch(e){}t.value="",o&&(o.innerHTML='✅ Comment posted!'),b(e)}catch(e){o&&(o.innerHTML='Error posting comment')}else o&&(o.innerHTML='Inappropriate language')}},window.articleDeleteReply=async function(e,t){if(confirm("Delete this comment?"))try{await db.collection("article_replies").doc(e).delete(),await db.collection("articles").doc(t).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Comment deleted"),b(t)}catch(e){}},window.articleEdit=async function(e){try{var o=await db.collection("articles").doc(e).get();if(!o.exists)return;var n=o.data();if(auth.currentUser.uid!==n.authorId&&!t())return;localStorage.setItem("btc_article_draft",JSON.stringify({title:n.title,subtitle:n.subtitle||"",body:n.body,tags:n.tags||[]})),window._articleEditId=e,articleNew(),setTimeout(function(){var e=document.querySelector('[onclick="articleSubmit()"]');e&&(e.textContent="✏️ Update Article",e.setAttribute("onclick","articleUpdate()"))},100)}catch(e){"function"==typeof showToast&&showToast("Error loading article for edit")}},window.articleUpdate=async function(){var e=window._articleEditId;if(e){var t=document.getElementById("articleStatus"),o=(document.getElementById("articleTitle").value||"").trim(),n=(document.getElementById("articleSubtitle").value||"").trim(),i=(document.getElementById("articleBody").value||"").trim(),a=i.split(/\s+/).filter(function(e){return e.length>0}).length;if(!o||o.length<10)t&&(t.innerHTML='Title must be at least 10 characters');else if(a<500)t&&(t.innerHTML='Min 500 words');else{var r=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&r.push(e.getAttribute("data-tag"))}),t&&(t.innerHTML='Updating...');try{var s=null,l=document.getElementById("articleCover");if(l&&l.files&&l.files[0]){var c=l.files[0];if(c.size>3145728)return void(t&&(t.innerHTML='Cover too large (max 3MB)'));t&&(t.innerHTML='Uploading cover...');try{var d=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),u=await d.put(c);s=await u.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}var p={title:o.substring(0,120),subtitle:n.substring(0,200),body:i.substring(0,5e4),tags:r.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};s&&(p.coverUrl=s),t&&(t.innerHTML='Saving...'),await db.collection("articles").doc(e).update(p),localStorage.removeItem("btc_article_draft"),window._articleEditId=null,"function"==typeof showToast&&showToast("✏️ Article updated!"),articleView(e)}catch(e){t&&(t.innerHTML='Error updating')}}}},window.articleTogglePin=async function(e,t){try{await db.collection("articles").doc(e).update({pinned:t}),"function"==typeof showToast&&showToast(t?"📌 Article pinned!":"📌 Article unpinned"),articleView(e)}catch(e){}},window.articleDelete=async function(e){if(confirm("Delete this article and all its comments? This cannot be undone."))try{var t=await db.collection("article_replies").where("articleId","==",e).get(),o=db.batch();t.forEach(function(e){o.delete(e.ref)}),o.delete(db.collection("articles").doc(e)),await o.commit(),"function"==typeof showToast&&showToast("🗑️ Article deleted"),u="articles",renderForum()}catch(e){"function"==typeof showToast&&showToast("Error deleting article")}},window.loadStackerNewsFeed=function(e,t,o){var n=document.getElementById("snFeed");if(n){var i="https://embed-proxy.needcreations.workers.dev/api/sn?sort="+encodeURIComponent(e)+"&when="+encodeURIComponent(t)+"&limit=21";o&&(i+="&sub="+encodeURIComponent(o)),fetch(i).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.items&&e.data.items.items){var t=e.data.items.items;t.length?n.innerHTML=v(t):n.innerHTML='
    No posts found
    '}else n.innerHTML='
    Could not load Stacker News feed
    '}).catch(function(){n.innerHTML='
    Failed to load feed.
    '})}},window.snDoSearch=function(){var e=document.getElementById("snSearchInput");if(e){var t=e.value.trim();t.length<2||(window._snSearchQuery=t,renderForum())}},window.snClearSearch=function(){window._snSearchQuery="",renderForum()},window.snOpenPost=function(e){var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading post...
    ',fetch("https://embed-proxy.needcreations.workers.dev/api/sn/item?id="+e).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.item){var o=e.data.item;!function(e,t){var o='
    ';if(o+='',o+='
    ',o+='

    '+S(t.title)+"

    ",o+='
    ',o+='⚡ '+B(t.sats)+" sats",o+="·",o+='@'+S(t.user.name)+"",o+="·",o+=""+k(t.createdAt)+"",t.ncomments>0&&(o+="·",o+="💬 "+t.ncomments+" comments"),o+="
    ",t.url){var n="";try{n=new URL(t.url).hostname.replace("www.","")}catch(e){}o+='🔗 '+S(n||t.url)+" ↗"}t.text&&(o+='
    '+x(t.text)+"
    "),o+='",o+="
    ",t.comments&&t.comments.comments&&t.comments.comments.length>0&&(o+='
    ',o+='
    💬 Comments ('+t.ncomments+")
    ",o+=w(t.comments.comments,0),o+="
    "),o+="
    ",e.innerHTML=o,e.scrollTop=0}(t,o)}else t.innerHTML='
    Post not found.
    '}).catch(function(){t.innerHTML='
    Failed to load post. ·
    '}))},window.forumMentionClick=function(e){e&&void 0!==db&&db.collection("users").where("username","==",e).limit(1).get().then(function(t){t.empty?db.collection("users").where("username_lower","==",e.toLowerCase()).limit(1).get().then(function(t){t.empty?"function"==typeof showToast&&showToast("User @"+e+" not found"):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){}):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){})},window.forumNotifyMentions=async function(e,t,o,n){if(e&&void 0!==db&&auth&&auth.currentUser){var i=e.match(/@([a-zA-Z0-9_\-\.]{2,20})/g);if(i){var a={},r=[];i.forEach(function(e){var t=e.substring(1).toLowerCase();a[t]||(a[t]=!0,r.push(e.substring(1)))});for(var s=auth.currentUser.uid,l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone",c=(n||"").substring(0,40),d=0;d=",e).where("username","<=",e+"").limit(5).get().then(function(e){e.forEach(function(e){var t=e.data();t.username&&!a[e.id]&&(a[e.id]=!0,i.push({uid:e.id,username:t.username,points:t.points||0}))})}).catch(function(){}).then(function(){++r>=t.length&&(i.sort(function(e,t){return(t.points||0)-(e.points||0)}),_.activeTextarea&&function(e,t){if(E(),t&&0!==t.length){_.results=t,_.selectedIdx=0;var o=document.createElement("div");o.id="mentionDropdown",o.style.cssText="position:absolute;z-index:9999;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,0.4);overflow:hidden;max-height:220px;overflow-y:auto;min-width:200px;",t.forEach(function(e,t){var n=document.createElement("div");n.className="mention-item",n.setAttribute("data-idx",t);var i="function"==typeof getLevel?getLevel(e.points||0):{emoji:"🟢"};n.innerHTML=''+i.emoji+' '+s(e.username)+""+(e.points?''+(e.points||0).toLocaleString()+" XP":""),n.style.cssText="padding:10px 14px;cursor:pointer;display:flex;align-items:center;gap:8px;font-size:0.85rem;color:var(--text);transition:background 0.15s;"+(0===t?"background:var(--accent-bg);":""),n.onmouseenter=function(){_.selectedIdx=t,C()},n.onmousedown=function(e){e.preventDefault(),A(t)},o.appendChild(n)});var n=e.getBoundingClientRect();window.pageYOffset||document.documentElement.scrollTop,o.style.position="fixed",o.style.left=n.left+"px",o.style.top=n.bottom+4+"px",o.style.width=Math.min(n.width,320)+"px",document.body.appendChild(o),_.dropdown=o}}(_.activeTextarea,i.slice(0,5)))})})}}(t.prefix)},300))}),e.addEventListener("keydown",function(e){_.dropdown&&("ArrowDown"===e.key?(e.preventDefault(),_.selectedIdx=Math.min(_.selectedIdx+1,_.results.length-1),C()):"ArrowUp"===e.key?(e.preventDefault(),_.selectedIdx=Math.max(_.selectedIdx-1,0),C()):"Enter"===e.key||"Tab"===e.key?_.results.length>0&&_.selectedIdx>=0&&(e.preventDefault(),A(_.selectedIdx)):"Escape"===e.key&&E())}),e.addEventListener("blur",function(){setTimeout(E,200)}))}function M(){var e=["forumNewBody","forumReplyInput","articleReplyInput"];if(e.forEach(function(e){var t=document.getElementById(e);t&&z(t)}),"undefined"!=typeof MutationObserver){var t=new MutationObserver(function(){e.forEach(function(e){var t=document.getElementById(e);t&&z(t)})}),o=document.getElementById("forumContainer");if(o)t.observe(o,{childList:!0,subtree:!0});else{var n=new MutationObserver(function(){var o=document.getElementById("forumContainer");o&&(n.disconnect(),t.observe(o,{childList:!0,subtree:!0}),e.forEach(function(e){var t=document.getElementById(e);t&&z(t)}))});n.observe(document.body,{childList:!0,subtree:!0})}}}var P=document.createElement("style");P.textContent=".forum-mention{color:var(--accent);cursor:pointer;font-weight:600;transition:opacity 0.15s;}.forum-mention:hover{opacity:0.8;text-decoration:underline;}",document.head.appendChild(P),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(M,1e3)}):setTimeout(M,1e3)}(),function(){"use strict";var e=[{emoji:"⚡",title:"Bitcoin Payments Only",desc:"All transactions use Bitcoin (Lightning or on-chain). No fiat payments. Buyers and sellers handle payment directly — LightningMart is not an escrow or payment processor."},{emoji:"🚫",title:"No Illegal or Illicit Items",desc:"Strictly prohibited: drugs, weapons, stolen goods, counterfeit items, hacking tools, malware, pirated content, illegal services of any kind. Violation results in immediate ban and may be reported to authorities."},{emoji:"🔞",title:"No Adult or Sexual Content",desc:"No selling or advertising of sexual services, adult content, escort services, or any sexually explicit material. This is an educational Bitcoin marketplace — keep it appropriate for all ages."},{emoji:"🎭",title:"No Fraud or Misrepresentation",desc:"List items honestly. No fake photos, misleading descriptions, bait-and-switch tactics, or counterfeit goods. If it's used, say so. If it has defects, disclose them."},{emoji:"🛡️",title:"Buyer & Seller Safety",desc:"Meet in public places for local trades. Never share your seed phrase, private keys, or send Bitcoin before receiving the item. Use Lightning for instant, irreversible payments."},{emoji:"💰",title:"No Money Laundering or Wash Trading",desc:"No using the marketplace to launder money, create fake transactions, artificially inflate sales, or manipulate pricing. All listings must represent genuine offers."},{emoji:"📋",title:"Accurate Listings",desc:"Titles must clearly describe the item. Include condition, shipping options, and price in sats. One listing per item — no duplicate spam listings."},{emoji:"🤝",title:"Be Professional & Respectful",desc:"Communicate clearly with buyers/sellers. Respond to messages promptly. No harassment, threats, discrimination, or abusive language in any marketplace interaction."},{emoji:"🚫",title:"No Financial Products or Securities",desc:'No selling of financial instruments, investment schemes, MLM/pyramid schemes, "guaranteed returns," or unregistered securities. This is a marketplace for goods and services, not investments.'},{emoji:"⚖️",title:"Disputes & Moderation",desc:"LightningMart does not mediate disputes. All sales are final between buyer and seller. Report fraudulent listings using the 🚩 button. Moderators may remove listings and ban users without notice."}];function t(t){for(var o='

    LightningMart Rules

    Read before buying or selling
    ',n=0;n'+i.emoji+'
    '+i.title+'
    '+i.desc+"
    "}o+='',o+="
    ";var a=document.createElement("div");a.id="marketRulesOverlay",a.innerHTML=o,document.body.appendChild(a)}function o(){if(!auth||!auth.currentUser)return!1;var e=auth.currentUser.email||"";return"needcreations@gmail.com"===e||"info.603btc@gmail.com"===e}window.acceptMarketRules=function(){localStorage.setItem("btc_market_rules_accepted","true");var e=document.getElementById("marketRulesOverlay");e&&e.remove()},window.showMarketRulesBtn=function(){t()};var n=[{id:"educational",name:"Educational Products",emoji:"🎓",desc:"Learn Bitcoin with the best tools"},{id:"general",name:"Other Products",emoji:"🛒",desc:"Buy & sell everything else"},{id:"merchants",name:"More Bitcoin Merchants",emoji:"🏪",desc:"Browse more Bitcoin merchants"},{id:"noderunners",name:"Even More Merchants",emoji:"🌐",desc:"Bitcoin shops via Node Runners"}],i=[{id:"books",name:"Books",emoji:"📚",section:"educational"},{id:"courses",name:"Courses & Workshops",emoji:"🎓",section:"educational"},{id:"hardware_edu",name:"Hardware Wallets",emoji:"🔐",section:"educational"},{id:"nodes",name:"Node Kits & Guides",emoji:"💻",section:"educational"},{id:"kids",name:"Kids & Family",emoji:"👨‍👩‍👧‍👦",section:"educational"},{id:"tools",name:"Learning Tools",emoji:"🧰",section:"educational"},{id:"edu_other",name:"Other Educational",emoji:"📦",section:"educational"},{id:"mining",name:"Mining Equipment",emoji:"⛏️",section:"general"},{id:"merch",name:"Apparel & Merch",emoji:"👕",section:"general"},{id:"art",name:"Art & Collectibles",emoji:"🎨",section:"general"},{id:"stickers",name:"Stickers & Prints",emoji:"🖼️",section:"general"},{id:"services",name:"Services",emoji:"🛠️",section:"general"},{id:"electronics",name:"Electronics & Tech",emoji:"📱",section:"general"},{id:"other",name:"Other",emoji:"📦",section:"general"}],a=[{id:"new",label:"New",color:"#22c55e"},{id:"like_new",label:"Like New",color:"#84cc16"},{id:"good",label:"Good",color:"#eab308"},{id:"fair",label:"Fair",color:"#f97316"},{id:"for_parts",label:"For Parts",color:"#ef4444"}],r=[{id:"newest",label:"Newest First"},{id:"price_low",label:"Price: Low → High"},{id:"price_high",label:"Price: High → Low"},{id:"popular",label:"Most Saved"}];function s(e,t){"listing"===e?history.pushState({channel:"marketplace",mktView:"listing",listingId:t},"","#marketplace/listing/"+t):"my"===e&&history.pushState({channel:"marketplace",mktView:"my"},"","#marketplace/my")}window.handleMarketplacePopState=function(e,t){if(e&&"listing"===e.mktView&&e.listingId)return renderMarketplace({listingId:e.listingId,_noHistory:!0}),!0;if(e&&"my"===e.mktView)return showMyListings(!0),!0;if(t&&0===t.indexOf("marketplace/listing/")){var o=t.replace("marketplace/listing/","");return renderMarketplace({listingId:o,_noHistory:!0}),!0}return"marketplace/my"===t?(showMyListings(!0),!0):(renderMarketplace({_noHistory:!0}),!0)};var l=!1,c=!1;function d(e,t){var o=document.getElementById(e),n=document.getElementById(t);if(o&&n){var i=n.getBoundingClientRect();o.style.cssText="position:fixed;left:"+i.left+"px;top:"+i.top+"px;width:"+i.width+"px;height:"+i.height+"px;z-index:100;border-radius:12px;overflow:hidden;border:1px solid var(--border);background:var(--card-bg);pointer-events:auto;",o._reposition=function(){var e=n.getBoundingClientRect();o.style.left=e.left+"px",o.style.top=e.top+"px",o.style.width=e.width+"px",o.style.height=e.height+"px"},window.addEventListener("scroll",o._reposition,!0),window.addEventListener("resize",o._reposition)}}function u(e){var t=document.getElementById(e);t&&(t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t._reposition&&(window.removeEventListener("scroll",t._reposition,!0),window.removeEventListener("resize",t._reposition),t._reposition=null))}function p(e){var t=document.getElementById("forumContainer");if(t){t.style.display="block",t.innerHTML="";var l=e.category||"all",c=e.search||"",p=e.sort||"newest",m=e.listingId||null;if(m)return e._noHistory||s("listing",m),void function(e,t){e.innerHTML='
    Loading...
    ',db.collection("marketplace").doc(t).get().then(function(n){if(n.exists){var r={id:n.id,...n.data()},s=a.find(function(e){return e.id===r.condition}),l=s?s.label:"",c=s?s.color:"var(--text-faint)",d=i.find(function(e){return e.id===r.category}),u=d?d.emoji+" "+d.name:"📦 Other",p=-1!==safeJSON("btc_market_saved",[]).indexOf(r.id),m=void 0!==auth&&auth.currentUser&&auth.currentUser.uid===r.sellerUid,g=o(),f=r.priceSats>=1e6?(r.priceSats/1e6).toFixed(2)+"M sats":r.priceSats>=1e3?Math.floor(r.priceSats/1e3)+"K sats":r.priceSats.toLocaleString()+" sats",y="";try{var b=parseFloat(localStorage.getItem("btc_last_price")||"0");b>0&&(y=' (~$'+(r.priceSats/1e8*b).toFixed(2)+")")}catch(e){}var v=h(r.createdAt?r.createdAt.toDate():new Date),w='
    ';w+='',r.imageUrl?w+="
    ]/g,""):"")+"') center/contain no-repeat;background-color:var(--bg-side);border-radius:14px;border:1px solid var(--border);margin-bottom:16px;\">
    ":w+='
    '+(d?d.emoji:"📦")+"
    ",w+='
    '+escapeHtml(r.title)+'
    ⚡ '+f+y+"
    ",w+='
    '+l+''+u+'🕐 '+v+""+(r.shipping?'📦 Ships':"")+(r.localPickup?'📍 Local pickup':"")+"
    ",w+='
    Description
    '+escapeHtml(r.description||"No description provided.")+"
    ",w+='
    Seller
    '+(r.sellerName?r.sellerName.charAt(0).toUpperCase():"?")+'
    '+escapeHtml(r.sellerName||"Anonymous")+"
    "+(r.sellerRank?'
    '+escapeHtml(r.sellerRank)+"
    ":"")+'
    👤
    ',m?w+='
    ':(w+='
    '+(g?"':"")+"
    ",w+='
    🛡️ Safety Tips: Use escrow when possible. Never send payment before receiving the item. Meet in public if trading locally. Report suspicious listings.
    ',r.lightningAddress&&(w+='
    ⚡ This seller accepts Lightning payments
    ')),w+="
    ",e.innerHTML=w,db.collection("marketplace").doc(t).update({views:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})}else e.innerHTML='
    😕
    Listing not found
    '}).catch(function(){e.innerHTML='
    Error loading listing.
    '})}(t,m);var g='
    ';g+='
    Home
    ',g+='
    Lightning Mart
    Buy & sell with Bitcoin ⚡
    ',g+='
    ';var f=e.section||"merchants";if("all"!==l&&"all"===f){var y=i.find(function(e){return e.id===l});y&&(f=y.section)}g+='
    ';for(var b=[{id:"all",name:"All",emoji:"🛒"}].concat(n),v=0;v'+w.emoji+" "+w.name+""}if(g+="
    ",u("gmIframeWrap"),u("nrIframeWrap"),"merchants"===f)return g+='
    ',g+="
    ",t.innerHTML=g,void d("gmIframeWrap","gmIframePlaceholder");if("noderunners"===f)return g+='
    ',g+="",t.innerHTML=g,void d("nrIframeWrap","nrIframePlaceholder");var k="all"===f?i:i.filter(function(e){return e.section===f});g+='
    ',g+="';for(var B=0;B'+S.emoji+" "+S.name+""}g+="
    ","educational"!==f&&"all"!==f||(g+='
    🛒
    603BTC Pleb Shop
    Bitcoin educational products, merch & gear
    '),g+='
    Loading...
    ",g+='
    ',g+="",t.innerHTML=g,function(e,t,o,n){var r=document.getElementById("marketListings"),s=document.getElementById("marketResultCount");if(r&&void 0!==db){for(var l='
    ',c=0;c<6;c++)l+='
    ';l+="
    ",r.innerHTML=l;var d=db.collection("marketplace").where("status","==","active");e&&"all"!==e&&(d=d.where("category","==",e)),(d="price_low"===o?d.orderBy("priceSats","asc"):"price_high"===o?d.orderBy("priceSats","desc"):"popular"===o?d.orderBy("saves","desc"):d.orderBy("createdAt","desc")).limit(50).get().then(function(e){var o=[];if(e.forEach(function(e){o.push({id:e.id,...e.data()})}),n&&"all"!==n){var l=i.filter(function(e){return e.section===n}).map(function(e){return e.id});o=o.filter(function(e){return-1!==l.indexOf(e.category)})}if(t){var c=t.toLowerCase();o=o.filter(function(e){return(e.title||"").toLowerCase().includes(c)||(e.description||"").toLowerCase().includes(c)})}if(s&&(s.textContent=o.length+" listing"+(1!==o.length?"s":"")),0!==o.length){var d=safeJSON("btc_market_saved",[]);r.innerHTML=o.map(function(e){var t,o=-1!==d.indexOf(e.id),n=a.find(function(t){return t.id===e.condition}),r=n?n.color:"var(--text-faint)",s=n?n.label:"",l=i.find(function(t){return t.id===e.category}),c=l?l.emoji:"📦";return t=e.priceSats>=1e6?(e.priceSats/1e6).toFixed(2)+"M sats":e.priceSats>=1e3?Math.floor(e.priceSats/1e3)+"K sats":e.priceSats.toLocaleString()+" sats","
    '+(e.imageUrl?"
    ]/g,""):"")+"') center/cover;border-bottom:1px solid var(--border);\">
    ":'
    '+c+"
    ")+'
    '+escapeHtml(e.title)+'
    ⚡ '+t+"
    "+(satsToUSD(e.priceSats)?'
    '+satsToUSD(e.priceSats)+"
    ":'
    ')+'
    '+s+"'+(o?"❤️":"🤍")+"
    "}).join("")}else r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){console.error("Marketplace load error:",e),r&&("failed-precondition"===e.code?(console.log("Trying fallback marketplace query..."),db.collection("marketplace").orderBy("createdAt","desc").limit(50).get().then(function(e){var t=[];e.forEach(function(e){var o=e.data();o.id=e.id,"active"===o.status&&t.push(o)}),t.length>0?(r.innerHTML=t.map(function(e){return"
    '+escapeHtml(e.title||"Untitled")+'
    ⚡ '+(e.priceSats||0).toLocaleString()+" sats
    "}).join(""),s&&(s.textContent=t.length+" listing"+(1!==t.length?"s":""))):r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){r.innerHTML='
    ⚙️ Marketplace needs a database index.
    This is a one-time setup.

    Click here to create the index manually if requested →
    '})):r.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+". Try refreshing.
    ")})}}(l,c,p,f)}}window._hideMarketIframes=function(){u("gmIframeWrap"),u("nrIframeWrap")},window.renderMarketplace=function(e){if(e=e||{},document.getElementById("forumContainer")){if(l||(l=!0,"true"!==localStorage.getItem("btc_market_rules_accepted")&&t()),function(){if(!c){if(c=!0,!document.getElementById("gmIframeWrap")){var e=document.createElement("div");e.id="gmIframeWrap",e.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",e.innerHTML='',document.body.appendChild(e)}if(!document.getElementById("nrIframeWrap")){var t=document.createElement("div");t.id="nrIframeWrap",t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t.innerHTML='',document.body.appendChild(t)}}}(),"function"==typeof showSkeletonLoader&&!e.listingId&&!e.search)return showSkeletonLoader("forumContainer"),void setTimeout(()=>p(e),300);p(e)}},window.showCreateListing=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to create a listing!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e='
    📝 Create Listing
    — or paste an image URL —
    ',t=document.createElement("div");t.innerHTML=e,document.body.appendChild(t.firstChild)};var m=0;function h(e){var t=Math.floor((new Date-e)/1e3);if(t<60)return"just now";var o=Math.floor(t/60);if(o<60)return o+"m ago";var n=Math.floor(o/60);if(n<24)return n+"h ago";var i=Math.floor(n/24);return i<30?i+"d ago":Math.floor(i/30)+"mo ago"}window.submitListing=function(){if(!window._mktSubmitting){var e=Date.now();if(e-m<6e4)"function"==typeof showToast&&showToast("⏳ Wait 60 seconds between listings");else{m=e;var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim();"function"==typeof sanitizeInput&&(t=sanitizeInput(t),a=sanitizeInput(a));var r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),l=document.getElementById("mktShipping").checked,c=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1||o>1e11)showToast("Price must be between 1 and 100B sats");else{var d=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anonymous",u="";if(void 0!==currentUser&¤tUser&&"function"==typeof getLevel){var p=getLevel(currentUser.points||0);u=p.emoji+" "+p.name}var h={title:t,description:a,priceSats:o,category:n,condition:i,imageUrl:r||null,lightningAddress:s||null,shipping:l,localPickup:c,sellerUid:auth.currentUser.uid,sellerName:d,sellerRank:u,status:"active",views:0,saves:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()};db.collection("marketplace").add(h).then(function(){window._mktUploadedImage=null;var e=document.getElementById("createListingOverlay");e&&e.remove(),"function"==typeof showToast&&showToast("🛒 Listing posted!"),"function"==typeof awardPoints&&awardPoints(15,"🛒 Marketplace listing!"),auth&&auth.currentUser&&(db.collection("users").doc(auth.currentUser.uid).update({marketListings:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketListings=(currentUser.marketListings||0)+1)),renderMarketplace()}).catch(function(e){console.error("Marketplace post error:",e),showToast("Error posting: "+(e.code||e.message||"Unknown error"))})}}}},window.toggleMarketSave=function(e){var t=safeJSON("btc_market_saved",[]),o=t.indexOf(e);-1!==o?(t.splice(o,1),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(-1)}).catch(function(e){console.error("[marketplace] Error:",e)})):(t.push(e),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})),localStorage.setItem("btc_market_saved",JSON.stringify(t)),void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({marketSaved:t}).catch(function(e){console.error("[marketplace] Error:",e)});var n=document.getElementById("forumContainer");n&&n.innerHTML.includes("marketListings")&&renderMarketplace()},window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return showToast("🔒 Sign in to contact sellers"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var o='
    💬 Message '+escapeHtml(t)+'
    ',n=document.createElement("div");n.innerHTML=o,document.body.appendChild(n.firstChild)},window.sendMarketMessage=function(e){var t=(document.getElementById("mktMessage").value||"").trim();if(t){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Buyer";db.collection("marketplace").doc(e).get().then(function(n){if(n.exists){var i=n.data().sellerUid||"";return db.collection("marketplace_messages").add({listingId:e,buyerUid:auth.currentUser.uid,sellerUid:i,buyerName:o,message:t,createdAt:firebase.firestore.FieldValue.serverTimestamp(),read:!1})}showToast("Listing not found")}).then(function(){var t=document.getElementById("contactSellerOverlay");t&&t.remove(),showToast("💬 Message sent to seller!"),"function"==typeof sendNotification&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists&&t.data().sellerUid){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(t.data().sellerUid,"dm","🛒 "+o+" is interested in your listing!","marketplace",e)}}).catch(function(){}),db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1)}).catch(function(){showToast("Error sending message. Try again.")})}else showToast("Please write a message")},window.showMyListings=function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){e||s("my");var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading your listings...
    ',db.collection("marketplace").where("sellerUid","==",auth.currentUser.uid).orderBy("createdAt","desc").get().then(function(e){var o,n='
    ';n+='',n+='
    📋 My Listings
    ',e.empty?n+='
    No listings yet. Create one!
    ':e.forEach(function(e){var t=e.data(),o="active"===t.status?"#22c55e":"sold"===t.status?"#ef4444":"var(--text-faint)";n+='
    '+escapeHtml(t.title)+'
    ⚡ '+(t.priceSats||0).toLocaleString()+' sats
    👁️ '+(t.views||0)+" views · ❤️ "+(t.saves||0)+' saves
    '+(t.status||"active")+""+("active"===t.status?"':"")+"
    "}),n+='
    💬 Messages
    ',n+='
    Loading messages...
    ',n+="
    ",t.innerHTML=n,(o=document.getElementById("myMarketMessages"))&&db.collection("marketplace_messages").orderBy("createdAt","desc").limit(20).get().then(function(e){var t=auth.currentUser.uid,n=[];e.forEach(function(e){var o=e.data();o.buyerUid===t&&n.push({id:e.id,...o,role:"buyer"})}),db.collection("marketplace").where("sellerUid","==",t).get().then(function(i){var a=[];i.forEach(function(e){a.push(e.id)}),e.forEach(function(e){var o=e.data();-1!==a.indexOf(o.listingId)&&o.buyerUid!==t&&n.push({id:e.id,...o,role:"seller"})}),0!==n.length?o.innerHTML=n.map(function(e){var t=e.createdAt?h(e.createdAt.toDate()):"";return'
    '+("seller"===e.role?"📩 From ":"📤 To seller · ")+escapeHtml(e.buyerName||"Buyer")+''+t+'
    '+escapeHtml(e.message)+"
    "}).join(""):o.innerHTML='
    No messages yet.
    '})})}).catch(function(e){console.error("My listings error:",e),"failed-precondition"===e.code?t.innerHTML='
    ⚙️ Setting up marketplace database (index)...
    Please refresh in 1 minute.
    ':t.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+"
    "}))}else showToast("🔒 Sign in to see your listings")},window.markSold=function(e){db.collection("marketplace").doc(e).update({status:"sold"}).then(function(){showToast("✅ Marked as sold!"),showMyListings()})},window.editListing=function(e){auth&&auth.currentUser&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists){var n=t.data();n.sellerUid===auth.currentUser.uid||o()?(showCreateListing(),setTimeout(function(){var t=document.getElementById("mktTitle"),o=document.getElementById("mktPrice"),i=document.getElementById("mktCategory"),a=document.getElementById("mktCondition"),r=document.getElementById("mktDesc"),s=document.getElementById("mktImage"),l=document.getElementById("mktLightning"),c=document.getElementById("mktShipping"),d=document.getElementById("mktLocal");t&&(t.value=n.title||""),o&&(o.value=n.priceSats||"",updateMktPriceUSD()),i&&(i.value=n.category||""),a&&(a.value=n.condition||""),r&&(r.value=n.description||""),s&&n.imageUrl&&!n.imageUrl.startsWith("data:")&&(s.value=n.imageUrl||""),l&&(l.value=n.lightningAddress||""),c&&(c.checked=!!n.shipping),d&&(d.checked=!!n.local);var u=document.getElementById("createListingOverlay");if(u){var p=u.querySelector('div[style*="font-size:1.2rem"]');p&&(p.textContent="✏️ Edit Listing")}var m=u?u.querySelector('button[onclick*="submitListing"]'):null;m&&(m.textContent="✏️ Update Listing",m.onclick=function(){updateExistingListing(e)})},100)):showToast("You can only edit your own listings")}else showToast("Listing not found")}).catch(function(e){showToast("Error loading listing: "+(e.message||"Unknown"))})},window.updateExistingListing=function(e){var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim(),r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),l=document.getElementById("mktShipping").checked,c=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1)showToast("Please enter a price in sats");else{var d={title:t.substring(0,80),priceSats:o,category:n,condition:i,description:a.substring(0,1e3),lightningAddress:s,shipping:l,local:c,updatedAt:firebase.firestore.FieldValue.serverTimestamp()};r&&(d.imageUrl=r),db.collection("marketplace").doc(e).update(d).then(function(){var t=document.getElementById("createListingOverlay");t&&t.remove(),showToast("✅ Listing updated!"),window._mktUploadedImage=null,renderMarketplace({listingId:e})}).catch(function(e){showToast("Error updating: "+(e.message||"Unknown"))})}},window.deleteListing=function(e){if(auth&&auth.currentUser){var t=o();confirm(t?"Admin: Delete this listing?":"Delete this listing?")&&db.collection("marketplace").doc(e).update({status:"deleted",deletedBy:t?"admin":"owner",deletedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){showToast("🗑️ Listing deleted"),renderMarketplace()})}},window.updateMktPriceUSD=function(){var e=parseInt(document.getElementById("mktPrice").value)||0,t=document.getElementById("mktPriceUSD");if(t)if(e<=0)t.textContent="";else{var o=parseFloat(localStorage.getItem("btc_last_price")||"0");if(o<=0)return fetch("https://mempool.space/api/v1/prices").then(function(e){return e.json()}).then(function(e){e&&e.USD&&(localStorage.setItem("btc_last_price",e.USD),updateMktPriceUSD())}).catch(function(e){console.error("[marketplace] Error:",e)}),void(t.textContent="Loading USD price...");var n=e/1e8*o;t.textContent="≈ $"+n.toFixed(2)+" USD"}},window.satsToUSD=function(e){var t=parseFloat(localStorage.getItem("btc_last_price")||"0");return t<=0||!e?"":"~$"+(e/1e8*t).toFixed(2)},window.handleMktImageUpload=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var o=new FileReader;o.onload=function(e){var t=new Image;t.onload=function(){var e=t.width,o=t.height;e>800&&(o=Math.round(800*o/e),e=800);var n=document.createElement("canvas");n.width=e,n.height=o,n.getContext("2d").drawImage(t,0,0,e,o);var i=n.toDataURL("image/jpeg",.8),a=document.getElementById("mktImagePreview"),r=document.getElementById("mktImagePreviewImg");a&&r&&(r.src=i,a.style.display="block"),window._mktUploadedImage=i;var s=document.getElementById("mktImage");s&&(s.value="")},t.src=e.target.result},o.readAsDataURL(t)}},window._plebShopOpen=!1,window._togglePlebShop=function(){var e=document.getElementById("plebShopEmbed"),t=document.getElementById("plebShopToggle");e&&(window._plebShopOpen=!window._plebShopOpen,window._plebShopOpen?(e.style.display="block",e.style.height="calc(100vh - 280px)",e.style.minHeight="500px",e.querySelector("iframe")||(e.innerHTML=''),t&&(t.textContent="Close Shop",t.style.background="var(--border)")):(e.style.height="0",e.style.minHeight="0",setTimeout(function(){e.style.display="none"},300),t&&(t.textContent="Open Shop",t.style.background="var(--accent)")))},window.clearMktImage=function(){window._mktUploadedImage=null;var e=document.getElementById("mktImagePreview");e&&(e.style.display="none");var t=document.getElementById("mktImageFile");t&&(t.value="")}}();var MSG_CONFIG={onlineThreshold:3e5,awayThreshold:9e5,presenceInterval:6e4,maxMsgLength:500,maxMsgsPerHour:30,maxConvoHistory:100,unreadPollInterval:3e4,maxNewConvosPerDay:5,newAccountCooldownMs:864e5,minPointsToDM:50,duplicateWindowMs:5e3},SUSPICIOUS_PATTERNS=[/send\s*(?:me|ur|your)\s*(?:btc|bitcoin|sats|seed|key|phrase)/i,/(?:double|triple|multiply)\s*(?:your|ur)\s*(?:btc|bitcoin|sats|crypto)/i,/(?:free|win|won|claim|airdrop)\s*(?:btc|bitcoin|sats|crypto|nft)/i,/(?:invest|deposit)\s*(?:now|today|here)\b/i,/(?:guaranteed|100%)\s*(?:return|profit|roi)/i,/send\s*\d+\s*(?:btc|sats)\s*(?:to|and)\s*(?:get|receive|earn)/i,/(?:seed|private)\s*(?:phrase|key)\s*(?:here|now|please|share)/i,/(?:validate|verify|sync)\s*(?:your|ur)\s*(?:wallet|account)/i,/(?:connect|link)\s*(?:your|ur)\s*(?:wallet|metamask|phantom)/i,/(?:nigerian|prince|inheritance|lottery)\s*(?:fund|money|payment)/i],SUSPICIOUS_URLS=[/bit\.ly|tinyurl|t\.co|goo\.gl|is\.gd|buff\.ly|ow\.ly|rebrand\.ly/i,/(?:discord\.gift|discordapp\.gift|nitro.*free)/i,/(?:steamcommunity|steampowered).*(?:gift|trade|login)/i,/(?:wallet|connect|validate|sync|claim|airdrop).*(?:\.com|\.io|\.xyz|\.site|\.app)/i,/(?:dapp|defi|swap|bridge|mint).*(?:\.com|\.io|\.xyz|\.site)/i],BLOCKED_CONTENT=[/(?:child|minor|underage).*(?:porn|nude|nsfw)/i,/(?:kill|murder|attack|bomb|shoot).*(?:yourself|someone|them|people|school)/i,/\b(?:doxx|doxing|swat)\b/i,/\b(?:nigger|nigga|faggot|kike|spic|wetback|chink|gook|towelhead|raghead|beaner|coon|darkie|zipperhead)\b/i,/\b(?:white\s*power|white\s*supremacy|sieg\s*heil|race\s*war|ethnic\s*cleansing|final\s*solution)\b/i,/\b(?:gas\s*the|death\s*to)\s+\w+/i,/\b(?:heil\s*hitler|genocide)\b/i,/\b(?:i\s*(?:will|wanna|gonna|want\s*to)\s*(?:kill|hurt|stab|shoot|beat|attack|find)\s*(?:you|u|him|her|them))\b/i,/\b(?:i\s*know\s*where\s*(?:you|u)\s*live)\b/i,/\b(?:watch\s*your\s*back|you(?:'re|\s*are)\s*dead)\b/i,/\b(?:track\s*(?:you|u)\s*down|come\s*find\s*(?:you|u))\b/i,/\b(?:kill\s*myself|cut(?:ting)?\s*myself|slit\s*my\s*wrist|hang\s*myself|end\s*my\s*life)\b/i,/\b(?:want(?:a)?\s*(?:to\s*)?die|kys|kill\s*yourself)\b/i,/\b(?:self[\s-]*harm|overdose\s*on|jump\s*off\s*a)\b/i,/\b(?:blowjob|handjob|gangbang|threesome|deepthroat|rimjob|creampie)\b/i,/\b(?:send\s*(?:me\s*)?nudes|dick\s*pic|show\s*(?:me\s*)?(?:your|ur)\s*(?:body|tits|boobs|ass|pussy|dick))\b/i,/\b(?:wanna|want\s*to|lets)\s*(?:fuck|bang|screw|bone|smash)\b/i,/\b(?:suck\s*my|sit\s*on\s*my|bend\s*over|get\s*on\s*your\s*knees)\b/i,/\b(?:masturbat|fingering|bondage|bdsm|fetish|dominatrix)\b/i,/\b(?:escort|prostitut|hooker|camgirl|sexting)\b/i],PII_PATTERNS=[/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:phone|number|address|email|ssn|social|zip|location|real name|full name|home|where.*live)/i,/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:id|passport|driver.?s?\s*license|bank|routing|account\s*number|credit\s*card|debit\s*card)/i,/(?:dm|message|text|call|contact)\s*(?:me\s+)?(?:on|at|@)\s*(?:whatsapp|telegram|signal|insta|instagram|snap|snapchat|facebook|messenger|wechat|line)\b/i,/(?:my|here(?:'s| is))\s*(?:phone|number|cell|whatsapp|telegram|signal)\s*(?:is|:|\s)\s*[\+\d\(\)\-\s]{7,}/i,/(?:my|here(?:'s| is))\s*(?:email|e-mail)\s*(?:is|:|\s)\s*\S+@\S+\.\S+/i,/(?:my|here(?:'s| is))\s*(?:address|location)\s*(?:is|:)/i];function containsSuspiciousLink(e){for(var t=e.match(/https?:\/\/[^\s<>"{}|\\^`\[\]]+/gi)||[],o=0;o]*>/g,"")).trim()).length>MSG_CONFIG.maxMsgLength&&(e=e.substring(0,MSG_CONFIG.maxMsgLength)),e):""}function containsPII(e){for(var t=0;t"']+)/gi,function(e){return''+e+""})}function _getDailyConvoLog(){try{var e=localStorage.getItem("btc_dm_daily_log");if(!e)return{date:"",recipients:[]};var t=JSON.parse(e),o=(new Date).toISOString().slice(0,10);return t.date!==o?{date:o,recipients:[]}:t}catch(e){return{date:(new Date).toISOString().slice(0,10),recipients:[]}}}function _logNewConvo(e){var t=_getDailyConvoLog();t.date=(new Date).toISOString().slice(0,10),-1===t.recipients.indexOf(e)&&t.recipients.push(e),localStorage.setItem("btc_dm_daily_log",JSON.stringify(t))}function _canStartNewConvo(e){var t=_getDailyConvoLog();return-1!==t.recipients.indexOf(e)||t.recipients.length
    🚨
    "Friends in Distress" Scam
    Scammers will impersonate people you know and trust — your friends, family, even coworkers. They can:
    • Clone their profile picture, name, and bio
    • Copy their writing style and messages
    • Use AI-generated voice clones that sound exactly like them
    • Create fake emergencies — "I\'m stuck," "I need help," "send me Bitcoin and I\'ll pay you back"
    The scammer will pressure you to act fast so you don\'t have time to think or verify. They prey on your emotions and trust.
    🛡️ How to protect yourself:
    NEVER send Bitcoin to anyone claiming to be in distress over a message
    Verify their identity through a separate channel — call them, video chat, or meet in person
    Real friends will understand if you take time to verify
    Bitcoin transactions are irreversible — once sent, it\'s gone forever
    • If it feels urgent and emotional, that\'s exactly what the scammer wants
    ',document.body.appendChild(e.firstChild)};var _lastSentMsg={text:"",time:0};function _isDuplicateMessage(e){var t=Date.now();return e===_lastSentMsg.text&&t-_lastSentMsg.time
    Why are you reporting this user?
    ',i=document.createElement("div");return i.innerHTML=n,void document.body.appendChild(i.firstChild)}},window.submitReport=function(e,t,o){var n=document.getElementById("reportModal");if(n&&n.remove(),db&&auth&&auth.currentUser){var i=void 0!==currentUser&¤tUser?currentUser.username:"Anonymous";db.collection("reports").add({reportedUid:e,reportedName:t,reporterUid:auth.currentUser.uid,reporterName:i,reason:o,createdAt:firebase.firestore.FieldValue.serverTimestamp(),status:"pending"}).then(function(){"function"==typeof showToast&&showToast("🚩 Report submitted. Thank you for keeping the community safe."),blockUser(e,t)}).catch(function(){"function"==typeof showToast&&showToast("Failed to submit report")})}};var _presenceTimer=null;function updatePresence(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e="false"!==localStorage.getItem("btc_online_status");try{e?db.collection("users").doc(auth.currentUser.uid).update({lastSeen:firebase.firestore.FieldValue.serverTimestamp(),isOnline:!0}).catch(function(){}):db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:null}).catch(function(){})}catch(e){}}}function startPresenceTracking(){updatePresence(),_presenceTimer&&clearInterval(_presenceTimer),_presenceTimer=setInterval(updatePresence,MSG_CONFIG.presenceInterval),window.addEventListener("beforeunload",function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db)try{db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){}}),document.addEventListener("visibilitychange",function(){"visible"===document.visibilityState&&updatePresence()})}function profileStat(e,t,o){return'
    '+e+'
    '+t+'
    '+o+"
    "}window.toggleOnlineStatus=function(){updatePresence()},window.getOnlineStatus=function(e){if(!e)return{status:"offline",color:"#6b7280",label:"Offline",dot:"⚫"};var t=e.toDate?e.toDate().getTime():"number"==typeof e?e:new Date(e).getTime(),o=Date.now()-t;return o'},window.showUserProfile=function(e){if(e&&db){var t=document.createElement("div");t.innerHTML='
    Loading profile...
    ',document.body.appendChild(t.firstChild),db.collection("users").doc(e).get().then(function(t){if(!t.exists)return(m=document.getElementById("userProfileModal"))&&m.remove(),void("function"==typeof showToast&&showToast("User not found"));var o=t.data(),n=getOnlineStatus(o.lastSeen),i="function"==typeof getLevel?getLevel(o.points||0):{name:"Newbie",emoji:"🌱"},a=o.createdAt&&o.createdAt.toDate?o.createdAt.toDate().toLocaleDateString():"Unknown",r="function"==typeof escapeHtml?escapeHtml(o.displayBadge||o.equippedBadge||""):(o.displayBadge||o.equippedBadge||"").replace(//g,">").replace(/"/g,"""),s=0;o.visibleBadges&&(s+=o.visibleBadges.length),o.hiddenBadges&&(s+=o.hiddenBadges.length);var l="";if(r){var c=r;if(void 0!==HIDDEN_BADGES&&r.length>5){var d=HIDDEN_BADGES.find(e=>e.id===r);d&&(c=d.emoji)}l='
    '+c+' '+i.emoji+"
    "}else l='
    '+i.emoji+"
    ";var u,p,m,h=auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&auth.currentUser.uid!==e,g=h?_canAccountDM():{ok:!1},f='
    '+l+'
    '+escapeHtml(o.username||"Bitcoiner")+'
    '+i.name+" · "+(o.points||0).toLocaleString()+' XP
    '+n.label+"
    "+(o.bio?'
    About
    '+escapeHtml(o.bio)+"
    ":"")+(o.twitter||o.nostr||o.website?'
    '+(o.twitter?'𝕏 '+escapeHtml(o.twitter)+"":"")+(o.nostr?'🟣 Nostr':"")+(o.website&&!/^(javascript|data|vbscript|blob):/i.test(o.website.trim())?'🌐 Website':"")+"
    ":"")+'
    '+profileStat("🏅",s,"Badges")+profileStat("📖",Array.isArray(o.visitedChannelsList)?o.visitedChannelsList.length:Array.isArray(o.readChannels)?o.readChannels.length:0,"Channels")+profileStat("🎟️",o.orangeTickets||0,"Tickets")+'
    '+profileStat("🗣️",o.forumPosts||0,"Posts")+profileStat("🔥",(o.streak||0)+"("+(o.bestStreak||o.streak||0)+")","Streak")+profileStat("📅",a,"Joined")+"
    "+(o.pvpWins||o.pvpLosses?'
    '+profileStat("⚔️",(o.pvpWins||0)+"W","PVP Wins")+profileStat("💀",(o.pvpLosses||0)+"L","PVP Losses")+profileStat("📊",((o.pvpWins||0)+(o.pvpLosses||0)>0?Math.round((o.pvpWins||0)/((o.pvpWins||0)+(o.pvpLosses||0))*100):0)+"%","Win Rate")+"
    ":"")+(o.predictions&&o.predictions.total?(p=(u=o.predictions).total>0?Math.round(u.correct/u.total*100):0,'
    '+profileStat("📈",u.total,"Predictions")+profileStat("🎯",p+"%","Accuracy")+profileStat("🔥",u.bestStreak||u.streak||0,"Best Streak")+"
    "):"")+(o.lightningAddress||o.lightning?(window._profileTipData={recipientName:o.username||"Bitcoiner",recipientUid:e,lightningAddress:o.lightningAddress||o.lightning||"",label:"Tip "+(o.username||"Bitcoiner"),context:"profile"},'
    '+escapeHtml(o.lightningAddress||o.lightning)+'
    "):"")+(h&&g.ok?"":h&&!g.ok?'
    '+escapeHtml(g.reason)+"
    ":auth&&auth.currentUser&&!auth.currentUser.isAnonymous?"":"")+(h?'
    '+(isUserBlocked(e)?"":"")+"
    ':"")+"
    ";(m=document.getElementById("userProfileModal"))&&m.remove();var y=document.createElement("div");y.innerHTML=f,document.body.appendChild(y.firstChild)}).catch(function(t){console.error("Profile load error:",t);var o=document.getElementById("userProfileModal");o&&o.remove(),"function"==typeof showToast&&showToast("Could not load profile ["+e+"]: "+(t.message||"permission error"))})}},window._tipFromProfile=function(){var e=window._profileTipData;if(e){var t=document.getElementById("userProfileModal");t&&t.remove(),"function"==typeof showTipOverlay?showTipOverlay(e):"function"==typeof showToast&&showToast("⚡ Lightning tips still loading, try again in a moment")}};var _msgSentTimestamps=[];function checkRateLimit(){var e=Date.now();return(_msgSentTimestamps=_msgSentTimestamps.filter(function(t){return e-t<36e5})).length
    💬 '+escapeHtml(o)+'
    ⚠️ Never share your seed phrase, private keys, or send Bitcoin to strangers or "friends in distress."
    ',s=document.createElement("div");s.innerHTML=r,document.body.appendChild(s.firstChild),setTimeout(function(){var e=document.getElementById("dmInput");e&&e.focus()},300),loadDMMessages(e,n,t,o),db.collection("dm_conversations").doc(e).get().then(function(e){if(e.exists&&e.data().isBuddyMatch){var t=document.getElementById("dmWindow");if(!t)return;var o=t.querySelector('div[style*="rgba(234,179,8,0.1)"]');o&&(o.style.background="rgba(34,197,94,0.08)",o.style.borderColor="rgba(34,197,94,0.2)",o.style.color="#22c55e",o.innerHTML="🦌 Nacho is in this chat! Ask any Bitcoin question and Nacho will jump in. Teachers can add context to help learners.")}}).catch(function(){}),db.collection("users").doc(t).get().then(function(e){if(e.exists){var t=getOnlineStatus(e.data().lastSeen),o=document.getElementById("dmStatusDot");o&&(o.innerHTML='')}}).catch(function(){})}function loadDMMessages(e,t,o,n){var i=document.getElementById("dmMessages");i&&(i.innerHTML='
    Loading messages...
    ',window._dmUnsubscribe=db.collection("dm_conversations").doc(e).collection("messages").orderBy("createdAt","asc").limit(MSG_CONFIG.maxConvoHistory).onSnapshot(function(o){if(i.innerHTML="",o.empty)i.innerHTML='
    💬
    Start a conversation with '+escapeHtml(n)+'!
    Messages are private between you two.
    ';else{var a="";o.forEach(function(e){var o=e.data(),n=o.senderUid===t;if(n||o.isNachoAuto||"function"!=typeof isUserBlocked||!isUserBlocked(o.senderUid)){var r=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):new Date,s=r.toLocaleDateString();s!==a&&(i.innerHTML+='
    '+s+"
    ",a=s);var l=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),c="nacho-bot"===o.senderUid||!0===o.isNachoAuto,d=n||c||!containsScamPattern(o.text)&&!containsSuspiciousLink(o.text)?"":'
    ⚠️ This message may contain a scam. Never send money to strangers.
    ',u=n||c||!containsPII(o.text)?"":'
    ⚠️ This person is asking for personal info. Only share details for Lightning Mart transactions.
    ',p=c?"rgba(34,197,94,0.08)":n?"var(--accent)":"var(--card-bg)",m=c?"1px solid rgba(34,197,94,0.25)":"none",h=c?"var(--text)":n?"#fff":"var(--text)",g=c?'
    🦌 Nacho
    ':"",f=linkifyText(escapeHtml(o.text)).replace(/\n/g,"
    "),y="";o.imageUrl&&(y=''),i.innerHTML+='
    '+g+(f||"")+y+d+u+'
    '+l+"
    "}}),i.scrollTop=i.scrollHeight,markDMRead(e,t)}},function(e){i.innerHTML='
    💬
    Start a conversation!
    Send your first message below.
    '}))}window.openDM=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to send messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var o=_canAccountDM();if(o.ok)if(isUserBlocked(e))"function"==typeof showToast&&showToast("🚫 This user is blocked. Unblock them to message.");else if(_canStartNewConvo(e)){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";showDMWindow(getConversationId(n,e),e,t,n,i)}else"function"==typeof showToast&&showToast("⏳ You can only message "+MSG_CONFIG.maxNewConvosPerDay+" new people per day. This helps keep the community safe.");else"function"==typeof showToast&&showToast(o.reason)},window.closeDM=function(){window._dmUnsubscribe&&(window._dmUnsubscribe(),window._dmUnsubscribe=null);var e=document.getElementById("dmWindow");e&&e.remove()},window.handleDMImage=function(e,t,o,n){if(e&&e.files&&e.files[0]){var i=e.files[0];if(e.value="",i.type.startsWith("image/"))if(i.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var a=null;try{a=firebase.storage()}catch(e){}if(a){"function"==typeof showToast&&showToast("📷 Uploading image…");var r=auth.currentUser.uid,s=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",l=i.type.indexOf("png")>-1?"png":i.type.indexOf("gif")>-1?"gif":i.type.indexOf("webp")>-1?"webp":"jpg",c=Date.now()+"_"+Math.random().toString(36).substr(2,6)+"."+l,d=a.ref("dm-images/"+r+"/"+c),u=document.getElementById("dmMessages");u&&(u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML=""),(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),u.innerHTML+='
    📷
    Uploading…
    ',u.scrollTop=u.scrollHeight),d.put(i,{contentType:i.type}).then(function(e){return e.ref.getDownloadURL()}).then(function(e){var i=u&&u.querySelector("[data-dm-img-uploading]");i&&i.remove();var a=db.collection("dm_conversations").doc(t),l={senderUid:r,senderName:s,text:"",imageUrl:e,createdAt:firebase.firestore.FieldValue.serverTimestamp()},c={lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r};return c["unread_"+o]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(o,"dm","📷 Image from @"+s,"dm",t),a.update(c).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[r,o],lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r,participantNames:{}};return t.participantNames[r]=s,t.participantNames[o]=n,t["unread_"+o]=firebase.firestore.FieldValue.increment(1),a.set(t)}throw e}).then(function(){return a.collection("messages").add(l)}).then(function(){"function"==typeof showToast&&showToast("📷 Image sent!"),u&&document.getElementById("dmMessages")&&loadDMMessages(t,r,o,n)})}).catch(function(e){console.error("[DM Image] Upload failed:",e),"function"==typeof showToast&&showToast("Failed to send image: "+(e.message||"upload error"));var t=u&&u.querySelector("[data-dm-img-uploading]");t&&t.remove()})}else"function"==typeof showToast&&showToast("Image upload unavailable")}else"function"==typeof showToast&&showToast("Sign in to send images");else"function"==typeof showToast&&showToast("Only images are allowed")}},window.showDMGifPicker=function(e,t,o){var n=document.getElementById("dmGifPicker");if(n)n.remove();else{var i=document.createElement("div");i.id="dmGifPicker",i.style.cssText="position:fixed;bottom:80px;left:50%;transform:translateX(-50%);z-index:600000;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:16px;padding:12px;width:90%;max-width:360px;max-height:350px;display:flex;flex-direction:column;box-shadow:0 8px 32px rgba(0,0,0,0.5);",window._dmGifConvo={convoId:e,recipientUid:t,recipientName:o},i.innerHTML='
    Type to search or tap a category
    ',document.body.appendChild(i),document.getElementById("dmGifSearchInput").focus()}};var _dmGifSearchTimer=null;function markDMRead(e,t){db.collection("dm_conversations").doc(e).update({["unread_"+t]:0}).catch(function(){})}window.searchDMGifs=function(e){_dmGifSearchTimer&&clearTimeout(_dmGifSearchTimer);var t=document.getElementById("dmGifResults");if(t)if(!e||e.length<2)t.innerHTML='
    Type to search
    ';else{var o=document.getElementById("dmGifSearchInput");o&&o.value!==e&&(o.value=e),t.innerHTML='
    Searching...
    ',_dmGifSearchTimer=setTimeout(function(){fetch("https://g.tenor.com/v1/search?q="+encodeURIComponent(e)+"&key=LIVDSRZULELA&limit=20&media_filter=minimal").then(function(e){return e.json()}).then(function(e){if(e.results&&0!==e.results.length){for(var o="",n=0;n')}t.innerHTML=o||'
    No GIFs found
    '}else t.innerHTML='
    No GIFs found
    '}).catch(function(){t.innerHTML='
    Search failed
    '})},400)}},window.sendDMGifUrl=function(){var e=document.getElementById("dmGifUrlInput");e&&e.value.trim()&&sendDMGif(e.value.trim())},window.sendDMGif=function(e){if(e){var t=window._dmGifConvo;if(t){var o=document.getElementById("dmGifPicker");if(o&&o.remove(),auth&&auth.currentUser){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",a=t.convoId,r=t.recipientUid,s=t.recipientName,l=document.getElementById("dmMessages");if(l){var c=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});l.innerHTML+='
    '+c+"
    ",l.scrollTop=l.scrollHeight}var d=db.collection("dm_conversations").doc(a),u={senderUid:n,senderName:i,text:"",imageUrl:e,isGif:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp()},p={lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n};p["unread_"+r]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(r,"dm","GIF from @"+i,"dm",a),d.update(p).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[n,r],lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n,participantNames:{}};return t.participantNames[n]=i,t.participantNames[r]=s,t["unread_"+r]=firebase.firestore.FieldValue.increment(1),d.set(t)}throw e}).then(function(){return d.collection("messages").add(u)}).then(function(){l&&document.getElementById("dmMessages")&&loadDMMessages(a,n,r,s)}).catch(function(e){console.error("[DM GIF] Send failed:",e),"function"==typeof showToast&&showToast("Failed to send GIF")})}else"function"==typeof showToast&&showToast("Sign in to send GIFs")}else"function"==typeof showToast&&showToast("Error: no conversation context")}},window.sendDM=function(e,t,o){var n=document.getElementById("dmInput");if(n){var i=sanitizeMessage(n.value);if(i)if(i.length>MSG_CONFIG.maxMsgLength)"function"==typeof showToast&&showToast("Message too long (max "+MSG_CONFIG.maxMsgLength+" chars)");else if(_isDuplicateMessage(i))"function"==typeof showToast&&showToast("⏳ Message already sent");else if(isUserBlocked(t))"function"==typeof showToast&&showToast("🚫 You have blocked this user");else if(containsBlockedContent(i))"function"==typeof showToast&&showToast("⛔ Message contains prohibited content");else{if(containsPII(i)&&!confirm("⚠️ This message appears to contain or request personal information (phone numbers, addresses, emails, etc.).\n\nSharing personal info with strangers is risky. Only share contact details for Lightning Mart transactions.\n\nSend anyway?"))return;if(!containsScamPattern(i)||confirm("⚠️ This message contains patterns commonly used in scams. Are you sure you want to send it?"))if(containsSuspiciousLink(i)&&"function"==typeof showToast&&showToast("⚠️ Warning: Suspicious link detected. Be cautious with URLs."),checkRateLimit()){var a=auth.currentUser.uid,r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";n.value="",_msgSentTimestamps.push(Date.now()),_logNewConvo(t);var s=db.collection("dm_conversations").doc(e),l={senderUid:a,senderName:r,text:i,createdAt:firebase.firestore.FieldValue.serverTimestamp()},c={lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a};c["unread_"+t]=firebase.firestore.FieldValue.increment(1);var d={participants:[a,t],lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a,participantNames:{}};d.participantNames[a]=r,d.participantNames[t]=o,d["unread_"+t]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(t,"dm","💬 New message from @"+r,"dm",e);var u=document.getElementById("dmMessages");if(u){u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML="");var p=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),m=(new Date).toLocaleDateString(),h=u.querySelector("div[data-dm-date]:last-of-type");m!==(h?h.getAttribute("data-dm-date"):"")&&(u.innerHTML+='
    '+m+"
    "),u.innerHTML+='
    '+linkifyText(escapeHtml(i))+'
    '+p+"
    ",u.scrollTop=u.scrollHeight}s.update(c).catch(function(e){if("not-found"===e.code||"permission-denied"===e.code||-1!==e.message.indexOf("NOT_FOUND")||-1!==e.message.indexOf("No document to update")||-1!==e.message.indexOf("PERMISSION_DENIED"))return s.set(d,{merge:!0});throw e}).then(function(){return s.collection("messages").add(l)}).then(function(){u&&document.getElementById("dmMessages")&&loadDMMessages(e,a,t,o);var n=parseInt(localStorage.getItem("btc_dms_sent")||"0");localStorage.setItem("btc_dms_sent",String(n+1)),"function"==typeof checkBadges&&setTimeout(checkBadges,500)}).catch(function(e){console.error("DM send error:",e),"function"==typeof showToast&&showToast("Failed to send: "+(e.code||e.message||"Unknown error"));var t=u&&u.querySelector("[data-optimistic]");t&&t.remove()})}else"function"==typeof showToast&&showToast("⏳ Slow down! Max "+MSG_CONFIG.maxMsgsPerHour+" messages per hour.")}}},window.showInbox=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to see messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e=auth.currentUser.uid,t=document.getElementById("dmInbox");t&&t.remove();var o=document.createElement("div");o.innerHTML='
    📬 Messages
    Loading...
    ',document.body.appendChild(o.firstChild),db.collection("dm_conversations").where("participants","array-contains",e).orderBy("lastMessageTime","desc").limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");o&&(console.log("Inbox snap size:",t.size),t.empty?o.innerHTML='
    📬
    No messages yet
    Tap a user on the leaderboard to start chatting!
    ':(o.innerHTML="",t.forEach(function(t){var n=t.data(),i=n.participants.find(function(t){return t!==e}),a=n.participantNames&&n.participantNames[i]||"User",r=n["unread_"+e]||0,s=n.lastMessage||"";s.length>50&&(s=s.substring(0,50)+"...");var l=n.lastMessageTime?timeAgo(n.lastMessageTime):"",c=n.lastSenderUid===e,d=!0===n.isBuddyMatch,u=d?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+';" onmouseover="this.style.background=\'var(--card-bg)\'" onmouseout="this.style.background=\''+(r>0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+'\'">
    '+(d?"🦌":a.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(a)+u+'
    '+l+'
    0?"600":"400")+';white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">'+(c?"You: ":"")+escapeHtml(s)+"
    "+(r>0?'
    '+r+"
    ":"")+"
    "})))}).catch(function(t){console.error("Inbox load error:",t);var o=document.getElementById("dmInboxList");o&&("failed-precondition"!==t.code?o.innerHTML='
    💬
    No messages yet
    Tap a user on the leaderboard or in PlebTalk to start chatting!
    ':db.collection("dm_conversations").where("participants","array-contains",e).limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");if(o)if(t.empty)o.innerHTML='
    📬
    No messages yet
    ';else{o.innerHTML="";var n=[];t.forEach(function(e){n.push({id:e.id,...e.data()})}),n.sort(function(e,t){return(t.lastMessageTime||0)-(e.lastMessageTime||0)}),n.forEach(function(t){var n=t.participants.find(function(t){return t!==e}),i=t.participantNames&&t.participantNames[n]||"User",a=t["unread_"+e]||0,r=t.lastMessage||"";r.length>50&&(r=r.substring(0,50)+"...");var s=t.lastSenderUid===e,l=!0===t.isBuddyMatch,c=l?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":l?"rgba(34,197,94,0.03)":"none")+';">
    '+(l?"🦌":i.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(i)+c+'
    '+(s?"You: ":"")+escapeHtml(r)+"
    "+(a>0?'
    '+a+"
    ":"")+"
    "})}}).catch(function(e){var t=document.getElementById("dmInboxList");t&&(t.innerHTML='
    💬
    No messages yet
    ')}))})};var _unreadCount=0,_unreadTimer=null;function checkUnreadCount(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e=auth.currentUser.uid;db.collection("dm_conversations").where("participants","array-contains",e).get().then(function(t){var o=0;t.forEach(function(t){var n=t.data();o+=n["unread_"+e]||0}),_unreadCount=o,updateUnreadBadge()}).catch(function(){})}}function updateUnreadBadge(){document.querySelectorAll(".dm-unread-badge").forEach(function(e){_unreadCount>0?(e.textContent=_unreadCount>99?"99+":_unreadCount,e.style.display="inline-flex"):e.style.display="none"});var e=document.getElementById("bnavMsgBadge");e&&(_unreadCount>0?(e.textContent=_unreadCount,e.style.display="block"):e.style.display="none")}function startUnreadPolling(){checkUnreadCount(),_unreadTimer&&clearInterval(_unreadTimer),_unreadTimer=setInterval(checkUnreadCount,MSG_CONFIG.unreadPollInterval)}window.initMessaging=function(){startPresenceTracking(),restoreBlockedList(),setTimeout(startUnreadPolling,5e3)},void 0!==auth&&auth&&auth.currentUser&&initMessaging();const HIDDEN_BADGES=[{id:"nacho_friend",name:"Nacho's Friend",emoji:"🦌",pts:25,desc:"Interact with Nacho",hint:"Click on Nacho!",hidden:!1,check:function(){return"true"===localStorage.getItem("btc_nacho_clicked")}},{id:"genesis",name:"Genesis Reader",emoji:"📜",pts:75,desc:"Read the whitepaper channel",hint:"Open the Whitepaper channel",hidden:!1,check:function(){return"undefined"!=typeof currentChannelId&&"whitepaper"===currentChannelId}},{id:"nacho_curious",name:"Curious Deer",emoji:"❓",pts:50,desc:"Ask Nacho your first question",hint:"Ask Nacho anything!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=1}},{id:"ticket_bronze",name:"Ticket Fish",emoji:"🐟",pts:200,desc:"Earn 25 Orange Tickets",hint:"Spin daily + referrals!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=25},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,25)+"/25":"0/25"}},{id:"ticket_silver",name:"Ticket Shark",emoji:"🦈",pts:500,desc:"Earn 50 Orange Tickets",hint:"Keep spinning & referring!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=50},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,50)+"/50":"0/50"}},{id:"ticket_gold",name:"Ticket Whale",emoji:"🐋",pts:1e3,desc:"Earn 100 Orange Tickets",hint:"The ultimate ticket badge!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=100},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,100)+"/100":"0/100"}},{id:"nacho_10q",name:"Inquisitive Buck",emoji:"🔍",pts:200,desc:"Ask Nacho 10 questions",hint:"Keep asking Nacho!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=10},progress:function(){return Math.min(parseInt(localStorage.getItem("btc_nacho_questions")||"0"),10)+"/10"}},{id:"collector",name:"Collector",emoji:"💎",pts:150,desc:"Save 10+ topics to favorites",hint:"Star your favorite topics",hidden:!1,check:function(){return safeJSON("btc_favs",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_favs",[]).length,10)+"/10"}},{id:"first_post",name:"Town Crier",emoji:"📣",pts:100,desc:"Make your first Pleb Talk post",hint:"Post in PlebTalk!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=1||void 0!==currentUser&¤tUser&¤tUser.forumPosts>=1}},{id:"first_reply",name:"Conversationalist",emoji:"💬",pts:75,desc:"Reply to a forum post",hint:"Join a discussion!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.forumReplies>=1}},{id:"market_seller",name:"Merchant",emoji:"🏪",pts:150,desc:"List an item on Lightning Mart",hint:"Sell something for sats on Lightning Mart!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketListings>=1}},{id:"market_buyer",name:"Shopper",emoji:"🛍️",pts:150,desc:"Contact a seller on the marketplace",hint:"Find something to buy!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketMessages>=1}},{id:"donor_100",name:"Giving Pleb",emoji:"🫷",pts:50,desc:"Donate 100 XP for charity",hint:"Donate 100 XP in the Charity tab!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=100},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,100)+"/100"}},{id:"donor_500",name:"Stack Sharer",emoji:"💛",pts:150,desc:"Donate 500 XP for charity",hint:"Keep donating!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=500},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,500)+"/500"}},{id:"donor_1000",name:"Community Builder",emoji:"🧡",pts:300,desc:"Donate 1,000 XP for charity",hint:"A true community builder!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e3)+"/1,000"}},{id:"donor_5000",name:"Archive Patron",emoji:"❤️",pts:1e3,desc:"Donate 5,000 XP for charity",hint:"An archive patron — legendary!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e3)+"/5,000"}},{id:"donor_10000",name:"Sats Saint",emoji:"🔥",pts:2e3,desc:"Donate 10,000 XP for charity",hint:"A sats saint among us!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e4)+"/10,000"}},{id:"donor_25000",name:"Lightning Philanthropist",emoji:"⚡",pts:4e3,desc:"Donate 25,000 XP for charity",hint:"A lightning philanthropist!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=25e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,25e3)+"/25,000"}},{id:"donor_50000",name:"Satoshi's Steward",emoji:"🏆",pts:7500,desc:"Donate 50,000 XP for charity",hint:"Satoshi's Steward — incredible!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e4)+"/50,000"}},{id:"donor_100000",name:"Legend of the Archive",emoji:"👑",pts:15e3,desc:"Donate 100,000 XP for charity",hint:"A true legend of the archive!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e5},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e5)+"/100,000"}},{id:"night_owl",name:"Night Owl",emoji:"🦉",pts:50,desc:"Visit the archive after midnight",hidden:!0,check:function(){return(new Date).getHours()>=0&&(new Date).getHours()<5}},{id:"speed_runner",name:"Speed Runner",emoji:"⚡",pts:100,desc:"Visit 15+ channels in one session",hidden:!0,check:function(){return void 0!==sessionChannels&&sessionChannels.size>=15}},{id:"scholar",name:"Bitcoin Scholar",emoji:"🎓",pts:300,desc:"Pass the Scholar Certification",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_scholar_passed")}},{id:"nacho_20q",name:"20 Questions",emoji:"🏅",pts:500,desc:"Ask Nacho 20 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=20}},{id:"explorer_10",name:"Curious Pleb",emoji:"🗺️",pts:100,desc:"Explore 10 topics",hint:"Keep exploring!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,10)+"/10"}},{id:"explorer_25",name:"Rabbit Holer",emoji:"🐇",pts:250,desc:"Explore 25 topics",hint:"Dive deeper!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=25},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,25)+"/25"}},{id:"explorer_50",name:"Half Stack",emoji:"📚",pts:500,desc:"Explore 50 topics",hint:"Halfway there!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=50},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,50)+"/50"}},{id:"explorer_100",name:"Century Club",emoji:"💯",pts:1e3,desc:"Explore 100 topics",hint:"Almost all of them!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=100},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,100)+"/100"}},{id:"explorer_all",name:"Archive Master",emoji:"👑",pts:2e3,desc:"Explore every single topic",hint:"Visit them all!",hidden:!0,check:function(){return void 0!==CHANNELS&&safeJSON("btc_visited_channels",[]).length>=Object.keys(CHANNELS).length}},{id:"marathon",name:"Marathon Reader",emoji:"🏃",pts:150,desc:"Spent 30+ minutes reading in one session",hidden:!0,check:function(){return Date.now()-(window._sessionStart||Date.now())>18e5}},{id:"early_adopter",name:"Early Adopter",emoji:"🌅",pts:200,desc:"Browsing between 5am and 7am",hidden:!0,check:function(){var e=(new Date).getHours();return e>=5&&e<7}},{id:"weekend_warrior",name:"Weekend Warrior",emoji:"🎉",pts:75,desc:"Learning Bitcoin on a weekend",hidden:!0,check:function(){var e=(new Date).getDay();return 0===e||6===e}},{id:"triple_threat",name:"Triple Threat",emoji:"🎯",pts:300,desc:"Completed a quest, sent a chat message, and read a channel in one session",hidden:!0,check:function(){return"true"===sessionStorage.getItem("btc_quest_done")&&"true"===sessionStorage.getItem("btc_chat_sent")&&void 0!==sessionChannels&&sessionChannels.size>=1}},{id:"nacho_50q",name:"Nacho Sage",emoji:"🧙",pts:500,desc:"Ask Nacho 50 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=50}},{id:"bookmark_collector",name:"Bookmark Hoarder",emoji:"📚",pts:100,desc:"Bookmarked 20+ messages",hidden:!0,check:function(){return safeJSON("btc_bookmarks",[]).length>=20}},{id:"pvp_streak",name:"Undefeated",emoji:"🔱",pts:250,desc:"Won 5 PVP battles in a row",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_pvp_win_streak")||"0")>=5}},{id:"sats_maxed",name:"Faucet King",emoji:"👑",pts:1e3,desc:"Claimed all 10,000 sats from the faucet",hidden:!0,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e4}},{id:"streak_freeze",name:"Ice Shield",emoji:"🧊",pts:50,desc:"Used a streak freeze to save your streak",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_freeze_used")}},{id:"nacho_closet_full",name:"Fashionista",emoji:"👗",pts:200,desc:"Unlocked all Nacho closet items from the spin wheel",hidden:!0,check:function(){return safeJSON("btc_spin_closet_items",[]).length>=10}}];function _syncPredictionToFirestore(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db)return;var t=auth.currentUser.uid;db.collection("users").doc(t).set({predictions:{lastPrediction:{direction:e.direction,price:e.price,time:e.time}}},{merge:!0}).catch(function(){}),db.collection("active_predictions").doc(t).set({uid:t,direction:e.direction,price:e.price,time:e.time,resolved:!1}).catch(function(){})}catch(e){}}function _updatePredictionStats(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db||"undefined"==typeof firebase)return;var t=auth.currentUser.uid,o=firebase.firestore.FieldValue.increment,n=parseInt(localStorage.getItem("btc_predict_streak")||"0"),i=parseInt(localStorage.getItem("btc_predict_best_streak")||"0"),a={"predictions.total":o(1),"predictions.lastResolved":Date.now()};if(e){a["predictions.correct"]=o(1);var r=n+1;a["predictions.streak"]=r,r>i&&(a["predictions.bestStreak"]=r,localStorage.setItem("btc_predict_best_streak",r.toString()))}else a["predictions.streak"]=0;db.collection("users").doc(t).set(a,{merge:!0}).catch(function(){});var s={total:o(1)};e&&(s.correct=o(1)),db.collection("stats").doc("predictions").set(s,{merge:!0}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.predictions||(currentUser.predictions={total:0,correct:0,streak:0,bestStreak:0}),currentUser.predictions.total=(currentUser.predictions.total||0)+1,e?(currentUser.predictions.correct=(currentUser.predictions.correct||0)+1,currentUser.predictions.streak=(currentUser.predictions.streak||0)+1,currentUser.predictions.streak>(currentUser.predictions.bestStreak||0)&&(currentUser.predictions.bestStreak=currentUser.predictions.streak)):currentUser.predictions.streak=0)}catch(e){}}!function(){const e=["🎓 Someone just passed the Bitcoin Basics Certification! Can you?","⚡ A pleb just completed a Lightning Network quest — 50 XP earned!","🗺️ Someone just finished all 10 steps of the Bitcoin Journey!","🎮 A Bitcoiner just aced a quiz in Nacho Mode — 10/10!","📚 A new user just explored their first 3 topics — features unlocking!","🧠 Someone just asked Nacho 100 questions — Bitcoin Scholar status!","🎯 A pleb just scored 5/5 on a Conversation Quest!","📖 Someone just read through the entire Timechain channel!","🔥 A Bitcoiner just hit a 30-day streak! Legendary dedication!","🔥 Someone just started a 7-day streak — can you beat them?","🏆 A pleb just crossed 5,000 XP! Climbing the leaderboard!","⭐ Someone just earned 200 XP in a single session!","🔥 A user just protected their streak with a Freeze Ticket! Smart move.","📈 Someone just jumped 10 spots on the Leaderboard!","🧡 A Bitcoiner just leveled up to Bitcoin Believer!","🏔 Someone just reached Maxi status — top of the mountain!","👑 A pleb just entered the Top 25 on the Leaderboard!","🌱 A brand new user just earned their first 50 XP! Welcome!","🎡 Someone just spun the daily wheel and won 5 Orange Tickets!","🎟️ A pleb just earned bonus tickets from a referral!","🧊 Someone won a Streak Freeze on the daily spin — lucky!","🎡 A Bitcoiner just won a closet item from the spin wheel!","💬 New discussion in PlebTalk: 'Best cold storage for beginners?'","💬 Someone just posted in PlebTalk — join the conversation!","🛒 New listing on LightningMart — check it out!","🤝 A meetup was just created in IRL Sync — find one near you!","💬 A PlebTalk post just got 5 upvotes!","⚡ Someone just tipped a forum post with Lightning!","🦌 Someone just entered Nacho Mode for a 30-minute deep dive!","🎽 A pleb just equipped Diamond Hooves in Nacho's Closet! 💎","🕶️ Someone just unlocked Cool Shades from the spin wheel!","👑 A Bitcoiner just equipped the Royal Crown — looking regal!","🦌 Nacho just helped someone understand seed phrases!","🗺️ Someone just explored their 50th channel — almost full coverage!","🦉 A Night Owl badge was just earned at 2 AM!","🎲 Someone just used Random Channel and discovered 'cypherpunks'!","🎨 A user just browsed the Art Gallery — 200+ Bitcoin artworks!","📡 A Bitcoiner just opted in to The Signal newsletter!","🎉 Over 100 users are learning Bitcoin here right now!","📊 The archive has been visited over 10,000 times this month!","🧡 146 channels of pure Bitcoin education — and growing!","⚡ Over 500 Nacho conversations happened this week!","🏆 The Leaderboard top 10 just shuffled — who's climbing?"];async function t(){const t=safeJSON("btc_visited_channels",[]).length,o=firebase.auth().currentUser&&!firebase.auth().currentUser.isAnonymous;if(t<3&&!o)return;const n=document.getElementById("activity-ticker"),i=document.getElementById("ticker-content");if(n&&i){var a=e.slice();try{var r=firebase.firestore();(await r.collection("forum_posts").orderBy("createdAt","desc").limit(3).get()).forEach(function(e){var t=e.data(),o=t.authorName||"A pleb";a.push("💬 "+o+' just posted in PlebTalk: "'+(t.title||"").substring(0,40)+'..."')});try{(await r.collection("marketplace").where("status","==","active").orderBy("createdAt","desc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🛒 New on LightningMart: "'+(t.title||"Item").substring(0,35)+'" for '+(t.priceSats||t.price||"???")+" sats!")})}catch(e){}try{var s=await r.collection("users").orderBy("points","desc").limit(10).get(),l=[];if(s.forEach(function(e){var t=e.data();t.username&&l.push(t.username)}),l.length>=3){a.push("👑 "+l[0]+" is holding #1 on the Leaderboard! Can you catch them?");var c=l[Math.floor(Math.random()*Math.min(5,l.length))];a.push("📈 "+c+" just climbed the Leaderboard — competition is heating up!")}}catch(e){}try{(await r.collection("irl_events").where("date",">=",(new Date).toISOString()).orderBy("date","asc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🤝 Upcoming meetup: "'+(t.title||"Bitcoin Meetup").substring(0,35)+'" — RSVP in IRL Sync!')})}catch(e){}}catch(e){console.log("Ticker live data skipped:",e)}for(var d=a.length-1;d>0;d--){var u=Math.floor(Math.random()*(d+1)),p=a[d];a[d]=a[u],a[u]=p}n.style.display="flex";var m=0;h(),setInterval(h,12e3)}function h(){i.style.animation="none",i.offsetHeight,i.textContent=a[m],i.style.animation="tickerScroll 12s linear infinite",m=(m+1)%a.length}}const o=document.createElement("style");o.textContent="\n #ticker-content { \n white-space: nowrap !important;\n overflow: visible !important;\n text-overflow: clip !important;\n display: inline-block !important;\n width: auto !important;\n padding-right: 50px;\n }\n @keyframes tickerScroll {\n 0% { transform: translateX(100%); }\n 100% { transform: translateX(-100%); }\n }\n ",document.head.appendChild(o),window.rateChannel=async function(e,t){const o=document.getElementById("sentiment-"+e);if(o){o.innerHTML='
    Thank you! 🦌
    Nacho will use this to organize better content.
    ';try{const o=firebase.firestore();await o.collection("channel_feedback").add({channelId:e,rating:t,uid:firebase.auth().currentUser?firebase.auth().currentUser.uid:"anon",createdAt:firebase.firestore.FieldValue.serverTimestamp()}),"function"==typeof awardPoints&&awardPoints(5,"Feedback bonus")}catch(e){console.log("Feedback save skipped:",e)}}},window.checkNewsletterPrompt=function(){localStorage.getItem("btc_newsletter_prompt_shown")||safeJSON("btc_visited_channels",[]).length>=10&&(function(){const e=document.createElement("div");e.id="newsletterModal",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);z-index:10000;display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(5px);",e.innerHTML='
    📡

    Stay Orange-Pilled

    You\'ve explored 10+ channels! Stay connected with Bitcoin updates and community news.

    📱 Join Telegram Updates📧 Subscribe on Substack
    ',document.body.appendChild(e)}(),localStorage.setItem("btc_newsletter_prompt_shown","true"))},window.optInNewsletter=async function(){const e=document.getElementById("newsletterModal"),t=firebase.auth().currentUser;if(!t||t.isAnonymous)return showToast("Please sign in with email to join the newsletter!"),"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void(e&&e.remove());try{const e=firebase.firestore();await e.collection("users").doc(t.uid).update({newsletterOptIn:!0,newsletterOptInDate:firebase.firestore.FieldValue.serverTimestamp()}),showToast("🎉 Welcome to the Orange Pill newsletter!")}catch(e){console.log("Newsletter opt-in failed:",e)}e&&e.remove()},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){t(),checkNewsletterPrompt()}):(t(),checkNewsletterPrompt())}(),window.showNachoStory=function(e){var t=[{title:"Chapter 1: The Genesis Block",text:"In the beginning, there was nothing but fiat. Nacho was just a young buck growing up in the White Mountains of New Hampshire — the Live Free or Die state. He spent his fawn days splashing in the Pemigewasset River, racing chipmunks through birch groves, and nibbling on leaves of debt from the forest of traditional finance. His mama always said the acorns were getting smaller every year, but nobody could explain why. One cold January day in 2009, a mysterious message appeared carved into a sugar maple: 'Chancellor on brink of second bailout for banks.' Nacho didn't understand it yet, but something had changed forever. A new kind of money had been born — one that no government could print, no bank could freeze, and no deer could counterfeit. It was called Bitcoin."},{title:"Chapter 2: The Pizza That Changed Everything",text:"Nacho heard a rumor from a blue jay passing through Franconia Notch: someone had traded 10,000 bitcoins for two pizzas. 'That's crazy!' he thought, nearly choking on a wild blueberry. But was it? Those pizzas proved Bitcoin had real value — people would actually exchange goods for it. Nacho realized this wasn't just internet magic beans. It was the beginning of price discovery. He thought about all the acorns he'd traded with the squirrels over the years — weren't those his first 'transactions' too? Every great journey starts with a single trade, and Bitcoin's started with pepperoni and cheese."},{title:"Chapter 3: Down the Rabbit Hole",text:"Nacho found a weathered copy of the whitepaper pinned to a bulletin board at a general store in Lincoln, New Hampshire. Only 9 pages, but each one hit different. Peer-to-peer. No trusted third party. Proof of work. 21 million cap. He read it by the light of a campfire near the Kancamagus Highway, the stars of the Granite State blazing overhead. The deeper he went, the more he understood: Bitcoin wasn't just new money. It was a paradigm shift. Sound money that couldn't be debased. A monetary network with no CEO, no headquarters, no off switch. Nacho's antlers tingled — literally. His first set was coming in. He was growing up, and he was becoming a Bitcoiner."},{title:"Chapter 4: HODL Through the Storm",text:"A nor'easter hit New Hampshire that winter, and the price of Bitcoin crashed right along with the temperature. Then crashed again. Nacho watched his sats lose 80% of their dollar value from a snow-covered ridge overlooking the Presidential Range. His forest friends laughed. 'Told you it was a scam!' chirped a skeptical chickadee. But Nacho had done his homework. He understood the halving cycles. He knew that every 210,000 blocks, the new supply gets cut in half. Scarcity + time = value. So Nacho did what legends do: he stood firm in the blizzard and held. Not because he was reckless, but because he understood what he held. The storms always pass. The mountains remain."},{title:"Chapter 5: Not Your Keys, Not Your Cheese",text:"One crisp autumn morning, as the New Hampshire maples blazed orange and gold, Nacho woke up to terrible news. An exchange had been hacked. Billions gone. Friends who kept their bitcoin on the exchange lost everything. A young doe from Vermont had her entire savings wiped out. Nacho felt sick — but also relieved. He'd moved his sats to a hardware wallet weeks ago, buried it in a waterproof case near his favorite granite boulder in the White Mountains. Cold storage. Air-gapped. His keys, his bitcoin. From that day forward, Nacho's motto was clear: 'Not your keys, not your cheese.' 🧀🔑 He even carved it into a birch tree so no deer would forget."},{title:"Chapter 6: The Halving",text:"Every four years, something magical happens — and Nacho had the perfect view from Mount Washington's summit. The block reward — the number of new bitcoins created with each block — gets cut in half. He watched the countdown with a group of bitcoiners who'd hiked up for the occasion, huddled together at 6,288 feet with thermoses of coffee and Lightning-powered phones. From 6.25 BTC to 3.125 BTC per block. Less new supply entering the market. Same or growing demand. The wind howled, but nobody cared. It's not magic; it's math. And it's the most predictable monetary policy in the history of money. Nacho shed a single tear — which immediately froze to his fur."},{title:"Chapter 7: Nacho's Mission",text:"Nacho looked out from his favorite overlook in the White Mountains — the same spot where he'd first read the whitepaper by campfire light. He'd grown from a gangly fawn into a strong buck with a magnificent rack of antlers (seven points, if you're counting). But so many deer — so many people — still didn't understand Bitcoin. They heard 'crypto' and thought of scams, memecoins, and celebrity tokens. But Bitcoin is different. It's the signal in the noise. So Nacho decided to dedicate his life to education, right here from the Live Free or Die state. Not shilling. Not pumping. Teaching. Because the best way to orange-pill someone isn't to tell them to buy — it's to help them understand WHY. And that's why you're here. Welcome to the Archive. 🦌🟠"}],o=(new Date).toISOString().split("T")[0],n=safeJSON("btc_nacho_story_days",[]);(0===n.length||-1===n.indexOf(o))&&(n.push(o),localStorage.setItem("btc_nacho_story_days",JSON.stringify(n)));var i,a=Math.min(n.length,t.length);if(void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryProgress:a,nachoStoryDate:o,nachoStoryDays:n}).catch(function(){})}catch(e){}localStorage.setItem("btc_nacho_story_highest",a.toString()),localStorage.setItem("btc_nacho_story_date",o),"number"==typeof e?(i=Math.min(e,a-1))<0&&(i=0):(i=a-1)<0&&(i=0);var r=t[i],s=document.createElement("div");s.id="nachoStoryOverlay",s.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",s.onclick=function(e){e.target===s&&s.remove()};for(var l='
    ',c=0;c'+(c+1)+"":''}l+="
    ";var u,p=i>0?"':"";u=i+1Next →':i>=t.length-1?'✅ Story Complete!':'🔒 Come back tomorrow!';var m=document.createElement("div");m.style.cssText="background:#1a1a2e;border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:500px;width:100%;margin:40px auto;color:#e2e8f0;font-family:inherit;",m.innerHTML='
    🦌📖
    '+l+'

    '+r.title+'

    '+r.text+'

    📖 Chapter '+(i+1)+" of "+t.length+" · "+a+" unlocked ("+(t.length-a)+' remaining)
    '+p+u+'
    ',s.appendChild(m),document.body.appendChild(s);var h=safeJSON("btc_nacho_story_awarded",[]);if("function"==typeof awardPoints&&-1===h.indexOf(i)){h.push(i),localStorage.setItem("btc_nacho_story_awarded",JSON.stringify(h));var g=i===t.length-1?50:15;awardPoints(g,"📖 Completed Chapter "+(i+1)),"function"==typeof showToast&&showToast("📖 +"+g+" XP — Chapter "+(i+1)+" complete!"),h.length===t.length&&setTimeout(function(){if(awardPoints(100,"📖🎉 Completed Nacho's Story!"),"function"==typeof awardOrangeTickets)awardOrangeTickets(25,"📖 Nacho's Story Complete!");else{var e=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(e+25).toString())}"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound();var t=document.createElement("div");if(t.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",t.onclick=function(){t.style.opacity="0",t.style.transition="opacity 0.4s",setTimeout(function(){t.remove()},400)},t.innerHTML='
    🦌📖🎉
    STORY COMPLETE!
    You\'ve followed Nacho\'s entire Bitcoin journey from the Genesis Block to his mission of education. You\'re officially a Story Master! 🏆
    +100
    BONUS PTS
    +25
    🎟️ TICKETS
    ',document.body.appendChild(t),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryComplete:!0,nachoStoryCompletedAt:(new Date).toISOString()}).catch(function(){})}catch(e){}},800)}},window.showPricePrediction=function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0;if(!e&&"undefined"!=typeof _lastWsPrice&&_lastWsPrice&&(e=_lastWsPrice,localStorage.setItem("btc_last_price",e.toString())),!e&&"undefined"!=typeof _dashData&&_dashData&&_dashData.price&&(e=_dashData.price,localStorage.setItem("btc_last_price",e.toString())),!e)return"function"==typeof showToast&&showToast("⏳ Fetching price..."),void fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd?(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),showPricePrediction()):"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")}).catch(function(){"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")});var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&t.remove()};var o=safeJSON("btc_price_prediction",null),n=document.createElement("div");if(n.style.cssText="background:var(--card-bg,#1a1a2e);border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:420px;width:100%;color:var(--text,#e2e8f0);font-family:inherit;text-align:center;",o&&Date.now()-o.time<864e5){var i=Date.now()-o.time;if(!(i>=864e5)){var a=Math.ceil((864e5-i)/36e5);return n.innerHTML='

    Prediction Locked In!

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+'

    ⏳ Results in ~'+a+" hour"+(1!==a?"s":"")+'
    Come back after 24 hours to see if you were right!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},500),t.appendChild(n),void document.body.appendChild(t)}var r=e-o.price,s=(r/o.price*100).toFixed(2),l="up"===o.direction&&r>0||"down"===o.direction&&r<0;o._notified||("function"==typeof notifyPredictionResult&¬ifyPredictionResult(l,o.direction),o._notified=!0,localStorage.setItem("btc_price_prediction",JSON.stringify(o)));var c=parseInt(localStorage.getItem("btc_predict_streak")||"0");n.innerHTML=''+(l?"🎉":"😅")+'

    Your Prediction

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+" ("+(r>=0?"+":"")+s+'%)

    '+(l?"✅ You were RIGHT! +25 XP":"❌ Not this time!")+"

    "+(l&&c>=2?'

    🔥 '+c+" correct in a row!

    ":"")+'
    Come back tomorrow for a new prediction!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},100)}else n.innerHTML='📈📉

    Predict Bitcoin\'s Price

    Current BTC Price:

    $'+Math.round(e).toLocaleString()+'

    Will Bitcoin go UP or DOWN in the next 24 hours?

    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStats");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 Be the first to predict!"})},100);t.appendChild(n),document.body.appendChild(t)},window._savePrediction=function(e){var t={direction:e,price:parseFloat(localStorage.getItem("btc_last_price"))||0,time:Date.now(),resolved:!1};localStorage.setItem("btc_price_prediction",JSON.stringify(t)),"function"==typeof showToast&&showToast("🎯 Prediction saved! Check back tomorrow to see if you were right."),"function"==typeof awardPoints&&awardPoints(5,"📈 Price prediction made"),_syncPredictionToFirestore(t)},window.checkPredictionResult=function(){var e=safeJSON("btc_price_prediction",null);if(e&&!e.resolved&&!(Date.now()-e.time<864e5)){var t=parseFloat(localStorage.getItem("btc_last_price"))||0;if(t&&e.price){var o=t-e.price,n=(o/e.price*100).toFixed(2),i="up"===e.direction&&o>0||"down"===e.direction&&o<0;e.resolved=!0,e.result=i?"correct":"wrong",e.finalPrice=t,localStorage.setItem("btc_price_prediction",JSON.stringify(e)),_updatePredictionStats(i);try{void 0!==auth&&auth.currentUser&&void 0!==db&&db.collection("active_predictions").doc(auth.currentUser.uid).delete().catch(function(){})}catch(e){}if(i){"function"==typeof awardPoints&&awardPoints(25,"🎯 Correct price prediction!");var a=parseInt(localStorage.getItem("btc_predict_streak")||"0")+1;localStorage.setItem("btc_predict_streak",a.toString()),setTimeout(function(){"function"==typeof showToast&&showToast("🎉 Your prediction was RIGHT! Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"% — +25 XP!"+(a>=3?" 🔥 "+a+" correct in a row!":""))},2e3)}else localStorage.setItem("btc_predict_streak","0"),setTimeout(function(){"function"==typeof showToast&&showToast("📉 Your prediction was wrong — Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"%. Try again tomorrow!")},2e3)}}};var _globalPredCache=null,_globalPredCacheTs=0;window.getGlobalPredictionStats=function(e){if(_globalPredCache&&Date.now()-_globalPredCacheTs<12e4)e(_globalPredCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{db.collection("stats").doc("predictions").get().then(function(t){t.exists?(_globalPredCache=t.data(),_globalPredCacheTs=Date.now(),e(_globalPredCache)):e(null)}).catch(function(){e(null)})}catch(t){e(null)}else e(null)},window.getPredictionStats=function(e){var t=e&&e.predictions?e.predictions:null;if(!t||!t.total)return null;var o=t.total>0?Math.round(t.correct/t.total*100):0;return{total:t.total||0,correct:t.correct||0,percentage:o,streak:t.streak||0,bestStreak:t.bestStreak||0}};var _communityStatsCache=null,_communityStatsCacheTs=0,_communityStatsUnsub=null;function _renderCommunityStats(e,t,o){var n=[];o.channelVisits&&n.push("📖 "+_fmtNum(o.channelVisits)+" channel reads"),o.questsCompleted&&n.push("⚡ "+_fmtNum(o.questsCompleted)+" quests completed"),o.chatMessages&&n.push("💬 "+_fmtNum(o.chatMessages)+" chat messages"),o.spins&&n.push("🎡 "+_fmtNum(o.spins)+" daily spins"),o.pvpMatches&&n.push("⚔️ "+_fmtNum(o.pvpMatches)+" PVP battles");var i=document.getElementById("visitCount");if(i&&"—"!==i.textContent&&n.push("👥 "+i.textContent+" total visits"),o.userCount&&n.push("🧑‍🤝‍🧑 "+_fmtNum(o.userCount)+" registered users"),o.watchTimeMinutes){var a=Math.floor(o.watchTimeMinutes/60);n.push("📺 "+(a>0?_fmtNum(a)+" hours":o.watchTimeMinutes+" min")+" Timechain TV watched")}if(0!==n.length){e.innerHTML=n.join("  ·  ");var r=function(e,t){var o=document.getElementById(e);o&&t&&(o.textContent=t.toLocaleString())};if(r("csChannelReads",o.channelVisits),r("csQuests",o.questsCompleted),r("csChatMsgs",o.chatMessages),r("csSpins",o.spins),r("csPvp",o.pvpMatches),r("csUsers",o.userCount),o.watchTimeMinutes){var s=Math.floor(o.watchTimeMinutes/60);r("csWatchTime",s>0?s:o.watchTimeMinutes)}}else e.innerHTML="No stats yet"}function _fmtNum(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function renderExplorationMap(){var e=document.getElementById("explorationMap");if(e&&void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]);void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>t.length&&(t=currentUser.readChannels);var o=Object.keys(CHANNELS),n=o.length,i=t.length,a=Math.round(i/n*100),r="";o.forEach(function(e){var o=-1!==t.indexOf(e),n=CHANNELS[e].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}|\u{2700}-\u{27BF}|\u{FE00}-\u{FEFF}|\u{1F900}-\u{1F9FF}|\u{1FA00}-\u{1FA6F}|\u{1FA70}-\u{1FAFF}|\u{200D}|\u{FE0F}]+)/u),i=n?n[1]:"📄";r+="
    '+(o?i:"?")+"
    "});var s="true"===localStorage.getItem("btc_explore_map_open");e.innerHTML="
    "+(s?"▾":"▸")+'🗺️ Exploration Map
    '+i+"/"+n+" ("+a+'%)
    '+r+"
    "}}window.loadCommunityStats=function(){var e=document.getElementById("communityStatsInner");if(e){var t=e.parentElement;if(_communityStatsUnsub&&_communityStatsCache)_renderCommunityStats(e,t,_communityStatsCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{_communityStatsUnsub=db.collection("stats").doc("global").onSnapshot(function(e){var t=e.exists?e.data():{};_communityStatsCache=t,_communityStatsCacheTs=Date.now();var o=document.getElementById("communityStatsInner");o&&_renderCommunityStats(o,o.parentElement,t)})}catch(e){}}},setTimeout(function(){"function"==typeof loadCommunityStats&&loadCommunityStats()},5e3),window.updatePredictionLabel=function(){var e=document.getElementById("predAccuracyLabel");return!!e&&void 0!==db&&"undefined"!=typeof firebase&&"function"==typeof getGlobalPredictionStats&&(getGlobalPredictionStats(function(t){var o=[];if(t&&t.total){var n=Math.round(t.correct/t.total*100);o.push("🌍 "+n+"% community accuracy")}if(void 0!==currentUser&¤tUser&¤tUser.predictions&¤tUser.predictions.total){var i=Math.round(currentUser.predictions.correct/currentUser.predictions.total*100);o.push("👤 "+i+"% you")}e.innerHTML=o.join("
    ")}),!0)},function(){var e=0,t=setInterval(function(){e++,(window.updatePredictionLabel&&window.updatePredictionLabel()||e>60)&&clearInterval(t)},1e3)}(),function e(){if("function"==typeof window.goHome){if(!window.goHome.__predHooked){var t=window.goHome;window.goHome=function(){var e=t.apply(this,arguments);return setTimeout(function(){window.updatePredictionLabel&&window.updatePredictionLabel()},400),e},window.goHome.__predHooked=!0}}else var o=setInterval(function(){"function"==typeof window.goHome&&(clearInterval(o),e())},500)}(),window.renderExplorationMap=renderExplorationMap;var BITCOIN_QUOTES=[{text:"If you don't believe it or don't get it, I don't have the time to try to convince you, sorry.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"The root problem with conventional currency is all the trust that's required to make it work.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"It might make sense just to get some in case it catches on.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"Running bitcoin.",author:"Hal Finney",channel:"history"},{text:"Bitcoin is a remarkable cryptographic achievement and the ability to create something that is not duplicable in the digital world has enormous value.",author:"Eric Schmidt",channel:"dominant"},{text:"Bitcoin is a technological tour de force.",author:"Bill Gates",channel:"one-stop-shop"},{text:"I think the internet is going to be one of the major forces for reducing the role of government. The one thing that's missing, but that will soon be developed, is a reliable e-cash.",author:"Milton Friedman (1999)",channel:"videos"},{text:"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.",author:"Bitcoin Genesis Block",channel:"history"},{text:"Not your keys, not your coins.",author:"Bitcoin Proverb",channel:"self-custody"},{text:"Stay humble, stack sats.",author:"Bitcoin Community",channel:"investment-strategy"},{text:"In the long run, hard money is superior to soft money.",author:"Gigi, 21 Lessons",channel:"articles-threads"},{text:"Bitcoin is the first truly digital solution to the problem of money.",author:"Saifedean Ammous",channel:"books"},{text:"Fix the money, fix the world.",author:"Bitcoin Mantra",channel:"problems-of-money"},{text:"The supply of Bitcoin is limited. Period. No central bank is going to come along and print more.",author:"Andreas Antonopoulos",channel:"scarce"},{text:"Everyone is a scammer until proven otherwise. Don't trust, verify.",author:"Bitcoin Culture",channel:"secure"},{text:"Bitcoin makes money great again. It lets you transact freely, save freely, and live freely.",author:"Michael Saylor",channel:"giga-chad"},{text:"There is no second best.",author:"Michael Saylor",channel:"maximalism"},{text:"I don't think there's anything more important in my lifetime to work on.",author:"Jack Dorsey",channel:"giga-chad"},{text:"Bitcoin is the most important invention in the history of the world since the internet.",author:"Roger Ver (before he fell off)",channel:"history"},{text:"The computer can be used as a tool to liberate and protect people, rather than to control them.",author:"Hal Finney",channel:"cryptography"},{text:"One of the greatest things that Satoshi did was disappear.",author:"Gigi, 21 Lessons",channel:"satoshi-nakamoto"},{text:"Bitcoin has no CEO, no marketing department, no headquarters. It has math.",author:"Bitcoin Education Archive",channel:"decentralized"},{text:"We are all Satoshi.",author:"Bitcoin Community",channel:"satoshi-nakamoto"},{text:"Cypherpunks write code.",author:"Eric Hughes",channel:"cryptography"},{text:"Privacy is necessary for an open society in the electronic age.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Money is a tool for trading human time.",author:"Robert Breedlove",channel:"articles-threads"},{text:"Bitcoin is Time.",author:"Gigi",channel:"time"},{text:"The root cause of the housing crisis, student debt crisis, and healthcare crisis is the money crisis.",author:"Saifedean Ammous",channel:"problems-of-money"},{text:"Tick tock, next block.",author:"Bitcoin Community",channel:"blockchain-timechain"},{text:"The difficulty adjustment is the most elegant feature of Bitcoin.",author:"Bitcoin Educators",channel:"difficulty-adjustment"},{text:"Every informed person needs to know about Bitcoin because it might be one of the world's most important developments.",author:"Leon Luow",channel:"one-stop-shop"},{text:"Bitcoin is the only commodity in the world that the more demand there is, the more supply does NOT increase.",author:"Parker Lewis",channel:"scarce"},{text:"Gradually, then suddenly.",author:"Parker Lewis / Ernest Hemingway",channel:"articles-threads"},{text:"You can't stop an idea whose time has come.",author:"Victor Hugo (on Bitcoin)",channel:"organic"},{text:"Bitcoin is a hedge against the entire system.",author:"Lyn Alden",channel:"investment-strategy"},{text:"The question isn't what Bitcoin's price will be. The question is what the dollar's price will be.",author:"Bitcoiners",channel:"problems-of-money"},{text:"I was once told that nobody ever lost money saving in Bitcoin for 4+ years. I checked. It's true.",author:"Anonymous Bitcoiner",channel:"investment-strategy"},{text:"Bitcoin is the exit.",author:"Bitcoin Maximalists",channel:"maximalism"},{text:"Don't trust, verify.",author:"Bitcoin Ethos",channel:"nodes"},{text:"Number go up technology.",author:"Bitcoin Twitter",channel:"fun-facts"},{text:"Energy is the universal currency. Bitcoin makes that literal.",author:"Bitcoin Mining Community",channel:"energy"},{text:"Bitcoin is not an investment — it is a savings technology.",author:"Bitcoin Educators",channel:"money"},{text:"Fiat currency always returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Give me control of a nation's money supply, and I care not who makes its laws.",author:"Mayer Amschel Rothschild",channel:"problems-of-money"},{text:"Inflation is taxation without legislation.",author:"Milton Friedman",channel:"problems-of-money"},{text:"Bitcoin is for enemies. That's the whole point.",author:"Bitcoin Community",channel:"game_theory"},{text:"When you understand Bitcoin, you understand everything else differently.",author:"Many Bitcoiners",channel:"philosophy"},{text:"Bitcoin doesn't care about your feelings.",author:"Bitcoin Proverb",channel:"fun-facts"},{text:"Stack sats and stay humble.",author:"Matt Odell",channel:"investment-strategy"},{text:"Number go up because money printer go brr.",author:"Bitcoin Memes",channel:"memes-funny"},{text:"Those who would give up essential liberty, to purchase a little temporary safety, deserve neither liberty nor safety.",author:"Benjamin Franklin",channel:"human_rights__social_justice_and_freedo"},{text:"Freedom is never more than one generation away from extinction.",author:"Ronald Reagan",channel:"human_rights__social_justice_and_freedo"},{text:"The only way to deal with an unfree world is to become so absolutely free that your very existence is an act of rebellion.",author:"Albert Camus",channel:"philosophy"},{text:"If the American people ever allow private banks to control the issue of their currency, first by inflation, then by deflation, the banks and corporations that will grow up around them will deprive the people of all property.",author:"Thomas Jefferson",channel:"problems-of-money"},{text:"It is well enough that people of the nation do not understand our banking and monetary system, for if they did, I believe there would be a revolution before tomorrow morning.",author:"Henry Ford",channel:"problems-of-money"},{text:"The most dangerous man to any government is the man who is able to think things out for himself.",author:"H.L. Mencken",channel:"philosophy"},{text:"In a time of deceit, telling the truth is a revolutionary act.",author:"George Orwell",channel:"philosophy"},{text:"The urge to save humanity is almost always a false front for the urge to rule it.",author:"H.L. Mencken",channel:"philosophy"},{text:"A society that puts equality before freedom will get neither. A society that puts freedom before equality will get a high degree of both.",author:"Milton Friedman",channel:"philosophy"},{text:"The state is that great fiction by which everyone tries to live at the expense of everyone else.",author:"Frédéric Bastiat",channel:"austrian_school_of_economics"},{text:"There is no means of avoiding the final collapse of a boom brought about by credit expansion.",author:"Ludwig von Mises",channel:"austrian_school_of_economics"},{text:"The first panacea for a mismanaged nation is inflation of the currency; the second is war. Both bring a temporary prosperity; both bring a permanent ruin.",author:"Ernest Hemingway",channel:"problems-of-money"},{text:"Gold is money. Everything else is credit.",author:"J.P. Morgan",channel:"money"},{text:"We don't have a trillion-dollar debt because we haven't taxed enough; we have a trillion-dollar debt because we spend too much.",author:"Ronald Reagan",channel:"problems-of-money"},{text:"Government is the only institution that can take a valuable commodity like paper, and make it worthless by applying ink.",author:"Ludwig von Mises",channel:"problems-of-money"},{text:"Whenever destroyers appear among men, they start by destroying money.",author:"Ayn Rand",channel:"problems-of-money"},{text:"The way to crush the bourgeoisie is to grind them between the millstones of taxation and inflation.",author:"Vladimir Lenin",channel:"problems-of-money"},{text:"Savings represent goods produced but not yet consumed. That's what real wealth is — not digits in a bank database.",author:"Saifedean Ammous",channel:"money"},{text:"Civilization is in a race between education and catastrophe. Let us learn the truth and spread it as far and wide as our circumstances allow.",author:"H.G. Wells",channel:"one-stop-shop"},{text:"Paper money eventually returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Bitcoin is the separation of money and state.",author:"Bitcoin Community",channel:"maximalism"},{text:"Bitcoin is the first money in the history of the world where the supply is entirely unaffected by an increase in demand.",author:"Jeff Booth",channel:"scarce"},{text:"In a world where everything is printed, scarcity is the ultimate feature.",author:"Bitcoin Educators",channel:"scarce"},{text:"Bitcoin is hope for humanity.",author:"Jack Mallers",channel:"one-stop-shop"},{text:"The cost of Bitcoin is measured in electricity. The cost of fiat is measured in human freedom.",author:"Bitcoin Community",channel:"energy"},{text:"Your savings should not be someone else's liability.",author:"Bitcoin Educators",channel:"self-custody"},{text:"Bitcoin is the peaceful protest that cannot be silenced.",author:"Alex Gladstein",channel:"human_rights__social_justice_and_freedo"},{text:"Bitcoin gives us the ability to opt out of a system that was designed to extract value from us.",author:"Many Bitcoiners",channel:"problems-of-money"},{text:"Proof of work means proof of energy. Energy is the one thing that cannot be faked.",author:"Bitcoin Mining Community",channel:"mining"},{text:"The Bitcoin network processes more value per year than Visa. Without a CEO.",author:"Bitcoin Stats",channel:"decentralized"},{text:"If Bitcoin is a bubble, it's the only bubble that reflated itself five times in a row.",author:"Bitcoin Community",channel:"fun-facts"},{text:"Bitcoin has died 474 times according to the media. It's still here.",author:"Bitcoin Obituaries",channel:"misconceptions-fud"},{text:"Your grandchildren will ask you why you didn't buy Bitcoin when it was under six figures.",author:"Bitcoin Twitter",channel:"predictions"},{text:"The next 4 years are going to be very exciting for Bitcoin.",author:"Every Bitcoiner, Every Year",channel:"fun-facts"},{text:"Bitcoin isn't getting more expensive. Your dollars are getting cheaper.",author:"Bitcoin Community",channel:"problems-of-money"},{text:"If you can't hold it, you don't own it. If you didn't earn it, you'll lose it.",author:"Bitcoin Wisdom",channel:"self-custody"},{text:"Think in sats, not dollars.",author:"Bitcoin Community",channel:"sats__or__bits"},{text:"The best time to buy Bitcoin was 10 years ago. The second best time is now.",author:"Bitcoin Proverb",channel:"investment-strategy"},{text:"Work is the transfer of energy over time. Money should measure exactly that.",author:"Jason Lowery",channel:"energy"},{text:"Bitcoin is not anti-government. Bitcoin is anti-fraud.",author:"Bitcoin Educators",channel:"regulation"},{text:"We must defend our own privacy if we expect to have any.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Cryptography is the ultimate form of non-violent direct action.",author:"Julian Assange",channel:"cryptography"},{text:"Strong cryptography can resist an unlimited application of violence.",author:"Jacob Appelbaum",channel:"cryptography"},{text:"The Net interprets censorship as damage and routes around it.",author:"John Gilmore",channel:"privacy-nonkyc"},{text:"Bitcoin is a weapon of peace.",author:"Jason Lowery, Softwar",channel:"geopolitics___macroeconomics"},{text:"Running a node means nobody can change the rules on you.",author:"Bitcoin Node Runners",channel:"nodes"},{text:"Hashrate is the heartbeat of Bitcoin. As long as miners mine, Bitcoin lives.",author:"Bitcoin Mining Community",channel:"mining"},{text:"Lightning is what makes Bitcoin usable for 8 billion people.",author:"Lightning Network Community",channel:"layer-2-lightning"},{text:"2,099,999,997,690,000 satoshis. That's all there will ever be.",author:"The Bitcoin Protocol",channel:"scarce"},{text:"Code is speech. Math is law. Cryptography is defense.",author:"Cypherpunks",channel:"cryptography"},{text:"I predict the Internet will go spectacularly supernova and in 1996 catastrophically collapse.",author:"Robert Metcalfe (1995) — They said this about Bitcoin too",channel:"misconceptions-fud"},{text:"Every generation needs a new revolution.",author:"Thomas Jefferson",channel:"philosophy"},{text:"First they ignore you, then they laugh at you, then they fight you, then you win.",author:"Often attributed to Gandhi",channel:"organic"},{text:"I do not think there is any other quality so essential to success of any kind as the quality of perseverance.",author:"John D. Rockefeller",channel:"philosophy"},{text:"The world is a dangerous place, not because of those who do evil, but because of those who look on and do nothing.",author:"Albert Einstein",channel:"philosophy"},{text:"Hard times create strong men. Strong men create good times. Good times create weak men. Weak men create hard times.",author:"G. Michael Hopf",channel:"time_preference"},{text:"An investment in knowledge pays the best interest.",author:"Benjamin Franklin",channel:"one-stop-shop"}];window.renderDailyQuote=function(){var e=document.getElementById("quoteOfDay");if(e){var t=new Date,o=Math.floor((t-new Date(t.getFullYear(),0,0))/864e5),n=BITCOIN_QUOTES[o%BITCOIN_QUOTES.length];n&&(e.innerHTML="
    💬 Quote of the Day
    "'+n.text+'"
    — '+n.author+"
    ")}},window.renderReadNext=function(e){if(void 0===CHANNELS)return"";var t=CHANNELS[e];if(!t)return"";var o=Object.entries(CHANNELS).filter(function(o){return o[1].cat===t.cat&&o[0]!==e});if(0===o.length)return"";var n=o.sort(function(){return Math.random()-.5}).slice(0,3),i='
    📖 Read Next
    ';return n.forEach(function(e){var t=e[1].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}]+)/u),o=t?t[1]:"📄";i+=""}),i+="
    "},window.getNachoStoryProgress=function(){return parseInt(localStorage.getItem("btc_nacho_story_highest")||"0")},window.checkHiddenBadges=function(){if(void 0!==HIDDEN_BADGES&&window._hiddenBadgesReady){var e=safeJSON("btc_hidden_badges",[]),t=!1;HIDDEN_BADGES.forEach(function(o){if(-1===e.indexOf(o.id))try{if(o.check&&o.check()&&(e.push(o.id),t=!0,"function"==typeof showToast&&showToast(o.emoji+" Secret Badge: "+(o.revealName||o.name)+"! +"+o.pts+" XP"),"function"==typeof awardPoints&&awardPoints(o.pts,"Hidden Badge: "+(o.revealName||o.name)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:e})}catch(e){}}catch(e){}}),t&&localStorage.setItem("btc_hidden_badges",JSON.stringify(e))}},setInterval(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},3e4),setTimeout(function(){window._hiddenBadgesReady||(window._hiddenBadgesReady=!0)},2e4),window.awardHiddenBadge=function(e,t){var o=safeJSON("btc_hidden_badges",[]);if(-1===o.indexOf(e)&&(o.push(e),localStorage.setItem("btc_hidden_badges",JSON.stringify(o)),t&&"function"==typeof showToast&&showToast("🏅 "+t),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:o})}catch(e){}},window.awardOrangeTickets=function(e,t){void 0!==currentUser&¤tUser&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,currentUser._isLocal||"function"!=typeof awardPoints||awardPoints(0,"🎟️ "+(t||"Orange Tickets"),null,e));var o=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(o+e).toString()),"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Ticket"+(e>1?"s":"")+(t?" — "+t:""))},window.setFloatingElementsVisible=function(e){["floatingRandomBtn","lbFloatBtn","mobileSearchBtn","backToTop","scrollToBottom","chatOverlayBtn","aiToolsBtn","dashboardFloatBtn"].forEach(function(t){var o=document.getElementById(t);o&&(o.style.display=e?"":"none")})},window.showCelebration=function(e){var t=e.emoji||"🎉",o=e.title||"Achievement Unlocked!",n=e.message||"",i=e.rewards||[],a=e.btnText||"Amazing! 🎉",r=document.createElement("div");r.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",r.onclick=function(e){e.target===r&&(r.style.opacity="0",r.style.transition="opacity 0.4s",setTimeout(function(){r.remove()},400))};var s="";i.length>0&&(s='
    ',i.forEach(function(e){s+='
    +'+e.label+'
    '+e.sub+"
    "}),s+="
    "),r.innerHTML='
    '+t+'
    '+o+'
    '+n+"
    "+s+'
    ",document.body.appendChild(r),"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound(),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200)},setInterval(function(){["prop","tech"].forEach(function(e){var t="btc_scholar_"+e+"_passed",o="btc_scholar_"+e+"_celebrated";if("true"===localStorage.getItem(t)&&"true"!==localStorage.getItem(o)){localStorage.setItem(o,"true");var n="tech"===e;setTimeout(function(){showCelebration({emoji:n?"🛠️🎓🏆":"📖🎓🎉",title:n?"PROTOCOL EXPERT!":"BITCOIN SCHOLAR!",message:n?"You passed the Technical Protocol Expert Certification! You understand Bitcoin at the deepest level. True cypherpunk material! 🔐":"You passed the Bitcoin Scholar Certification! You have a thorough understanding of Bitcoin's properties and economics! 🧡",rewards:[{label:"2,100",sub:"PTS",color:"#22c55e"},{label:n?"🛠️":"🎓",sub:"BADGE",color:"#f7931a"}],btnText:n?"Protocol Expert! 🛠️":"Scholar! 🎓"})},500)}})},3e3),function(){var e=[{pct:25,key:"explore_25",emoji:"🗺️🌱",title:"25% EXPLORED!",msg:"A quarter of the archive explored! You're building a solid Bitcoin foundation.",pts:50,tickets:10},{pct:50,key:"explore_50",emoji:"🗺️🔥",title:"50% EXPLORED!",msg:"Halfway through the entire archive! You know more about Bitcoin than most people on Earth.",pts:100,tickets:25},{pct:75,key:"explore_75",emoji:"🗺️⚡",title:"75% EXPLORED!",msg:"Three quarters done! You're in the top tier of Bitcoin knowledge seekers.",pts:200,tickets:50},{pct:100,key:"explore_100",emoji:"🗺️👑🏆",title:"ARCHIVE COMPLETE!",msg:"You've explored EVERY SINGLE channel in the archive. You are a true Bitcoin scholar. Satoshi would be proud! 🧡",pts:500,tickets:100}];window._checkExplorationMilestones=function(){if(void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]),o=Object.keys(CHANNELS).length,n=Math.round(t.length/o*100);e.forEach(function(e){if(n>=e.pct&&"true"!==localStorage.getItem("btc_"+e.key+"_celebrated")){if(localStorage.setItem("btc_"+e.key+"_celebrated","true"),"function"==typeof awardPoints&&awardPoints(e.pts,"🗺️ "+e.pct+"% Explored"),"function"==typeof awardOrangeTickets)awardOrangeTickets(e.tickets,"🗺️ "+e.pct+"% Explored");else{var t=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(t+e.tickets).toString())}if(setTimeout(function(){showCelebration({emoji:e.emoji,title:e.title,message:e.msg,rewards:[{label:e.pts.toString(),sub:"PTS",color:"#22c55e"},{label:e.tickets.toString(),sub:"🎟️ TICKETS",color:"#f7931a"}]})},800),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o={};o["explorationMilestone_"+e.pct]=!0;try{db.collection("users").doc(auth.currentUser.uid).update(o).catch(function(){})}catch(e){}}}})}};var t=window.renderExplorationMap;window.renderExplorationMap=function(){t(),window._checkExplorationMilestones()}}(),function(){var e=window.showQuestFinalResults;e&&(window.showQuestFinalResults=function(){e.apply(this,arguments);var t=window._questScore||0;5===t?("function"==typeof showToast&&showToast("🏆 PERFECT SCORE! You nailed every question!"),"function"==typeof launchConfetti&&setTimeout(launchConfetti,300)):t>=3&&"function"==typeof showToast&&showToast("⚡ Quest passed! +"+(window._questPts||0)+" XP earned!")});var t=window.nachoQuizAnswer;t&&(window.nachoQuizAnswer=function(e,o){t.apply(this,arguments),o&&"function"==typeof haptic&&haptic("success")});var o=window.convoQuizAnswer;o&&(window.convoQuizAnswer=function(e,t){o.apply(this,arguments),t&&"function"==typeof haptic&&haptic("light")})}(),function(){window._scrollPositions={};var e=window.go;e&&(window.go=async function(t,o,n){var i=document.getElementById("main"),a=location.hash.slice(1);a&&i&&(window._scrollPositions[a]=i.scrollTop),await e(t,o,n),window._scrollPositions[t]&&i&&setTimeout(function(){i.scrollTop=window._scrollPositions[t]},100)}),window.haptic=function(e){if("visible"===document.visibilityState&&"false"!==localStorage.getItem("btc_haptic")&&navigator.vibrate)switch(e){case"light":navigator.vibrate(10);break;case"medium":navigator.vibrate(25);break;case"heavy":navigator.vibrate([30,50,30]);break;case"success":navigator.vibrate([15,30,15,30,15]);break;case"error":navigator.vibrate([50,30,50]);break;default:navigator.vibrate(15)}};var t=window.awardPoints;t&&(window.awardPoints=function(){return haptic("success"),t.apply(this,arguments)});var o=window.showLevelUpCelebration;o&&(window.showLevelUpCelebration=function(){return haptic("heavy"),o.apply(this,arguments)}),function(){var e=document.createElement("style");e.textContent="@keyframes slideInRight{from{transform:translateX(30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInLeft{from{transform:translateX(-30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInUp{from{transform:translateY(20px);opacity:0}to{transform:translateY(0);opacity:1}}.page-transition-right{animation:slideInRight 0.25s ease-out;}.page-transition-left{animation:slideInLeft 0.25s ease-out;}.page-transition-up{animation:slideInUp 0.2s ease-out;}",document.head.appendChild(e);var t=document.getElementById("main");t&&new MutationObserver(function(){var e=document.getElementById("hero");e&&e.innerHTML&&(e.classList.remove("page-transition-right"),e.offsetWidth,e.classList.add("page-transition-right"))}).observe(document.getElementById("hero")||t,{childList:!0})}();var n=0;document.addEventListener("touchend",function(e){var t=Date.now();if(t-n<300){var o=e.target.closest&&e.target.closest('[onclick*="forumViewPost"]');if(o){var i=o.querySelector('[onclick*="forumVotePost"]');i&&(i.click(),haptic("medium")),e.preventDefault()}}n=t},{passive:!1});var i=(new Date).toISOString().split("T")[0];function a(e){return localStorage.getItem(e+"_"+i)||null}function r(e,t){localStorage.setItem(e+"_"+i,t)}function s(e){return parseInt(a(e)||"0",10)}function l(e){var t=s(e)+1;return r(e,String(t)),t}var c,d=[{id:"read",text:"📖 Read a new channel",check:function(){return"true"===a("btc_new_channel_read")}},{id:"nacho",text:"🦌 Ask Nacho a question",check:function(){return s("btc_nacho_asked")>0}},{id:"quiz",text:"🎮 Complete a quiz question",check:function(){return"true"===a("btc_quiz_done")}},{id:"explore",text:"🗺️ Visit 3 different channels",check:function(){return s("btc_channels_today")>=3}},{id:"forum",text:"🗣️ Visit the PlebTalk",check:function(){return"true"===a("btc_forum_visited")}},{id:"streak",text:"🔥 Log in to keep your streak",check:function(){return!0}},{id:"favorite",text:"⭐ Save a channel to favorites",check:function(){return"true"===a("btc_fav_added")}},{id:"tctv_10m",text:"📺 Watch 10 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=10}},{id:"tctv_visit",text:"📺 Tune in to Timechain TV",check:function(){return"true"===a("btc_tctv_visited")}},{id:"tctv_3ch",text:"📺 Watch 3 different TCTV stations",check:function(){try{var e=a("btc_tctv_stations_visited");return!!e&&JSON.parse(e).length>=3}catch(e){return!1}}},{id:"tctv_30m",text:"📺 Watch 30 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=30}},{id:"tip_send",text:"⚡ Send a Lightning tip to someone",check:function(){return"true"===a("btc_tip_sent")}},{id:"tip_3",text:"⚡ Send 3 Lightning tips today",check:function(){return s("btc_tips_sent_count")>=3}},{id:"ln_setup",text:"⚡ Set up your Lightning wallet",check:function(){return!!(localStorage.getItem("btc_nwc_url")||localStorage.getItem("btc_ln_address")||void 0!==currentUser&¤tUser&¤tUser.lightningAddress)}},{id:"chat_msg",text:"🌍 Send a message in Global Chat",check:function(){return"true"===a("btc_chat_sent")}},{id:"pvp_battle",text:"⚔️ Complete a PVP trivia battle",check:function(){return"true"===a("btc_pvp_done")}},{id:"beats_listen",text:"🎸 Listen to a track on Bitcoin Beats",check:function(){return"true"===a("btc_beats_played")}},{id:"explore_5",text:"🗺️ Explore 5 different channels today",check:function(){return s("btc_channels_today")>=5}},{id:"nacho_3",text:"🦌 Ask Nacho 3 questions",check:function(){return s("btc_nacho_asked")>=3}}];function u(){var e=(new Date).toISOString().split("T")[0],t=Math.floor(new Date(e).getTime()/864e5);return d[t%d.length]}function p(){var e=u(),t=(new Date).toISOString().split("T")[0],o=localStorage.getItem("btc_challenge_done")===t,n=document.getElementById("dailyChallengeCard");n&&(o?(n.style.borderColor="#22c55e",n.style.background="rgba(34,197,94,0.05)",n.innerHTML='
    Today\'s Challenge ✔️
    '+e.text+" — Done! +100 XP 🎉
    "):(n.style.borderColor="var(--border)",n.style.background="var(--card-bg)",n.innerHTML='
    🎯
    Today\'s Challenge
    '+e.text+"
    "))}if(window.checkDailyChallenge=function(){var e=(new Date).toISOString().split("T")[0];if(localStorage.getItem("btc_challenge_done")!==e&&u().check()){localStorage.setItem("btc_challenge_done",e),"function"==typeof awardPoints&&awardPoints(100,"🎯 Daily challenge!"),"function"==typeof awardOrangeTickets&&awardOrangeTickets(5,"🎯 Daily challenge!"),"function"==typeof showToast&&showToast("🎯 Daily challenge complete! +100 XP + 🎟️ 5 tickets!"),haptic("success"),p();var t=document.getElementById("dailyChallengeCard");t&&(t.style.transition="transform 0.3s, box-shadow 0.3s",t.style.transform="scale(1.03)",t.style.boxShadow="0 0 20px rgba(34,197,94,0.4)",setTimeout(function(){t.style.transform="",t.style.boxShadow=""},1500))}},setInterval(window.checkDailyChallenge,3e3),window._raidHomeUnsub=null,window._raidHomeTimer=null,window.renderRaidBossHome=function(){var e=document.getElementById("raidBossHomeCard");e&&("undefined"!=typeof firebase&&void 0!==db?(window._raidHomeUnsub&&(window._raidHomeUnsub(),window._raidHomeUnsub=null),window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),window._raidHomeUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.style.display="none";else{var o=Date.now(),n=null,i=null,a=null;t.forEach(function(e){var t=e.data();t.id=e.id;var r=t.startTime&&t.startTime.toDate?t.startTime.toDate().getTime():0,s=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime&&i.startTime.toDate?i.startTime.toDate().getTime():0))&&(i=t):t.defeated&&(a||(a=t))}),function(e,t,o,n){if(window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),t||o||n){e.style.display="";var i="if(typeof showQuestHub==='function'){showQuestHub();setTimeout(function(){if(typeof window._questHubTab!=='undefined'){window._questHubTab='raid';if(typeof _renderQuestHubTab==='function')_renderQuestHubTab();}},300)}",a="";if(t){var r=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0,s=t.target>0?Math.min(100,Math.round((t.current||0)/t.target*100)):0,l=Math.max(0,(t.target||0)-(t.current||0)),c=Math.max(0,100-s),d=c<=25?"#ef4444":c<=50?"#f59e0b":"#22c55e",u=t.image||"";if(!u){var p={"Channel-Crawler":"channel-crawler","Quiz-Crusader":"quiz-crusader","TV-Titan":"tv-titan","Beats-Baron":"beats-baron","Flash-Flash":"flash-flash","XP-Hoarder":"xp-hoarder","Poll-Patroller":"poll-patroller","Chat-Charger":"chat-charger","Badge-Builder":"badge-builder","Streak-Sage":"streak-sage","Topic-Explorer":"topic-explorer","Lightning-Lancer":"lightning-lancer","Forum-Forge":"forum-forge","Trivia-Tactician":"trivia-tactician","Content-Conqueror":"content-conqueror"};p[t.name]&&(u="images/raid-bosses/"+p[t.name]+".png")}a+='
    '+(u?'':'⚔️')+'
    ⚔️ CURRENT RAID BOSS
    '+(t.name||"Raid Boss")+'
    ❤️ '+l+"/"+t.target+' HP⏱ '+g(r)+'
    ',window._raidActiveEndMs=r}if(o){var m=o.startTime&&o.startTime.toDate?o.startTime.toDate().getTime():0,h=new Date(m).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"});a+='
    ⚔️
    NEXT BOSS
    '+(o.name||"TBD")+" — "+h+'
    Starts in '+g(m)+'
    ',window._raidUpcomingStartMs=m}n&&!t&&(a='
    💀
    🎉 BOSS DEFEATED!
    '+("function"==typeof escapeHtml?escapeHtml(n.name||"Raid Boss"):n.name||"Raid Boss")+' has fallen!
    🏆 Orange ticket drawing this Friday!
    '+a),e.innerHTML=a,window._raidHomeTimer=setInterval(function(){var e=document.getElementById("raidHomeCountdown");e&&window._raidActiveEndMs&&(e.textContent="⏱ "+g(window._raidActiveEndMs));var t=document.getElementById("raidHomeUpcomingCountdown");t&&window._raidUpcomingStartMs&&(t.textContent="Starts in "+g(window._raidUpcomingStartMs)),e||t||(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null)},1e3)}else e.style.display="none";function g(e){var t=Math.max(0,e-Date.now());if(t<=0)return"⏳ Any moment now...";var o=Math.floor(t/864e5),n=Math.floor(t%864e5/36e5),i=Math.floor(t%36e5/6e4),a=Math.floor(t%6e4/1e3);return o>0?o+"d "+n+"h "+i+"m":n>0?n+"h "+i+"m "+a+"s":i+"m "+a+"s"}}(e,n,i,a)}},function(){e.style.display="none"})):e.style.display="none")},c="",window._trackChallengeNav=function(e){e&&e!==c&&(c=e,"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e||r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},500))},window.go){var m=window.go;window.go=async function(e){var t=!1;e&&"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e&&(t=-1===safeJSON("btc_visited_channels",[]).indexOf(e));var o=await m.apply(this,arguments);return"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e),e&&"forum"!==e&&(l("btc_channels_today"),t&&r("btc_new_channel_read","true")),"forum"===e&&r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},300),o}}var h=window.nachoUnifiedAnswer;h&&(window.nachoUnifiedAnswer=function(e,t){return l("btc_nacho_asked"),h.apply(this,arguments)}),window.addEventListener("hashchange",function(){var e=location.hash.slice(1);e&&"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e)}),window.renderProgressRings=function(){var e=document.getElementById("progressRings");if(e){var t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=0;void 0!==currentUser&¤tUser&&(currentUser.readChannels&¤tUser.readChannels.length?o=currentUser.readChannels.length:currentUser.channelsVisited&&(o=currentUser.channelsVisited)),0===o&&(o=safeJSON("btc_visited_channels",[]).length);var n=void 0!==currentUser&¤tUser&¤tUser.streak||0,i=void 0!==currentUser&¤tUser&¤tUser.points||0,a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.innerHTML='
    '+r(Math.min(100,o/t*100),"#f7931a","Channels",o+"/"+t)+r(Math.min(100,5*n),"#22c55e","Streak","🔥"+n)+r(Math.min(100,i/21e3*100),"#8B5CF6","XP",i>999?Math.floor(i/1e3)+"k":i)+r(Math.min(100,2*a),"#3B82F6","Nacho",a)+"
    "}function r(e,t,o,n){var i=2*Math.PI*32;return'
    '+n+'
    '+o+"
    "}};var g=null;function f(){console.log("[MobileUX] Initializing..."),function(){var e=document.createElement("div");e.id="bottomNav",e.className="mobile-nav",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:200000;background:rgba(10,10,10,0.95);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border-top:1px solid rgba(255,255,255,0.1);padding:10px 0 env(safe-area-inset-bottom,10px) 0;padding-bottom:max(env(safe-area-inset-bottom,10px),10px);display:none;transition:transform 0.25s ease;-webkit-transform:translateZ(0);transform:translateZ(0);",e.innerHTML='
    ';var t=document.createElement("style");t.textContent=".bnav-btn{background:none;border:none;color:var(--text-dim,#666);font-size:0.6rem;cursor:pointer;font-family:inherit;padding:6px 0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;touch-action:manipulation;-webkit-tap-highlight-color:transparent;transition:0.2s;flex:1;min-width:0;}.bnav-icon{font-size:1.3rem;line-height:1;display:block;transition:transform 0.2s;}.bnav-label{font-size:0.55rem;line-height:1;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;}.bnav-btn:active .bnav-icon{transform:scale(1.2);}.bnav-btn.active{color:var(--accent);}@media(min-width:901px){#bottomNav{display:none!important;}}@media(max-width:900px){#bottomNav{display:block!important;visibility:visible!important;opacity:1!important;}.messages{padding-bottom:140px!important;}.home-page{padding-bottom:100px!important;}}",document.head.appendChild(t),document.body.appendChild(e)}(),function(){var e=document.getElementById("main");if(e){var t=0,o=document.getElementById("bottomNav");o&&e.addEventListener("scroll",function(){if(!(window.innerWidth>900)){var n=e.scrollTop,i=n-t;i>10&&n>200?o.classList.add("nav-hidden"):(i<-5||n<=10)&&o.classList.remove("nav-hidden"),t=n}},{passive:!0})}}(),setTimeout(function(){!function(){var e=0;if(void 0!==currentUser&¤tUser&&(e=currentUser.streak||0),!(e<2||document.getElementById("streakBanner"))){var t=document.createElement("div");t.id="streakBanner",t.style.cssText="position:fixed;top:32px;left:0;right:0;z-index:300;background:linear-gradient(135deg,#f7931a,#ea580c);color:#fff;padding:10px 16px;text-align:center;font-size:0.85rem;font-weight:700;cursor:pointer;animation:slideInUp 0.3s;",t.innerHTML="🔥 Day "+e+' streak! Keep it alive! tap to dismiss',t.onclick=function(){t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.remove()},300)},document.body.appendChild(t),setTimeout(function(){t.parentNode&&(t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.parentNode&&t.remove()},300))},5e3)}}(),function(){if("function"==typeof forceShowBubble&&!sessionStorage.getItem("btc_welcomed_back")){sessionStorage.setItem("btc_welcomed_back","true");var e="";void 0!==currentUser&¤tUser&¤tUser.username&&(e=currentUser.username);var t,o=void 0!==currentUser&¤tUser&¤tUser.streak||0,n=(new Date).getHours(),i=n<12?"Morning":n<17?"Afternoon":"Evening",a=u();t=e&&o>=2?"Good "+i.toLowerCase()+", "+e+"! ☀️ Day "+o+" streak — you're on fire! 🔥 Today's challenge: "+a.text:e?"Hey "+e+"! 🦌 Welcome back! Today's challenge: "+a.text:"Welcome back! 🦌 Today's challenge: "+a.text,setTimeout(function(){forceShowBubble(t)},3e3)}}(),p(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof renderProgressRings&&renderProgressRings()},2500)}window.addEventListener("beforeinstallprompt",function(e){if(e.preventDefault(),g=e,!window.matchMedia("(display-mode: standalone)").matches){var t=localStorage.getItem("btc_pwa_dismissed");if(t&&Date.now()-parseInt(t)<6048e5)return;window._pwaLoadTime=Date.now(),window._pwaCheckInterval=setInterval(function(){if(!(Date.now()-(window._pwaLoadTime||Date.now())<9e4)){var e=[];try{e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}e.length>=3&&(clearInterval(window._pwaCheckInterval),function(){if(!document.getElementById("pwaInstallBanner")){var e=document.createElement("div");if(e.id="pwaInstallBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Install Bitcoin Education
    Add to home screen for the best experience — works offline!
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}}())}},1e4)}}),window.installPWA=function(){g&&(g.prompt(),g.userChoice.then(function(e){"accepted"===e.outcome&&"function"==typeof showToast&&showToast("🦌 Welcome aboard! App installed!"),g=null})),dismissPWABanner()},window.dismissPWABanner=function(){var e=document.getElementById("pwaInstallBanner");e&&e.remove(),localStorage.setItem("btc_pwa_dismissed",Date.now().toString())},function(){var e=/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,t=/Safari/.test(navigator.userAgent)&&!/CriOS|FxiOS|Chrome/.test(navigator.userAgent),o=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(e&&t&&!o){var n=localStorage.getItem("btc_ios_a2hs_dismissed");n&&Date.now()-parseInt(n)<2592e6||setTimeout(function(){if(!document.getElementById("iosA2HSBanner")){var e=document.createElement("div");if(e.id="iosA2HSBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Add to Home Screen
    For the best experience, add this app to your home screen:
    1. Tap the Share button ⬆️ at the bottom
    2. Scroll down and tap Add to Home Screen
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}},12e4)}}(),window.dismissIOSA2HS=function(){var e=document.getElementById("iosA2HSBanner");e&&e.remove(),localStorage.setItem("btc_ios_a2hs_dismissed",Date.now().toString())},window.toggleMobileLearnMenu=function(){var e=document.getElementById("mobileLearnMenu");if(e)e.remove();else{var t=document.getElementById("appsMenu");t&&t.remove();var o=document.createElement("div");o.id="mobileLearnMenu",o.style.cssText="position:fixed;bottom:70px;left:8px;right:8px;z-index:250;max-width:400px;margin:0 auto;background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:18px;box-shadow:0 -8px 40px rgba(0,0,0,0.6);animation:fadeSlideIn 0.25s ease-out;",o.innerHTML='

    🎓 Learn

    ',document.body.appendChild(o),setTimeout(function(){document.addEventListener("click",function e(t){var o=document.getElementById("mobileLearnMenu");!o||o.contains(t.target)||t.target.closest("#bnavLearn")||(o.remove(),document.removeEventListener("click",e))})},100)}},window.toggleMobileFlashcards=function(){var e=document.getElementById("mLearnFlashGrid"),t=document.getElementById("mLearnFlashBtn");e&&("none"===e.style.display?(e.style.display="flex",t&&(t.textContent="📚 Flashcards ▼")):(e.style.display="none",t&&(t.textContent="📚 Flashcards ▶")))},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",f):f()}(),function(){"use strict";var e=null,t=null,o=null,n=null;function i(){if(!(e&&e.readyState<=1))try{(e=new WebSocket("wss://ws.coincap.io/prices?assets=bitcoin")).onopen=function(){console.log("[Dashboard] Price WebSocket connected (CoinCap)"),window._wsDataTimer=setTimeout(function(){t||(console.warn("[Dashboard] WS connected but no data — falling back"),r())},1e4)},e.onmessage=function(e){try{window._wsDataTimer&&(clearTimeout(window._wsDataTimer),window._wsDataTimer=null);var i=JSON.parse(e.data);if(!i.bitcoin)return;var a=parseFloat(i.bitcoin);!n&&t&&(n=t),t=a,n&&(o=(t-n)/n*100),n=parseFloat(i.o);var r=document.getElementById("dashLivePrice");r&&(r.textContent="$"+p(t,2));var s=document.getElementById("dashLiveChange");if(s){var l=o>=0?"#22c55e":"#ef4444",c=o>=0?"▲":"▼";s.innerHTML=''+c+" "+Math.abs(o).toFixed(2)+"% (24h)"}var d=document.getElementById("dashBtnPrice");if(d){var u=o>=0?"#22c55e":"#ef4444",m=o>=0?"▲":"▼";d.innerHTML="$"+p(t,0)+' '+m+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}catch(e){}},e.onclose=function(){console.log("[Dashboard] WS closed, reconnecting..."),e=null,setTimeout(i,5e3)},e.onerror=function(t){console.warn("[Dashboard] WS error, falling back to polling");try{e.close()}catch(e){}e=null,r()}}catch(e){r()}}var a=null;function r(){function e(){fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true").then(function(e){return e.json()}).then(function(e){if(e&&e.bitcoin){t=e.bitcoin.usd,o=e.bitcoin.usd_24h_change||0;var n=document.getElementById("dashLivePrice");n&&(n.textContent="$"+p(t,2));var i=document.getElementById("dashLiveChange");if(i){var a=o>=0?"#22c55e":"#ef4444",r=o>=0?"▲":"▼";i.innerHTML=''+r+" "+Math.abs(o).toFixed(2)+"% (24h)"}var s=document.getElementById("dashBtnPrice");if(s){var l=o>=0?"#22c55e":"#ef4444",c=o>=0?"▲":"▼";s.innerHTML="$"+p(t,0)+' '+c+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}}).catch(function(){})}a||(console.log("[Dashboard] Starting price polling fallback (CoinGecko)"),e(),a=setInterval(e,3e4))}var s="btc_dashboard_cache",l=12e4,c=null,d=!1,u=null;function p(e,t){return null==e?"—":"number"==typeof t?Number(e).toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t}):Number(e).toLocaleString()}function m(e){return null==e?"—":e>=1e12?"$"+(e/1e12).toFixed(1)+"T":e>=1e9?"$"+(e/1e9).toFixed(1)+"B":e>=1e6?"$"+(e/1e6).toFixed(1)+"M":e>=1e3?"$"+(e/1e3).toFixed(0)+"K":"$"+Math.round(e)}function h(e){return null==e?"—":e>=1e12?(e/1e12).toFixed(2)+" T":e>=1e9?(e/1e9).toFixed(2)+" B":p(e)}async function g(){if(d)return await new Promise(function(e){var t=setInterval(function(){d||(clearInterval(t),e())},200);setTimeout(function(){clearInterval(t),d=!1,e()},1e4)}),c||{};d=!0;var e=null;try{var i=JSON.parse(localStorage.getItem(s));if(i&&i.data&&(e=i.data,Date.now()-i.tse.text()).then(e=>{a.blockHeight=parseInt(e);try{localStorage.setItem("btc_last_height",a.blockHeight.toString())}catch(e){}var t=document.getElementById("btcDashCard");t&&!a.price&&a.blockHeight&&(t.innerHTML=f(a))}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/fees/recommended").then(e=>e.json()).then(e=>{a.feeFast=e.fastestFee,a.feeHalf=e.halfHourFee,a.feeHour=e.hourFee,a.feeEcon=e.economyFee,a.feeMin=e.minimumFee}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/mining/hashrate/1m").then(e=>e.json()).then(e=>{if(e.currentHashrate&&(a.hashrate=e.currentHashrate),e.currentDifficulty&&(a.difficulty=e.currentDifficulty),e.hashrates&&e.hashrates.length>=6){var t=e.hashrates.length,o=(e.hashrates[t-1].avgHashrate+e.hashrates[t-2].avgHashrate+e.hashrates[t-3].avgHashrate)/3,n=(e.hashrates[t-4].avgHashrate+e.hashrates[t-5].avgHashrate+e.hashrates[t-6].avgHashrate)/3;n>0&&(a.hashrateChange24h=(o-n)/n*100)}}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/difficulty-adjustment").then(e=>e.json()).then(e=>{a.diffChange=e.difficultyChange,a.diffEstDate=e.estimatedRetargetDate,a.diffRemaining=e.remainingBlocks,a.diffProgress=e.progressPercent}).catch(()=>{})),r.push(fetch("https://mempool.space/api/mempool").then(e=>e.json()).then(e=>{a.mempoolTxs=e.count,a.mempoolSize=e.vsize}).catch(()=>{})),r.push(fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true&include_24hr_vol=true&include_market_cap=true").then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{if(e.bitcoin){a.price=e.bitcoin.usd;try{localStorage.setItem("btc_last_price",e.bitcoin.usd.toString())}catch(e){}a.change24h=e.bitcoin.usd_24h_change,a.volume24h=e.bitcoin.usd_24h_vol,a.marketCap=e.bitcoin.usd_market_cap,!n&&a.price&&a.change24h&&(n=a.price/(1+a.change24h/100),o=a.change24h)}var t=document.getElementById("btcDashCard");return t&&a.price&&(t.innerHTML=f(a)),new Promise(function(e){setTimeout(e,1500)})}).then(function(){return fetch("https://api.coingecko.com/api/v3/coins/bitcoin?localization=false&tickers=false&community_data=false&developer_data=false")}).then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{e.market_data&&(a.supply=e.market_data.circulating_supply,a.ath=e.market_data.ath?e.market_data.ath.usd:null,a.athDate=e.market_data.ath_date?e.market_data.ath_date.usd:null,a.athChange=e.market_data.ath_change_percentage?e.market_data.ath_change_percentage.usd:null,a.high24h=e.market_data.high_24h?e.market_data.high_24h.usd:null,a.low24h=e.market_data.low_24h?e.market_data.low_24h.usd:null,a.mktCapChange24h=e.market_data.market_cap_change_percentage_24h||null)}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/lightning/statistics/latest").then(e=>e.json()).then(e=>{e&&(a.lnCapacity=e.latest?e.latest.total_capacity:e.total_capacity,a.lnNodes=e.latest?e.latest.node_count:e.node_count,a.lnChannels=e.latest?e.latest.channel_count:e.channel_count)}).catch(()=>{})),r.push(fetch("https://api.alternative.me/fng/?limit=1").then(e=>e.json()).then(e=>{e.data&&e.data[0]&&(a.fearGreed=parseInt(e.data[0].value),a.fearGreedLabel=e.data[0].value_classification)}).catch(()=>{})),await Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,12e3))]),!a.price&&t&&(a.price=t);for(var u=[s,"btc_dash_backup"],p=0;p'+(r<=2?"Live metrics · Updates every 2 min":"📦 Data from "+(r<60?r+"m":Math.round(r/60)+"h")+" ago · Refreshing...")+"",a+='',a+="";var s=t||n.price,l=null!==o?o:n.change24h||0,c=l>=0?"#22c55e":"#ef4444",d=l>=0?"▲":"▼";if(a+='
    ',a+='
    $'+p(s,2)+"
    ",a+='
    '+d+" "+Math.abs(l).toFixed(2)+"%
    ",a+='
    🔴 Live — updates automatically · All % changes are 24h
    ',a+='
    ',a+='24h High: $'+p(n.high24h,0)+"",a+='24h Low: $'+p(n.low24h,0)+"",a+="
    ",a+="
    ",void 0!==n.halvingDays){var u=n.halving?((21e4-n.halving)/21e4*100).toFixed(1):0,m=n.halvingEta?n.halvingEta.toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"}):"—";a+='
    ',a+='
    ⏳ Next Halving — Block #'+p(n.halvingBlock)+'
    ',window._halvingTargetMs=Date.now()+10*n.halving*60*1e3,a+='
    ',a+='
    '+(n.halvingDays||0)+'
    Days
    ',a+='
    :
    ',a+='
    '+(n.halvingHours||0)+'
    Hours
    ',a+='
    :
    ',a+='
    '+(n.halvingMins||0)+'
    Mins
    ',a+='
    :
    ',a+='
    00
    Secs
    ',a+="
    ",a+='
    Est. '+m+" · "+p(n.halving)+" blocks remaining
    ",a+='
    ',a+='
    ',a+="
    ",a+='
    '+u+"% through epoch · Subsidy drops "+n.subsidy+" → "+(n.nextSubsidy||"?")+" BTC
    ",a+="
    "}a+='
    ',a+=y("⚡","Sats per Dollar",p(n.satsPerDollar),"Moscow Time","How many satoshis (sats) you get for $1 USD. A satoshi is the smallest unit of Bitcoin (0.00000001 BTC). Also called Moscow Time — the number on the clock is how many sats per dollar."),a+=y("⛓️","Block Height",p(n.blockHeight),"","The total number of blocks mined since Bitcoin's Genesis Block on Jan 3, 2009. A new block is added roughly every 10 minutes. This number only goes up — never down."),a+=y("🪙","Block Subsidy",n.subsidy+" BTC",p(n.halving)+" blocks to halving","The reward miners receive for finding each new block. Started at 50 BTC in 2009 and halves every 210,000 blocks (~4 years). Currently 3.125 BTC per block.");var g,f="";if(null!=n.hashrateChange24h){var b=n.hashrateChange24h;f=''+(b>=0?"▲":"▼")+" "+Math.abs(b).toFixed(1)+"%"}a+=y("⛏️","Hashrate",null==(g=n.hashrate)?"—":g>=1e18?(g/1e18).toFixed(2)+" EH/s":g>=1e15?(g/1e15).toFixed(2)+" PH/s":g>=1e12?(g/1e12).toFixed(2)+" TH/s":g>=1e9?(g/1e9).toFixed(2)+" GH/s":g>=1e6?(g/1e6).toFixed(2)+" M":g>=1e3?(g/1e3).toFixed(1)+"K":p(g),f,"The total computing power securing the Bitcoin network, measured in hashes per second. Higher hashrate = more secure network. EH/s = quintillion hashes per second."),a+=y("🎯","Difficulty",h(n.difficulty),"","How hard it is to mine a new block. Adjusts every 2,016 blocks (~2 weeks) to keep block times at ~10 minutes. If miners join, difficulty goes up. If miners leave, it goes down."),a+=y("🔄","Next Adjustment",(n.diffChange>=0?"+":"")+(n.diffChange||0).toFixed(2)+"%",i+" · "+p(n.diffRemaining)+" blocks","The estimated change in mining difficulty at the next adjustment. Positive means blocks are being found faster than 10 min (more miners joined). Negative means slower (miners left)."),a+=y("💸","Fast Fee",(n.feeFast||"—")+" sat/vB","Half-hour: "+(n.feeHalf||"—")+" · Economy: "+(n.feeEcon||"—"),"The recommended transaction fee in satoshis per virtual byte (sat/vB). Fast = next block (~10 min). Half-hour = 1-3 blocks. Economy = lowest priority. Higher fees = faster confirmation."),a+=y("📋","Mempool",p(n.mempoolTxs)+" txs",n.mempoolSize?(n.mempoolSize/1e6).toFixed(1)+" MvB":"","The waiting room for unconfirmed Bitcoin transactions. Shows how many transactions are waiting to be included in a block and their total size. A full mempool means higher fees."),a+=y("💰","Circulating Supply",function(e){return e?(e/1e6).toFixed(2)+"M / 21M":"—"}(n.supply),function(e){return e?(e/21e6*100).toFixed(2)+"%":"—"}(n.supply)+" mined","How many of the 21 million total Bitcoin have been mined so far. No more than 21 million will ever exist — this is enforced by code and consensus. The last Bitcoin will be mined around the year 2140.");var v="";if(null!=n.mktCapChange24h){var w=n.mktCapChange24h;v=''+(w>=0?"▲":"▼")+" "+Math.abs(w).toFixed(1)+"%"}a+=y("📊","Market Cap","$"+h(n.marketCap),v,"Total value of all Bitcoin in circulation (price × circulating supply). Puts Bitcoin's size in perspective compared to gold (~$16T), the S&P 500, or global real estate.");var x="";n.volume24h&&n.marketCap&&(x="Vol/MCap: "+(n.volume24h/n.marketCap*100).toFixed(2)+"%"),a+=y("📈","24h Volume","$"+h(n.volume24h),x,"Total USD value of Bitcoin traded across all exchanges in the last 24 hours. High volume often signals strong market interest or significant price moves.");var k=n.lnCapacity?(n.lnCapacity/1e8).toFixed(0):"—",T=n.lnCapacity&&n.price?"$"+h(n.lnCapacity/1e8*n.price):"",E=(n.lnNodes?p(n.lnNodes)+" nodes · ":"")+(n.lnChannels?p(n.lnChannels)+" channels":"")+(T?"
    "+T:"");a+=y("⚡","Lightning Capacity",p(k)+" BTC",E,"Total Bitcoin locked in Lightning Network payment channels. Lightning enables instant, near-free Bitcoin payments. More capacity = more liquidity for fast payments. Nodes route payments; channels connect them."),n.ath&&(a+='
    ',a+='🏔️',a+='
    All-Time High
    ',a+='
    $'+p(n.ath,0)+"
    ",a+='
    '+(n.athChange||0).toFixed(1)+"%
    ",n.athDate&&(a+='
    '+new Date(n.athDate).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})+"
    "),a+="
    "),a+="
    ";var A=n.marketCap?n.marketCap/1e12:0;return a+='
    ',a+='
    ⚖️ Bitcoin vs Gold
    ',a+='
    ',a+='
    ₿ Bitcoin$'+A.toFixed(2)+"T
    ",a+='
    ',a+='
    🥇 GoldLoading...
    ',a+='
    Fetching live gold price...
    ',a+="
    ",setTimeout(function(){!function(e,t){if(!B)try{var o=JSON.parse(localStorage.getItem("btc_gold_cache"));o&&o.p&&(B=o.p,S=o.t||0)}catch(e){}B&&Date.now()-S<18e5?_(B,e,t):(B&&_(B,e,t),fetch("https://api.coingecko.com/api/v3/simple/price?ids=tether-gold&vs_currencies=usd").then(function(e){return e.json()}).then(function(o){var n=o["tether-gold"]?o["tether-gold"].usd:null;if(n){B=n,S=Date.now();try{localStorage.setItem("btc_gold_cache",JSON.stringify({p:n,t:Date.now()}))}catch(e){}_(n,e,t)}}).catch(function(){B||_(3200,e,t)}))}(A,n.supply||0)},150),a+='
    ',a+='
    🏛️ Bitcoin Treasuries ⓘ tap for top holders
    ',a+='
    Loading live treasury data...
    ',a+="
    ",setTimeout(function(){!function(e){var t=document.getElementById("treasuryData");if(t){if(!I)try{var o=JSON.parse(localStorage.getItem("btc_treasury_cache"));o&&o.d&&(I=o.d,C=o.t||0)}catch(e){}I&&Date.now()-C<18e5?z(t,I,e):(I&&z(t,I,e),fetch("https://api.coingecko.com/api/v3/companies/public_treasury/bitcoin").then(function(e){return e.json()}).then(function(o){I=o,C=Date.now();try{localStorage.setItem("btc_treasury_cache",JSON.stringify({d:o,t:Date.now()}))}catch(e){}z(t,o,e)}).catch(function(){I||(t.innerHTML='
    Could not load treasury data
    ')}))}}(n.price||0)},200),a+='
    ',a+='
    🏦 Bitcoin ETFs top 5 by BTC in custody
    ',a+='
    Loading ETF holdings...
    ',a+="
    ",setTimeout(function(){!function(e,t){var o=document.getElementById("etfHoldingsData");if(o){var n=e||parseFloat(localStorage.getItem("btc_last_price"))||83e3,i=t||1984e4,a=null;try{a=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"))}catch(e){}a&&a.holdings&&L(o,a.holdings,a.totalBtc,n,i,a.updated),fetch("data/etf-holdings.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.holdings&&e.holdings.length){try{localStorage.setItem("btc_etf_holdings_cache",JSON.stringify(e))}catch(e){}L(o,e.holdings,e.totalBtc,n,i,e.updated)}}).catch(function(){a||L(o,M,P,n,i,null)})}}(n.price||0,n.supply||0)},250),a+='
    ',a+='',a+='
    ",a+='
    ',a+="Data Sources: ",a+='mempool.space (blocks, fees, hashrate, difficulty, mempool) · ',a+='CoinGecko (price, market cap, supply, volume) · ',a+='Alternative.me (Fear & Greed Index) · ',a+='BitcoinTreasuries.net (company & government holdings)',a+='
    Last updated: '+new Date(n.ts||Date.now()).toLocaleTimeString()+"
    ",a+="
    ",setTimeout(function(){window._halvingTargetMs&&document.getElementById("halvSecs")&&"function"==typeof window._startHalvingTicker&&window._startHalvingTicker(),"function"==typeof window._attachTipListeners&&window._attachTipListeners()},100),a}function y(e,t,o,n,i){return"
    '+e+" "+t+(i?' ':"")+'
    '+(o||"—")+"
    "+(n?'
    '+n+"
    ":"")+""}setInterval(function(){d&&(console.warn("[Dashboard] Force-clearing stuck loading flag"),d=!1)},15e3);var b="ontouchstart"in window||navigator.maxTouchPoints>0;function v(){injectDashboardButton(),injectHomeDashboardButton(),i()}window.showDashTip=function(e,t){var o=document.getElementById("dashTipPopup");o&&o.remove();var n=document.createElement("div");n.id="dashTipPopup",n.style.cssText="position:absolute;left:50%;transform:translateX(-50%);bottom:calc(100% + 8px);z-index:10;background:var(--bg-side,#1a1a2e);border:1px solid var(--accent);border-radius:10px;padding:10px 14px;max-width:320px;width:max-content;box-shadow:0 8px 24px rgba(0,0,0,0.5);animation:fadeSlideIn 0.2s ease-out;pointer-events:auto;",n.innerHTML='
    '+t.replace(/\\n/g,"
    ").replace(/\n/g,"
    ")+'
    ',e.style.position="relative",e.appendChild(n),setTimeout(function(){document.addEventListener("click",function e(t){n.parentNode&&n.remove(),document.removeEventListener("click",e)},{once:!0})},50)},window.hideDashTip=function(e){var t=e?e.querySelector("#dashTipPopup"):document.getElementById("dashTipPopup");t&&t.remove()},window._attachTipListeners=function(){document.querySelectorAll("[data-dash-tip]:not([data-tip-bound])").forEach(function(e){e.setAttribute("data-tip-bound","1");var t=e.getAttribute("data-dash-tip");t&&(b?e.addEventListener("click",function(o){o.stopPropagation();var n=e.querySelector("#dashTipPopup");n?n.remove():showDashTip(e,t)}):(e.addEventListener("mouseenter",function(){showDashTip(e,t)}),e.addEventListener("mouseleave",function(){hideDashTip(e)})))})},window.injectDashboardButton=function(){},window.injectHomeDashboardButton=function(){},window.toggleDashboard=async function(){var e=document.getElementById("btcDashOverlay");if(e)return e.remove(),clearInterval(u),void(u=null);var t=document.createElement("div");t.id="btcDashOverlay",t.style.cssText="position:fixed;inset:0;z-index:10002;background:rgba(0,0,0,0.88);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&closeDashboard()};var o=document.createElement("div");o.id="btcDashCard",o.style.cssText="background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:24px;max-width:500px;width:100%;margin:40px auto;box-shadow:0 20px 60px rgba(0,0,0,0.5);animation:fadeSlideIn 0.3s ease-out;",t.appendChild(o),document.body.appendChild(t),i();var n=!1;try{var a=JSON.parse(localStorage.getItem(s));a&&a.data&&(a.data.price||a.data.blockHeight)&&(o.innerHTML=f(a.data),n=!0)}catch(e){}if(!n){var r={};if("undefined"!=typeof nachoLiveData&&(nachoLiveData.price&&(r.price=nachoLiveData.price),nachoLiveData.blockHeight&&(r.blockHeight=nachoLiveData.blockHeight)),!r.price)try{r.price=parseFloat(localStorage.getItem("btc_last_price"))||0}catch(e){}if(!r.blockHeight)try{r.blockHeight=parseInt(localStorage.getItem("btc_last_height"))||0}catch(e){}r.price||r.blockHeight?(o.innerHTML=f(r),n=!0):o.innerHTML='
    Loading Bitcoin metrics...
    '}g().then(function(e){var t=document.getElementById("btcDashCard");if(t){var o=document.getElementById("topIndicatorsPanel"),i=o&&"none"!==o.style.display;if(e&&(e.price||e.blockHeight)?t.innerHTML=f(e):n||(t.innerHTML='
    📊
    Unable to load fresh metrics.
    Showing last known data. Try again later.
    '),i){var a=document.getElementById("topIndicatorsPanel"),r=document.getElementById("topIndArrow");a&&(a.style.display="block",w=!1,k()),r&&(r.textContent="▲")}}}),u=setInterval(async function(){if(document.getElementById("btcDashOverlay")){var e=document.getElementById("topIndicatorsPanel"),t=e&&"none"!==e.style.display;localStorage.removeItem(s);var o=await g(),n=document.getElementById("btcDashCard");if(n&&(n.innerHTML=f(o),t)){var i=document.getElementById("topIndicatorsPanel"),a=document.getElementById("topIndArrow");i&&(i.style.display="block",w=!1,k()),a&&(a.textContent="▲")}}else clearInterval(u)},l)},window.closeDashboard=function(){var e=document.getElementById("btcDashOverlay");e&&e.remove(),u&&(clearInterval(u),u=null)},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(v,2e3)}):setTimeout(v,2e3),window.toggleTopIndicators=function(){var e=document.getElementById("topIndicatorsPanel"),t=document.getElementById("topIndArrow");e&&("none"===e.style.display?(e.style.display="block",t.textContent="▲",k()):(e.style.display="none",t.textContent="▼"))};var w=!1,x="btc_top_indicators_cache";function k(){if(!w){w=!0;var e=document.getElementById("topIndContent");if(e){try{var t=JSON.parse(localStorage.getItem(x));if(t&&t.html){var o=Math.round((Date.now()-t.ts)/6e4),n=o>5?'
    📦 Cached '+(o<60?o+"m":Math.round(o/60)+"h")+" ago · refreshing...
    ":"";e.innerHTML=n+t.html}}catch(e){}var i=c||{},a=i.price||0,r=i.blockHeight||0,s=i.supply||0,l=i.fearGreed||0,d=i.fearGreedLabel||"—",u=[];if(r){var m=Math.floor(r/21e4),h=50/Math.pow(2,m)*6*24*365,g=h>0?(s||198e5)/h:0,f=Math.pow(10,3.31954*Math.log10(g)-1.32093),y=a>0?(a/f).toFixed(2):"—";u.push({emoji:"📈",name:"Stock-to-Flow",value:g.toFixed(1),sub:"Model: $"+p(Math.round(f))+" · Ratio: "+y+"x",tip:"Stock-to-Flow measures scarcity. Higher S2F = scarcer asset. Bitcoin's S2F increases with each halving. Gold is ~62, Silver ~22. A ratio below 1x suggests undervalued vs the model."})}if(l){var b=l<=25?"#ef4444":l<=45?"#f97316":l<=55?"#eab308":l<=75?"#84cc16":"#22c55e";u.push({emoji:"😱",name:"Fear & Greed",value:l,color:b,sub:d,tip:"Crypto Fear & Greed Index. 0 = Extreme Fear (potential buy), 100 = Extreme Greed (potential sell). Aggregates volatility, momentum, social media, and surveys."})}if(u.push({emoji:"📐",name:"Mayer Multiple",value:"...",sub:"Loading...",tip:"Price divided by 200-day moving average. Below 1.0 = historically cheap. Above 2.4 = overheated. Named after Trace Mayer.",id:"mayerMultiple"}),r){var v=r%21e4,k=(v/21e4*100).toFixed(1),B=Math.round(10*v/1440),S=B>=365&&B<=730;u.push({emoji:"🔄",name:"Halving Cycle",value:k+"%",sub:"Day "+B+"/~1460"+(S?" · 🔥 Peak Window":""),color:S?"#f97316":null,tip:"Position in the current 4-year halving cycle (210,000 blocks). Historically, price peaks occur 12-24 months after a halving (Day 365-730). We are at day "+B+"."})}if(i.ath&&i.athDate){var T=new Date(i.athDate),_=Math.floor((Date.now()-T.getTime())/864e5),I=i.athChange?Math.abs(i.athChange).toFixed(1):"—";u.push({emoji:"🏔️",name:"ATH Drawdown",value:"-"+I+"%",sub:_+" days since ATH ($"+p(Math.round(i.ath))+")",tip:"Current drawdown from the all-time high. In previous cycles, bear markets saw -70% to -85% drawdowns. Recovery to new ATH has always followed."})}if(a&&s&&r){m=Math.floor(r/21e4);for(var C=0,E=r,A=0;A<=m&&E>0;A++){var z=Math.min(E,21e4);C+=z*(50/Math.pow(2,A)),E-=z}var M=3e4*C,L=M>0?(a*s/M).toFixed(1):"—";u.push({emoji:"🌡️",name:"Thermo Multiple",value:L+"x",sub:"Market Cap / Thermocap",tip:'Thermocap Multiple compares market cap to total miner revenue (a proxy for "energy spent"). Values >5x historically signal overheating (cycle tops hit 4-8x). <10x = accumulation zone.'})}if(a&&s&&i.volume24h){var U=a*s,q=i.volume24h>0?(U/i.volume24h).toFixed(1):"—",N=q<30?"#22c55e":q>150?"#ef4444":"var(--heading)";u.push({emoji:"📡",name:"NVT Ratio",value:q,color:N,sub:q<30?"Undervalued zone":q>150?"Overvalued zone":"Normal range",tip:"Network Value to Transactions ratio. Compares market cap to annualized transaction volume. Below 30 = undervalued relative to usage. Above 150 = potentially overvalued. Think of it like P/E ratio for Bitcoin."})}if(i.marketCap){var H=i.marketCap/.62;(i.marketCap/H*100).toFixed(1),u.push({emoji:"👑",name:"BTC Dominance",value:"~62%",sub:"Market cap share vs all crypto",tip:"Bitcoin's share of the total cryptocurrency market cap. Higher dominance = Bitcoin is outperforming alts. During alt seasons, dominance drops below 40%. During Bitcoin seasons (now), it rises above 55-65%. Historically, increasing dominance signals strength.",id:"btcDominance"})}if(u.push({emoji:"💎",name:"MVRV Z-Score",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Market Value to Realized Value ratio. Compares market cap to realized cap (sum of each coin valued at its last move price). Above 3.0 historically marks cycle tops. Below 1.0 marks bottoms. Data from CBBI open-source API. Top threshold: normalized ≥ 0.7 (≈ MVRV 3+).",id:"mvrvScore"}),a){var D=new Date("2009-01-03T00:00:00Z"),O=Math.floor((Date.now()-D.getTime())/864e5),W=5.82*Math.log10(O)-17.01,R=Math.pow(10,W),j=((a-R)/R*100).toFixed(0),F=parseFloat(j),G=F>200?"#ef4444":F>100?"#f97316":F<-30?"#22c55e":"var(--heading)",V=F>200,Q=F>200?"Far above — extreme ⚠️":F>100?"Above trend — elevated":F>0?"Above fair value":F>-30?"Near fair value":"Below trend — deep value 🟢";u.push({emoji:"📏",name:"Power Law",value:(F>=0?"+":"")+j+"%",color:G,sub:"Fair value: ~$"+p(Math.round(R))+" · "+Q,tip:"Bitcoin Power Law model tracks the long-term price trend using a log-log regression since genesis (Jan 3, 2009). Parameters: P = 10^(5.82 × log₁₀(days) - 17.01). Above +200% = historically extreme (cycle top zone). Below -30% = deep value accumulation. Current: "+O+" days since genesis.",flashing:V})}if(u.push({emoji:"🔵",name:"Pi Cycle Top",value:"...",sub:"Loading...",tip:"When the 111-day MA crosses above the 350-day MA × 2, it has historically signaled the exact top of every Bitcoin cycle. Flashes when the gap narrows to <5%.",id:"piCycleTop",flashing:!1}),r&&a){var J=(144*(i.subsidy?parseFloat(i.subsidy):3.125)*a/27e6).toFixed(2),Y=parseFloat(J);u.push({emoji:"⛏️",name:"Puell Multiple",value:J,color:Y>2.2?"#ef4444":Y<.5?"#22c55e":"var(--heading)",sub:Y>2.2?"Miners overleveraged ⚠️":Y<.5?"Miner capitulation zone 🟢":"Normal range",tip:"Ratio of daily miner revenue to its 365-day moving average. Above 2.2 = miners are earning far more than usual (historically a sell signal). Below 0.5 = miner capitulation (buy signal). Top threshold: ≥ 2.2.",flashing:Y>=2.2})}if(a){for(var X=new Date("2010-07-18"),K=Math.floor((Date.now()-X.getTime())/864e5),$=Math.log(K+1400),Z=[2.775,2.788,2.801,2.815,2.8295,2.8445,2.859,2.872,2.886,2.9],ee=10,te=0;te=9})}if(a){for(var ae=new Date("2009-01-03T00:00:00Z"),re=Math.floor((Date.now()-ae.getTime())/864e5),se=0,le=0;le<1460;le++){var ce=re-le;ce>365&&(se+=Math.pow(10,5.82*Math.log10(ce)-17.01))}var de=se/1460,ue=de>0?(a/de).toFixed(2):"—",pe=parseFloat(ue);u.push({emoji:"📊",name:"4-Year MA Multiple",value:ue+"x",color:pe>=3.5?"#ef4444":pe<1?"#22c55e":"var(--heading)",sub:"Est. 4Y MA: ~$"+p(Math.round(de))+(pe>=3.5?" · Top zone ⚠️":""),tip:"Price divided by the 4-year (1460-day) moving average. Historically, when price exceeds 3.5× the 4-year MA, it signals a cycle top. Below 1× = accumulation zone. Top threshold: ≥ 3.5.",flashing:pe>=3.5})}if(u.push({emoji:"💰",name:"NUPL",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Net Unrealized Profit/Loss. Shows aggregate profit/loss of all Bitcoin holders. Above 75% = euphoria (top zone). Below 0% = capitulation (bottom zone). Data from CBBI open-source API. Top threshold: normalized ≥ 0.75.",id:"nuplScore"}),a&&r){var me=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),he=Math.pow(10,5.82*Math.log10(me)-17.01),ge=he>0?(a/he).toFixed(2):"—",fe=parseFloat(ge);u.push({emoji:"🔢",name:"AHR999",value:ge,color:fe>1.2?"#ef4444":fe<.45?"#22c55e":"var(--heading)",sub:fe>1.2?"Overvalued — stop DCA ⚠️":fe<.45?"Deep value — DCA zone 🟢":fe<1?"Below model — DCA":"Near model",tip:"AHR999 compares current price to its long-term model value. Below 0.45 = extreme buy (accumulate aggressively). Above 1.2 = stop DCA, consider selling. Used by cost-averaging investors to time entries. Top threshold: ≥ 1.2.",flashing:fe>=1.2})}if(a){for(var ye=new Date("2009-01-03T00:00:00Z"),be=Math.floor((Date.now()-ye.getTime())/864e5),ve=0,we=0;we<730;we++){var xe=be-we;xe>365&&(ve+=Math.pow(10,5.82*Math.log10(xe)-17.01))}var ke=ve/730,Be=5*ke,Se=a>Be;u.push({emoji:"📉",name:"2-Year MA ×5",value:(a/ke).toFixed(2)+"x",color:Se?"#ef4444":a365&&(Ie+=Math.pow(10,5.82*Math.log10(Ee)-17.01))}var Ae=Ie/350,ze=Ae>0?(a/Ae).toFixed(2):"—",Me=parseFloat(ze),Pe=Me>=8?"Above ×8 — max top ⚠️":Me>=5?"Above ×5 — overheated":Me>=3?"Above ×3 — elevated":Me>=1.6?"Above ×1.6 — bullish":"Below ×1.6";u.push({emoji:"🔱",name:"Golden Ratio",value:ze+"x",color:Me>=5?"#ef4444":Me>=3?"#f97316":"var(--heading)",sub:"350d MA: $"+p(Math.round(Ae))+" · "+Pe,tip:"Price relative to the 350-day MA using Fibonacci golden ratio multiples (1.6, 2, 3, 5, 8, 13, 21). Each cycle top has touched a lower multiple. Top threshold: ≥ 5×.",flashing:Me>=5})}if(r&&s&&a){for(var Le=0,Ue=r,qe=0;qe<=Math.floor(r/21e4)&&Ue>0;qe++){var Ne=Math.min(Ue,21e4);Le+=Ne*(50/Math.pow(2,qe)),Ue-=Ne}var He=21*(s>0?3e4*Le/s:0),De=He>0?(a/He*100).toFixed(0):"—";u.push({emoji:"🎯",name:"Terminal Price",value:"$"+p(Math.round(He)),color:a>=He?"#ef4444":"var(--heading)",sub:"Current: "+De+"% of terminal · "+(a>=He?"ABOVE — extreme ⚠️":"Below terminal"),tip:"Terminal Price = Transferred Price × 21. Represents a theoretical maximum based on cumulative miner revenue and coin movement. Every cycle top has approached or exceeded this level. Top threshold: price ≥ Terminal Price.",flashing:a>=He})}if(a){var Oe=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),We=Math.pow(10,5.82*Math.log10(Oe)-17.01),Re=(We>0?(Math.log10(a)-Math.log10(We))/.3:0).toFixed(1),je=parseFloat(Re);u.push({emoji:"🫧",name:"Bubble Index",value:Re+"σ",color:je>=2?"#ef4444":je>=1?"#f97316":je<-1?"#22c55e":"var(--heading)",sub:je>=2?"Extreme bubble ⚠️":je>=1?"Elevated":je<-1?"Deep discount 🟢":"Normal",tip:"How many standard deviations Bitcoin's price is above its long-term log trend. Above +2σ = extreme bubble territory (historical tops). Below -1σ = deep value. Top threshold: ≥ 2σ.",flashing:je>=2})}if(a){var Fe=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),Ge=Math.pow(10,5.82*Math.log10(Fe-90)-17.01),Ve=(Ge>0?100*(Math.pow(a/Ge,4)-1):0).toFixed(0),Qe=parseFloat(Ve);u.push({emoji:"🚀",name:"3M Annualized",value:(Qe>=0?"+":"")+Ve+"%",color:Qe>200?"#ef4444":Qe>100?"#f97316":"var(--heading)",sub:Qe>200?"Unsustainable — top risk ⚠️":Qe>100?"Very high":"Normal",tip:"3-month return annualized. When Bitcoin is gaining over 200% annualized, it historically signals the late stages of a bull run. Top threshold: > 200%.",flashing:Qe>200,id:"ann3m"})}if(a){var Je=75694,Ye=762099,Xe=((a-Je)/Je*100).toFixed(1);u.push({emoji:"🏢",name:"MSTR Avg Cost",value:"$"+p(Je),sub:p(Ye)+" BTC · P&L: "+(Xe>=0?"+":"")+Xe+"%",tip:"MicroStrategy (MSTR) average Bitcoin acquisition cost. When price is far above MSTR's cost basis, it indicates broader market euphoria. MSTR holds "+p(Ye)+" BTC. Informational — no top threshold.",flashing:!1,noFlashLogic:!0})}if(u.push({emoji:"🎯",name:"CBBI Index",value:"...",color:"var(--heading)",sub:"Loading CBBI data...",tip:"Colin Talks Crypto Bitcoin Bull Run Index. Combines 9 on-chain metrics into a single 0-100 confidence score. Above 80 = approaching cycle top. Below 20 = approaching bottom. Open source. Top threshold: ≥ 80.",id:"cbbiScore"}),u.push({emoji:"💎",name:"RHODL Ratio",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Realized HODL Ratio. Compares 1-week realized value to 1-2 year realized value, adjusted by market age. High values = speculative activity dominating (top signal). Low values = long-term holders dominating. Top threshold: normalized ≥ 0.85.",id:"rhodlRatio"}),u.push({emoji:"📊",name:"Macro Oscillator",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Bitcoin Macro Oscillator (Woobull). Composite z-score of MVRV, VWAP, CVDD, and Sharpe ratios. Above 0.7 = euphoria zone. Below 0.2 = accumulation zone. Top threshold: normalized ≥ 0.7.",id:"macroOsc"}),a){var Ke=23e4,$e=(a/Ke*100).toFixed(1);u.push({emoji:"🔮",name:"Smithson's Forecast",value:$e+"%",color:parseFloat($e)>=90?"#ef4444":"var(--heading)",sub:"Target: $"+p(175e3)+"-$"+p(Ke)+" · Current: $"+p(Math.round(a)),tip:"Sminston With quantile regression model (99th percentile). Forecasts cycle top at $175K-$230K. Progress shows how close current price is to the upper target. Top threshold: ≥ 90% of target.",flashing:parseFloat($e)>=90})}u.push({emoji:"⏳",name:"LTH/STH Ratio",value:"...",color:"var(--heading)",sub:"Estimated from CBBI data...",tip:"Long-Term Holder to Short-Term Holder supply ratio (estimated). When LTH supply drops sharply (distributing to STH), it signals late-cycle selling. When LTH supply grows, holders are accumulating. Derived from CBBI on-chain metrics. Top threshold: CBBI MVRV + Puell both > 0.7.",id:"lthSthRatio"}),u.push({emoji:"📉",name:"RSI-22 Day",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Relative Strength Index over 22 days. Above 80 = overbought (potential top signal). Below 30 = oversold (potential bottom). 22-day RSI smooths out short-term noise. Top threshold: ≥ 80.",id:"rsi22d"}),u.push({emoji:"🚨",name:"AHR999x",value:"...",color:"var(--heading)",sub:"Loading 200d MA...",tip:"AHR999x Escape Top indicator. Calculated as (price / 200-day MA)². When above 8, signals extreme overvaluation. Above 3.5 = elevated. A complement to the AHR999 DCA indicator. Top threshold: ≥ 8.",id:"ahr999x"}),u.push({emoji:"🏦",name:"ETF/BTC Ratio",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Bitcoin spot ETF total AUM divided by BTC market cap. Shows how much of Bitcoin's value is held in ETFs. High ratios (>8%) could indicate institutional overexposure. Low ratios = room to grow. Top threshold: ≥ 8%.",id:"etfBtcRatio"}),u.push({emoji:"📊",name:"ETF Net Flow",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Daily Bitcoin spot ETF net inflows/outflows. Sustained outflows (7+ days) can signal institutional selling. Sustained inflows signal demand. Data from Bitbo/BitcoinTreasuries. Top threshold: 7+ consecutive outflow days.",flashing:!1,id:"etfNetFlow"}),u.push({emoji:"📈",name:"ETF 5-Day Flow",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Sum of last 5 trading days of ETF flows. Large negative = sustained selling pressure. Large positive = accumulation. Top threshold: 5-day sum below -$500M.",flashing:!1,id:"etf5dFlow"}),u.forEach(function(e){if(!e.noFlashLogic&&void 0===e.flashing){var t=e.name;e.flashing="Stock-to-Flow"===t?a>0&&f>0&&a>1.5*f:"Fear & Greed"===t?l>=75:"Mayer Multiple"!==t&&("Halving Cycle"===t?e.sub&&-1!==e.sub.indexOf("Peak Window"):"ATH Drawdown"===t?parseFloat(e.value)>-5:"Thermo Multiple"===t?parseFloat(e.value)>5:"NVT Ratio"===t&&parseFloat(e.value)>150)}});var Ze=u.filter(function(e){return e.flashing}).length,et=u.filter(function(e){return!e.noFlashLogic}).length,tt="",ot=et>0?Math.round(Ze/et*100):0,nt=0===Ze?"#22c55e":ot<15?"#eab308":ot<40?"#f97316":"#ef4444";tt+='
    ',tt+='
    '+Ze+" / "+et+"
    ",tt+='
    '+(0===Ze?"No top signals — Accumulate 🟢":ot<15?"Few signals — Monitor 🟡":ot<40?"Multiple signals — Caution 🟠":"Many signals — Extreme caution 🔴")+"
    ",tt+='
    Top indicators flashing 🔴 = potential cycle top signal
    ',tt+="
    ",u.forEach(function(e){var t=e.flashing?"rgba(239,68,68,0.5)":"var(--border)",o=e.flashing?"background:rgba(239,68,68,0.04);":"";tt+="",e.noFlashLogic||(e.flashing?tt+='
    🔴 TOP
    ':tt+='
    🟢 OK
    '),tt+='
    '+e.emoji+" "+e.name+(e.tip?' ':"")+"
    ",tt+='
    '+(e.value||"—")+"
    ",e.sub&&(tt+='
    '+e.sub+"
    "),tt+=""}),tt+='',e.innerHTML=tt,setTimeout(function(){"function"==typeof window._attachTipListeners&&window._attachTipListeners()},50);try{localStorage.setItem(x,JSON.stringify({html:tt,ts:Date.now()}))}catch(e){}fetch("https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=365&interval=daily").then(function(e){return e.json()}).then(function(e){if(e&&e.prices&&e.prices.length>=200){for(var t=e.prices,o=t.length,n=0,i=Math.max(0,o-200);i2.4?"#ef4444":"var(--heading)";l.style.color=c,l.textContent=s+"x";var d=l.nextElementSibling;d&&(d.textContent="200d MA: $"+p(Math.round(a))+(s<1?" · Below MA ✅":s>2.4?" · Overheated ⚠️":""));var u=l.closest('div[style*="border-radius:12px"]');if(u&&s>2.4){u.style.borderColor="rgba(239,68,68,0.5)",u.style.background="rgba(239,68,68,0.04)";var m=u.querySelector('div[style*="OK"]');m&&(m.innerHTML="🔴 TOP",m.style.color="#ef4444",m.style.background="rgba(239,68,68,0.15)",m.style.borderColor="rgba(239,68,68,0.4)")}}if(o>=111){for(var h=0,g=o-111;g0?((f-w)/w*100).toFixed(1):0,k=parseFloat(x),B=document.getElementById("piCycleTop");if(B){var S=k>=0;B.textContent=(k>=0?"+":"")+x+"%",B.style.color=S?"#ef4444":k>-5?"#f97316":"var(--heading)";var T=B.nextElementSibling;T&&(T.textContent="111d: $"+p(Math.round(f))+" vs 350d×2: $"+p(Math.round(w))+(S?" · CROSSED ⚠️":k>-5?" · Narrowing!":""));var _=B.closest('div[style*="border-radius:12px"]');if(_&&S){_.style.borderColor="rgba(239,68,68,0.5)",_.style.background="rgba(239,68,68,0.04)";var I=_.querySelector('div[style*="OK"]');I&&(I.innerHTML="🔴 TOP",I.style.color="#ef4444",I.style.background="rgba(239,68,68,0.15)",I.style.borderColor="rgba(239,68,68,0.4)")}}}if(o>=23){for(var C=0,E=0,A=o-22;A0?C+=z:E-=z}var M=E/22,P=0===M?100:100-100/(1+C/22/M),L=P.toFixed(1),U=document.getElementById("rsi22d");if(U){var q=P>=80;U.textContent=L,U.style.color=P>=80?"#ef4444":P<=30?"#22c55e":"var(--heading)";var N=U.nextElementSibling;if(N&&(N.textContent=P>=80?"Overbought ⚠️":P<=30?"Oversold ✅":P>=60?"Bullish":P<=40?"Bearish":"Neutral"),q){var H=U.closest('div[style*="border-radius:12px"]');if(H){H.style.borderColor="rgba(239,68,68,0.5)",H.style.background="rgba(239,68,68,0.04)";var D=H.querySelector('div[style*="OK"]');D&&(D.innerHTML="🔴 TOP",D.style.color="#ef4444",D.style.background="rgba(239,68,68,0.15)",D.style.borderColor="rgba(239,68,68,0.4)")}}}}var O=Math.pow(r/a,2).toFixed(2),W=document.getElementById("ahr999x");if(W){var R=parseFloat(O),j=R>=8;W.textContent=O,W.style.color=R>=8?"#ef4444":R>=3.5?"#f97316":"var(--heading)";var F=W.nextElementSibling;if(F&&(F.textContent="200d MA: $"+p(Math.round(a))+(R>=8?" · Extreme top ⚠️":R>=3.5?" · Elevated":R<1?" · Below MA":" · Normal")),j){var G=W.closest('div[style*="border-radius:12px"]');if(G){G.style.borderColor="rgba(239,68,68,0.5)",G.style.background="rgba(239,68,68,0.04)";var V=G.querySelector('div[style*="OK"]');V&&(V.innerHTML="🔴 TOP",V.style.color="#ef4444",V.style.background="rgba(239,68,68,0.15)",V.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("mayerMultiple");e&&(e.textContent="N/A")}),fetch("https://api.coingecko.com/api/v3/global").then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.market_cap_percentage&&e.data.market_cap_percentage.btc){var t=e.data.market_cap_percentage.btc.toFixed(1),o=document.getElementById("btcDominance");if(o){o.textContent=t+"%";var n=t>55?"#22c55e":t<40?"#ef4444":"var(--heading)";o.style.color=n;var i=o.nextElementSibling;i&&(i.textContent=t>55?"Bitcoin season 👑":t<40?"Alt season ⚠️":"Neutral")}}}).catch(function(){}),fetch("https://colintalkscrypto.com/cbbi/data/latest.json").then(function(e){return e.json()}).then(function(e){if(e&&e.Confidence){var t=Object.keys(e.Confidence).sort(),o=t[t.length-1],n=(100*e.Confidence[o]).toFixed(0),i=parseInt(n),a=document.getElementById("cbbiScore");if(a){a.textContent=n+"%",a.style.color=i>=80?"#ef4444":i<=20?"#22c55e":"var(--heading)";var r=a.nextElementSibling;if(r&&(r.textContent=i>=80?"Approaching top ⚠️":i<=20?"Approaching bottom 🟢":i>=50?"Mid-cycle bullish":"Early cycle"),i>=80){var s=a.closest('div[style*="border-radius:12px"]');if(s){s.style.borderColor="rgba(239,68,68,0.5)",s.style.background="rgba(239,68,68,0.04)";var l=s.querySelector('div[style*="OK"]');l&&(l.innerHTML="🔴 TOP",l.style.color="#ef4444",l.style.background="rgba(239,68,68,0.15)",l.style.borderColor="rgba(239,68,68,0.4)")}}}var c=Object.keys(e.RHODL).sort(),d=e.RHODL[c[c.length-1]],u=document.getElementById("rhodlRatio");if(u){u.textContent=(100*d).toFixed(0)+"%",u.style.color=d>=.85?"#ef4444":d<=.2?"#22c55e":"var(--heading)";var p=u.nextElementSibling;if(p&&(p.textContent=d>=.85?"Speculative frenzy ⚠️":d<=.2?"Accumulation zone 🟢":"Normalized: "+(100*d).toFixed(0)+"%"),d>=.85){var m=u.closest('div[style*="border-radius:12px"]');if(m){m.style.borderColor="rgba(239,68,68,0.5)",m.style.background="rgba(239,68,68,0.04)";var h=m.querySelector('div[style*="OK"]');h&&(h.innerHTML="🔴 TOP",h.style.color="#ef4444",h.style.background="rgba(239,68,68,0.15)",h.style.borderColor="rgba(239,68,68,0.4)")}}}var g=Object.keys(e.Woobull).sort(),f=e.Woobull[g[g.length-1]],y=document.getElementById("macroOsc");if(y){y.textContent=(100*f).toFixed(0)+"%",y.style.color=f>=.7?"#ef4444":f<=.2?"#22c55e":"var(--heading)";var b=y.nextElementSibling;if(b&&(b.textContent=f>=.7?"Euphoria zone ⚠️":f<=.2?"Accumulation 🟢":"Normalized: "+(100*f).toFixed(0)+"%"),f>=.7){var v=y.closest('div[style*="border-radius:12px"]');if(v){v.style.borderColor="rgba(239,68,68,0.5)",v.style.background="rgba(239,68,68,0.04)";var w=v.querySelector('div[style*="OK"]');w&&(w.innerHTML="🔴 TOP",w.style.color="#ef4444",w.style.background="rgba(239,68,68,0.15)",w.style.borderColor="rgba(239,68,68,0.4)")}}}var x=Object.keys(e.MVRV).sort(),k=Object.keys(e.Puell).sort(),B=e.MVRV[x[x.length-1]],S=e.Puell[k[k.length-1]],T=document.getElementById("lthSthRatio");if(T){var _=((B+S)/2*100).toFixed(0),I=parseInt(_);T.textContent=I+"%",T.style.color=I>=70?"#ef4444":I<=25?"#22c55e":"var(--heading)";var C=T.nextElementSibling;if(C&&(C.textContent=I>=70?"LTH distributing ⚠️":I<=25?"LTH accumulating 🟢":"Distribution score: "+I+"%"),I>=70){var E=T.closest('div[style*="border-radius:12px"]');if(E){E.style.borderColor="rgba(239,68,68,0.5)",E.style.background="rgba(239,68,68,0.04)";var A=E.querySelector('div[style*="OK"]');A&&(A.innerHTML="🔴 TOP",A.style.color="#ef4444",A.style.background="rgba(239,68,68,0.15)",A.style.borderColor="rgba(239,68,68,0.4)")}}}var z=document.getElementById("mvrvScore");if(z){var M=(100*B).toFixed(0);z.textContent=M+"%",z.style.color=B>=.7?"#ef4444":B<=.2?"#22c55e":"var(--heading)";var P=z.nextElementSibling;if(P&&(P.textContent=B>=.7?"Overvalued — top zone ⚠️":B<=.2?"Undervalued — accumulate 🟢":"Normalized: "+M+"%"),B>=.7){var L=z.closest('div[style*="border-radius:12px"]');if(L){L.style.borderColor="rgba(239,68,68,0.5)",L.style.background="rgba(239,68,68,0.04)";var U=L.querySelector('div[style*="OK"]');U&&(U.innerHTML="🔴 TOP",U.style.color="#ef4444",U.style.background="rgba(239,68,68,0.15)",U.style.borderColor="rgba(239,68,68,0.4)")}}}var q=Object.keys(e.RUPL).sort(),N=e.RUPL[q[q.length-1]],H=document.getElementById("nuplScore");if(H){var D=(100*N).toFixed(0);H.textContent=D+"%",H.style.color=N>=.75?"#ef4444":N<=.2?"#22c55e":"var(--heading)";var O=H.nextElementSibling;if(O&&(O.textContent=N>=.75?"Euphoria ⚠️":N<=.2?"Capitulation zone 🟢":"Normalized: "+D+"%"),N>=.75){var W=H.closest('div[style*="border-radius:12px"]');if(W){W.style.borderColor="rgba(239,68,68,0.5)",W.style.background="rgba(239,68,68,0.04)";var R=W.querySelector('div[style*="OK"]');R&&(R.innerHTML="🔴 TOP",R.style.color="#ef4444",R.style.background="rgba(239,68,68,0.15)",R.style.borderColor="rgba(239,68,68,0.4)")}}}var j=Object.keys(e.ReserveRisk).sort();e.ReserveRisk[j[j.length-1]];try{localStorage.setItem("cbbi_cache",JSON.stringify({ts:Date.now(),confidence:n,rhodl:d,woobull:f,mvrv:B,puell:S}))}catch(e){}}}).catch(function(){try{var e=JSON.parse(localStorage.getItem("cbbi_cache"));if(e&&Date.now()-e.ts<864e5){var t=document.getElementById("cbbiScore");t&&(t.textContent=e.confidence+"%")}}catch(e){}}),fetch("data/etf-flows.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.latestFlow){var t=document.getElementById("etfNetFlow");if(t){var o=e.latestFlow,n=(o>=0?"+":"")+o.toFixed(1)+"M";t.textContent=n,t.style.color=o>0?"#22c55e":o<-100?"#ef4444":o<0?"#f97316":"var(--heading)";var i=t.nextElementSibling;if(i&&(i.textContent=e.latestDate+" · "+e.outflowDays+"/"+e.totalDays+" outflow days"+(e.outflowDays>=7?" ⚠️":"")),e.outflowDays>=7){var a=t.closest('div[style*="border-radius:12px"]');if(a){a.style.borderColor="rgba(239,68,68,0.5)",a.style.background="rgba(239,68,68,0.04)";var r=a.querySelector('div[style*="OK"]');r&&(r.innerHTML="🔴 TOP",r.style.color="#ef4444",r.style.background="rgba(239,68,68,0.15)",r.style.borderColor="rgba(239,68,68,0.4)")}}}var s=document.getElementById("etf5dFlow");if(s){var l=e.sum5d;s.textContent=(l>=0?"+":"")+l.toFixed(1)+"M",s.style.color=l>100?"#22c55e":l<-500?"#ef4444":l<0?"#f97316":"var(--heading)";var c=s.nextElementSibling;if(c&&(c.textContent="5-day total"+(l<-500?" · Heavy selling ⚠️":l>500?" · Strong inflows 🟢":"")),l<-500){var d=s.closest('div[style*="border-radius:12px"]');if(d){d.style.borderColor="rgba(239,68,68,0.5)",d.style.background="rgba(239,68,68,0.04)";var u=d.querySelector('div[style*="OK"]');u&&(u.innerHTML="🔴 TOP",u.style.color="#ef4444",u.style.background="rgba(239,68,68,0.15)",u.style.borderColor="rgba(239,68,68,0.4)")}}}var p=P;try{var m=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"));m&&m.totalBtc&&(p=m.totalBtc)}catch(e){}var h=parseFloat(localStorage.getItem("btc_last_price"))||83e3,g=p*h,f=1984e4*h,y=f>0?(g/f*100).toFixed(1):"—",b=document.getElementById("etfBtcRatio");if(b){var v=parseFloat(y);b.textContent=y+"%",b.style.color=v>=8?"#ef4444":"var(--heading)";var w=b.nextElementSibling;if(w&&(w.textContent="ETF AUM: ~$"+(g/1e9).toFixed(0)+"B / Mkt Cap: ~$"+(f/1e12).toFixed(2)+"T"+(v>=8?" · High exposure ⚠️":"")),v>=8){var x=b.closest('div[style*="border-radius:12px"]');if(x){x.style.borderColor="rgba(239,68,68,0.5)",x.style.background="rgba(239,68,68,0.04)";var k=x.querySelector('div[style*="OK"]');k&&(k.innerHTML="🔴 TOP",k.style.color="#ef4444",k.style.background="rgba(239,68,68,0.15)",k.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("etfNetFlow");e&&(e.textContent="N/A")})}}}var B=null,S=0,T=212582*32150.7;function _(e,t,o){var n=e*T/1e12,i=t>0?(t/n*100).toFixed(1):"—",a=o>0?Math.round(1e12*n/o):"—",r=document.getElementById("goldMktCapLabel");r&&(r.textContent="$"+n.toFixed(1)+"T");var s=document.getElementById("goldBar");s&&(s.style.width=Math.min(parseFloat(i)||0,100)+"%");var l=document.getElementById("goldPctArea");l&&(l.innerHTML='
    '+i+'% of Gold Market Cap
    BTC needs ~$'+("number"==typeof a?p(a):a)+'/coin to match Gold
    Gold: $'+p(Math.round(e))+"/oz · Live via CoinGecko
    ");var c=document.getElementById("goldCompareCard");if(c){var d="Gold has been humanitys store of value for 5,000+ years. Bitcoin is digital gold — scarce, durable, portable, divisible, and verifiable. Gold price: $"+p(Math.round(e))+"/oz. Total above-ground gold: ~212,582 tonnes (~6.83B troy oz). Gold market cap: ~$"+n.toFixed(1)+"T. The flippening = Bitcoin absorbs golds entire monetary premium.";c.setAttribute("data-dash-tip",d),"function"==typeof window._attachTipListeners&&window._attachTipListeners()}}var I=null,C=0,E=[{name:"🇺🇸 United States",btc:325293},{name:"🇨🇳 China",btc:19e4},{name:"🇬🇧 United Kingdom",btc:61245},{name:"🇧🇹 Bhutan",btc:10635},{name:"🇸🇻 El Salvador",btc:6135}],A=649864;function z(e,t,o){var n=(t.companies||[]).slice(0,5),i=Math.round(t.total_holdings||0),a=t.total_value_usd||0,r=o||(i>0?a/i:0),s=n.map(function(e){return'
    '+(e.name||"?")+''+p(e.total_holdings)+" BTC
    "}).join(""),l=E.map(function(e){return'
    '+e.name+''+p(e.btc)+" BTC
    "}).join(""),c=i+A;e.innerHTML='
    🏢 Public Companies
    '+p(i)+'
    BTC · ~'+m(a||i*r)+'
    🏛️ Governments
    '+p(A)+'
    BTC · ~'+m(A*r)+'
    Total: '+p(c)+" BTC ("+(c/21e6*100).toFixed(1)+'% of supply)
    TOP 5 COMPANIES
    '+s+'
    TOP 5 GOVERNMENTS
    '+l+'
    Companies: live via CoinGecko · Governments: bitcointreasuries.net
    ';var d=document.getElementById("treasuryCard");d&&d.removeAttribute("onclick")}var M=[{ticker:"IBIT",name:"BlackRock",btc:787044,color:"#6366f1"},{ticker:"FBTC",name:"Fidelity",btc:213399,color:"#22c55e"},{ticker:"GBTC",name:"Grayscale",btc:180584,color:"#eab308"},{ticker:"ARKB",name:"ARK 21Shares",btc:63920,color:"#f97316"},{ticker:"BITB",name:"Bitwise",btc:53930,color:"#06b6d4"}],P=1367239;function L(e,t,o,n,i,a){var r=o*n,s=(o/i*100).toFixed(1),l=t[0].btc,c=t.map(function(e){var t=Math.max(4,e.btc/l*100).toFixed(0),o=m(e.btc*n);return'
    '+e.ticker+' '+e.name+''+p(e.btc)+' BTC
    '+o+"
    "}).join(""),d="";if(a){var u=Math.round((Date.now()-new Date(a).getTime())/36e5);d=u<1?"Updated just now":u<24?"Updated "+u+"h ago":"Updated "+Math.round(u/24)+"d ago"}e.innerHTML='
    '+p(o)+' BTC
    ~'+m(r)+" AUM · "+s+'% of supply held in ETFs
    '+c+'
    Data: SEC filings + CoinGlass'+(d?" · "+d:"")+"
    "}var U=null;window._startHalvingTicker=function(){U&&clearInterval(U),U=setInterval(function(){if(window._halvingTargetMs){var e=document.getElementById("halvSecs");if(!e)return clearInterval(U),void(U=null);var t=Math.max(0,window._halvingTargetMs-Date.now()),o=Math.floor(t/1e3),n=Math.floor(o/86400),i=Math.floor(o%86400/3600),a=Math.floor(o%3600/60),r=o%60,s=document.getElementById("halvDays"),l=document.getElementById("halvHours"),c=document.getElementById("halvMins");s&&(s.textContent=n),l&&(l.textContent=i),c&&(c.textContent=a),e.textContent=r<10?"0"+r:r}},1e3)}}(),function(){if(window._sessionStart=window._sessionStart||Date.now(),window._cleanUrl=function(e){if(!e)return"/";var t=window.location.pathname;return t==="/"+e||t==="/app/"+e?t:"#"+e},window._parseCleanUrl=function(){var e,t=window.location.pathname;return(e=t.match(/^\/channels\/(.+)$/))||(e=t.match(/^\/app\/(.+)$/))?e[1]:"/timechain-tv"===t||"/tv"===t?"timechain-tv":"/meetup-builder"===t?"meetup-builder":"/irl-sync"===t||"/meet"===t?"irl-sync":"/forum"===t?"forum":"/marketplace"===t?"marketplace":"/bitcoin-beats"===t||"/beats"===t?"bitcoin-beats":"/chat"===t?"chat":"/pvp"===t?"pvp":window.location.hash.replace("#","")||null},!document.getElementById("lb")){var e=document.createElement("div");e.id="lb",e.onclick=function(){document.getElementById("lb").classList.remove("open")},e.innerHTML='',document.body.appendChild(e)}function t(e){document.getElementById("lb-img").src=e,document.getElementById("lb").classList.add("open")}function o(){return window.innerWidth<=900}function n(){const e="light"!==document.body.getAttribute("data-theme");document.body.setAttribute("data-theme",e?"light":"dark"),localStorage.setItem("theme",e?"light":"dark");const t=document.getElementById("themeBtn");t&&(t.textContent=e?"☀️":"🌙");const o=document.getElementById("mobileThemeBtn");o&&(o.textContent=e?"☀️":"🌙")}function i(){var e=document.getElementById("sidebar");e&&(e.classList.toggle("open"),"function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!e.classList.contains("open")))}function a(){var e=document.getElementById("sidebar");if(e){var t=e.classList.toggle("sidebar-collapsed");try{localStorage.setItem("sidebar-collapsed",t?"1":"0")}catch(e){}}}function r(e){var t=e.nextElementSibling;if(t){var o=e.querySelector(".cat-arrow");"true"===e.getAttribute("data-expanded")?(t.style.display="none",e.setAttribute("data-expanded","false"),o&&(o.textContent="▶")):(t.style.display="",e.setAttribute("data-expanded","true"),o&&(o.textContent="▼"))}}function s(e){if(e){var t=e.closest(".cat-group");if(t&&"none"===t.style.display){var o=t.previousElementSibling;if(o&&o.classList.contains("cat-toggle")){t.style.display="",o.setAttribute("data-expanded","true");var n=o.querySelector(".cat-arrow");n&&(n.textContent="▼")}}}}function l(){return safeJSON("btc_favs",[])}function c(){var e=document.getElementById("favsList"),t=document.getElementById("favsSection");if(e){var o=l(),n=safeJSON("btc_bookmarks",[]);if(!(o.length>0||n.length>0))return e.innerHTML="",(i=document.getElementById("bookmarksList"))&&(i.innerHTML=""),void(t&&(t.style.display="none"));t&&(t.style.display="block");var i,a="";if(o.forEach(function(e){var t=void 0!==CHANNELS?CHANNELS[e]:null,o=t?(t.emoji||"")+" "+(t.name||e):e;a+="
    "+o+"
    "}),e.innerHTML=a,i=document.getElementById("bookmarksList"))if(0===n.length)i.innerHTML="";else{var r='
    🔖 Bookmarked Messages
    ';n.slice(0,15).forEach(function(e){var t=void 0!==CHANNELS&&CHANNELS[e.channel]?CHANNELS[e.channel]:null,o=t?(t.emoji||"")+" "+(t.name||e.channel):e.channel;r+="
    🔖 "+o+"
    "}),i.innerHTML=r}}}function d(e,t){let o=l();if(o.includes(e))o=o.filter(t=>t!==e),t&&(t.innerHTML="☆ Save");else{o.push(e),t&&(t.innerHTML="⭐ Saved");try{var n=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_fav_added_"+n,"true")}catch(e){}}var i;i=o,localStorage.setItem("btc_favs",JSON.stringify(i)),c(),"function"==typeof syncFavsToFirebase&&syncFavsToFirebase()}!function(){try{if(window.innerWidth>900&&"1"===localStorage.getItem("sidebar-collapsed")){var e=document.getElementById("sidebar");e&&e.classList.add("sidebar-collapsed")}}catch(e){}}();let u=!1,p=null,m=null;function h(e){u=!u;const t=document.getElementById("galleryBtn");t&&(t.classList.toggle("active",u),t.textContent=u?"📄 List View":"🖼️ Gallery View"),g(e)}function g(e){const t=p;if(!t)return;const n=document.getElementById("msgs");if(u){let e=[];t.msgs.forEach(t=>{t.imgs&&t.imgs.forEach(t=>e.push(t))});let i='",e.length>a&&(window._galleryImgs=e,window._galleryOffset=a,i+='"),n.innerHTML=i}else{const i=o()?20:50,a=t.msgs;let r=function(){const t=a.slice(0,0+i);let n="";{const t=void 0!==CHANNELS?CHANNELS[e]:null;t&&t.desc&&(n+='
    🦌
    Nacho\'s Summary
    '+t.desc+"
    ")}return t.forEach((t,i)=>{if(n+='
    ',t.text){let e=t.text,i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"});let a=[];e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){const t=e.startsWith("http")?e:"https://"+e;return a.push(t),"%%TW"+(a.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){const n=a[parseInt(t)],i="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),l=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+l+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),n+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?n+='':n+=''});var a=0+i,r=safeJSON("btc_bookmarks",[]).some(function(t){return t.channel===e&&t.idx===a});n+="',n+="
    "}),n}();a.length>i&&(r+='"),n.innerHTML=r,window._currentMsgs=a,window._currentOffset=i}window._sidebarOrder||(window._sidebarOrder=[...document.querySelectorAll(".ch-btn")].map(e=>{const t=e.getAttribute("onclick").match(/go\('([^']+)'/);return t?t[1]:null}).filter(Boolean));const i=window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),a=i.indexOf(e),r=a0?i[a-1]:i[i.length-1]);CHANNELS[s]&&CHANNELS[s].title;let l='
    ';l+="',l+='',l+='',l+='',l+='',l+="',l+="
    ",l+='
    ',l+='',l+="
    ","function"==typeof renderReadNext&&(l+=renderReadNext(e)),l+='
    Disclaimer
    This Bitcoin education is presented authentically and from a first-principles standpoint that maximizes truth. However, this is not financial, investment, legal, or tax advice and anyone reading this material should still verify its validity by doing their own research. Bitcoin is volatile and you can lose money. Bitcoin Education Archive, its operators, and contributors make no warranty regarding the accuracy, completeness, or timeliness of any educational content and accept no liability for decisions made based on it. Always consult a licensed professional before making financial decisions. Terms · Privacy
    ',n.innerHTML+=l,n.classList.add("fade-in")}let f=!1;function y(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML='
    Loading tweet...
    ',f)b(e,t);else{const o=document.createElement("script");o.src="https://platform.twitter.com/widgets.js",o.async=!0,o.onload=function(){f=!0,b(e,t)},document.head.appendChild(o)}}function b(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML="",window.twttr&&window.twttr.widgets){const e=t.match(/status\/(\d+)/);if(e){const n=document.createElement("div");o.appendChild(n),twttr.widgets.createTweet(e[1],n,{theme:"light"===document.body.getAttribute("data-theme")?"light":"dark",align:"center",conversation:"none",width:500}).then(function(e){e||(o.innerHTML='')})}}else o.innerHTML=''}async function v(){window._keepFloatingBtn=!0;const e=Object.keys(CHANNELS);window._randomChannelHistory||(window._randomChannelHistory=[]);var t=e.filter(function(e){return-1===window._randomChannelHistory.indexOf(e)});0===t.length&&(window._randomChannelHistory.length=0,t=e);const o=t[Math.floor(Math.random()*t.length)];window._randomChannelHistory.push(o),window._randomChannelHistory.length>Math.floor(.3*e.length)&&window._randomChannelHistory.shift(),await go(o),window._keepFloatingBtn=!1,S("__random__","🎲","Next Random Channel")}async function w(e,t,o){window._keepFloatingBtn=!0;const n=CHANNELS[e];if(!n)return void(window._keepFloatingBtn=!1);let i;if(V[e])i=V[e];else try{const t=await fetch(n.file);i=await t.json(),V[e]=i}catch(e){return}const a=i.msgs.length>1?i.msgs.slice(1):i.msgs,r=[];if(a.forEach((e,t)=>{e.imgs&&e.imgs.length>0&&r.push(t)}),0!==r.length){window._randomHistory||(window._randomHistory={}),window._randomHistory[e]||(window._randomHistory[e]=[]);var s=window._randomHistory[e],l=Math.min(Math.floor(.2*r.length),50),c=r.filter(function(e){return-1===s.indexOf(e)});0===c.length&&(s.length=0,c=r);var d=c[Math.floor(Math.random()*c.length)];s.push(d),s.length>l&&s.shift();var u=a[d];if(u&&u.imgs&&u.imgs.forEach(function(e){(new Image).src=e}),await go(e),d>=50){const e=document.getElementById("loadMoreBtn");for(var p=0;window._currentOffset<=d&&e&&document.contains(e)&&p<50;)window.loadMoreMsgs(),p++}setTimeout(function(){const n=document.getElementById("msg-"+d);n&&(n.querySelectorAll('img[loading="lazy"]').forEach(function(e){e.loading="eager"}),n.scrollIntoView({behavior:"smooth",block:"center"}),n.style.transition="box-shadow 0.3s, border-color 0.3s",n.style.boxShadow="0 0 20px rgba(247,147,26,0.4)",n.style.borderColor="#f7931a",setTimeout(function(){n.style.boxShadow="",n.style.borderColor=""},2e3),window._keepFloatingBtn=!1,S(e,t,o))},300)}}function x(){return w("memes-funny","😂","Next Random Meme")}function k(){return w("art-inspiration","🎨","Next Random Art")}function B(){return w("graphics","📊","Next Random Graphic")}function S(e,t,o){var n=document.getElementById("floatingRandomBtn");n||((n=document.createElement("button")).id="floatingRandomBtn",n.style.cssText="position:fixed;bottom:140px;right:180px;z-index:150;padding:12px 20px;background:var(--accent);color:#fff;border:none;border-radius:12px;font-size:0.9rem;font-weight:700;cursor:pointer;font-family:inherit;box-shadow:0 4px 20px rgba(0,0,0,0.3);transition:0.2s;display:flex;align-items:center;gap:6px;",document.body.appendChild(n)),n.innerHTML=t+" "+o,n.onclick="__random__"===e?function(){v()}:function(){w(e,t,o)},n.style.display="flex",window.addEventListener("popstate",function e(){n.style.display="none",window.removeEventListener("popstate",e)},{once:!0})}function T(e,t){const o=e+"\n\n"+t;navigator.clipboard.writeText(o).then(()=>{showToast("📋 Note copied! Paste it in Primal to post.")}).catch(()=>{}),window.open("https://primal.net/home","_blank")}window.goRandomMeme=x,window.goRandomArt=k,window.goRandomGraphic=B,window.toggleBookmark=function(e,t,o){var n=safeJSON("btc_bookmarks",[]),i=n.findIndex(function(o){return o.channel===e&&o.idx===t});-1!==i?(n.splice(i,1),o&&(o.style.opacity="0.3",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Bookmark removed")):(n.push({channel:e,idx:t,ts:Date.now()}),o&&(o.style.opacity="1",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Saved to sidebar")),localStorage.setItem("btc_bookmarks",JSON.stringify(n)),c(),"function"==typeof syncBookmarksToFirebase&&syncBookmarksToFirebase()},window.loadMoreGallery=function(){const e=window._galleryImgs,o=window._galleryOffset,n=document.querySelector(".gallery-grid"),i=document.getElementById("loadMoreGallery");e.slice(o,o+100).forEach(e=>{const o=document.createElement("img");o.src=e,o.loading="lazy",o.onclick=function(){t(this.src)},n.appendChild(o)}),window._galleryOffset=o+100,window._galleryOffset>=e.length?i.remove():i.textContent="Load more ("+(e.length-window._galleryOffset)+" remaining)"},window.showSpinWheel=function(){var e=localStorage.getItem("btc_last_spin_date"),t=(new Date).toDateString();if(e!==t){var o=document.getElementById("spinModal");o&&o.remove();var n=document.createElement("div");n.id="spinModal",n.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.85);-webkit-overflow-scrolling:touch;overflow-y:auto;padding:20px;";var i=[{label:"🎟️ 1 Ticket",value:"ticket_1",weight:25,color:"#f7931a"},{label:"🎟️ 2 Tickets",value:"ticket_2",weight:22,color:"#ea580c"},{label:"⭐ 25 XP",value:"points_25",weight:18,color:"#22c55e"},{label:"🎟️ 3 Tickets",value:"ticket_3",weight:12,color:"#fbbf24"},{label:"⭐ 50 XP",value:"points_50",weight:8,color:"#3b82f6"},{label:"👔 Closet!",value:"closet_item",weight:5,color:"#ec4899"},{label:"🧊 Freeze!",value:"freeze",weight:4,color:"#06b6d4"},{label:"⭐ 100 XP",value:"points_100",weight:3,color:"#8b5cf6"},{label:"🎟️ 5 Tickets",value:"ticket_5",weight:1.5,color:"#a855f7"},{label:"💎 RARE!",value:"rare_drop",weight:1.5,color:"#ef4444"}],a=[{label:"🎟️ 10 Tickets",value:"ticket_10",weight:1e3},{label:"🎟️ 25 Tickets",value:"ticket_25",weight:500},{label:"🎟️ 50 Tickets",value:"ticket_50",weight:100},{label:"🎟️ 100 Tickets!",value:"ticket_100",weight:50},{label:"🎟️ 500 Tickets!!",value:"ticket_500",weight:10},{label:"🎟️💎 1,000 Tickets!!!",value:"ticket_1000",weight:3},{label:"🎟️👑 10,000 TICKETS!!!!",value:"ticket_10000",weight:1}];n.innerHTML='
    🎡
    Daily Spin

    Spin for Orange Tickets, XP, Nacho Closet items, and rare Freeze Tickets!

    ',document.body.appendChild(n);var r=document.getElementById("spinCanvas").getContext("2d"),s=125,l=125,c=2*Math.PI/i.length;i.forEach(function(e,t){r.beginPath(),r.moveTo(s,l),r.arc(s,l,120,t*c,(t+1)*c),r.fillStyle=e.color,r.fill(),r.strokeStyle="#fff",r.lineWidth=2,r.stroke(),r.save(),r.translate(s,l),r.rotate(t*c+c/2),r.textAlign="right",r.fillStyle="#fff",r.font="bold 12px sans-serif",r.fillText(e.label,105,4),r.restore()});var d=!1,u=document.getElementById("spinBtn"),p=document.getElementById("spinResult");u.addEventListener("click",function(){if(!d){d=!0,u.disabled=!0,u.style.opacity="0.5";for(var e=i.reduce(function(e,t){return e+t.weight},0),o=Math.random()*e,n=0,m=0,h=0;hMath.floor(30*(d-.01))&&"function"==typeof playSpinTick&&playSpinTick(),requestAnimationFrame(e);else{"function"==typeof playSpinWin&&playSpinWin();var h="",f=g.value.split("_")[0],y=parseInt(g.value.split("_")[1])||1;if("rare_drop"===g.value){for(var b=a.reduce(function(e,t){return e+t.weight},0),w=Math.random()*b,x=a[0],B=0,S=0;S.01&&(T=100,x={label:"🎟️ 100 Tickets!",value:"ticket_100"}),h="💎 RARE DROP! "+x.label,"function"==typeof awardOrangeTickets)awardOrangeTickets(T,"Rare Spin Drop");else{var _=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",_+T)}T>=100&&("function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound())}else if("closet"===f){var I=safeJSON("btc_spin_closet_items",[]),C=["orange_scarf","sunglasses","bowtie","mining_helmet","lightning_chain","party_hat","hodl_hoodie","crown","steak","diamond_hooves"].filter(function(e){return-1===I.indexOf(e)});if(C.length>0){var E=C[Math.floor(Math.random()*C.length)];if(I.push(E),localStorage.setItem("btc_spin_closet_items",JSON.stringify(I)),void 0!==currentUser&¤tUser&&!currentUser._isLocal)try{db.collection("users").doc(auth.currentUser.uid).update({spinClosetItems:firebase.firestore.FieldValue.arrayUnion(E)}).catch(function(){})}catch(e){}h="👔 CLOSET ITEM! You unlocked: "+({orange_scarf:"Bitcoin Scarf 🧣",sunglasses:"Cool Shades 🕶️",bowtie:"Fancy Bowtie 🎀",mining_helmet:"Mining Helmet ⛑️",lightning_chain:"Lightning Chain ⚡",party_hat:"Party Hat 🎉",hodl_hoodie:"HODL Hoodie 🧥",crown:"Royal Crown 👑",steak:"Proof of Steak 🥩",diamond_hooves:"Diamond Hooves 💎"}[E]||E)+"! Equip it in Nacho's Closet!"}else h="👔 You already own all spin closet items! +25 bonus XP instead!","function"==typeof awardPoints&&awardPoints(25,"Closet bonus")}else if("freeze"===f){h="🧊 STREAK FREEZE TICKET! Your streak is protected for 1 missed day!";var A=parseInt(localStorage.getItem("btc_streak_freezes")||"0");localStorage.setItem("btc_streak_freezes",A+1),"function"==typeof awardPoints&&awardPoints(0,"🧊 Streak Freeze",null,0,1),void 0!==currentUser&¤tUser&&(currentUser.streakFreezes=(currentUser.streakFreezes||0)+1)}else if("ticket"===f)if(h="🎟️ You won "+y+" Orange Ticket"+(y>1?"s":"")+"!","function"==typeof awardOrangeTickets)awardOrangeTickets(y,"Daily Spin");else{var z=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",z+y)}else if("points"===f)if(h="⭐ You won "+y+" XP!","function"==typeof awardPoints)awardPoints(y,"Daily Spin");else{var M=parseInt(localStorage.getItem("btc_points")||"0");localStorage.setItem("btc_points",M+y)}p.innerHTML='
    '+g.label.split(" ")[0]+'
    '+h+'
    ',"function"==typeof notifySelfSpin&¬ifySelfSpin(h);var P=parseInt(localStorage.getItem("btc_spin_count")||"0");localStorage.setItem("btc_spin_count",String(P+1));var L=localStorage.getItem("btc_spin_last_day")||"";if(L===new Date(Date.now()-864e5).toISOString().slice(0,10)){var U=parseInt(localStorage.getItem("btc_spin_streak")||"0");localStorage.setItem("btc_spin_streak",String(U+1))}else L!==t&&localStorage.setItem("btc_spin_streak","1");localStorage.setItem("btc_spin_last_day",t),"rare_drop"===g.value&&localStorage.setItem("btc_spin_hit_rare","true"),localStorage.setItem("btc_last_spin_date",t),"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("dailySpin")({}).catch(function(e){console.log("[SPIN] Server validation:",e.message||"ok")}),void 0!==currentUser&¤tUser&¤tUser._isLocal}})}}),n.addEventListener("click",function(e){e.target===n&&n.remove()})}else showToast("🎡 You already spun today! Come back tomorrow!")};var _=null;function I(e,t,o,n,i){var a="dc_"+Math.random().toString(36).substr(2,6),r=n?'Open ↗':"";return'
    '+e+"
    "+(i?'
    '+e+' QR
    ':"")+(t?'
    "+o+'
    "+r+"
    ":"")+"
    "}function C(e,t){navigator.clipboard.writeText(e).then(()=>{t.classList.add("copied"),t.textContent="✅ Copied!",setTimeout(()=>{t.classList.remove("copied"),t.innerHTML="🔗 Copy Link"},2e3)})}setTimeout(function(){var e=new Image;e.crossOrigin="anonymous",e.src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:spontaneousleopard54@zeuspay.com",e.onload=function(){try{var t=document.createElement("canvas");t.width=e.width,t.height=e.height,t.getContext("2d").drawImage(e,0,0),_=t.toDataURL("image/png")}catch(t){_=e.src}}},3e3),window.showDonateModal=function(){var e=document.getElementById("donateModal");e&&e.remove();var t=document.createElement("div");t.id="donateModal",t.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:flex-start;justify-content:center;background:rgba(2,6,23,0.9);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;";var o="spontaneousleopard54@zeuspay.com",n=_||"https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:"+o;t.innerHTML='
    🧡
    Support the Archive

    Your sats help keep this archive free and open for the next billion Bitcoiners! 🦌⚡

    Lightning QR Code
    '+o+"

    ⚠️ Donations are non-refundable

    "+I("💵 Cash App","$NEEDcreations","$NEEDcreations","https://cash.app/$NEEDcreations","images/donate/cashapp-qr.jpg")+I("💜 Venmo","@Phil2140","@Phil2140","https://venmo.com/code?user_id=1358236213051392692&created=1773155307","images/donate/venmo-qr.jpg")+I("💙 PayPal","paypal.me/PhilipFazioli","paypal.me/PhilipFazioli","https://paypal.me/PhilipFazioli","images/donate/paypal-qr.jpg")+I("💚 Zelle",null,null,null,"images/donate/zelle-qr.jpg")+I("₿ On-Chain Bitcoin","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf",null,"images/donate/onchain-qr.jpg")+I("🔒 BIP47 Payment Code","PM8TJWpq8HqPeBEuz3dAoB3uyZADVxQjWekQJCJYddpWPce9nDaeK6XjYnifBUnjjKcWF8Y98EkfPZYaftC7uDJkiFqBTBYrd8TJhRg5qQwXtfnTTg89","PM8TJWpq8Hq...Tg89",null,"images/donate/bip47-qr.jpg")+"
    ",document.body.appendChild(t);var i=document.getElementById("donateCopyBtn");i&&i.addEventListener("click",function(e){e.stopPropagation();var t=this;if(navigator.clipboard)navigator.clipboard.writeText(o).then(function(){t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)});else{var n=document.createElement("textarea");n.value=o,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)}}),t.addEventListener("click",function(e){e.target===t&&t.remove()})};let E=!1;function A(){const e=document.getElementById("supportBtn");E?(navigator.clipboard.writeText("info.603btc@gmail.com").then(function(){e.innerHTML="✅ Copied!",e.style.color="#22c55e",setTimeout(function(){e.innerHTML='info.603btc@gmail.com tap to copy',e.style.color="var(--text)"},1500)}).catch(function(){}),window.location.href="mailto:info.603btc@gmail.com?subject=Support%20-%20Bitcoin%20Education%20Archive"):(E=!0,e.style.transition="0.3s",e.style.background="var(--accent)",e.style.color="#fff",e.style.borderColor="var(--accent)",e.innerHTML='info.603btc@gmail.com tap to copy',setTimeout(function(){e.style.background="var(--card-bg)",e.style.color="var(--text)",e.style.borderColor="var(--border)"},400))}function z(e){if(!e)return"";var t=new Date(e),o=t.getHours(),n=t.getMinutes(),i=o>=12?"PM":"AM";return 0==(o%=12)&&(o=12),o+":"+(n<10?"0":"")+n+" "+i}window._nachoMode=!1,window._nachoModeEarnings={points:0,badges:[],interactions:0},window.enterNachoMode=function(e){if(window._nachoMode=!0,window._nachoBusy=!0,window._nachoModeEarnings={points:0,badges:[],interactions:0},window._nachoModeStartTime=Date.now(),window._nachoModeTopics=[],window._nachoConvoQuizOffered=!1,!window._nachoPointsHooked){window._nachoPointsHooked=!0;var t=window.awardPoints;t&&(window.awardPoints=function(e,o){return window._nachoMode&&window._nachoModeEarnings&&(window._nachoModeEarnings.points+=e),t.apply(this,arguments)});var o=window.showToast;o&&(window.showToast=function(e){return window._nachoMode&&window._nachoModeEarnings&&"string"==typeof e&&(-1!==e.indexOf("badge")||-1!==e.indexOf("Badge")||-1!==e.indexOf("🏅"))&&window._nachoModeEarnings.badges.push(e),o.apply(this,arguments)})}e||history.pushState({nachoMode:!0},"","/app/nacho"),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="none")});var n=document.querySelector(".mobile-bar");n&&(n.style.display="none");var i=document.getElementById("main");i.scrollTop=0,"undefined"!=typeof NACHO_SVG&&NACHO_SVG,void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var a=!(!window.SpeechRecognition&&!window.webkitSpeechRecognition),r=a?'':"";window._nachoChatHistory=safeJSON("btc_nacho_chat",[]),window._nachoSentHistory=safeJSON("btc_nacho_sent",[]),window._nachoSentIdx=-1;var s=document.createElement("div");s.id="nachoModeScreen",s.style.cssText="display:flex;flex-direction:column;height:calc(100vh - 32px);margin-top:32px;animation:fadeSlideIn 0.4s ease-out;position:relative;z-index:9999;",s.innerHTML='
    Nacho
    '+("function"==typeof nachoNickname?nachoNickname():"Nacho").toUpperCase()+' MODE
    Home
    '+r+'
    ',i.appendChild(s),q(),setTimeout(function(){var e=document.getElementById("nachoModeChat");e&&(e.scrollTop=e.scrollHeight)},100),W();var l=document.getElementById("nachoEli5Btn");l&&(l.style.opacity=window._nachoEli5?"1":"0.5"),function(){var e=document.getElementById("nachoModeOverlay");if(e&&(e.innerHTML="","function"==typeof getEquippedItem)){var t=getEquippedItem();if(t){var o=t.hidden?t.revealEmoji:t.emoji,n=document.createElement("span");n.textContent=t.overlay&&t.overlay.custom?t.overlay.custom:o,n.style.cssText="position:absolute;font-size:2.5rem;pointer-events:none;",t.overlay&&(t.overlay.top&&(n.style.top=t.overlay.top),t.overlay.left&&(n.style.left=t.overlay.left),t.overlay.right&&(n.style.right=t.overlay.right),t.overlay.bottom&&(n.style.bottom=t.overlay.bottom),t.overlay.transform&&(n.style.transform=t.overlay.transform)),e.appendChild(n)}}}(),setTimeout(function(){var e=document.getElementById("nachoModeInput");e&&e.focus()},300)},window.nachoModeKeydown=function(e){if("Enter"!==e.key){var t=document.getElementById("nachoModeInput");if(t){var o=window._nachoSentHistory||[];if("ArrowUp"===e.key){if(0===o.length)return;-1===window._nachoSentIdx&&(window._nachoSentDraft=t.value),window._nachoSentIdx=Math.min(window._nachoSentIdx+1,o.length-1),t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault(),setTimeout(function(){t.setSelectionRange(t.value.length,t.value.length)},0)}else if("ArrowDown"===e.key){if(window._nachoSentIdx<=0)return window._nachoSentIdx=-1,void(t.value=window._nachoSentDraft||"");window._nachoSentIdx--,t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault()}}}else nachoModeSend()};var M=["There will only ever be 21 million Bitcoin. No government, company, or person can change this. 🔒","The Bitcoin network has been running non-stop since January 3, 2009 — over 99.98% uptime. No bank can say that! 🏦","The first Bitcoin transaction was 10,000 BTC for two pizzas. Today that's worth hundreds of millions! 🍕","Bitcoin processes over $10 billion in transactions daily — more than most countries' payment systems. 💸","Bitcoin mining now uses more renewable energy than almost any other industry — over 50%! ⚡","Satoshi Nakamoto's true identity remains unknown. They hold about 1 million BTC and have never spent any. 🕵️","A 'satoshi' (sat) is the smallest unit of Bitcoin: 0.00000001 BTC. You don't need to buy a whole coin! 🪙","The Bitcoin Lightning Network can process millions of transactions per second — faster than Visa! ⚡","El Salvador became the first country to adopt Bitcoin as legal tender in September 2021. 🇸🇻","Bitcoin's code is completely open source — anyone can read, verify, and contribute to it. 📖","Every 4 years, Bitcoin's new supply gets cut in half. This is called the 'halving.' The next one is in 2028! 📉","There are more Bitcoin wallets than bank accounts in most countries. Over 100 million and growing! 📈","Bitcoin can be sent anywhere in the world in minutes, 24/7, with no middleman. Try that on a Sunday with a bank! 🌍","The Genesis Block contains a hidden message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰","About 20% of all Bitcoin is estimated to be permanently lost — mostly from early users who lost their keys. 🔑","Bitcoin's difficulty adjustment is like a thermostat — it automatically adapts every 2 weeks to keep blocks at ~10 minutes. ⚙️","Running a Bitcoin node means YOU verify every transaction yourself. No trust required. Don't trust, verify! ✅","The Lightning Network lets you send payments as small as 1 sat (~$0.0003). Try doing that with a credit card! 💳","Bitcoin has survived 400+ declared 'deaths' by media. It keeps coming back stronger every time. 💪","Over 50 publicly traded companies now hold Bitcoin on their balance sheets, led by MicroStrategy. 🏢","Bitcoin transactions are pseudonymous, not anonymous. Every transaction is recorded on the public blockchain forever. 🔍","The Bitcoin network is protected by more computing power than all the world's supercomputers combined. 🖥️","You can run a full Bitcoin node on a Raspberry Pi — a $50 computer can verify the entire monetary system. 🥧","Bitcoin's inflation rate is currently lower than gold's. After the 2028 halving, it'll be even lower. 🥇","Multisig wallets require multiple keys to spend Bitcoin — like a safety deposit box that needs 2 of 3 keys. 🗝️","Bitcoin doesn't care about borders, politics, or holidays. It works the same everywhere, always. 🌐","The last Bitcoin won't be mined until approximately the year 2140. We're still very early! ⏰","Jack Dorsey, Elon Musk, and many tech leaders have publicly supported Bitcoin's vision. 🚀","A Bitcoin block is mined roughly every 10 minutes. That's about 144 blocks per day, every day, forever. ⛏️","Nostr is a decentralized social protocol that many Bitcoiners are building on — social media you can't be censored from. 📡"];window.nachoModeChip=function(e){var t=document.getElementById("nachoModeInput");t&&(t.value=e,nachoModeSend())},window._nachoEli5="true"===localStorage.getItem("btc_nacho_eli5"),window.toggleNachoEli5=function(){window._nachoEli5=!window._nachoEli5,localStorage.setItem("btc_nacho_eli5",window._nachoEli5?"true":"false");var e=document.getElementById("nachoEli5Btn");e&&(e.style.opacity=window._nachoEli5?"1":"0.5",e.title=window._nachoEli5?"ELI5 Mode ON — Simple language":"Explain Like I'm 5"),"function"==typeof showToast&&showToast(window._nachoEli5?"🧒 ELI5 Mode ON — Nacho will use simple language!":"🧒 ELI5 Mode OFF — Back to normal")},window.showEli5Prompt=function(){var e=window._nachoEli5,t='
    🧒
    ELI5 Mode
    Explain Like I\'m 5

    When turned on, Nacho will answer your questions using super simple language — like explaining Bitcoin to a 5-year-old! 🦌

    Perfect for beginners or anyone who wants the basics without the jargon.
    Currently: '+(e?"ON ✅":"OFF")+'
    ',o=document.createElement("div");o.innerHTML=t,document.body.appendChild(o.firstChild)},window.nachoShareAnswer=function(e){var t="🦌 I learned this from Nacho at bitcoineducation.quest:\n\n"+e.replace(/<[^>]+>/g,"").replace(/🦌\s*/g,"").substring(0,280);if(navigator.share)navigator.share({title:"Bitcoin Fact from Nacho 🦌",text:t,url:"https://bitcoineducation.quest"}).catch(function(){});else{var o=document.createElement("textarea");o.value=t,document.body.appendChild(o),o.select();try{document.execCommand("copy")}catch(e){}document.body.removeChild(o),"function"==typeof showToast&&showToast("📋 Copied to clipboard!")}};var P=!1,L=[{step:1,emoji:"📘",title:"What is Bitcoin?",q:"What is Bitcoin and how does it work?"},{step:2,emoji:"💡",title:"Why Bitcoin Matters",q:"Why is Bitcoin important? Why should I care?"},{step:3,emoji:"📈",title:"Bitcoin vs Money",q:"How is Bitcoin different from regular money and gold?"},{step:4,emoji:"🛒",title:"Buying Your First Bitcoin",q:"How do I buy my first Bitcoin? Where do I start?"},{step:5,emoji:"💼",title:"Wallets & Storage",q:"What Bitcoin wallet should I use? What are the types?"},{step:6,emoji:"🔑",title:"Seed Phrases & Security",q:"What is a seed phrase and how do I keep my Bitcoin safe?"},{step:7,emoji:"⚡",title:"Lightning Network",q:"What is the Lightning Network and why does it matter?"},{step:8,emoji:"⛏️",title:"Mining & Proof of Work",q:"How does Bitcoin mining work? What is proof of work?"},{step:9,emoji:"🏃",title:"Running a Node",q:"What is a Bitcoin node and should I run one?"},{step:10,emoji:"🔒",title:"Privacy & KYC",q:"How private is Bitcoin? What is KYC and why does it matter?"}];window.nachoLearningPath=function(){var e=parseInt(localStorage.getItem("btc_nacho_path_step")||"0");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth&&auth?auth.currentUser:null;if(document.getElementById("nachoModeChat")){var o='
    🗺️ Your Bitcoin Journey
    '+Math.round(e/L.length*100)+"% concepts mastered
    ";o+='
    ✅ All Features Unlocked

    Every app and feature is available to you. Explore freely! 🦌

    🗣️ Pleb Talk
    🤝 IRL Sync
    ⚡ Lightning Mart
    🔹 Sign Up: 🏁 Profile & Persistence
    ',o+='
    ';for(var n=0;n'+(a?"✅":i.emoji)+'
    Level '+i.step+": "+i.title+"
    "+(r?'NEXT →':"")+""}e>=L.length&&(o+='
    🎓🦌🎉
    Journey Complete!
    You\'ve covered all the Bitcoin basics. You\'re officially not a normie anymore!
    '),H("nacho","",o)}},window.nachoPathStep=function(e){var t=L[e];t&&(e>=parseInt(localStorage.getItem("btc_nacho_path_step")||"0")&&localStorage.setItem("btc_nacho_path_step",(e+1).toString()),nachoModeChip(t.q))};const U=[{q:"What is the primary benefit of running a Bitcoin full node?",a:"You can independently verify the consensus rules and your own transactions.",w:["It earns you a small percentage of every transaction fee on the network.","It automatically mines new Bitcoins using your computer's idle CPU.","It hides your IP address from everyone else using the network.","It increases the speed of your internet connection by 21%."]},{q:"What does 'Satoshi' represent in the context of Bitcoin?",a:"The smallest unit of Bitcoin, equal to 0.00000001 BTC.",w:["A type of advanced encryption used for private messages.","The official name for a Bitcoin wallet's public address.","A digital certificate of ownership for a single Bitcoin.","The name of the first computer used to mine block zero."]},{q:"Why is Bitcoin's difficulty adjustment important?",a:"It ensures blocks are produced roughly every 10 minutes regardless of total hash rate.",w:["It prevents the price of Bitcoin from dropping below its mining cost.","It automatically updates the Bitcoin Core software for all users.","It calculates the total number of users active on the network daily.","It decides which transactions are most important for the miners."]},{q:"What happens if you lose your 12 or 24-word seed phrase?",a:"You lose access to your funds forever, as there is no central 'reset' authority.",w:["You can call Bitcoin's customer support to verify your identity and reset it.","The government can recover your coins using your social security number.","Your hardware wallet will automatically generate a new phrase after 24 hours.","Your Bitcoin is donated to a pool for new developers to use for testing."]},{q:"What is the primary function of the Lightning Network?",a:"To enable instant, near-free Bitcoin payments by moving them off-chain.",w:["To increase the total number of Bitcoins that will ever exist to 42 million.","To allow Bitcoin to be mined using only mobile phones and tablets.","To encrypt the entire blockchain so it cannot be read by anyone.","To create a secondary blockchain that is faster but less secure than Bitcoin."]}];function q(){var e=document.getElementById("nachoModeChat");if(e){var t=window._nachoChatHistory||[];if(0!==t.length){for(var o,n="",i="",a=0;a'+s+"",i=s),"user"===r.role?n+='
    '+escapeHtml(r.text)+'
    '+z(r.ts)+"
    ":n+='
    🦌 '+escapeHtml("function"==typeof nachoNickname?nachoNickname():"Nacho")+": "+r.html+'
    '+z(r.ts)+"
    "}e.innerHTML=n,e.scrollTop=e.scrollHeight}else{var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"";e.innerHTML='
    Nacho
    🦌 NACHO MODE
    '+(l?"Hey "+escapeHtml(l)+"! Let's talk Bitcoin.":"Hey! Let's talk Bitcoin.")+'
    💡 DID YOU KNOW?
    '+(o=Math.floor((Date.now()-new Date((new Date).getFullYear(),0,0))/864e5),M[o%M.length]+'
    Tap a topic or ask me anything:
    ')+function(){for(var e=[{emoji:"📘",label:"What is Bitcoin?",q:"What is Bitcoin and what problem does it solve?"},{emoji:"💰",label:"Why Bitcoin?",q:"Why is Bitcoin better than regular money and why should I care?"},{emoji:"🔒",label:"21 Million",q:"Why is the 21 million cap important and why can't it be changed?"},{emoji:"🛒",label:"How to Buy",q:"How do I buy my first Bitcoin and start stacking sats?"},{emoji:"🔑",label:"Self-Custody",q:"What is self-custody and why is it the most important thing in Bitcoin?"},{emoji:"⚡",label:"Lightning",q:"What is the Lightning Network and how does it make Bitcoin faster?"},{emoji:"🪙",label:"Why Not Altcoins?",q:"Why do Bitcoiners only focus on Bitcoin and not other cryptocurrencies?"},{emoji:"🌍",label:"Fix the World",q:"How is Bitcoin actually changing the world for the better?"}],t='
    ',o=0;o"+e[o].emoji+" "+e[o].label+"";return t+"
    "}()+'
    '}}}function N(e,t,o){var n={role:e,text:t||"",html:o||escapeHtml(t||""),ts:Date.now()};return window._nachoChatHistory.push(n),nachoChatSave(),n}function H(e,t,o){var n=document.getElementById("nachoModeChat");if(n){window._nachoChatHistory.length<=1&&n.querySelector("#nachoModeAvatar")&&(n.innerHTML="");var i=z(Date.now()),a=document.createElement("div");if(a.className="nm-msg "+("user"===e?"nm-user":"nm-nacho"),"user"===e)a.innerHTML=""+escapeHtml(t)+'
    '+i+"
    ";else{var r="function"==typeof nachoNickname?nachoNickname():"Nacho";a.innerHTML='🦌 '+escapeHtml(r)+": "+o+'
    '+i+"
    "}n.appendChild(a),"user"===e?n.scrollTop=n.scrollHeight:a.scrollIntoView({behavior:"smooth",block:"start"})}}function D(){if(window._nachoMode){var e=document.getElementById("nachoModeInput");if(e&&e===document.activeElement)setTimeout(D,3e4);else if(document.querySelector(".nm-nacho .thinking, .nm-thinking"))setTimeout(D,1e4);else{var t=window._nachoModeTopics||[];if(!(t.length<3)){var o=[],n=[],i=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;if(i&&"object"==typeof i&&Object.keys(i).forEach(function(e){var t=i[e];Array.isArray(t)&&t.forEach(function(t){n.push({question:t.q,options:[t.a].concat(t.wrong||[]),answer:t.a,category:e})})}),n.length>0){for(var a=0;a3&&-1!==c.indexOf(r[d])){o.push(l);break}}for(;o.length<3&&n.length>0;){var u=n[Math.floor(Math.random()*n.length)];-1===o.indexOf(u)&&o.push(u)}}0!==o.length&&(H("nacho","",'
    🎯
    Conversation Quest!
    You\'ve been learning a lot! Let\'s see how much you remember from our chat.
    '),window._convoQuizQuestions=o)}}}}function O(){var e,t,o,n,i=window._convoQuizQuestions||[],a=window._convoQuizIdx||0;if(a>=window._convoQuizTotal||a>=i.length)e=window._convoQuizScore||0,t=window._convoQuizTotal||3,H("nacho","",'
    '+(o>=80?"🏆":o>=60?"⭐":o>=40?"💪":"📚")+'
    Conversation Quest Complete!
    '+e+"/"+t+' correct
    '+(o>=80?"Outstanding! You really paid attention!":o>=60?"Great job! You learned a lot from our chat!":o>=40?"Not bad! Keep learning and you'll get there!":"Keep going! Every question is a learning opportunity!")+"
    "+((n=5*e)>0?'
    +'+n+" XP earned! 🎉
    ":"")+"
    "),n>0&&("function"==typeof awardPoints&&awardPoints(n,"🎯 Conversation Quest!"),"function"==typeof showToast&&showToast("🎯 +"+n+" XP — Conversation Quest!"));else{for(var r=i[a],s='
    Question '+(a+1)+" of "+window._convoQuizTotal+'
    '+escapeHtml(r.question)+"
    ",l=r.options||[],c=0;c'+escapeHtml(l[c])+""}H("nacho","",s+="
    ")}}function W(){var e=document.getElementById("nachoModeFriendship");if(e){var t="function"==typeof getNachoFriendship?getNachoFriendship():{emoji:"🦌",name:"Unknown",level:0},o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.textContent=t.emoji+" Friendship: "+t.name+" · "+o+" interactions"}}function R(){const e=document.getElementById("continueReading");if(!e)return;const t=localStorage.getItem("btc_last_channel");if(t&&CHANNELS[t]){const o=CHANNELS[t];e.style.display="block",e.innerHTML='
    📖 Continue Reading
    "+o.title+'
    '+o.cat+"
    "}else e.style.display="none"}window.nachoQuizMe=function(e){if(!window._nachoMode)return void("function"==typeof enterNachoMode&&(enterNachoMode(),setTimeout(function(){nachoQuizMe(e)},500)));let t=[];var o=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;o&&"object"==typeof o&&Object.keys(o).length>0&&Object.keys(o).forEach(e=>{var n=o[e];Array.isArray(n)&&n.forEach(o=>{t.push({question:o.q,options:fisherYates([o.a,...o.wrong||o.w||[]]),answer:o.a,category:e})})}),U.forEach(e=>{t.push({question:e.q,options:fisherYates([e.a,...e.w]),answer:e.a,category:"generic"})});var n=e?t.filter(function(t){return t.category&&-1!==t.category.toLowerCase().indexOf(e.toLowerCase())}):t;0===n.length&&(n=t);for(var i=n[Math.floor(Math.random()*n.length)],a='
    🎮 Quiz Time!
    '+(e?"Topic: "+e:"Nacho Challenge")+'
    '+escapeHtml(i.question)+"
    ",r=i.options||[],s=0;s'+escapeHtml(r[s])+""}a+="
    ",e||(a+='
    🦌 Pro Tip: Chat with me first! Future quizzes will be based on the questions you ask me.
    '),H("nacho","",a+="')},window.nachoQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n,i=e.parentElement.querySelectorAll("button");i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.7"}),t?(e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1","function"==typeof awardPoints&&awardPoints(10,"🎮 Quiz correct!"),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(34,197,94,0.1);border:1px solid #22c55e;border-radius:8px;color:#22c55e;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="✅ Correct! +10 XP",e.parentElement.appendChild(n)):(e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.borderColor="#22c55e",t.style.color="#22c55e",t.style.opacity="1")}),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(239,68,68,0.1);border:1px solid #ef4444;border-radius:8px;color:#ef4444;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="❌ Incorrect. Try another!",e.parentElement.appendChild(n))},window.nachoChatSave=function(){var e=window._nachoChatHistory||[];e.length>100&&(e=e.slice(e.length-100)),window._nachoChatHistory=e;try{localStorage.setItem("btc_nacho_chat",JSON.stringify(e))}catch(e){}},window.startConversationQuiz=function(){var e=window._convoQuizQuestions||[];0!==e.length&&(window._convoQuizIdx=0,window._convoQuizScore=0,window._convoQuizTotal=Math.min(e.length,5),O())},window.convoQuizAnswer=function(e,t){var o=e.parentElement,n=o.querySelectorAll("button");if(n.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1",window._convoQuizScore=(window._convoQuizScore||0)+1;var i=document.createElement("div");i.style.cssText="margin-top:6px;color:#22c55e;font-size:0.8rem;font-weight:700;",i.textContent="✅ Correct!",o.appendChild(i)}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",n.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var a=document.createElement("div");a.style.cssText="margin-top:6px;color:#ef4444;font-size:0.8rem;font-weight:700;",a.textContent="❌ Not quite!",o.appendChild(a)}window._convoQuizIdx=(window._convoQuizIdx||0)+1,setTimeout(O,1500)},window.nachoChatExport=function(){var e=window._nachoChatHistory||[];if(0!==e.length){for(var t=["=== Nacho Mode Chat Export ===","Exported: "+(new Date).toLocaleString(),""],o=0;o]+>/g,"");t.push("["+i+"] "+a+": "+r)}t.push("","--- bitcoineducation.quest ---");var s=new Blob([t.join("\n")],{type:"text/plain"}),l=document.createElement("a");l.href=URL.createObjectURL(s),l.download="nacho-chat-"+(new Date).toISOString().slice(0,10)+".txt",l.click(),URL.revokeObjectURL(l.href),"function"==typeof showToast&&showToast("💾 Chat saved!")}else"function"==typeof showToast&&showToast("No chat to save!")},window.nachoChatClear=function(){confirm("Clear all chat history with Nacho?")&&(window._nachoChatHistory=[],localStorage.removeItem("btc_nacho_chat"),q(),"function"==typeof showToast&&showToast("🗑️ Chat cleared"))},window.nachoModeSend=function(){var e=document.getElementById("nachoModeInput");if(e){var t=e.value.trim();if(t){e.value="",window._nachoSentIdx=-1,window._nachoSentDraft="",window._nachoAskedQuestions||(window._nachoAskedQuestions=[]),window._nachoAskedQuestions.push(t.toLowerCase()),window._nachoAskedQuestions.length>30&&(window._nachoAskedQuestions=window._nachoAskedQuestions.slice(-20)),window._nachoSentHistory.push(t),window._nachoSentHistory.length>50&&window._nachoSentHistory.shift();try{localStorage.setItem("btc_nacho_sent",JSON.stringify(window._nachoSentHistory))}catch(e){}var o;(o=document.getElementById("nachoHeroAvatar"))&&o.classList.add("talking"),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,window._nachoModeTopics&&t.length>10&&window._nachoModeTopics.push(t),!window._nachoConvoQuizOffered&&window._nachoModeStartTime&&window._nachoModeTopics&&(Date.now()-window._nachoModeStartTime)/6e4>=15&&window._nachoModeTopics.length>=5&&(window._nachoConvoQuizOffered=!0,setTimeout(function(){D()},8e3)),N("user",t),H("user",t),function(){var e=document.getElementById("nachoModeChat");if(e){e.querySelector("#nachoModeAvatar")&&(e.innerHTML="");var t=document.createElement("div");t.id="nmThinking",t.className="nm-msg nm-nacho",t.innerHTML='🦌 Thinking',e.appendChild(t),e.scrollTop=e.scrollHeight;var o=t.querySelector(".nacho-dots"),n=0;window._nmDotsTimer=setInterval(function(){n=(n+1)%4,o&&(o.textContent=".".repeat(n))},400)}}();var n="nm_"+Date.now()+"_"+Math.random().toString(36).substr(2,4),i=!1,a=setTimeout(function(){i||(i=!0,console.warn("[Nacho] Master timer fired — pipeline took >15s for:",t),s("That's a great question! I'm having a little trouble with my brain right now 🦌 Try asking me again in a moment, or explore the channels on the left to learn about Bitcoin!","fallback"))},15e3);if("function"!=typeof nachoUnifiedAnswer){if(!document.querySelector("script[data-nacho-retry]")){var r=document.createElement("script");r.src="nacho-qa.js?v="+Date.now(),r.setAttribute("data-nacho-retry","1"),document.head.appendChild(r)}setTimeout(function(){if("function"==typeof nachoUnifiedAnswer)try{nachoUnifiedAnswer(t,l)}catch(e){console.warn("Nacho pipeline retry error:",e),l({type:"fallback",answer:"I'm still loading up my Bitcoin knowledge! Try again in a moment 🦌"})}else!function(e,t){if("function"==typeof checkOffTopic){var o=checkOffTopic(e);if(o)return void t("function"==typeof personalize?personalize(o):o,"offtopic")}var n=e.toLowerCase().trim();if(/^(hey|hi|hello|yo|sup|howdy|hola|what'?s up|how are you|how'?s it going|good morning|good evening|good afternoon|gm|greetings)$/i.test(n)||/^(hey|hi|hello|yo) (nacho|there|buddy|friend|deer)/i.test(n)){var i=["Hey there! 🦌 Doing great — just hanging out waiting for someone to ask me about Bitcoin! What's on your mind?","Hey hey! 🧡 Welcome! I'm Nacho, your Bitcoin buddy. What would you like to learn about today?","Well hello! 🦌 Nice to see you. Ask me anything about Bitcoin — I've got 146 channels of knowledge in these antlers!","Hey! 👋 I'm good, thanks for asking! Ready to talk Bitcoin whenever you are. What's on your mind?"];t(i[Math.floor(Math.random()*i.length)],"offtopic")}else"function"==typeof nachoTrackMiss&&nachoTrackMiss(e),t("Give me just a moment — I'm loading up my Bitcoin knowledge! Try again in a few seconds. 🦌","fallback")}(t,s)},2e3)}else try{console.log("[Nacho] Calling nachoUnifiedAnswer for:",t),nachoUnifiedAnswer(t,function(e){console.log("[Nacho] Pipeline returned:",e?e.type:"null"),l(e)})}catch(e){console.error("[Nacho] Pipeline CRASH:",e),l({type:"fallback",answer:"Oops, my brain hit a bump! 🦌 Try asking again — I know a LOT about Bitcoin!"})}}}function s(e,o){!function(){window._nmDotsTimer&&(clearInterval(window._nmDotsTimer),window._nmDotsTimer=null);var e=document.getElementById("nmThinking");e&&e.remove()}(),function(){var e=document.getElementById("nachoHeroAvatar");e&&e.classList.remove("talking")}();var i="";if(o&&"safety"!==o){window._nachoAnswerData||(window._nachoAnswerData={}),window._nachoAnswerData[n]=e;var a="background:none;border:1px solid var(--border);border-radius:16px;cursor:pointer;font-size:0.75rem;padding:4px 10px;transition:0.2s;color:var(--text-muted);display:inline-flex;align-items:center;gap:3px;touch-action:manipulation;",r='
    ';"function"==typeof nachoRatingHtml&&(r+='",r+='"),r+="',i+=r+="
    ",i+=function(e){if(!e||0===e.length)return"";for(var t='
    ',o=0;o💬 "+e[o]+"";return t+"
    "}("function"==typeof nachoFollowUps?nachoFollowUps((t||"")+" "+(e||"")):[])}N("nacho","",e+i),H("nacho","",e+i),W(),"function"==typeof nachoTrackTopic&&nachoTrackTopic(t,o||"unknown");var s=function(){if(P)return null;for(var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[10,25,50,100,200,500],o=safeJSON("btc_nacho_q_milestones",[]),n=null,i=0;i=a&&-1===o.indexOf(r)&&-1===o.indexOf(a)&&(o.push(r),n=a)}return null===n?null:(localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(o)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({nachoMilestones:o}).catch(function(){}),P=!0,{10:"🎉 10 questions! You're officially a Bitcoin Beginner! Keep going — there's so much to learn! 🦌",25:"🎉 25 questions! You've leveled up to Bitcoin Explorer! You're asking the right questions! 💪",50:"🎉 50 questions! Bitcoin Apprentice unlocked! You know more than most people already! 🧠",100:"🏆 100 questions! You're a Bitcoin Scholar now! Satoshi would be proud! 🎓",200:"🔥 200 questions! Bitcoin Expert status! You could probably teach ME a thing or two! 🦌💡",500:"👑 500 QUESTIONS! You are a Bitcoin LEGEND! There's nothing Nacho can't discuss with you now! 🦌🏆🔥"}[n]||null)}();s&&setTimeout(function(){N("nacho","",s),H("nacho","",s)},1500)}function l(e){if(!i){i=!0,clearTimeout(a);var t="";e&&e.siteAction?t='

    ":e&&e.channel&&(t='

    📖 Read more: '+(e.channelName||e.channel)+" →"),s((e&&e.answer?e.answer:"Hmm, let me think about that... Try asking another way! 🦌")+t,e&&e.type||"fallback")}}},window.nachoModeAvatarTap=function(){var e=document.getElementById("nachoModeAvatar");e&&(e.style.transform="scale(1.1) rotate("+(Math.random()>.5?"5":"-5")+"deg)",setTimeout(function(){e.style.transform=""},300),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,W())},window._nachoModeRecognition=null,window._nachoModeListening=!1,window.nachoModeVoice=function(){var e=window.SpeechRecognition||window.webkitSpeechRecognition;if(e){var t=document.getElementById("nachoModeInput"),o=document.getElementById("nachoModeMic");if(t&&o)if(window._nachoModeListening&&window._nachoModeRecognition)window._nachoModeRecognition.stop();else{var n=new e;window._nachoModeRecognition=n,n.lang="en-US",n.interimResults=!0,n.maxAlternatives=1,n.continuous=!0,o.style.opacity="1",o.innerHTML="🛑",t.placeholder="Nacho is listening... (Tap 🛑 to finish)",t.style.borderColor="#f7931a",window._nachoModeListening=!0;var i="";n.onresult=function(e){for(var o="",n=e.resultIndex;n0&&nachoModeSend()},n.onerror=function(){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6",t.style.borderColor="var(--border,#333)",t.placeholder="Voice error — try typing"};try{n.start()}catch(e){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6"}}}},window.exitNachoMode=function(e){window._nachoMode=!1,window._nachoBusy=!1,window._btcPriceTimer&&(clearInterval(window._btcPriceTimer),window._btcPriceTimer=null);var t=document.getElementById("nachoModeScreen");t&&t.remove(),document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="")});var o=document.querySelector(".mobile-bar");if(o&&window.innerWidth<=900&&(o.style.display="flex"),!e){var n=window._nachoModeEarnings,i=window._nachoModeStartTime||Date.now(),a=Math.round((Date.now()-i)/6e4);if("function"==typeof showToast){var r=[];a>0&&r.push("⏱️ "+a+" min"),n&&n.interactions>0&&r.push("🦌 "+n.interactions+" interactions"),n&&n.points>0&&r.push("+"+n.points+" XP");var s=n?Array.isArray(n.badges)?n.badges.length:n.badges||0:0;s>0&&r.push("🏅 "+s+" badge"+(s>1?"s":"")),r.length>0?showToast(r.join(" · ")):showToast("🦌 Thanks for hanging out with "+("function"==typeof nachoNickname?nachoNickname():"Nacho")+"!")}goHome()}},window.goHome=function(e){if(document.activeElement&&document.activeElement.blur&&document.activeElement.blur(),"function"==typeof hideUsernamePrompt){var t=document.getElementById("usernameModal");t&&t.classList.contains("open")&&hideUsernamePrompt()}"function"==typeof _tctvStopTracker&&_tctvStopTracker();var n=document.getElementById("bottomNav");n&&n.classList.remove("nav-hidden"),"function"==typeof _updateSEO&&_updateSEO("home","Learn Bitcoin","A curated Bitcoin education archive with 146 topics, 8800+ messages, and community tools.");var i=document.getElementById("floatingRandomBtn");i&&(i.style.display="none");var a=document.getElementById("lbFloatBtn");a&&a.classList.remove("chat-shifted"),(c=document.getElementById("forumContainer"))&&(c.style.display="none"),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes();var r=document.getElementById("msgs");r&&(r.style.display="none");var s=document.getElementById("hero");s&&(s.style.display="none");var l=void 0!==auth&&auth?auth.currentUser:null;l&&l.email,void 0!==currentUser&¤tUser&¤tUser.totalVisits;try{safeJSON("btc_visited_channels",[]).length}catch(e){}var c,d=document.querySelector('[onclick*="showSpinWheel"]'),u=(document.querySelector('[onclick*="showPricePrediction"]'),document.querySelector('[onclick*="showNachoStory"]'),document.getElementById("dailyChallengeCard")),p=document.querySelector("[onclick*=\"go('bitcoin-beats'\"]"),m=document.querySelector("[onclick*=\"go('forum'\"]"),h=document.querySelector("[onclick*=\"go('marketplace'\"]"),g=document.querySelector('[onclick*="enterNachoMode"]');d&&(d.parentElement.style.display="grid"),u&&(u.style.display=""),m&&(m.style.display=""),p&&(p.style.display=""),h&&(h.style.display=""),g&&(g.style.display=""),(c=document.getElementById("forumContainer"))&&(c.style.display="none",c.innerHTML="");var f=document.getElementById("hero");f&&(f.style.display="none",f.innerHTML="");var y=document.getElementById("msgs");if(y&&(y.style.display="none",y.innerHTML=""),document.getElementById("home").classList.remove("hidden"),document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),document.getElementById("main").scrollTop=0,e||history.pushState({channel:null},"","/"),"function"==typeof window._renderSatoshiFavorHome&&window._renderSatoshiFavorHome(),o()){document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0);var b=document.querySelector(".mobile-bar");b&&(b.style.display="flex"),"function"==typeof updateRankUI&&updateRankUI()}R(),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof loadCommunityStats&&loadCommunityStats(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof window._renderCharityHome&&window._renderCharityHome(),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn()},document.addEventListener("keydown",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.isContentEditable){var t=e.key.toLowerCase();if(!e.ctrlKey&&!e.metaKey)if("h"!==t)if("/"!==t)if("c"!==t)if("r"!==t)if("m"!==t)if("a"!==t)if("t"!==t)if("s"!==t)if("l"!==t)if("q"!==t)if("f"!==t)if("n"!==t)if("d"!==t)if("v"!==t)if("g"!==t)if("p"!==t)if("x"!==t)if("j"!==t)if("k"!==t){if(" "===t)return e.preventDefault(),void document.getElementById("main").scrollBy({top:.8*window.innerHeight,behavior:"smooth"});if("?"===t||e.shiftKey&&"/"===t)!function(){var e=document.getElementById("kbHelpModal");if(e)e.remove();else{var t=document.createElement("div");t.id="kbHelpModal",t.style.cssText="position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.7);",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

    ⌨️ Keyboard Shortcuts

    Press ? to toggle this menu
    Navigation
    '+G("H","Go home")+G("/","Search")+G("C","Random topic")+G("M","Random Meme")+G("R","Random Art")+G("G","Random Graphic")+G("B","Back to last channel")+G("T","PlebTalk (Forum)")+G("S","Lightning Mart")+'
    Actions
    '+G("F","Favorite channel")+G("A","Ask Nacho")+G("N","Nacho Mode")+G("D","Dark / Light mode")+G("L","Leaderboard")+G("Q","Start quest")+G("V","Gallery view")+G("X","PVP Battle")+G("P","Donate")+G("I","Settings")+'
    Scrolling
    '+G("J","Scroll down")+G("K","Scroll up")+G("Space","Page down")+G("Esc","Close modals")+'
    Mobile Gestures
    '+G("2-finger","Nacho Mode")+G("3-finger","Settings")+G("Long-press","Explore Apps (on logo)")+"
    ",document.body.appendChild(t)}}();else if("i"!==t)if("b"!==t)if("2"!==t)if("3"!==t)if("1"!==t){if("0"===t)return F("Don't trust. Verify."),void("function"==typeof earnSticker&&earnSticker("cool"));if("9"===t)return F("Number go up!"),void("function"==typeof nachoFly&&nachoFly());if("2"!==window._eggBuffer||"1"!==t)if("w"!==t){if(window._eggBuffer=(window._eggBuffer||"")+t,window._eggBuffer.length>10&&(window._eggBuffer=window._eggBuffer.slice(-10)),-1!==window._eggBuffer.indexOf("btc")&&(window._eggBuffer="",localStorage.setItem("btc_bitcoin_eyes_unlocked","true"),"function"==typeof showToast&&showToast("₿₿ Secret unlocked: Bitcoin Eyes! Check Nacho's Closet!"),"function"==typeof haptic&&haptic("success")),"escape"===t){e.preventDefault();var i=document.getElementById("lb");if(i&&i.classList.contains("open"))return void i.classList.remove("open");var a=document.getElementById("usernameModal");if(a&&a.classList.contains("open"))return void("function"==typeof hideUsernamePrompt&&hideUsernamePrompt());var r=document.getElementById("questModal");if(r&&r.classList.contains("open"))return void r.classList.remove("open");var s=document.getElementById("searchOverlay");if(s&&"none"!==s.style.display)return void(s.style.display="none");var l=document.getElementById("nachoStoryOverlay");if(l)return void l.remove();var c=document.getElementById("spinModal");if(c)return void c.remove();var d=document.getElementById("donateModal");if(d)return void d.remove();var u=document.getElementById("kbHelpModal");if(u)return void u.remove();if(document.getElementById("pvpOverlay"))return void("function"==typeof exitPVPMode&&exitPVPMode());var p=document.getElementById("appsMenu");if(p&&"block"===p.style.display)return void(p.style.display="none");if(o()){var m=document.getElementById("sidebar");if(m&&m.classList.contains("open"))return m.classList.remove("open"),void("function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!0))}if(window._nachoMode&&"function"==typeof exitNachoMode)return void exitNachoMode()}}else F("Stay humble. Stack sats.");else F("Twenty-one million. Final and absolute.")}else F("One more block.");else F("Three point one two five. The current block reward.");else F("There is no second best.");else{var h=localStorage.getItem("btc_last_channel");h&&go(h)}else"function"==typeof showSettingsPage&&showSettingsPage("account")}else document.getElementById("main").scrollBy({top:-300,behavior:"smooth"});else document.getElementById("main").scrollBy({top:300,behavior:"smooth"});else"function"==typeof enterPVPMode&&enterPVPMode();else showDonateModal();else B();else{var g=document.getElementById("galleryBtn");g&&g.click()}else n();else"function"==typeof enterNachoMode&&enterNachoMode();else{var f=document.getElementById("favBtn");f&&f.click()}else{var y=document.getElementById("questBtn");y&&y.click()}else"function"==typeof toggleLeaderboard&&toggleLeaderboard();else go("marketplace");else go("forum");else"function"==typeof showNachoInput&&showNachoInput();else x();else k();else v();else{e.preventDefault();var b=document.getElementById("searchInput");b&&(b.focus(),o()&&document.getElementById("sidebar").classList.add("open"))}else goHome()}});var j=0;function F(e){var t=Date.now();if(!(t-j<3e3)){j=t,"function"==typeof showToast&&showToast("🟠 "+e);try{var o=new SpeechSynthesisUtterance(e);o.rate=.9,o.pitch=.85,o.volume=.8;var n=speechSynthesis.getVoices().find(function(e){return-1!==e.name.indexOf("Daniel")||-1!==e.name.indexOf("Google UK English Male")||-1!==e.name.indexOf("Male")});n&&(o.voice=n),speechSynthesis.cancel(),speechSynthesis.speak(o)}catch(e){}}}function G(e,t){return'
    '+e+'
    '+t+"
    "}"undefined"!=typeof speechSynthesis&&speechSynthesis.getVoices(),function(){if("ontouchstart"in window){var e=0,t=0;window.addEventListener("devicemotion",function(o){var n=o.acceleration&&null!==o.acceleration.x?o.acceleration:null;if(n&&Math.abs(n.x)+Math.abs(n.y)+Math.abs(n.z)>25){if(e++,clearTimeout(window._shakeResetTimer),window._shakeResetTimer=setTimeout(function(){e=0},1e3),e<3)return;e=0;var i=Date.now();if(i-t<1e4)return;t=i;var a=["There is no second best.","One more block.","Don't trust. Verify.","Number go up!","Stay humble. Stack sats.","Not your keys, not your coins.","Bitcoin fixes this.","Tick tock, next block."];F(a[Math.floor(Math.random()*a.length)]),Math.random()<.3&&"function"==typeof nachoFly&&nachoFly()}});var o=0,n=0,i=0,a=document.getElementById("main");a.addEventListener("touchstart",function(e){"INPUT"===e.target.tagName||"TEXTAREA"===e.target.tagName||e.target.closest(".no-swipe")||(o=e.touches[0].clientX,n=e.touches[0].clientY,i=Date.now())},{passive:!0}),a.addEventListener("touchend",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.closest(".no-swipe")){var t=e.changedTouches[0].clientX-o,a=e.changedTouches[0].clientY-n,r=Date.now()-i,s=Math.abs(t),l=Math.abs(a);r>600||s>150&&s>2.5*l&&(t>0?(goPrev(),"function"==typeof haptic&&haptic("light")):(goNext(),"function"==typeof haptic&&haptic("light")))}},{passive:!0});var r=0,s=0;document.getElementById("main").addEventListener("touchstart",function(e){2===e.touches.length&&(s=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(s&&0===e.touches.length&&e.changedTouches.length>=1){var t=Date.now()-s;if(s=0,t>400)return;var o=Date.now();if(o-r<3e3)return;r=o,"function"==typeof enterNachoMode&&enterNachoMode()}},{passive:!0}),document.querySelectorAll(".home-logos img, .channel-logos .channel-logo-img").forEach(d),new MutationObserver(function(){document.querySelectorAll(".channel-logos .channel-logo-img").forEach(d)}).observe(document.getElementById("main"),{childList:!0,subtree:!0});var l=0,c=0;document.getElementById("main").addEventListener("touchstart",function(e){3===e.touches.length&&(c=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(c&&0===e.touches.length){var t=Date.now()-c;if(c=0,t>400)return;var o=Date.now();if(o-l<3e3)return;l=o,"function"==typeof showSettings&&showSettings()}},{passive:!0})}function d(e){var t;e._logoLongPress||(e._logoLongPress=!0,e.addEventListener("touchstart",function(e){t=setTimeout(function(){"function"==typeof toggleAppsMenu&&toggleAppsMenu(),"function"==typeof haptic&&haptic("medium")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t)}),e.addEventListener("touchmove",function(){clearTimeout(t)}))}}();const V={};function Q(){const e=safeJSON("btc_visited_channels",[]).length;void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth?auth:null,o=t&&t.currentUser;o&&o.email;var n="function"==typeof getOnboardingProfile?getOnboardingProfile():null;n&&("advanced"===n.level||n.level);const i=document.querySelectorAll(".cat-label.cat-toggle"),a=document.querySelectorAll(".quest-start-btn, .home-cta, #beatsBtnHome, [onclick*=\"go('forum'\"], [onclick*=\"go('marketplace'\"]");function r(e){return function(){var t=e.match(/^go\(['"]([^'"]+)['"]/);if(t)go(t[1]);else{var o=e.match(/^(?:if\(typeof\s+(\w+)==='function'\))?\s*(\w+)\(\)/);if(o){var n=o[2]||o[1];if("function"==typeof window[n])return void window[n]()}var i=e.match(/renderChatHub\(['"](\w+)['"]\)/);if(i&&"function"==typeof window.renderChatHub)window.renderChatHub(i[1]);else{var a=e.match(/showSettingsPage\(['"](\w+)['"]\)/);a&&"function"==typeof window.showSettingsPage?window.showSettingsPage(a[1]):console.warn("[SECURITY] Unrecognized action pattern:",e)}}}}i.forEach(function(e){var t=e.nextElementSibling;t&&t.classList.contains("cat-group")&&(e.style.display="",t.style.display="true"===e.getAttribute("data-expanded")?"":"none")}),a.forEach(e=>{if(e.closest("#appsMenu")||e.closest("#guideOverlay")||e.closest("#questHubOverlay"))return;const t=e.getAttribute("data-name")||e.textContent.replace("🔒 ","").trim();e.getAttribute("data-name")||e.setAttribute("data-name",t);const o=e.getAttribute("data-onclick")||e.getAttribute("onclick");e.getAttribute("data-onclick")||e.setAttribute("data-onclick",o),e.innerHTML=t,e.style.opacity="1",e.style.filter="none",e.style.cursor="pointer",e.title="";var n=e.getAttribute("data-onclick");n&&(e.onclick=r(n))}),document.querySelectorAll("[data-tier]").forEach(t=>{const o=t.getAttribute("data-tier"),n=t.getAttribute("data-unlock-name")||t.textContent.trim(),i=t.getAttribute("data-onclick")||t.getAttribute("onclick");!t.getAttribute("data-onclick")&&i&&t.setAttribute("data-onclick","string"==typeof i?i:i.toString()),!t.getAttribute("data-orig-tooltip")&&t.getAttribute("data-tooltip")&&t.setAttribute("data-orig-tooltip",t.getAttribute("data-tooltip"));let a=!1,s="";if("explorer"===o?(a=true,s="🔒 Visit "+Math.max(0,3-e)+" more channel"+(3-e==1?"":"s")+" to unlock "+n+"!"):"community"===o?(a=true,s="🔒 Explore "+Math.max(0,5-e)+" more channel"+(5-e==1?"":"s")+" to unlock "+n+"!"):"full"===o&&(a=true,s="🔒 Explore "+Math.max(0,10-e)+" more channel"+(10-e==1?"":"s")+" or sign in to unlock "+n+"!"),a){t.innerHTML=n,t.style.opacity="1",t.style.filter="none";var l=t.getAttribute("data-orig-tooltip")||t.getAttribute("data-tooltip");l?(t.title=l,t.setAttribute("data-tooltip",l)):t.title=n,t.style.cursor="pointer",t.title="";var c=t.getAttribute("data-onclick");c&&(t.onclick=r(c))}else t.innerHTML="🔒 "+n,t.style.opacity="0.45",t.style.filter="grayscale(0.8)",t.style.cursor="help",t.title=s,t.setAttribute("data-tooltip",s),t.onclick=function(e){e.preventDefault(),e.stopPropagation(),"function"==typeof showToast&&showToast(s)}});var s=localStorage.getItem("btc_unlocked_tier")||"none",l=["none","explorer","community","full"],c="full",d=l.indexOf(s);if(l.indexOf(c)>d){localStorage.setItem("btc_unlocked_tier",c);var u=document.getElementById("appsMenu");u&&u.remove(),"function"==typeof showToast&&showToast("🚀 ⚡ Lightning Mart unlocked! You have full access!")}var p=document.getElementById("sidebarMilestone");p&&p.remove()}function J(){window.audioEnabled=!window.audioEnabled,localStorage.setItem("btc_audio",window.audioEnabled.toString()),X(),"function"==typeof showToast&&showToast(window.audioEnabled?"🔊 Sound on":"🔇 Sound off")}function Y(e){window.audioVolume=parseFloat(e),localStorage.setItem("btc_volume",window.audioVolume.toString()),window.audioVolume<=0?(window.audioEnabled=!1,localStorage.setItem("btc_audio","false")):window.audioEnabled||(window.audioEnabled=!0,localStorage.setItem("btc_audio","true")),window._beatsAudio&&(window._beatsAudio.volume=window.audioVolume),window._djAudio&&(window._djAudio.volume=window.audioVolume);var t=document.getElementById("beatsVolume");t&&(t.value=Math.round(100*window.audioVolume));var o=document.getElementById("djVolume");o&&(o.value=Math.round(100*window.audioVolume)),X()}function X(){const e=document.getElementById("audioBtn");e&&(e.textContent=window.audioEnabled&&window.audioVolume>0?window.audioVolume>.5?"🔊":"🔉":"🔇");const t=document.getElementById("volumeSlider");t&&(t.value=window.audioEnabled?window.audioVolume:0),document.querySelectorAll('button[onclick*="toggleAudio"]').forEach(function(e){"ON"!==e.textContent&&"OFF"!==e.textContent||(e.textContent=window.audioEnabled?"ON":"OFF",e.style.background=window.audioEnabled?"#22c55e":"var(--bg-side)",e.style.color=window.audioEnabled?"#fff":"var(--text-muted)")})}Q(),window._sidebarTierInterval=setInterval(Q,5e3),window.audioEnabled="false"!==localStorage.getItem("btc_audio"),window.audioVolume=parseFloat(localStorage.getItem("btc_volume")||"0.5"),window.canPlaySound=function(){return window.audioEnabled&&window.audioVolume>0&&"visible"===document.visibilityState},window.goNext=function(){if(void 0===CHANNELS)return;const e=window._sidebarOrder&&window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(m);if(-1===t)return void go(e[0]);const o=t0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(m);if(-1===t)return void go(e[e.length-1]);const o=t>0?e[t-1]:e[e.length-1];go(o)},window.go=async function(e,t,n){"function"==typeof _tctvStopTracker&&_tctvStopTracker();var i=document.getElementById("bottomNav");i&&i.classList.remove("nav-hidden"),window._nachoMode&&!n&&("function"==typeof nachoChatSave&&nachoChatSave(),window._nachoReturnPending=!0);var a=document.getElementById("msgs"),r=document.getElementById("hero");const c=CHANNELS[e];let d="";c&&(d='"),a.innerHTML=d+'
    \x3c!-- Nacho Summary skeleton --\x3e
    \x3c!-- Message skeletons --\x3e
    \x3c!-- Image skeleton --\x3e
    ',a.style.display="",document.getElementById("home").classList.add("hidden"),r.style.display="none",o()&&document.getElementById("sidebar").classList.remove("open");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var h,f=void 0!==auth&&auth?auth.currentUser:null;if(f&&f.email,"forum"===e||"marketplace"===e||"bitcoin-beats"===e||"irl-sync"===e||"dms"===e||"lightning"===e||"chat"===e||"first-purchase"===e||"timechain-tv"===e||"trails"===e)return window._nachoMode&&exitNachoMode(!0),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.getElementById("msgs").style.display="none",document.getElementById("hero").style.display="none",(h=document.getElementById("forumContainer"))&&(h.style.display="block"),n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&document.getElementById("sidebar").classList.remove("open"),function e(t,o){if(o=o||0,"first-purchase"===t&&"function"==typeof renderFirstPurchase)renderFirstPurchase(),document.getElementById("main").scrollTop=0;else if("timechain-tv"===t&&"function"==typeof renderTimechainTV)renderTimechainTV(),document.getElementById("main").scrollTop=0,"function"==typeof _tctvStartTracker&&_tctvStartTracker();else if("marketplace"===t&&"function"==typeof renderMarketplace)renderMarketplace();else if("bitcoin-beats"===t&&"function"==typeof renderBitcoinBeats)renderBitcoinBeats();else if("irl-sync"===t&&"function"==typeof renderIRLSync)renderIRLSync();else if("dms"===t&&"function"==typeof showInbox)showInbox();else if("lightning"===t&&"function"==typeof renderLightning)renderLightning();else if("chat"===t&&"function"==typeof renderChatHub)renderChatHub("global");else if("trails"===t&&"function"==typeof renderModules)renderModules();else if("forum"===t&&"function"==typeof renderForum)renderForum();else if(o<20){if(setTimeout(function(){e(t,o+1)},250),0===o){var n=document.getElementById("forumContainer");n&&(n.innerHTML='
    Loading...
    ')}}else if("forum"===t&&"function"==typeof renderForum)renderForum();else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
    ⚠️
    Still loading...
    This feature is taking longer than expected.
    ')}}(e),document.getElementById("main").scrollTop=0,h&&(h.scrollTop=0),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0,setTimeout(function(){document.getElementById("main").scrollTop=0,document.getElementById("forumContainer")&&(document.getElementById("forumContainer").scrollTop=0),window.scrollTo(0,0)},50),setFloatingElementsVisible(!0),void("function"==typeof nachoOnPage&&nachoOnPage(e));if(!c)return;if(window._nachoMode&&exitNachoMode(!0),(h=document.getElementById("forumContainer"))&&(h.style.display="none",h.innerHTML=""),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes(),document.getElementById("hero").style.display="",document.getElementById("msgs").style.display="",!window._keepFloatingBtn){var y=document.getElementById("floatingRandomBtn");y&&"none"!==y.style.display&&"memes-funny"!==e&&"art-inspiration"!==e&&"graphics"!==e&&(y.style.display="none")}localStorage.setItem("btc_last_channel",e),function(){if(window.canPlaySound())try{const e=new(window.AudioContext||window.webkitAudioContext),t=window.audioVolume,o=e.createOscillator(),n=e.createGain();o.connect(n),n.connect(e.destination),o.frequency.value=880,o.type="sine",n.gain.setValueAtTime(.08*t,e.currentTime),n.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15),o.start(e.currentTime),o.stop(e.currentTime+.15);const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=1318.5,i.type="sine",a.gain.setValueAtTime(.05*t,e.currentTime+.05),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.25),i.start(e.currentTime+.05),i.stop(e.currentTime+.25)}catch(e){}}(),document.getElementById("home").classList.add("hidden"),(a=document.getElementById("msgs")).innerHTML=d+'
    ',document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),t?(t.classList.add("active"),s(t)):document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("'"+e+"'")&&(t.classList.add("active"),s(t))});const b=["graphics","memes-funny","art-inspiration","charts","swag-merch","fun-facts"].includes(e),v="https://bitcoineducation.quest/#"+e,w=c.title+" — Bitcoin Education Archive";let x;if(document.getElementById("hero").innerHTML='
    Home
    '+c.cat+"

    "+c.title+'

    "+(b?'":""),document.getElementById("hero").classList.remove("fade-in"),document.getElementById("msgs").innerHTML='
    Loading channel...
    ',document.getElementById("main").scrollTop=0,n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&(document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0)),V[e])x=V[e];else try{const t=await fetch(c.file);x=await t.json(),V[e]=x}catch(e){return void(document.getElementById("msgs").innerHTML='
    Error loading channel data
    ')}if(p=x,m=e,window.currentChannelId=e,u=!1,"function"==typeof window._raidOnChannelVisit&&window._raidOnChannelVisit(e),"function"==typeof _updateSEO&&void 0!==CHANNELS&&CHANNELS[e]){var k=CHANNELS[e];_updateSEO(e,k.title||k.name,k.desc||"")}if(g(e),window._searchScrollTarget&&window._searchScrollTarget.channel===e){var B=0;setTimeout(function e(){B++,window._searchScrollTarget&&(document.getElementById("msg-"+window._searchScrollTarget.msgIdx)||B>=3?"function"==typeof window._tryScrollToSearchResult&&window._tryScrollToSearchResult():setTimeout(e,400*B))},200)}document.getElementById("hero").classList.add("fade-in"),document.getElementById("msgs").classList.add("fade-in"),window._currentMsgs=x.msgs,window._currentOffset=o()?20:50,window._currentLoadChannel=e,window.loadMoreMsgs=function(){if(window._currentLoadChannel!==m)return;const e=window._currentOffset,t=window._currentMsgs,n=document.getElementById("loadMoreBtn");if(!n)return;const i=t.slice(e,e+50);let a="";i.forEach((t,n)=>{if(a+='
    ',t.text){let e=t.text,n=[],i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){var t=e.startsWith("http")?e:"https://"+e;return i.push(t),"%%TW"+(i.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){var n=i[parseInt(t)],a="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),l=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+l+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),a+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?a+='':a+=''}),a+="
    "}),n.insertAdjacentHTML("beforebegin",a),window._currentOffset=e+50,window._currentOffset>=t.length?(n.remove(),window._scrollObserver&&window._scrollObserver.disconnect()):n.textContent="Load more ("+(t.length-window._currentOffset)+" remaining)"},function(){if(window._scrollObserver&&(window._scrollObserver.disconnect(),window._scrollObserver=null),document.getElementById("loadMoreBtn")){window._scrollObserver=new IntersectionObserver(function(e){e[0].isIntersecting&&"function"==typeof window.loadMoreMsgs&&window.loadMoreMsgs()},{root:null,rootMargin:"300px",threshold:0});var e=document.getElementById("loadMoreBtn");e&&window._scrollObserver.observe(e)}}(),document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")});let S=safeJSON("btc_visited_channels",[]);S.includes(e)||(S.push(e),localStorage.setItem("btc_visited_channels",JSON.stringify(S)),Q());try{void 0!==db&&"undefined"!=typeof firebase&&db.collection("stats").doc("global").set({channelVisits:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}if("function"==typeof window._raidContribute&&window._raidContribute("channelVisit",1,e),x.msgs&&x.msgs.length>0){const t='
    Did this help you learn something?
    Your feedback helps Nacho improve the archive!
    ';a.insertAdjacentHTML("beforeend",t)}window._lastChannelOpenTime=Date.now(),"function"==typeof onChannelOpen&&onChannelOpen(e)};let K=!1,$={},Z=null;const ee=[{id:"_irl",title:"🤝 IRL Sync",desc:"Find and create local Bitcoin meetups and events",keywords:"irl meetup events sync meeting community local map gather conference meetup event rsvp",action:"go('irl-sync')"},{id:"_beats",title:"🎸 Bitcoin Beats",desc:"Community music — discover, upload, and listen to Bitcoin tracks. Upload entire albums and EPs.",keywords:"beats music livestream live video radio stream audio upload song track listen discover artist genre community album ep discography bulk batch dj broadcast",action:"go('bitcoin-beats')"},{id:"_nacho",title:"🦌 Nacho Mode",desc:"Interactive AI-powered Bitcoin tutor",keywords:"nacho mode ai chat ask question tutor learn mascot deer",action:"enterNachoMode()"},{id:"_forum",title:"🗣️ PlebTalk",desc:"Discuss Bitcoin with the community",keywords:"forum community chat discuss talk conversation post plebtalk reply thread threaded replies nested conversation",action:"go('forum')"},{id:"_articles",title:"📝 Articles",desc:"Read and write long-form Bitcoin articles",keywords:"article write publish essay blog read long form content author",action:"forumTab='articles';go('forum')"},{id:"_market",title:"⚡ LightningMart",desc:"Buy and sell with Bitcoin",keywords:"marketplace market buy sell trade shop store bitcoin sats lightning wallet hardware merch",action:"go('marketplace')"},{id:"_settings",title:"⚙️ Settings",desc:"Profile, rank, tickets, referral link, theme",keywords:"settings profile account rank level points tickets referral theme dark light audio sound notifications push",action:"showSettings()"},{id:"_spin",title:"🎡 Daily Spin",desc:"Spin the wheel for free Orange Tickets",keywords:"spin wheel daily reward ticket prize free",action:"showSpinWheel()"},{id:"_quest",title:"⚔️ Quest Hub",desc:"Quiz, Trivia, and Poll quests — earn XP!",keywords:"quest mission journey learn guided start challenge quiz trivia poll hub",action:"showQuestHub()"},{id:"_scholar",title:"🎓 Scholar Certification",desc:"Bitcoin Scholar & Protocol Expert Certifications",keywords:"scholar certification exam test certificate diploma bitcoin technical protocol",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_signal",title:"📡 The Signal",desc:"Weekly curated Bitcoin insights newsletter",keywords:"signal newsletter weekly email updates curated insights",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_flashcards",title:"📚 Flashcards",desc:"Study Bitcoin topics with interactive flashcards",keywords:"flashcard study cards learn review quiz prep memorize practice drill test",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_leaderboard",title:"🏆 Leaderboard",desc:"See top ranked Bitcoiners",keywords:"leaderboard ranking top leaders scoreboard competition",action:"toggleLeaderboard()"},{id:"_tickets",title:"🎟️ Orange Tickets",desc:"Earn tickets for giveaways and rewards",keywords:"tickets orange giveaway raffle prize sats reward earn",action:"showSettings()"},{id:"_referral",title:"🔗 Referral Program",desc:"Invite friends and earn 50 tickets each",keywords:"referral invite share link friend earn bonus",action:"showSettings()"},{id:"_closet",title:"🎽 Nacho's Closet",desc:"Dress up Nacho with items you unlock",keywords:"closet outfit clothes dress costume item equip nacho customize color hat scarf sunglasses crown hoodie accessories wardrobe",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_badges",title:"🏅 Badges",desc:"View your earned badges and goals — chat, DJ, discovery, knowledge",keywords:"badges achievement trophy unlock goal progress medal chat dj streak listener",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_story",title:"📖 Nacho's Story",desc:"Read Nacho's Bitcoin adventure — one chapter per day",keywords:"story chapter read book adventure nacho tale",action:"showNachoStory()"},{id:"_predict",title:"📈 Price Prediction",desc:"Predict if Bitcoin goes up or down in 24 hours",keywords:"predict prediction price bitcoin up down forecast",action:"showPricePrediction()"},{id:"_random",title:"🎲 Random Channel",desc:"Jump to a random Bitcoin channel",keywords:"random channel surprise discover explore dice",action:"goRandom()"},{id:"_meme",title:"😂 Random Meme",desc:"See a random Bitcoin meme",keywords:"meme funny joke random humor laugh memes",action:"goRandomMeme()"},{id:"_art",title:"🎨 Random Art",desc:"See random Bitcoin art and inspiration",keywords:"art random artwork creative inspiration gallery",action:"goRandomArt()"},{id:"_graphic",title:"📊 Random Graphic",desc:"See a random Bitcoin graphic or chart",keywords:"graphic chart data visual infographic random graphics",action:"goRandomGraphic()"},{id:"_quiz",title:"🎮 Quiz Me",desc:"Test your Bitcoin knowledge with Nacho",keywords:"quiz question test knowledge trivia game answer",action:"nachoQuizMe()"},{id:"_pvp",title:"⚔️ PVP Battle",desc:"Real-time Bitcoin trivia battles against other players",keywords:"pvp battle fight 1v1 versus trivia quiz compete multiplayer arena duel challenge opponent leaderboard wins losses",action:"enterPVPMode()"},{id:"_donate",title:"💛 Donate",desc:"Support Bitcoin Education Archive with sats",keywords:"donate support tip sats lightning contribute funding",action:"showDonateModal()"},{id:"_theme",title:"🌙 Toggle Theme",desc:"Switch between dark and light mode",keywords:"theme dark light mode toggle switch appearance color night day",action:'document.getElementById("themeToggle").click()'},{id:"_audio",title:"🔊 Toggle Audio",desc:"Turn sound effects on or off",keywords:"audio sound music mute volume effects toggle",action:"toggleAudio()"},{id:"_keyboard",title:"⌨️ Keyboard Shortcuts",desc:"View all keyboard shortcuts",keywords:"keyboard shortcut hotkey key binding keys shortcuts help",action:"showKeyboardHelp()"},{id:"_explore",title:"🗺️ Exploration Map",desc:"See which topics you have visited",keywords:"exploration map progress visited topics grid complete coverage",action:"goHome()"},{id:"_globalchat",title:"🌍 Global Chat",desc:"Live global chat room — talk with the community in real time",keywords:"global chat room live talk community message send public chatroom online users presence dm reaction gif emoji sticker emoji picker smiley face emoticon",action:"if(typeof renderChatHub==='function')renderChatHub('global');else if(typeof toggleChatOverlay==='function')toggleChatOverlay()"},{id:"_timechaintv",title:"📺 Timechain TV",desc:"Live Bitcoin television — 8 channels of curated Bitcoin videos playing 24/7",keywords:"tv television video watch live stream channel timechain tube youtube documentary tutorial mining sync broadcast cinema epg guide schedule remote couch nacho",action:"go('timechain-tv')"},{id:"_djmode",title:"🎧 DJ Mode",desc:"Go live as a DJ — broadcast music, use sound effects, crossfade, and play Bitcoin quotes",keywords:"dj mode broadcast live music stream turntable crossfade sound effects horn airhorn scratch mixer controls",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('livestream')},300)"},{id:"_upload_album",title:"📀 Upload Album/EP",desc:"Upload up to 20 songs at once — group as Album or EP with cover art",keywords:"upload album ep discography batch bulk multiple songs tracks artist release collection",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('upload')},300)"},{id:"_messages",title:"💬 Messages / DMs",desc:"Direct messages — chat privately with other users",keywords:"messages dm direct message inbox chat private conversation contact send receive talk",action:"showInbox()"},{id:"_signin",title:"🔐 Sign In",desc:"Sign in or create an account",keywords:"sign in login register create account google twitter github facebook email",action:"showUsernamePrompt()"},{id:"_home",title:"🏠 Home",desc:"Return to the homepage",keywords:"home main start beginning",action:"goHome()"},{id:"_firstpurchase",title:"🛒 Your First Bitcoin Purchase",desc:"Step-by-step guide to buying your first Bitcoin — apps for 11 regions",keywords:"buy purchase first bitcoin exchange app strike river cash coinbase amber wallet region country how to start beginner dca",action:"go('first-purchase')"},{id:"_trails",title:"🦌 Nacho's Trails",desc:"Guided learning paths through Bitcoin education — Meadow, Mountain & Summit",keywords:"trails nacho guided path learning course module meadow mountain summit exam test progress curriculum education beginner intermediate advanced",action:"go('trails')"},{id:"_dashboard",title:"📊 Top Indicators",desc:"Live Bitcoin cycle top indicators — Pi Cycle, NUPL, Puell, Power Law & more",keywords:"dashboard indicators top cycle signal pi cycle nupl puell mayer multiple rsi ahr999 mstr etf power law rainbow reserve risk bitcoin metrics data analytics chart",action:"if(typeof toggleDashboard==='function')toggleDashboard()"},{id:"_meetupbox",title:"📦 Meetup-in-a-Box",desc:"Ready-made meetup templates with agendas and host tips",keywords:"meetup box template agenda host tips lightning workshop self custody mining event organize plan download",action:"go('irl-sync')"},{id:"_buddy",title:"🤝 Bitcoin Buddy",desc:"Find a learning partner — teachers matched with learners",keywords:"buddy partner match learn teach mentor mentee pair connect chat find friend study accountability group",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_certs",title:"📜 Shareable Certificates",desc:"Share your Scholar Certification with a verifiable public link",keywords:"certificate share verify link public proof scholar achievement social media url",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_satsvbits",title:"⚡ Sats vs Bits",desc:"Live community vote — sats or bits for the Bitcoin denomination?",keywords:"sats bits vote poll denomination unit satoshi community debate live",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_newbie",title:"🟢 Brand New to Bitcoin?",desc:"Quick introduction for absolute beginners",keywords:"new beginner brand new start zero nothing know nothing introduction first time newbie noob",action:"go('one-stop-shop')"},{id:"_meetupbuilder",title:"🔨 Meetup Builder",desc:"Plan, share, and discover Bitcoin meetups — resources, venues & guides",keywords:"meetup builder create plan share venue platform resource guide community",action:"go('meetup-builder')"},{id:"_sats",title:"⚡ Claim Sats",desc:"Convert your earned points into real Bitcoin sats via Lightning",keywords:"sats claim withdraw cashout bitcoin lightning faucet earn XP convert redeem payout real btc satoshi",action:"showSettings();setTimeout(function(){showSettingsPage('sats')},100)"},{id:"_tips",title:"⚡ Lightning Tips",desc:"Tip other users with Lightning sats",keywords:"tip tips lightning send sats zap reward give appreciation",action:"if(typeof showTipOverlay==='function')showTipOverlay()"},{id:"_network",title:"📡 Bitcoin Network",desc:"Live mempool, hashrate, difficulty, fees, and block explorer",keywords:"network mempool hashrate difficulty fees block explorer transaction confirmations bitcoin network stats",action:"go('bitcoin-dashboard')"},{id:"_notifications",title:"🔔 Notifications",desc:"Enable push notifications for updates and alerts",keywords:"notifications push alerts notify bell updates permission enable disable",action:"if(typeof requestNotificationPermission==='function')requestNotificationPermission();else showSettings()"},{id:"_streakfreeze",title:"🧊 Streak Freeze",desc:"Protect your visit streak with freeze tickets",keywords:"streak freeze ticket protect miss save guard insurance ice",action:"showSettings();setTimeout(function(){showSettingsPage('data')},100)"},{id:"_cotd",title:"📅 Channel of the Day",desc:"Today's featured Bitcoin education channel",keywords:"channel of the day daily featured recommendation today pick spotlight",action:"goHome()"},{id:"_nostr",title:"🟣 Nostr Login",desc:"Sign in with Nostr — extension, nsec, or npub",keywords:"nostr login sign in nip npub nsec extension relay decentralized identity",action:"showUsernamePrompt()"},{id:"_buddyfind",title:"🤝 Find a Bitcoin Buddy",desc:"Get matched with a learning partner — teachers meet learners",keywords:"buddy partner match learn teach mentor mentee pair connect study group accountability partner friend",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_favor",title:"✨⛏️ Satoshi's Favor",desc:"Community mining game — earn points, activate mining, hash for 21,000 sats",keywords:"satoshi favor mining hash mine community points activate 21 sats game block nonce difficulty target hashing brute force proof of work",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='favor';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_raid",title:"⚔️ Raid Boss",desc:"Monthly community challenge — deal damage by earning badges and completing activities",keywords:"raid boss challenge monthly community damage badge activity quest defeat winner prize leaderboard attack",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='raid';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_charity",title:"❤️ Donate XP for Charity",desc:"Donate your XP points for charity — 1,000 XP = 1,000 sats pledged. 10× more impact than redeeming for yourself.",keywords:"charity donate donation xp points sats bitcoin giving community philanthropy pledge faction badger hornet",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='charity';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_pow",title:"🚶 Proof of Walk",desc:"Connect Strava and earn XP for walking — proof of work with your feet",keywords:"proof of walk strava walking steps exercise fitness health outdoor move earn xp activity sync connect",action:"go('explore');setTimeout(function(){if(typeof renderProofOfWalk==='function')renderProofOfWalk()},300)"},{id:"_pop",title:"🕹️ Proof of Play",desc:"Bitcoin gaming hub — Timechain Arcade games + PVP trivia battles",keywords:"proof of play arcade games pvp battle timechain bitcoin gaming 1v1 trivia lightning to the moon node runner nakamoto knights block hunt",action:'if(typeof enterProofOfPlay==="function")enterProofOfPlay()'}];function te(e){const t=document.getElementById("searchResults"),o=document.getElementById("channelList");if(["searchInput","searchOverlayInput"].forEach(t=>{const o=document.getElementById(t);o&&o.value!==e&&(o.value=e)}),e&&"satoshi"===e.toLowerCase()&&("function"==typeof awardHiddenBadge&&awardHiddenBadge("discovery_satoshi","Found Satoshi! 🦢"),F("I am Satoshi. We are all Satoshi.")),e&&"deer"===e.toLowerCase()&&("function"==typeof setPose&&setPose("celebrate"),F("Fawntastic! You found the secret buck."),"function"==typeof nachoFly&&setTimeout(nachoFly,1e3)),!e||e.length<2){var n=safeJSON("btc_recent_searches",[]);if(n.length>0&&t){var i='
    🕐 Recent Searches
    ';n.forEach(function(e){i+=""}),i+="
    ",t.innerHTML=i,t.classList.add("active")}else t.classList.remove("active"),t.innerHTML="";return void(o&&(o.style.display=""))}e=e.toLowerCase(),o.style.display="none",t.classList.add("active");let a=[];for(const t of ee)(t.title.toLowerCase().includes(e)||t.keywords.includes(e)||t.desc.toLowerCase().includes(e))&&a.push({key:t.id,title:t.title,cat:"⚡ App",match:t.desc,action:t.action});let r=[];for(const[t,o]of Object.entries(CHANNELS))(o.title.toLowerCase().includes(e)||o.desc.toLowerCase().includes(e))&&r.push({key:t,title:o.title,cat:o.cat,match:"Channel match"});ie([...a,...r],t),clearTimeout(Z),Z=setTimeout(async()=>{await async function(){if(K)return;const e=Object.entries(CHANNELS).map(async([e,t])=>{if(V[e])$[e]=V[e];else try{const o=await fetch(t.file),n=await o.json();V[e]=n,$[e]=n}catch(e){}});await Promise.all(e),K=!0}();let o=[];for(const[t,n]of Object.entries($)){const i=CHANNELS[t];if(!i)continue;if(r.some(e=>e.key===t))continue;const a=n.msgs||[];for(let n=0;n0?"...":"")+r.text.substring(s,a+e.length+30).replace(/<[^>]+>/g,"")+"...";o.push({key:t,title:i.title,cat:i.cat,match:l,msgIdx:n});break}}}ie([...a,...r,...o],t)},500)}const oe=[{q:"What is Bitcoin?",icon:"💰",reason:"Most asked"},{q:"Lightning Network",icon:"⚡",reason:"Trending"},{q:"How to buy Bitcoin",icon:"🛒",reason:"Popular"},{q:"Self-custody wallets",icon:"🔐",reason:"Essential"},{q:"Bitcoin vs Ethereum",icon:"🆚",reason:"Hot topic"},{q:"Why 21 million?",icon:"🔢",reason:"Fundamental"},{q:"Mining explained",icon:"⛏️",reason:"Technical"},{q:"Bitcoin security",icon:"🛡️",reason:"Important"}];function ne(){var e=document.getElementById("searchResults");if(e){var t='
    🔥 Trending Topics
    ';oe.forEach(function(e){t+=""}),t+="
    ",e.innerHTML=t,e.classList.add("active")}}function ie(e,t){0!==e.length?t.innerHTML=e.slice(0,30).map(e=>{const t=e.key&&e.key.startsWith("_");return'
    "+e.cat+"
    "+e.title+'
    '+e.match+"
    "}).join(""):t.innerHTML='
    No results found
    Try: "Lightning Network" or "What is Bitcoin?"
    '}function ae(e,t){var o=document.getElementById("searchOverlayInput"),n=document.getElementById("searchInput"),i=o&&o.value||n&&n.value||"";!function(e){if(e&&!(e.length<2)){var t=safeJSON("btc_recent_searches",[]);(t=t.filter(function(t){return t.toLowerCase()!==e.toLowerCase()})).unshift(e.length>40?e.substring(0,40):e),t.length>10&&(t=t.slice(0,10)),localStorage.setItem("btc_recent_searches",JSON.stringify(t))}}(i),n&&(n.value=""),o&&(o.value=""),document.getElementById("searchOverlay").style.display="none",te(""),"number"==typeof t&&t>=0&&(window._searchScrollTarget={channel:e,msgIdx:t,query:i}),go(e)}window._tryScrollToSearchResult=function(){var e=window._searchScrollTarget;if(e){var t=e.msgIdx;if(e.query,window._searchScrollTarget=null,t>=(o()?20:50)&&"function"==typeof window.loadMoreMsgs)for(var n=0;!document.getElementById("msg-"+t)&&document.getElementById("loadMoreBtn")&&n<50;)window.loadMoreMsgs(),n++;var i=document.getElementById("msg-"+t);i&&setTimeout(function(){i.scrollIntoView({behavior:"smooth",block:"center"}),i.style.transition="background 0.3s, box-shadow 0.3s",i.style.background="rgba(249,115,22,0.12)",i.style.boxShadow="inset 3px 0 0 #f97316",i.style.borderRadius="8px",setTimeout(function(){i.style.background="",i.style.boxShadow="",i.style.borderRadius=""},3e3)},300)}},function(){const e=document.getElementById("visitCount");setTimeout(function(){if("undefined"==typeof firebase||!firebase.firestore)return;const t=firebase.firestore(),o=(new Date).toISOString().split("T")[0];for(var n=[screen.width,screen.height,screen.colorDepth,Intl.DateTimeFormat().resolvedOptions().timeZone,navigator.language,navigator.hardwareConcurrency||0,navigator.platform].join("|"),i=0,a=0;a{a.textContent="Submit Suggestion",a.disabled=!1},3e3)}catch(e){i.innerHTML='Error submitting. Please try again.',a.textContent="Submit Suggestion",a.disabled=!1}}else i.innerHTML='Please enter a suggestion!'},function(){const e=Object.keys(CHANNELS),t=new Date,o=e[Math.floor((t-new Date(t.getFullYear(),0,0))/864e5)%e.length],n=CHANNELS[o];if(n){const e=document.getElementById("dailyChannel");e.innerHTML='
    📅 Channel of the Day
    '+n.title+'
    '+n.desc+"
    ",e.onclick=()=>go(o)}}(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof renderExplorationMap&&renderExplorationMap(),window.innerWidth>900&&document.getElementById("main").addEventListener("scroll",function(){const e=this;document.getElementById("backToTop").classList.toggle("visible",e.scrollTop>400);var t=e.scrollTop+e.clientHeight>=e.scrollHeight-200;document.getElementById("scrollToBottom").classList.toggle("visible",!t)}),window._launchPVP=function(){if("function"==typeof enterPVPMode)enterPVPMode();else{"function"==typeof window._loadDeferred&&window._loadDeferred(),"function"==typeof showToast&&showToast("⚔️ Loading PVP arena...");var e=0,t=setInterval(function(){e++,"function"==typeof enterPVPMode?(clearInterval(t),enterPVPMode()):e>15&&(clearInterval(t),"function"==typeof showToast&&showToast("⚠️ PVP failed to load — try refreshing the page"))},200)}},window.toggleAppsMenu=function(e){e&&e.stopPropagation();var t=document.getElementById("appsMenu");if(t&&"block"===t.style.display)t.style.display="none";else{t&&t.remove();var o=safeJSON("btc_visited_channels",[]).length,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i=void 0!==auth?auth:null,a=i&&i.currentUser,r=a&&-1!==["needcreations@gmail.com","info.603btc@gmail.com"].indexOf(a.email||""),s="function"==typeof getOnboardingProfile?getOnboardingProfile():null,l=s&&("advanced"===s.level||"full"===s.level)||r||a&&!a.isAnonymous||n>=10||o>=10,c=l||n>=5||o>=5,d="padding:15px;background:var(--card-bg);border:1px solid var(--border);border-radius:16px;color:var(--text);font-size:0.85rem;font-weight:700;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:8px;transition:0.2s;",u=d+"opacity:0.45;filter:grayscale(0.8);cursor:help;",p={"Nacho Mode":"Chat with our AI Bitcoin tutor","Proof of Play":"Bitcoin gaming hub — Arcade + PVP","Pleb Talk":"Community discussion board for Bitcoin topics","Lightning Mart":"Buy and sell with Lightning sats","IRL Sync":"Find or host local Bitcoin meetups","Bitcoin Beats":"Community music player","Timechain TV":"21 channels of Bitcoin video content","Proof of Walk":"Earn XP by walking — connect Strava","Proof of Play":"Bitcoin gaming hub — Arcade + PVP"},m=!(c||n>=3||o>=3),h=!c,g=!l,f="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Bitcoin Beats!",y="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Pleb Talk!",b="🔒 Explore "+Math.max(0,5-o)+" more topics to unlock IRL Sync!",v="🔒 Explore "+Math.max(0,10-o)+" more topics or sign in to unlock Lightning Mart!",w='";document.body.insertAdjacentHTML("beforeend",w);var x=document.getElementById("appsMenu");document.addEventListener("click",function(e){"block"!==x.style.display||x.contains(e.target)||(x.style.display="none")}),x.style.display="block","function"==typeof playSound&&playSound("pop")}function k(e,t,o,n,i){var a=p[t]||t;return n?"":""}},window.showProofOfWalk=function(){var e=document.getElementById("appsMenu");e&&(e.style.display="none");var t=document.getElementById("main");t&&(t.innerHTML='
    ',window.renderProofOfWalk&&window.renderProofOfWalk())},window.toggleSidebarMenu=function(e){var t=document.getElementById(e);t&&("flex"===t.style.display||"grid"===t.style.display||"block"===t.style.display?t.style.display="none":(e.includes("Flash")?t.style.display="flex":e.includes("homeAppsMenu")?t.style.display="grid":(t.style.display="flex",t.style.flexDirection="column"),"function"==typeof playSound&&playSound("pop")))},window.onload=()=>{"true"!==localStorage.getItem("btc_nacho_mode_default")||window.location.hash||setTimeout(function(){"function"==typeof enterNachoMode&&enterNachoMode()},1500),safeJSON("btc_visited_channels",[]).forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})}),c(),R(),"function"==typeof checkPredictionResult&&setTimeout(checkPredictionResult,4e3);var e=window.location.hash||"";history.state||(history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname+e)),window.addEventListener("popstate",function(e){var t=e.state||{},o=location.hash.slice(1);if(o||"function"!=typeof _parseCleanUrl||(o=_parseCleanUrl()||""),!e.state||t.guard)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);if(!e.state&&!o)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);var n=document.getElementById("notifPanel");if(n&&"translateY(0px)"===n.style.transform)"function"==typeof toggleNotifOverlay&&toggleNotifOverlay();else if(window._chatOverlayOpen)"function"==typeof toggleChatOverlay&&toggleChatOverlay();else{var i=document.getElementById("usernameModal");if(i&&i.classList.contains("open"))return i.classList.remove("open"),void("function"==typeof window._restoreSignUpForm&&window._restoreSignUpForm());var a=document.getElementById("mobileLearnMenu");if(a)a.remove();else{var r=document.getElementById("appsMenu");if(r&&"block"===r.style.display)r.style.display="none";else{var s=document.getElementById("questModal");if(s&&s.classList.contains("open"))s.classList.remove("open");else if(t.returnToGuide)"function"==typeof showGuide&&(showGuide(),setTimeout(function(){var e=document.getElementById("guideOverlay");if(e&&window._guideScrollTop){var t=e.querySelector('div[style*="border-radius:24px"]');t&&(t.scrollTop=window._guideScrollTop)}},500));else{for(var l=["guideOverlay","onboardingOverlay","pvpNameOverlay","pvpOverlay","tipOverlay","donateModal","lnAuthModal","nostrAuthOverlay","spinModal","hostEventModal","eventDetailOverlay","editEventOverlay","nachoColorPicker","articleLinkDialog","articleImageDialog","eli5Prompt","kbHelpModal","forumRulesOverlay","chatRulesOverlay","marketRulesOverlay","irlRulesOverlay"],c=0;c30&&clearInterval(o)},300)},1500)},function(){function e(){var e=window.location.hash.replace("#","");if(e||"function"!=typeof _parseCleanUrl||(e=_parseCleanUrl()||""),e){console.log("[ROUTE] Routing to:",e);var t=0;setTimeout(function o(){if(t>8e3)console.warn("[HASH] Gave up routing to:",e);else{if(!document.getElementById("msgs")||!document.getElementById("home"))return t+=200,void setTimeout(o,200);switch(e){case"nacho":if("function"==typeof enterNachoMode)return void enterNachoMode();break;case"pvp":if("function"==typeof enterPVPMode)return void enterPVPMode();break;case"forum":if("function"==typeof go)return void go("forum");break;case"marketplace":if("function"==typeof go)return void go("marketplace");break;case"first-purchase":case"buy":if("function"==typeof go)return void go("first-purchase");break;case"trails":case"learn":case"modules":if("function"==typeof go)return void go("trails");break;case"meetup-builder":if(window._mbRouted)return;if("function"==typeof go){window._mbRouted=!0,window._skipIRLRules=!0,localStorage.setItem("btc_irl_rules_accepted","true"),go("irl-sync"),setTimeout(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove()},100),history.replaceState({channel:"meetup-builder"},"","#meetup-builder");var n=0,i=setInterval(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove();var t=document.getElementById("meetupBuilderSection");t&&(clearInterval(i),t.scrollIntoView({behavior:"smooth",block:"start"})),++n>30&&clearInterval(i)},300);return}break;case"irl-sync":case"meet":if("function"==typeof go)return void go("irl-sync");break;case"bitcoin-beats":if("function"==typeof go)return void go("bitcoin-beats");break;case"chat":if("function"==typeof renderChatHub)return void renderChatHub("global");break;case"dms":if("function"==typeof renderChatHub)return void renderChatHub("dms");if("function"==typeof openDMInbox)return void openDMInbox();if("function"==typeof showInbox)return void showInbox();break;case"lightning":if("function"==typeof go)return void go("lightning");break;case"timechain-tv":case"tv":if("function"==typeof go)return void go("timechain-tv");break;case"pow-support":if("function"==typeof renderPOWSupport)return void renderPOWSupport();break;case"quests":if("function"==typeof showQuestHub)return void showQuestHub();break;case"dashboard":case"bitcoin-dashboard":case"metrics":case"network":if("function"==typeof toggleDashboard)return history.replaceState({home:!0},"",window.location.pathname),void toggleDashboard();break;default:if(0===e.indexOf("beats/")&&"function"==typeof go&&!window._beatsRouted){if(0===e.indexOf("beats/playlist/")){var a=e.replace("beats/playlist/","").split("/");2===a.length&&(window._beatsDeepLink={type:"playlist",ownerUid:a[0],playlistId:a[1]})}else{var r=e.replace("beats/","");r&&-1===r.indexOf("/")&&(window._beatsDeepLink={type:"track",trackId:r})}return window._beatsRouted=!0,void go("bitcoin-beats")}if(0===e.indexOf("beats/")&&window._beatsRouted)return;if(0===e.indexOf("cert/")&&"function"==typeof go)return void go(e);if("function"==typeof go&&void 0!==CHANNELS&&CHANNELS[e])return void go(e)}t+=200,setTimeout(o,200)}},500)}}e(),window.addEventListener("load",function(){setTimeout(function(){var t=window.location.hash.replace("#","");t&&document.getElementById("home")&&!document.getElementById("home").classList.contains("hidden")&&(console.log("[HASH] Post-load fallback routing to:",t),e())},800)}),window.addEventListener("hashchange",e)}(),void 0!==r&&(window.toggleCat=r),void 0!==n&&(window.toggleTheme=n),void 0!==J&&(window.toggleAudio=J),void 0!==Y&&(window.setVolume=Y),void 0!==A&&(window.handleSupportClick=A),"undefined"!=typeof showDonateModal&&(window.showDonateModal=showDonateModal),"undefined"!=typeof enterNachoMode&&(window.enterNachoMode=enterNachoMode),"undefined"!=typeof goHome&&(window.goHome=goHome),void 0!==v&&(window.goRandom=v),void 0!==k&&(window.goRandomArt=k),void 0!==x&&(window.goRandomMeme=x),void 0!==B&&(window.goRandomGraphic=B),void 0!==te&&(window.doSearch=te),void 0!==ne&&(window.showTrendingTopics=ne),void 0!==ae&&(window.selectResult=ae),void 0!==i&&(window.toggleMenu=i),void 0!==a&&(window.toggleSidebarCollapse=a),void 0!==t&&(window.openImg=t),void 0!==d&&(window.toggleFav=d),void 0!==T&&(window.shareNostr=T),void 0!==C&&(window.copyLink=C),void 0!==h&&(window.toggleGallery=h),void 0!==g&&(window.renderContent=g),"undefined"!=typeof showBeginnerGuide&&(window.showBeginnerGuide=showBeginnerGuide),void 0!==y&&(window.loadTweetEmbed=y)}(),window._spinSoundCtx=null,window.playSpinTick=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx,t=e.createOscillator(),o=e.createGain();t.connect(o),o.connect(e.destination),t.frequency.value=800+400*Math.random(),t.type="triangle",o.gain.value=.08,o.gain.exponentialRampToValueAtTime(.001,e.currentTime+.08),t.start(e.currentTime),t.stop(e.currentTime+.08)}catch(e){}},window._tctvTimer=null,window._tctvMinutesSession=0,window._tctvStartTracker=function(){if(!window._tctvTimer){window._tctvMinutesSession=0;try{var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_tctv_visited_"+e,"true")}catch(e){}console.log("[TCTV] Watch tracker started."),window._tctvTimer=setInterval(function(){if("timechain-tv"===(window.currentChannelId||"")){if(!document.hidden){var e=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")+1;localStorage.setItem("btc_tctv_watch_time",e.toString()),window._tctvMinutesSession++;try{var t=(new Date).toISOString().split("T")[0],o=parseInt(localStorage.getItem("btc_tctv_minutes_"+t)||"0")+1;localStorage.setItem("btc_tctv_minutes_"+t,String(o))}catch(e){}console.log("[TCTV] Watch time:",e,"min (Session:",window._tctvMinutesSession,"min)");try{void 0!==db&&"undefined"!=typeof firebase&&void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("stats").doc("global").set({watchTimeMinutes:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}e%10==0?("function"==typeof awardPoints&&awardPoints(10,"tctv_watch_10m"),"function"==typeof checkBadges&&checkBadges(),"function"==typeof showToast&&showToast("👁️ +10 Points — Thanks for watching Timechain TV!")):1===e&&"function"==typeof showToast&&showToast("📺 Watching Timechain TV — Points awarded every 10 min!")}}else window._tctvStopTracker()},6e4)}},window._tctvStopTracker=function(){window._tctvTimer&&(clearInterval(window._tctvTimer),window._tctvTimer=null,console.log("[TCTV] Watch tracker stopped. Total minutes watched:",window._tctvMinutesSession))},window._updateSEO=function(e,t,o){if(e){document.title=(t?t+" | ":"")+"Bitcoin Education Archive";var n=document.querySelector('link[rel="canonical"]');if(n){var i="home"===e||"/"===e?"":"/app/"+e;n.setAttribute("href","https://bitcoineducation.quest"+i)}var a=document.querySelector('meta[name="description"]');a&&o&&a.setAttribute("content",o.substring(0,160));var r=window._cleanUrl(e);window.location.href.includes(r)||history.replaceState({channel:e},"",r)}},window.playSpinWin=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx;[523,659,784,1047].forEach(function(t,o){var n=e.createOscillator(),i=e.createGain();n.connect(i),i.connect(e.destination),n.frequency.value=t,n.type="sine",i.gain.value=.1,i.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15*(o+1)+.3),n.start(e.currentTime+.15*o),n.stop(e.currentTime+.15*(o+1)+.3)})}catch(e){}},window._aiToolsOpen=!1,window.toggleAITools=function(){var e=document.getElementById("aiToolsPanel");if(!e){(e=document.createElement("div")).id="aiToolsPanel",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:250000;background:var(--bg,#0a0a0f);border-top:2px solid var(--accent,#f7931a);border-radius:16px 16px 0 0;transform:translateY(100%);transition:transform 0.3s ease;box-shadow:0 -10px 40px rgba(0,0,0,0.6);",e.innerHTML='
    🤖AI Toolspowered by PPQ
    ',document.body.appendChild(e);var t=document.createElement("style");t.id="aiToolsPanelCSS",t.textContent="@media(min-width:901px){#aiToolsPanel{max-width:480px;right:16px;left:auto;border-radius:16px 16px 0 0;}}@media(max-width:900px){#aiToolsPanel iframe{height:calc(70vh - 56px);}}",document.head.appendChild(t)}window._aiToolsOpen=!window._aiToolsOpen,e.style.transform=window._aiToolsOpen?"translateY(0)":"translateY(100%)";var o=document.getElementById("aiToolsBtn");if(o&&(o.style.background=window._aiToolsOpen?"var(--card-bg)":"linear-gradient(135deg,#6366f1,#8b5cf6)",o.style.borderColor=window._aiToolsOpen?"var(--accent)":"transparent"),window._aiToolsOpen&&void 0!==db&&db)try{var n=auth&&auth.currentUser?auth.currentUser.uid:"anon_"+(localStorage.getItem("visitorId")||"unknown");db.collection("ai_tools_opens").add({uid:n,openedAt:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){console.warn("[AI Tools] tracking error",e)}},function(){function e(){var e=document.getElementById("aiToolsBtn");e||((e=document.createElement("button")).id="aiToolsBtn",e.className="fab-btn",e.innerHTML="🤖",document.body.appendChild(e)),e.onclick=toggleAITools}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}(),function(){var e=window.renderBitcoinBeats;e&&(window.renderBitcoinBeats=function(){e(),setTimeout(function(){document.getElementById("beatsLoader");var e=document.getElementById("beatsEmbedArea");if(e){var t=e.querySelector("iframe"),o=e.querySelector(".twitter-tweet-rendered, twitter-widget");t||o||(e.innerHTML='
    🎸
    Stream Unavailable
    The live stream couldn\'t be loaded. Check out these great Bitcoin audio sources instead:
    ')}},8e3)})}(),void 0===window.contactSeller&&(window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to contact sellers!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==db&&db.collection("marketplace").doc(e).get().then(function(e){if(e.exists){var t=e.data(),o=t.sellerUid;o!==auth.currentUser.uid?("function"==typeof openDM?openDM(o,t.sellerName||"Seller"):"function"==typeof showInbox&&(showInbox(),setTimeout(function(){"function"==typeof startNewDM&&startNewDM(o,t.sellerName||"Seller")},500)),void 0!==db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1),"function"==typeof showToast&&showToast("💬 Opening chat with "+(t.sellerName||"seller")+"...")):"function"==typeof showToast&&showToast("That's your own listing!")}})}),window.handleMktImageUploadV2=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var o=document.getElementById("mktImagePreview"),n=document.getElementById("mktImagePreviewImg");if(o&&(o.style.display="block",n&&(n.src=""),o.innerHTML='
    📤 Uploading...
    '),"undefined"!=typeof firebase&&firebase.storage){var i=firebase.storage().ref(),a="marketplace/"+auth.currentUser.uid+"/"+Date.now()+"_"+t.name.replace(/[^a-zA-Z0-9.]/g,"_"),r=i.child(a).put(t,{contentType:t.type});r.on("state_changed",function(e){var t=Math.round(e.bytesTransferred/e.totalBytes*100);o&&(o.innerHTML='
    📤 Uploading... '+t+"%
    ")},function(t){"function"==typeof showToast&&showToast("Upload failed: "+t.message),o&&(o.style.display="none"),handleMktImageUpload(e)},function(){r.snapshot.ref.getDownloadURL().then(function(e){window._mktUploadedImage=e,o&&n&&(o.innerHTML=''),"function"==typeof showToast&&showToast("✅ Image uploaded!")})})}else"function"==typeof handleMktImageUpload&&handleMktImageUpload(e)}else"function"==typeof showToast&&showToast("Sign in to upload images")},function(){var e=[{type:"youtube",id:"UvSnC7P-m-U",title:"What is Bitcoin? — Andreas Antonopoulos",desc:"The best intro talk ever given"},{type:"youtube",id:"l1si5ZWLgy0",title:"Bitcoin for Beginners — BTC Sessions",desc:"Step-by-step Bitcoin guide"},{type:"youtube",id:"ZKwqNgG-Sv4",title:"The Bitcoin Standard — Saifedean Ammous",desc:"Author presentation on sound money"},{type:"youtube",id:"2pDlaOGA2ac",title:"How Bitcoin Works Under the Hood",desc:"Technical deep-dive"},{type:"youtube",id:"bBC-nXj3Ng4",title:"But How Does Bitcoin Actually Work?",desc:"3Blue1Brown explains"},{type:"youtube",id:"Gc2en3nHxA4",title:"Michael Saylor on Why Bitcoin",desc:"The macro case for Bitcoin"},{type:"youtube",id:"xLYhx1z7gC4",title:"This Machine Greens — Bitcoin & Energy",desc:"Bitcoin mining documentary"},{type:"youtube",id:"HCLWDGYnAzk",title:"Running a Bitcoin Node — Ministry of Nodes",desc:"How to verify for yourself"}];window.beatsPlaylistIndex=parseInt(localStorage.getItem("btc_beats_idx")||"0")%e.length,window.renderBeatsPlaylist=function(t){if(t){var o=e[window.beatsPlaylistIndex],n=e.length,i=window.beatsPlaylistIndex,a='
    ';a+='
    ',a+='
    '+o.title+'
    '+o.desc+" • "+(i+1)+"/"+n+'
    ',t.innerHTML=a}},window.beatsNav=function(t){window.beatsPlaylistIndex=(window.beatsPlaylistIndex+t+e.length)%e.length,localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var o=document.getElementById("beatsEmbedArea");o&&renderBeatsPlaylist(o)},window.beatsNavRandom=function(){window.beatsPlaylistIndex=Math.floor(Math.random()*e.length),localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var t=document.getElementById("beatsEmbedArea");t&&renderBeatsPlaylist(t)};var t=8e3,o=setInterval(function(){var e=document.getElementById("beatsEmbedArea");e&&(document.getElementById("beatsLoader")?(t-=500)<=0&&(clearInterval(o),renderBeatsPlaylist(e)):clearInterval(o))},500)}(),window.fuzzyMatch=function(e,t){if(!t||!e)return!0;var o=e.toLowerCase();return t.toLowerCase().split(/\s+/).every(function(e){return-1!==o.indexOf(e)})},function(){function e(){return!(!auth||!auth.currentUser)&&"needcreations@gmail.com"===(auth.currentUser.email||"")}window.forumEditPost=function(t){auth&&auth.currentUser&&void 0!==db&&db.collection("forum_posts").doc(t).get().then(function(o){if(o.exists){var n=o.data();if(n.authorId===auth.currentUser.uid||e()){var i=n.createdAt?n.createdAt.toDate():new Date;if(Date.now()-i.getTime()>9e5&&!e())"function"==typeof showToast&&showToast("Posts can only be edited within 15 minutes of creation");else{var a='
    ✏️ Edit Post
    Edited posts will show an "edited" indicator
    ',r=document.createElement("div");r.innerHTML=a,document.body.appendChild(r.firstChild)}}else"function"==typeof showToast&&showToast("You can only edit your own posts")}})},window.forumSaveEdit=function(e){var t=(document.getElementById("editPostTitle").value||"").trim(),o=(document.getElementById("editPostBody").value||"").trim();!t||t.length<5?"function"==typeof showToast&&showToast("Title must be at least 5 characters"):"function"!=typeof isCleanText||isCleanText(t+" "+o)?db.collection("forum_posts").doc(e).update({title:t.substring(0,120),body:o.substring(0,2e3),editedAt:firebase.firestore.FieldValue.serverTimestamp(),edited:!0}).then(function(){var t=document.getElementById("forumEditOverlay");t&&t.remove(),"function"==typeof showToast&&showToast("✅ Post updated!"),"function"==typeof forumViewPost&&forumViewPost(e,!0)}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))}):"function"==typeof showToast&&showToast("Post contains inappropriate language")}}(),function(){var e=[{level:1,name:"Just Met",emoji:"🦌",threshold:1},{level:2,name:"Getting Acquainted",emoji:"👋",threshold:10},{level:3,name:"Good Friends",emoji:"😊",threshold:100},{level:4,name:"Close Friends",emoji:"🧡",threshold:350},{level:5,name:"Best Buds",emoji:"💛",threshold:750}],t=window.trackNachoInteraction;t&&(window.trackNachoInteraction=function(){for(var o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),n=0,i=e.length-1;i>=0;i--)if(o>=e[i].threshold){n=e[i].level;break}t();for(var a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r=0,s=null,l=e.length-1;l>=0;l--)if(a>=e[l].threshold){r=e[l].level,s=e[l];break}if(r>n&&s){var c=JSON.parse(localStorage.getItem("btc_nacho_level_celebrated")||"[]");-1===c.indexOf(s.level)&&(c.push(s.level),localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(c)),"function"==typeof syncCelebratedState&&syncCelebratedState(),setTimeout(function(){var e="function"==typeof nachoUserName?nachoUserName():"",t=s.emoji+" "+(e?e+", w":"W")+"e just became "+s.name+"! "+(s.level>=3?"New closet items are now available! Check the Closet! 👔✨":"Keep chatting with me to unlock more! 🦌");"function"==typeof forceShowBubble?(forceShowBubble(t),s.level>=3&&setTimeout(function(){var e=document.getElementById("nacho-bubble");e&&(e.style.cursor="pointer",e.onclick=function(){e.classList.remove("show"),window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},300)})},100)):"function"==typeof showToast&&showToast("🦌 Friendship Level Up: "+s.emoji+" "+s.name+"!")},1e3))}})}(),function(){var e=[],t=!1,o=0;function n(){if(!t&&0!==e.length){var i=Date.now();if(i-o<3e4)setTimeout(n,3e4-(i-o)+100);else{t=!0;var a=e.shift();o=i;try{a.show()}catch(e){console.log("Notification error:",e)}setTimeout(function(){t=!1,n()},5e3)}}}window.queueNotification=function(t,o){e.push({type:t,show:o,queued:Date.now()}),n()};var i=window.showToast;i&&(window.showToastQueued=function(e){queueNotification("toast",function(){i(e)})})}(),window.initMiniPlayer=function(){if(!document.getElementById("miniPlayer")){var e=document.createElement("div");e.id="miniPlayer",e.style.cssText="position:fixed;bottom:60px;left:0;right:0;z-index:180;background:rgba(10,10,10,0.95);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-top:1px solid rgba(247,147,26,0.3);padding:8px 16px;display:none;align-items:center;gap:12px;",e.innerHTML='
    Not playing
    Bitcoin Beats
    ',document.body.appendChild(e)}},window._miniPlayerAudio=null,window.playInMiniPlayer=function(e,t,o){initMiniPlayer();var n=document.getElementById("miniPlayer");n&&(window._miniPlayerAudio&&window._miniPlayerAudio.pause(),window._miniPlayerAudio=new Audio(e),window._miniPlayerAudio.play().catch(function(){}),document.getElementById("mpTitle").textContent=t||"Playing...",document.getElementById("mpArtist").textContent=o||"Bitcoin Beats",document.getElementById("mpPlayPause").textContent="⏸",n.style.display="flex")},window.toggleMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.paused?(window._miniPlayerAudio.play(),document.getElementById("mpPlayPause").textContent="⏸"):(window._miniPlayerAudio.pause(),document.getElementById("mpPlayPause").textContent="▶"))},window.closeMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.pause(),window._miniPlayerAudio=null);var e=document.getElementById("miniPlayer");e&&(e.style.display="none")},function(){var e=2592e6;window.isListingExpired=function(t){if(!t||!t.createdAt)return!1;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt);return Date.now()-o.getTime()>e},window.renewListing=function(e){auth&&auth.currentUser&&void 0!==db&&db.collection("marketplace").doc(e).update({createdAt:firebase.firestore.FieldValue.serverTimestamp(),renewed:!0,renewedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){"function"==typeof showToast&&showToast("✅ Listing renewed for 30 more days!"),"function"==typeof renderMarketplace&&renderMarketplace({listingId:e})}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))})},window.getExpiryStatus=function(t){if(!t||!t.createdAt)return null;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt),n=Date.now()-o.getTime(),i=Math.max(0,Math.ceil((e-n)/864e5));return i<=0?{status:"expired",text:"This listing has expired",color:"#ef4444"}:i<=5?{status:"expiring",text:"Expires in "+i+" day"+(1!==i?"s":""),color:"#eab308"}:null}}(),window.renderSellerReputation=function(e,t){e&&t&&void 0!==db&&db.collection("users").doc(e).get().then(function(e){if(e.exists){var o=e.data(),n=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):null,i=n?n.toLocaleDateString("en-US",{month:"short",year:"numeric"}):"Unknown",a="function"==typeof getLevel?getLevel(o.points||0):{emoji:"🟢",name:"Normie"},r='
    '+a.emoji+" "+a.name+'📅 Member since '+i+""+(o.forumPosts?'💬 '+o.forumPosts+" posts":"")+(o.marketListings?'🛒 '+o.marketListings+" listings":"")+"
    ";t.innerHTML+=r}}).catch(function(){})},function(){var e="btc_forum_draft",t="btc_forum_reply_",o=null;window.saveForumDraft=function(){var t=document.getElementById("forumNewTitle"),o=document.getElementById("forumNewBody"),n=document.getElementById("forumNewCategory");if(t||o){var i={title:t?t.value:"",body:o?o.value:"",category:n?n.value:"general",savedAt:Date.now()};localStorage.setItem(e,JSON.stringify(i))}},window.restoreForumDraft=function(){try{var t=JSON.parse(localStorage.getItem(e));return!t||Date.now()-t.savedAt>864e5?null:t}catch(e){return null}},window.clearForumDraft=function(){localStorage.removeItem(e)},window.saveReplyDraft=function(e){var o=document.getElementById("forumReplyInput");o&&o.value.trim()?localStorage.setItem(t+e,o.value):localStorage.removeItem(t+e)},window.restoreReplyDraft=function(e){return localStorage.getItem(t+e)||""},window.clearReplyDraft=function(e){localStorage.removeItem(t+e)};var n=new MutationObserver(function(){var e=document.getElementById("forumNewTitle"),t=document.getElementById("forumNewBody");if(e&&!e._draftBound){e._draftBound=!0,e.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)});var n=restoreForumDraft();n&&(n.title||n.body)&&(e.value=n.title||"",t&&(t.value=n.body||""),"function"==typeof showToast&&showToast("📝 Draft restored"))}t&&!t._draftBound&&(t._draftBound=!0,t.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)}));var i=document.getElementById("forumReplyInput");if(i&&!i._draftBound&&"undefined"!=typeof forumCurrentPost&&forumCurrentPost){i._draftBound=!0;var a=forumCurrentPost.id,r=restoreReplyDraft(a);r&&(i.value=r),i.addEventListener("input",function(){clearTimeout(o),o=setTimeout(function(){saveReplyDraft(a)},3e3)})}});document.body?n.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",function(){n.observe(document.body,{childList:!0,subtree:!0})})}(),window.isCleanTextV2=function(e){if(!e)return!0;for(var t=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","faggot","retard","nazi","hitler","kkk","porn","hentai","rape","pedo","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","jap","paki","wop","slut","whore","cum","dildo","tits","nude","naked","milf","molest","suicide","terrorist","jihad","genocide","lynch","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","supremacy","acab","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","erection","ejaculat","deepthroat","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes"],o=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g,"").split(/\s+/),n=0;n=4&&-1!==o[n].indexOf(t[i]))return!1}return!0},void 0!==window.isCleanText&&(window._origIsCleanText=window.isCleanText,window.isCleanText=window.isCleanTextV2),function(){var e=document.createElement("style");e.id="ux-patch-styles",e.textContent="\n /* Modal overlay */\n .modal-overlay {\n position: fixed; inset: 0;\n background: rgba(0,0,0,0.7);\n backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);\n z-index: 9999;\n display: flex; align-items: center; justify-content: center;\n padding: 16px;\n }\n /* Modal card */\n .modal-card {\n background: var(--bg-side, #1a1a2e);\n border: 1px solid rgba(255,255,255,0.1);\n border-radius: 24px;\n padding: 24px;\n max-width: 480px; width: 100%;\n max-height: 85vh; overflow-y: auto;\n box-shadow: 0 20px 60px rgba(0,0,0,0.5);\n animation: fadeSlideIn 0.3s;\n -webkit-overflow-scrolling: touch;\n }\n /* Pill button */\n .pill-btn {\n padding: 6px 14px;\n border-radius: 20px;\n border: 1px solid var(--border);\n background: var(--card-bg);\n color: var(--text-muted);\n font-size: 0.75rem;\n cursor: pointer;\n font-family: inherit;\n white-space: nowrap;\n font-weight: 600;\n transition: 0.2s;\n }\n .pill-btn.active {\n border-color: var(--accent);\n background: var(--accent);\n color: #fff;\n }\n /* scroll-top-btn removed — using #backToTop in index.html */\n /* Badge progress bar */\n .badge-progress {\n width: 100%; height: 4px;\n background: rgba(255,255,255,0.1);\n border-radius: 2px;\n margin-top: 4px;\n overflow: hidden;\n }\n .badge-progress-fill {\n height: 100%;\n background: var(--accent);\n border-radius: 2px;\n transition: width 0.5s ease;\n }\n ",document.head.appendChild(e)}(),window.renderQuestDashboard=function(){if(void 0===QUESTION_BANK)return"";var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=parseInt(localStorage.getItem("btc_quests_completed")||"0"),o=Object.keys(QUESTION_BANK).filter(function(t){return-1!==e.indexOf(t)}),n=Object.keys(QUESTION_BANK).length;return'
    ⚔️
    Quest Progress
    '+t+' quests completed
    Channels with questions unlocked'+o.length+"/"+n+'
    Visit more topics to unlock new quests! Each topic you read adds its questions to your quest pool.
    '},window.renderBadgeWithProgress=function(e,t){var o="";if(!t&&e.progress&&"function"==typeof e.progress){var n=e.progress(),i=n.match(/(\d+)\/(\d+)/);if(i){var a=parseInt(i[1]),r=parseInt(i[2]);o='
    '+n+"
    "}}return'
    '+e.emoji+'
    '+e.name+'
    '+e.desc+"
    "+(t?'
    ✅ Earned!
    ':"")+o+"
    "},function(){function e(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;for(var o=[],n=0;n<=t.length;n++)o[n]=[n];for(var i=0;i<=e.length;i++)o[0][i]=i;for(n=1;n<=t.length;n++)for(i=1;i<=e.length;i++)t.charAt(n-1)===e.charAt(i-1)?o[n][i]=o[n-1][i-1]:o[n][i]=Math.min(o[n-1][i-1]+1,o[n][i-1]+1,o[n-1][i]+1);return o[t.length][e.length]}window.fuzzyChannelSearch=function(t,o){if(!t||!o)return[];var n=t.toLowerCase().trim().split(/\s+/),i=[];for(var a in o){var r=o[a],s=(r.name||r.title||a).toLowerCase(),l=(r.desc||"").toLowerCase(),c=s+" "+l+" "+a.replace(/-/g," "),d=0,u=0;n.forEach(function(t){if(-1!==s.indexOf(t))d+=10,u++;else if(-1!==c.indexOf(t))d+=5,u++;else if(t.length>3)for(var o=c.split(/\s+/),n=0;n0&&i.push({id:a,channel:r,score:d})}return i.sort(function(e,t){return t.score-e.score}),i}}(),console.log("✅ UX Patches loaded — 24 tasks from the UX Review Report"),new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e].concat(Array.from(e.querySelectorAll('.msg-text, .msg-body, [class*="msg"]'))):[e]).forEach(function(e){e.innerHTML&&-1!==e.innerHTML.indexOf("this Discord")&&(e.innerHTML=e.innerHTML.replace(/this Discord/g,"this App"))})})})}).observe(document.body,{childList:!0,subtree:!0}),function(){var e=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e,...e.querySelectorAll("img.msg-img")]:[e]).forEach(function(e){"IMG"===e.tagName&&e.classList.contains("msg-img")&&!e.dataset.blurUp&&(e.dataset.blurUp="1",e.style.filter="blur(8px)",e.style.transition="filter 0.4s ease",e.complete&&e.naturalWidth>0?e.style.filter="none":(e.addEventListener("load",function(){e.style.filter="none"},{once:!0}),e.addEventListener("error",function(){e.style.filter="none"},{once:!0})))})})})});document.getElementById("main")&&e.observe(document.getElementById("main"),{childList:!0,subtree:!0})}(),function(){var e="btc_nacho_convo_persist",t=window.nachoRemember;"function"==typeof t&&(window.nachoRemember=function(o,n){t(o,n);try{var i=JSON.parse(localStorage.getItem(e)||"[]");i.push({q:o,a:(n||"").substring(0,200),t:Date.now()}),i.length>20&&(i=i.slice(-20)),localStorage.setItem(e,JSON.stringify(i))}catch(e){}}),setTimeout(function(){if(void 0!==window._nachoConvoHistory&&0===window._nachoConvoHistory.length)try{var t=JSON.parse(localStorage.getItem(e)||"[]");if(t.length>0)for(var o=Math.max(0,t.length-5);ot.clientHeight?Math.round(t.scrollTop/(t.scrollHeight-t.clientHeight)*100):100;try{var n=JSON.parse(localStorage.getItem(e)||"{}");o>(n[window.currentChannelId]||0)&&(n[window.currentChannelId]=o,localStorage.setItem(e,JSON.stringify(n)))}catch(e){}},500))},{passive:!0}),window.getChannelProgress=function(t){try{return JSON.parse(localStorage.getItem(e)||"{}")[t]||0}catch(e){return 0}}}}(),function(){var e=0,t=!1;window.addEventListener("unhandledrejection",function(o){if(!(++e>10)){var n=o.reason&&o.reason.message?o.reason.message:"",i=o.reason&&o.reason.code?o.reason.code:"";console.error("[Error Boundary] Unhandled promise rejection:",n||o.reason),/permission.denied|Missing or insufficient|requires an index|PERMISSION_DENIED/i.test(n+i)||!t&&/network|fetch|Failed to fetch|UNAVAILABLE|unavailable/i.test(n+i)&&(t=!0,"function"==typeof showToast&&showToast("⚠️ Connection issue — some features may not work. Try refreshing."))}}),window.addEventListener("error",function(t){++e>5||console.error("[Error Boundary]",t.message,t.filename,t.lineno)})}(),function(){var e="btc_offline_channels";"function"!=typeof window.go||window._offlineCacheHooked||(window._offlineCacheHooked=!0,setInterval(function(){if(window.currentChannelId&&void 0!==CHANNELS){var t=CHANNELS[window.currentChannelId];if(t&&t.file)try{var o=JSON.parse(localStorage.getItem(e)||"{}");if(o[window.currentChannelId]&&Date.now()-o[window.currentChannelId].ts<864e5)return;"caches"in window&&caches.open("btc-offline-channels").then(function(e){e.add(t.file).catch(function(){})}),o[window.currentChannelId]={ts:Date.now()};var n=Object.keys(o);if(n.length>10){n.sort(function(e,t){return o[e].ts-o[t].ts});for(var i=0;iwindow.innerWidth-8&&(n=window.innerWidth-240-8),t.style.left=n+"px",t.style.width="240px",window.innerWidth>900?(t.style.top=o.top-8+"px",t.style.transform="translateY(-100%)"):(t.style.top=o.bottom+8+"px",t.style.transform="none")}}document.addEventListener("mouseover",function(t){var o=t.target.closest(".badge-item");o&&e(o)}),document.addEventListener("click",function(t){var o=t.target.closest(".badge-item");o&&e(o)})}(),function(){"use strict";function e(){var e=function(){if(void 0===window.NACHO_TRAILS)return null;var e=[];try{e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]")}catch(e){}var t={};try{t=JSON.parse(localStorage.getItem("btc_trail_progress")||"{}")}catch(e){}for(var o=0;o0){var r=document.createElement("div");if(r.className="ch-progress",r.style.cssText="position:absolute;bottom:0;left:0;height:2px;background:"+(i>=100?"#22c55e":"var(--accent,#f7931a)")+";width:"+Math.min(i,100)+"%;border-radius:0 1px 0 0;transition:width 0.3s;opacity:0.7;",t.style.position="relative",t.style.overflow="hidden",t.appendChild(r),i>=100&&!t.querySelector(".ch-done")){var s=document.createElement("span");s.className="ch-done",s.style.cssText="position:absolute;right:6px;top:50%;transform:translateY(-50%);font-size:0.6rem;opacity:0.5;",s.textContent="✓",t.appendChild(s)}}}})}catch(e){}}setTimeout(e,2e3);var t=window.goHome;t&&(window.goHome=function(){var o=t.apply(this,arguments);return setTimeout(e,500),o});var o=window.go;o&&(window.go=function(){var t=o.apply(this,arguments);return setTimeout(e,1e3),t}),window.updateSidebarProgress=e}(); \ No newline at end of file +var CHANNELS={decentralized:{cat:"Properties Layer 1",title:"👪decentralized-censorship-resistant-ungovernable-incorruptible-trustless-unconfiscatable-updatable",desc:"Why no single person, company, or government controls Bitcoin — and why that's the most important feature.",file:"data/D_decentralized.json"},dominant:{cat:"Properties Layer 1",title:"🏆dominant-recognizable-brand-legitimate-limitless-infinite-exponential-transformative-revolutionary",desc:"Bitcoin's brand recognition, network effects, and why it has maintained the #1 position since 2009.",file:"data/D_dominant.json"},money:{cat:"Properties Layer 1",title:"💰money-deflationary-salable-durable-anti-fragile-divisible-portable-transmittable-verifiable-fair",desc:"What money actually is, how it works, and why Bitcoin satisfies every property of sound money better than anything before it.",file:"data/D_money.json"},organic:{cat:"Properties Layer 1",title:"🌳organic-empowering-elegant-freedom-centric-irrefutable-unseizable-irreversible-unbreakable",desc:"How Bitcoin grew from an idea worth nothing to a trillion-dollar network — without marketing, without a company, without a leader.",file:"data/D_organic.json"},peaceful:{cat:"Properties Layer 1",title:"☮peaceful-neutral-voluntary-open-universal-permissionless-borderless-global-inevitable-unstoppable",desc:"Bitcoin is voluntary, permissionless, borderless, and unstoppable. No one forces you to use it — and no one can stop you.",file:"data/D_peaceful.json"},programmable:{cat:"Properties Layer 1",title:"🤖programable-interoperable-deflationary-pseudonymous-opt-in-resilient-adiabatic-egalitarian",desc:"Bitcoin as programmable money — interoperable, pseudonymous, resilient, and thermodynamically sound.",file:"data/D_programmable.json"},scarce:{cat:"Properties Layer 1",title:"🍀scarce-unforgeable-hedge-scalable-p2p-instant-open-source-auditable-inaliable",desc:"Only 21 million will ever exist. Explore what makes Bitcoin the scarcest asset humanity has ever created.",file:"data/D_scarce.json"},secure:{cat:"Properties Layer 1",title:"™secure-fungible-immutable-incorruptible-immalleable-infallible-reliable-predictable-irreplicable",desc:"How Bitcoin's network security makes it virtually impossible to hack — protected by more computing power than anything on Earth.",file:"data/D_secure.json"},supranational:{cat:"Properties Layer 1",title:"🕊supranational-lindy-inviolate-dilution-proof-frictionless-freely-accessible-settlement-finality",desc:"Bitcoin transcends nations and governments. Explore the Lindy Effect, settlement finality, and dilution-proof money.",file:"data/D_supranational.json"},"use-cases":{cat:"Properties Layer 1",title:"✔use-cases",desc:"Real-world uses for Bitcoin: savings, payments, remittances, store of value, and more.",file:"data/D_use-cases.json"},whitepaper:{cat:"Properties Layer 1",title:"📄whitepaper",desc:"The 9-page document that started it all. Published October 31, 2008 by Satoshi Nakamoto — the foundation of Bitcoin.",file:"data/D_whitepaper.json"},bitvm:{cat:"Experienced Topics",title:"🖥bitvm",desc:"BitVM: computation on Bitcoin without changing the protocol. A new frontier for Bitcoin programmability.",file:"data/E_bitvm.json"},"blockchain-timechain":{cat:"Experienced Topics",title:"⛓blockchain-timechain-transactions-addresses",desc:"How the Bitcoin blockchain (timechain) works — blocks, transactions, timestamps, and the immutable ledger.",file:"data/E_blockchain-timechain.json"},"chaumian-mints":{cat:"Experienced Topics",title:"💸layer-2-chaumian-mints-ecash",desc:"Chaumian ecash, Cashu, and blinded signatures — the cutting edge of Bitcoin privacy technology.",file:"data/E_chaumian-mints.json"},consensus:{cat:"Additional Info",title:"🤝Consensus",desc:"How Bitcoin achieves consensus without a central authority — Nakamoto Consensus and beyond.",file:"data/H_consensus.json"},"core-source-code":{cat:"Experienced Topics",title:"💾core-source-code-forks-testnet-future-potential-upgrades",desc:"Bitcoin Core's source code, forks, testnet, and the open-source development process.",file:"data/E_core-source-code.json"},cryptography:{cat:"Experienced Topics",title:"🔒cryptography-cypherpunks",desc:"The cryptographic foundations of Bitcoin — SHA-256, elliptic curves, digital signatures, and the cypherpunk legacy.",file:"data/E_cryptography.json"},"ctv-covenants":{cat:"Experienced Topics",title:"📜ctv-bip119-covenants",desc:"BIP-119, CTV, and Bitcoin covenants — proposed upgrades and the debates around them.",file:"data/E_ctv-covenants.json"},developers:{cat:"Experienced Topics",title:"🖥developers",desc:"Building on Bitcoin — resources, guides, and paths for developers who want to contribute.",file:"data/E_developers.json"},"difficulty-adjustment":{cat:"Experienced Topics",title:"😤difficulty-adjustment",desc:"The most elegant part of Bitcoin's design — how the network self-adjusts every 2,016 blocks.",file:"data/E_difficulty-adjustment.json"},energy:{cat:"Experienced Topics",title:"💡energy",desc:"The truth about Bitcoin's energy use: 0.1% of global energy, renewable mining, methane capture, and grid stabilization.",file:"data/E_energy.json"},"evidence-against-alts":{cat:"Experienced Topics",title:"⚠evidence-against-ethereum-other-alt-coins-crypto-defi-nfts-web3-monero-bsv-bch-cbdcs-other-projects",desc:"Why every altcoin fails against Bitcoin — premines, centralization, broken promises, and the evidence.",file:"data/E_evidence-against-alts.json"},"extension-blocks":{cat:"Experienced Topics",title:"🚧extension-blocks-and-other-proposed-scaling-solutions",desc:"Extension blocks and other proposed scaling solutions for Bitcoin.",file:"data/E_extension-blocks.json"},"fedi-ark":{cat:"Experienced Topics",title:"🛡layer-2-fedi-ark",desc:"Fedimints, Ark, and Bitcoin's privacy/scaling layers — community custody with enhanced privacy.",file:"data/E_fedi-ark.json"},"investment-strategy":{cat:"Experienced Topics",title:"🤑investment-strategy-taxes-retirement-inheritance-loans-donate-gift-consulting-remittance",desc:"DCA, HODL, lump sum strategies, taxes, retirement planning, and thinking long-term with Bitcoin.",file:"data/E_investment-strategy.json"},"layer-2-lightning":{cat:"Experienced Topics",title:"⚡layer-2-lightning",desc:"The Lightning Network: instant, nearly-free Bitcoin payments. How Bitcoin scales without sacrificing decentralization.",file:"data/E_layer-2-lightning.json"},"layer-3-sidechains":{cat:"Experienced Topics",title:"📱layer-3-sidechain-applications",desc:"Sidechains, Liquid Network, and layer-3 applications built on top of Bitcoin.",file:"data/E_layer-3-sidechains.json"},maximalism:{cat:"Experienced Topics",title:"💯maximalism",desc:"Why people who study Bitcoin the most become maximalists. The case for Bitcoin-only.",file:"data/E_maximalism.json"},mining:{cat:"Experienced Topics",title:"🌋mining",desc:"How Bitcoin mining actually works — nonces, SHA-256 hashing, difficulty adjustment, and the brute-force lottery.",file:"data/E_mining.json"},nodes:{cat:"Experienced Topics",title:"💻nodes",desc:"Run your own Bitcoin node. Don't trust, verify. How 14,000+ nodes keep the network decentralized.",file:"data/E_nodes.json"},"op-codes":{cat:"Experienced Topics",title:"👨‍💻op-codes-simplicity",desc:"OP_CAT, Simplicity, and Bitcoin's scripting language — the building blocks of smart functionality.",file:"data/E_op-codes.json"},"pow-vs-pos":{cat:"Experienced Topics",title:"💪proof-of-work-vs-proof-of-stake",desc:"Why Proof of Work is fundamentally superior to Proof of Stake — energy, security, fairness, and decentralization.",file:"data/E_pow-vs-pos.json"},"privacy-nonkyc":{cat:"Experienced Topics",title:"🤫privacy-nonkyc-stacking-self-sovereignty",desc:"Financial privacy as a human right. KYC, non-KYC stacking, and protecting your sovereignty.",file:"data/E_privacy-nonkyc.json"},"problems-of-money":{cat:"Experienced Topics",title:"📉the-problems-of-todays-money-and-freedom",desc:"The broken fiat system: inflation, money printing, the Cantillon Effect, and why today's money is failing everyone.",file:"data/E_problems-of-money.json"},regulation:{cat:"Experienced Topics",title:"🏛regulation-policy-legal",desc:"Bitcoin and government: bans, adoption, legal tender, ETFs, and why regulation can't stop decentralization.",file:"data/E_regulation.json"},"self-custody":{cat:"Experienced Topics",title:"🔑personal-storage-self-custody-security",desc:"Not your keys, not your coins. Learn how to truly own your Bitcoin with wallets, seed phrases, and security.",file:"data/E_self-custody.json"},"smart-contracts":{cat:"Experienced Topics",title:"📱smart-contracts",desc:"Smart contracts on Bitcoin — what's possible, what's coming, and why Bitcoin's approach is different.",file:"data/E_smart-contracts.json"},stablecoins:{cat:"Additional Info",title:"🪙Stablecoins",desc:"The role of stablecoins in the Bitcoin economy — and why they're not a threat to Bitcoin.",file:"data/H_stablecoins.json"},"0_mining__hashing":{cat:"Additional Info",title:"0⃣Mining (Hashing)",desc:"Deep dive into Bitcoin mining and hashing — how SHA-256 works at the bit level.",file:"data/H_0_mining__hashing.json"},"100_sats":{cat:"Additional Info",title:"💯100 sats",desc:"What can you do with just 100 satoshis? More than you think.",file:"data/H_100_sats.json"},"1_first_principles":{cat:"Additional Info",title:"1⃣First Principles",desc:"First principles thinking applied to Bitcoin — reasoning from fundamentals, not analogies.",file:"data/H_1_first_principles.json"},"2__solved_technical_problems":{cat:"Additional Info",title:"2⃣ Solved Technical Problems",desc:"The technical problems Bitcoin solved — digital scarcity, double-spending, and Byzantine fault tolerance.",file:"data/H_2__solved_technical_problems.json"},analogies:{cat:"Additional Info",title:"🔋Analogies",desc:"The best analogies for explaining Bitcoin to anyone — from trees to brains to hearts.",file:"data/H_analogies.json"},austrian_school_of_economics:{cat:"Additional Info",title:"🇦🇹Austrian School of Economics",desc:"Austrian Economics and Bitcoin: Mises, Hayek, sound money theory, and the intellectual foundation.",file:"data/H_austrian_school_of_economics.json"},bip119:{cat:"Additional Info",title:"🚧BIP119",desc:"BIP-119 (CheckTemplateVerify) — what it is, why it's controversial, and the community debate.",file:"data/H_bip119.json"},bitcoin_exam:{cat:"Additional Info",title:"🎓Bitcoin Exam",desc:"Test questions for a Bitcoin exam — study material and self-assessment.",file:"data/H_bitcoin_exam.json"},bitcoin_vs_real_estate:{cat:"Additional Info",title:"Bitcoin vs Real Estate",desc:"Bitcoin vs. real estate as an investment — comparing the two hardest assets.",file:"data/H_bitcoin_vs_real_estate.json"},"block_time-block-size":{cat:"Additional Info",title:"⏰Block Time-Block-Size",desc:"Why Bitcoin uses 10-minute blocks and how block size affects the network.",file:"data/H_block_time-block-size.json"},burn_bitcoin:{cat:"Additional Info",title:"Burn bitcoin",desc:"How Bitcoin can be burned (made permanently unspendable) and why people do it.",file:"data/H_burn_bitcoin.json"},byzantine_generals__problem:{cat:"Additional Info",title:"⚔Byzantine Generals’ Problem",desc:"The Byzantine Generals' Problem — the computer science challenge Satoshi solved.",file:"data/H_byzantine_generals__problem.json"},"chaumian_e-cash_and_blind_signatures":{cat:"Additional Info",title:"💲Chaumian E-cash and Blind Signatures",desc:"David Chaum's ecash, blind signatures, and the cryptographic foundations of digital privacy.",file:"data/H_chaumian_e-cash_and_blind_signatures.json"},coin_mixing_coinjoin_coin_control_utxo:{cat:"Additional Info",title:"🌀Coin Mixing/Coinjoin/Coin Control/UTXO Management",desc:"CoinJoin, coin mixing, UTXO management — advanced Bitcoin privacy techniques.",file:"data/H_coin_mixing_coinjoin_coin_control_utxo.json"},cyles:{cat:"Additional Info",title:"🚲Cyles",desc:"Bitcoin's 4-year cycles, Gartner Hype Cycles, and whether the pattern continues.",file:"data/H_cyles.json"},derivation_path:{cat:"Additional Info",title:"↕Derivation Path",desc:"HD wallet derivation paths — how your seed phrase generates all your addresses.",file:"data/H_derivation_path.json"},discrete_log_contracts__dlcs:{cat:"Additional Info",title:"📝Discrete Log Contracts (DLCs)?",desc:"DLCs (Discrete Log Contracts) — smart contracts on Bitcoin using oracle signatures.",file:"data/H_discrete_log_contracts__dlcs.json"},"dollar-bitcoin_milkshake_theory":{cat:"Additional Info",title:"🥤Dollar-Bitcoin Milkshake Theory",desc:"The Dollar-Bitcoin Milkshake Theory — how global dollar demand and Bitcoin intersect.",file:"data/H_dollar-bitcoin_milkshake_theory.json"},dust:{cat:"Additional Info",title:"⏳Dust",desc:"Dust UTXOs: what they are, why they're a problem, and how to manage them.",file:"data/H_dust.json"},elevator_pitches:{cat:"Additional Info",title:"↕Elevator Pitches",desc:"Quick 20-30 second explanations of why Bitcoin matters — for every audience.",file:"data/H_elevator_pitches.json"},environment___energy:{cat:"Additional Info",title:"🌳Environment & Energy",desc:"Bitcoin and the environment: energy usage facts, renewable mining, and debunking the FUD.",file:"data/H_environment___energy.json"},faith___religion:{cat:"Additional Info",title:"🙏Faith & Religion",desc:"Bitcoin and faith — how sound money relates to religious and spiritual values.",file:"data/H_faith___religion.json"},fedimints:{cat:"Additional Info",title:"💚Fedimints",desc:"Fedimints: community custody with enhanced privacy using federated Chaumian mints.",file:"data/H_fedimints.json"},feedback_loops:{cat:"Additional Info",title:"➰Feedback Loops",desc:"Bitcoin's feedback loops — the self-reinforcing cycles that drive adoption and security.",file:"data/H_feedback_loops.json"},free_and_open_source_software__foss:{cat:"Additional Info",title:"💿Free and Open Source Software (FOSS)",desc:"Free and open source software (FOSS) projects connected to Bitcoin.",file:"data/H_free_and_open_source_software__foss.json"},game_theory:{cat:"Additional Info",title:"🏈Game Theory",desc:"Game theory and Bitcoin: Nash equilibrium, prisoner's dilemma, and strategic incentives.",file:"data/H_game_theory.json"},geopolitics___macroeconomics:{cat:"Additional Info",title:"💰Geopolitics & Macroeconomics",desc:"Bitcoin's role in geopolitics: nation-state adoption, reserve currencies, and macro trends.",file:"data/H_geopolitics___macroeconomics.json"},governance:{cat:"Additional Info",title:"🏛Governance",desc:"How Bitcoin is governed — consensus mechanisms, BIPs, and decentralized decision-making.",file:"data/H_governance.json"},ham_radio:{cat:"Additional Info",title:"Ham Radio",desc:"Using Bitcoin without internet — ham radio, mesh networks, and offline transactions.",file:"data/H_ham_radio.json"},human_rights__social_justice_and_freedo:{cat:"Additional Info",title:"🗽Human Rights, Social Justice and Freedom",desc:"Bitcoin as a tool for human rights, social justice, and financial freedom worldwide.",file:"data/H_human_rights__social_justice_and_freedo.json"},improved_incentive_structure:{cat:"Additional Info",title:"✅Improved Incentive Structure",desc:"How Bitcoin's incentive structure improves civilization — aligning individual and collective interests.",file:"data/H_improved_incentive_structure.json"},laws_of_thermodynamics:{cat:"Additional Info",title:"🔥Laws of Thermodynamics",desc:"How Bitcoin follows the laws of thermodynamics — energy, entropy, and proof of work.",file:"data/H_laws_of_thermodynamics.json"},lightning_node:{cat:"Additional Info",title:"⚡ Lightning Node",desc:"Running a Lightning Network node — setup guides, routing, and earning sats.",file:"data/H_lightning_node.json"},lindy_effect:{cat:"Additional Info",title:"👴Lindy Effect",desc:"The Lindy Effect: the longer Bitcoin survives, the longer it will survive.",file:"data/H_lindy_effect.json"},market_cap:{cat:"Additional Info",title:"🧢Market Cap",desc:"Bitcoin's market cap potential — can it reach millions per coin? The math says yes.",file:"data/H_market_cap.json"},math:{cat:"Additional Info",title:"➕Math",desc:"The mathematics of Bitcoin — from SHA-256 to elliptic curves to probability.",file:"data/H_math.json"},mathematics:{cat:"Additional Info",title:"➕Mathematics",desc:"Advanced mathematical concepts underlying Bitcoin's protocol and security.",file:"data/H_mathematics.json"},mev:{cat:"Additional Info",title:"⛏MEV",desc:"MEV (Miner Extractable Value) in Bitcoin — what it is and its implications.",file:"data/H_mev.json"},network_effects:{cat:"Additional Info",title:"🌐Network Effects",desc:"Bitcoin's network effects — why the most adopted network wins and keeps winning.",file:"data/H_network_effects.json"},open_source:{cat:"Additional Info",title:"⭕Open Source",desc:"What free and open source really means — and why it matters for Bitcoin.",file:"data/H_open_source.json"},oracle:{cat:"Additional Info",title:"🔮Oracle",desc:"Oracles in Bitcoin — how external data connects to the blockchain.",file:"data/H_oracle.json"},"orange-pilling":{cat:"Additional Info",title:"🟠Orange-Pilling",desc:"The art of orange-pilling — strategies for explaining Bitcoin to different audiences.",file:"data/H_orange-pilling.json"},ordinals:{cat:"Additional Info",title:"Ordinals",desc:"Bitcoin Ordinals and inscriptions — NFTs on the world's most secure blockchain.",file:"data/H_ordinals.json"},ordinals__nfts_on_bitcoin__and_block_spa:{cat:"Additional Info",title:"Ordinals, NFTs on Bitcoin, and Block Space",desc:"The Ordinals debate: NFTs on Bitcoin, block space economics, and community perspectives.",file:"data/H_ordinals__nfts_on_bitcoin__and_block_spa.json"},"peace_and_anti-war":{cat:"Additional Info",title:"☮Peace and Anti-War",desc:"Can a Bitcoin Standard end wars? The case for Bitcoin as a force for peace.",file:"data/H_peace_and_anti-war.json"},philosophy:{cat:"Additional Info",title:"🍎Philosophy",desc:"The philosophy of Bitcoin — from first principles to existential implications.",file:"data/H_philosophy.json"},politics:{cat:"Additional Info",title:"🏛Politics",desc:"Bitcoin and politics — how Bitcoin intersects with government policy and elections.",file:"data/H_politics.json"},predictions:{cat:"Additional Info",title:"🔮Predictions",desc:"Bitcoin predictions timestamped by the community — bold calls and their outcomes.",file:"data/H_predictions.json"},public_key_vs_private_key:{cat:"Additional Info",title:"🗝Public Key vs Private Key",desc:"Public keys vs. private keys — the cryptographic foundation of Bitcoin ownership.",file:"data/H_public_key_vs_private_key.json"},rbf:{cat:"Additional Info",title:"↔RBF",desc:"Replace-By-Fee (RBF) — how to speed up stuck Bitcoin transactions.",file:"data/H_rbf.json"},"referral-links":{cat:"Referral Links",title:"🔗free-btc-referral-links",desc:"Curated Bitcoin referral links — earn free sats with trusted platforms like River, Fold, and Strike.",file:"data/H_referral-links.json"},risks__threats__attack_vectors__weaknes:{cat:"Additional Info",title:"⚔Risks, Threats, Attack Vectors, Weaknesses, Issues",desc:"Bitcoin's risks, threats, and attack vectors — what could go wrong and why it probably won't.",file:"data/H_risks__threats__attack_vectors__weaknes.json"},rollups:{cat:"Additional Info",title:"🥐Rollups",desc:"Rollups on Bitcoin — scaling and privacy solutions using off-chain computation.",file:"data/H_rollups.json"},sats__or__bits:{cat:"Additional Info",title:'"Sats" or "Bits"?',desc:"The sats vs. bits debate — which denomination should Bitcoin use?",file:"data/H_sats__or__bits.json"},scalability:{cat:"Additional Info",title:"🌐Scalability",desc:"Can Bitcoin scale to serve the world? Layers, Lightning, and the path forward.",file:"data/H_scalability.json"},sidechains:{cat:"Additional Info",title:"♻Sidechains",desc:"Bitcoin sidechains like Liquid — benefits, tradeoffs, and use cases.",file:"data/H_sidechains.json"},simplified_payment_verification__spv:{cat:"Additional Info",title:"✔Simplified Payment Verification (SPV)",desc:"SPV (Simplified Payment Verification) — lightweight Bitcoin verification without a full node.",file:"data/H_simplified_payment_verification__spv.json"},soft_vs_hard_forks:{cat:"Additional Info",title:"🍴Soft vs Hard Forks",desc:"Soft forks vs. hard forks — how Bitcoin upgrades while maintaining consensus.",file:"data/H_soft_vs_hard_forks.json"},softwar:{cat:"Additional Info",title:"Softwar",desc:"Jason Lowery's Softwar thesis — Bitcoin as a non-lethal alternative to physical warfare.",file:"data/H_softwar.json"},stratum_v2:{cat:"Additional Info",title:"🟩Stratum V2",desc:"Stratum V2 — the next-generation mining protocol for better decentralization and efficiency.",file:"data/H_stratum_v2.json"},submarine_swap:{cat:"Additional Info",title:"⛵Submarine Swap",desc:"Submarine swaps — trustlessly moving Bitcoin between on-chain and Lightning.",file:"data/H_submarine_swap.json"},swaps:{cat:"Additional Info",title:"↔Swaps",desc:"How to swap between on-chain Bitcoin and Lightning — tools, techniques, and protocols.",file:"data/H_swaps.json"},ta_tips:{cat:"Additional Info",title:"📈TA Tips",desc:"Technical analysis tips for Bitcoin — chart patterns, indicators, and trading education.",file:"data/H_ta_tips.json"},tail_emission:{cat:"Additional Info",title:"🐈Tail Emission",desc:"The tail emission debate — should Bitcoin ever have perpetual block rewards?",file:"data/H_tail_emission.json"},taproot:{cat:"Additional Info",title:"🧰Taproot",desc:"Taproot: Bitcoin's latest major upgrade — Schnorr signatures, script improvements, and privacy.",file:"data/H_taproot.json"},taro:{cat:"Additional Info",title:"🥕Taro",desc:"Taro (now Taproot Assets) — issuing assets on the Bitcoin and Lightning networks.",file:"data/H_taro.json"},the_future:{cat:"Additional Info",title:"🔮The Future",desc:"How Bitcoin could change the future — hyperbitcoinization, global adoption, and beyond.",file:"data/H_the_future.json"},time:{cat:"Additional Info",title:"⏰Time",desc:"How Bitcoin keeps time — block time, timestamps, and the decentralized clock.",file:"data/H_time.json"},time_preference:{cat:"Additional Info",title:"🕑Time Preference",desc:"Time preference: how sound money encourages long-term thinking and civilization building.",file:"data/H_time_preference.json"},toxicity:{cat:"Additional Info",title:"☣ Toxicity",desc:"Is Bitcoin community toxicity real? Or is it integrity? The debate and its meaning.",file:"data/H_toxicity.json"},transaction_fees:{cat:"Additional Info",title:"💲Transaction Fees",desc:"Bitcoin transaction fees — how they work, fee markets, and long-term sustainability.",file:"data/H_transaction_fees.json"},unpopular_opinions:{cat:"Additional Info",title:"💀Unpopular Opinions",desc:"Unpopular opinions in the Bitcoin space — controversial takes and honest debates.",file:"data/H_unpopular_opinions.json"},utxos:{cat:"Additional Info",title:"🕳UTXOs",desc:"UTXOs (Unspent Transaction Outputs) — the fundamental building block of Bitcoin transactions.",file:"data/H_utxos.json"},vbyte:{cat:"Additional Info",title:"🏋vByte",desc:"Virtual bytes (vBytes) — how Bitcoin measures transaction weight for fee calculation.",file:"data/H_vbyte.json"},"apps-tools":{cat:"Resources",title:"🍎apps-tools-services-models",desc:"Bitcoin apps, tools, services, and platforms — everything you need to use Bitcoin daily.",file:"data/R_apps-tools.json"},"art-inspiration":{cat:"Resources",title:"🤩art-inspiration-motivation",desc:"Bitcoin art, inspiration, and motivational content from the community.",file:"data/R_art-inspiration.json"},"articles-threads":{cat:"Resources",title:"📃articles-threads",desc:"The best Bitcoin articles and Twitter threads — curated deep dives into every aspect of Bitcoin.",file:"data/R_articles-threads.json"},books:{cat:"Resources",title:"📚books",desc:"The essential Bitcoin reading list: The Bitcoin Standard, 21 Lessons, Mastering Bitcoin, and more.",file:"data/R_books.json"},charts:{cat:"Resources",title:"📊charts",desc:"Bitcoin price charts, on-chain analytics, stock-to-flow, and data visualizations.",file:"data/R_charts.json"},curriculum:{cat:"Resources",title:"🎓curriculum-presentations",desc:"Bitcoin education curriculum and presentations for teachers and students.",file:"data/R_curriculum.json"},"faq-glossary":{cat:"Resources",title:"❓faq-glossary-search-ai-calendar",desc:"Bitcoin FAQ, glossary of terms, and quick answers to common questions.",file:"data/R_faq-glossary.json"},"fun-facts":{cat:"Resources",title:"🎉fun-facts",desc:"Mind-blowing Bitcoin trivia: Pizza Day, Satoshi's birthday code, lost coins, and 200+ amazing facts.",file:"data/R_fun-facts.json"},games:{cat:"Resources",title:"🎮games",desc:"Bitcoin-themed games and gamified learning experiences.",file:"data/R_games.json"},"giga-chad":{cat:"Resources",title:"👑giga-chad",desc:"Michael Saylor, MicroStrategy, and the corporate Bitcoin movement.",file:"data/R_giga-chad.json"},graphics:{cat:"Resources",title:"🎨graphics",desc:"Bitcoin infographics, charts, diagrams, and visual explanations.",file:"data/R_graphics.json"},hardware:{cat:"Resources",title:"💻hardware",desc:"Bitcoin hardware: mining rigs, hardware wallets, nodes, and open-source projects like Bitaxe.",file:"data/R_hardware.json"},health:{cat:"Resources",title:"🥩health",desc:"Bitcoin and health: low time preference living, breaking free from the system.",file:"data/R_health.json"},history:{cat:"Resources",title:"📆history",desc:"The complete history of Bitcoin — from the cypherpunks to today.",file:"data/R_history.json"},"informational-sites":{cat:"Resources",title:"📃informational-sites-courses-workshops-newsletters-projects-communities-meetups-conferences",desc:"Bitcoin dashboards, tools, courses, newsletters, communities, and educational websites.",file:"data/R_informational-sites.json"},international:{cat:"Resources",title:"🌍international",desc:"Bitcoin resources in multiple languages and global adoption stories.",file:"data/R_international.json"},"jobs-earn":{cat:"Resources",title:"👷job-postings-employer-info-entrepreneurship-earn-bitcoin-stack-sats",desc:"Bitcoin job boards, entrepreneurship resources, and ways to earn sats.",file:"data/R_jobs-earn.json"},"memes-funny":{cat:"Resources",title:"😂memes-funny",desc:"The best Bitcoin memes, jokes, and humor from the community. Laugh while you learn.",file:"data/R_memes-funny.json"},"misconceptions-fud":{cat:"Resources",title:"🤡common-misconceptions-fud-debunked",desc:"Every Bitcoin myth debunked: too volatile, wastes energy, used by criminals, no intrinsic value — all wrong.",file:"data/R_misconceptions-fud.json"},"movies-tv":{cat:"Resources",title:"🎬movies-tv-documentaries",desc:"Bitcoin documentaries, films, and TV appearances. From The Big Short to Bitcoin-specific docs.",file:"data/R_movies-tv.json"},music:{cat:"Resources",title:"🎵music",desc:"Bitcoin-inspired music, songs, and audio content from the community.",file:"data/R_music.json"},"news-adoption":{cat:"Resources",title:"📰news-adoption",desc:"Latest Bitcoin news, adoption milestones, and real-world usage stories.",file:"data/R_news-adoption.json"},nostr:{cat:"Resources",title:"💜nostr",desc:"Nostr: the decentralized social protocol Bitcoiners are building on. Social media you can't be censored from.",file:"data/R_nostr.json"},"one-stop-shop":{cat:"Resources",title:"🛑one-stop-shop",desc:"The best resources to understand Bitcoin's value as fast as possible. Start here if you're new.",file:"data/R_one-stop-shop.json"},podcasts:{cat:"Resources",title:"🔊podcasts",desc:"Top Bitcoin podcasts: Bitcoin Audible, What Bitcoin Did, Stephan Livera, and more.",file:"data/R_podcasts.json"},"poems-stories":{cat:"Resources",title:"📒poems-stories-jokes",desc:"Bitcoin poetry, short stories, jokes, and creative writing from the community.",file:"data/R_poems-stories.json"},"projects-diy":{cat:"Resources",title:"🔧projects-diy",desc:"DIY Bitcoin projects: build your own node, Lightning ATM, and more.",file:"data/R_projects-diy.json"},"research-theses":{cat:"Resources",title:"✍research-theses",desc:"Academic research papers and theses on Bitcoin, monetary policy, and cryptographic systems.",file:"data/R_research-theses.json"},"satoshi-nakamoto":{cat:"Resources",title:"🦸satoshi-nakamoto",desc:"The mystery of Bitcoin's creator: who was Satoshi Nakamoto? The evidence, theories, and legacy.",file:"data/R_satoshi-nakamoto.json"},"social-media":{cat:"Resources",title:"👍social-media-proponents",desc:"Bitcoin Twitter/X accounts, influencers, and social media communities to follow.",file:"data/R_social-media.json"},"swag-merch":{cat:"Resources",title:"👕swag-merch-businesses-spend",desc:"Bitcoin merchandise, clothing, and businesses where you can spend your sats.",file:"data/R_swag-merch.json"},videos:{cat:"Resources",title:"📺videos",desc:"Must-watch Bitcoin lectures, talks, and presentations from Andreas Antonopoulos, Michael Saylor, and others.",file:"data/R_videos.json"},web5:{cat:"Resources",title:"5⃣web5",desc:"Web5 and decentralized web technologies built on Bitcoin.",file:"data/R_web5.json"}},_SAFE_COVER_PLACEHOLDER="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjMWUxYTJlIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZpbGw9IiNmNzkzMWEiIGZvbnQtc2l6ZT0iMjAiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj7wnY61PC90ZXh0Pjwvc3ZnPg==";function _safeCover(e){if(!e||"string"!=typeof e||""===e.trim())return _SAFE_COVER_PLACEHOLDER;var t=e.trim(),o=t.toLowerCase();return/^(javascript|data:text\/html|vbscript|blob):/i.test(o)?(console.warn("[XSS BLOCKED] Malicious image URL scheme rejected:",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER):/^(https:\/\/|data:image\/)/i.test(t)?t.replace(/["'<>\\]/g,""):(console.warn("[XSS BLOCKED] Invalid URL scheme (must be https:// or data:image/):",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER)}function safeJSON(e,t){try{var o=localStorage.getItem(e);return null===o?t:JSON.parse(o)}catch(o){console.warn('safeJSON: corrupted data for key "'+e+'", resetting.',o);try{localStorage.removeItem(e)}catch(e){}return t}}function escapeHtml(e){if(!e)return"";var t=document.createElement("div");return t.appendChild(document.createTextNode(e)),t.innerHTML}function sanitizeUrl(e){return e?(e=e.trim(),/^(javascript|data|vbscript|blob):/i.test(e)?"":e):""}function timeAgo(e){if(!e)return"";var t;t=e.toDate?e.toDate():e instanceof Date?e:new Date(e);var o=Math.floor((Date.now()-t.getTime())/1e3);return o<60?"just now":o<3600?Math.floor(o/60)+"m ago":o<86400?Math.floor(o/3600)+"h ago":o<604800?Math.floor(o/86400)+"d ago":t.toLocaleDateString()}function isPremium(){return void 0!==currentUser&¤tUser&¤tUser.premium&&!0===currentUser.premium.active}function getSatCap(){return isPremium()?21e3:1e4}!function(){var e=[],t=[];window.registerInterval=function(t,o,n){var i=setInterval(t,o);return e.push({id:i,fn:t,ms:o,name:n||"unnamed"}),i},document.addEventListener("visibilitychange",function(){document.hidden?(e.forEach(function(e){clearInterval(e.id)}),t=e.slice(),e=[]):(t.forEach(function(t){t.fn(),t.id=setInterval(t.fn,t.ms),e.push(t)}),t=[])})}(),window._factionNameStyle=function(e){return"cyber_hornets"===e?"color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;font-weight:700;":"honey_badgers"===e?"color:#1a1a1a;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff;font-weight:700;":""};var PREMIUM_CONFIG={FREE_SAT_CAP:1e4,PREMIUM_SAT_CAP:21e3,FREE_SPINS:1,PREMIUM_SPINS:3,MONTHLY_PRICE_USD:4.99,YEARLY_PRICE_USD:42,LIFETIME_SATS:21e4,TIER_NAME:"Bitcoin Maxi"};const FIREBASE_CONFIG={apiKey:"AIzaSyCkUGX2KWaVGmSQXpYJhWDxF_BSiHRX6SM",authDomain:"btc-archive-test.firebaseapp.com",projectId:"btc-archive-test",storageBucket:"btc-archive-test.firebasestorage.app",messagingSenderId:"60810625669",appId:"1:60810625669:web:ea4dacd55333e41429dfec",measurementId:"G-7C2FKDJ8E4"},LEVELS=[{name:"Normie",emoji:"🟢",min:0},{name:"Curious",emoji:"🔵",min:10},{name:"Pleb",emoji:"🟠",min:144},{name:"Pleb II",emoji:"🟠🟠",min:170},{name:"Pleb III",emoji:"🟠🟠🟠",min:256},{name:"Stacker",emoji:"📦",min:500},{name:"Stacker II",emoji:"📦📦",min:1913},{name:"Stacker III",emoji:"📦📦📦",min:2016},{name:"Maxi",emoji:"🔥",min:2140},{name:"Maxi II",emoji:"🔥🔥",min:6102},{name:"Maxi III",emoji:"🔥🔥🔥",min:8888},{name:"Papa John",emoji:"🍕",min:1e4},{name:"Full Node",emoji:"🖥️",min:18333},{name:"Whale",emoji:"🐋",min:5e4},{name:"Sovereign",emoji:"🏴",min:1e5},{name:"Cypherpunk",emoji:"🔒",min:133337},{name:"Satoshi",emoji:"👑",min:21e4}];function _renderQRCode(e,t,o){if(window.qrcode&&"function"==typeof window.qrcode)_drawQR(e,t,o);else{var n=document.createElement("script");n.src="https://cdnjs.cloudflare.com/ajax/libs/qrcode-generator/1.4.4/qrcode.min.js",n.integrity="sha384-mZT2gIty7ZDdOGkxfP6joZcYdMW1Jvj9dRlfpTmaJAKKXTqzygtB22k7FLe+KZC1",n.crossOrigin="anonymous",n.onload=function(){_drawQR(e,t,o)},n.onerror=function(){e.innerHTML='
    '+t+"
    "},document.head.appendChild(n)}}function _drawQR(e,t,o){try{var n=qrcode(0,"M");n.addData(t),n.make();var i=document.createElement("img");i.src=n.createDataURL(6,4),i.width=o,i.height=o,i.alt="QR Code",i.style.cssText="border-radius:8px;image-rendering:pixelated;",e.innerHTML="",e.appendChild(i)}catch(t){e.innerHTML='
    QR generation failed
    '}}const POINTS={visit:5,openChannel:10,readTime:15,explore10:50,streak:100};let db,auth,currentUser=null,signInAttempts=0,signInLockout=0,redirectResultResolved=!1,redirectResultPromise=Promise.resolve(null),sessionChannels=new Set,readTimer=null,readSeconds=0,lastReadAward=0,rankingReady=!1,allTimeChannels=new Set,lastLevelName="",lastLevelMin=0,levelUpReady=!1;function initRanking(){try{firebase.initializeApp(FIREBASE_CONFIG),db=firebase.firestore(),db.enablePersistence({synchronizeTabs:!0}).catch(function(e){"failed-precondition"!==e.code&&"unimplemented"!==e.code&&console.log("Persistence error:",e.code)}),auth=firebase.auth(),auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).catch(function(){}),auth.isSignInWithEmailLink(window.location.href)&&handleEmailSignIn(),redirectResultPromise=auth.getRedirectResult().then(async function(e){if(redirectResultResolved=!0,console.log("[Auth] getRedirectResult:",e?e.user?e.user.uid:"no user":"null"),!e||!e.user)return null;const t=e.user;sessionStorage.setItem("btc_redirect_auth","1");const o=await db.collection("users").doc(t.uid).get(),n=localStorage.getItem("btc_anon_uid");let i=null;try{i=JSON.parse(localStorage.getItem("btc_anon_data"))}catch(e){}if(localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),o.exists){if(i&&!o.data().mergedAnon){await o.ref.update({mergedAnon:!0});var a=Math.min(i.points||0,500);a>0&&"function"==typeof awardPoints&&await awardPoints(a,"🔗 Anonymous progress merged")}}else{i?(i.email=t.email||"",i.username||(i.username=t.displayName||"Bitcoiner"),await db.collection("users").doc(t.uid).set(i)):await db.collection("users").doc(t.uid).set({username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(t.uid)}if(n&&n!==t.uid)try{await db.collection("users").doc(n).delete()}catch(e){}return loadUser(t.uid),updateAuthButton(),"function"==typeof hideUsernamePrompt&&hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(t.displayName||t.email||"Bitcoiner")),t}).catch(function(e){return redirectResultResolved=!0,"auth/popup-closed-by-user"!==e.code&&console.log("Redirect result error:",e),null});let o=!0,n=auth.isSignInWithEmailLink(window.location.href);var e=localStorage.getItem("btc_pwa_auth_pending"),t=!!localStorage.getItem("btc_anon_uid")||"1"===sessionStorage.getItem("btc_redirect_pending")||!!e;e&&(localStorage.removeItem("btc_pwa_auth_pending"),console.log("[Auth] PWA auth pending detected")),t&&console.log("[Auth] Detected pending redirect return"),auth.onAuthStateChanged(e=>{if(console.log("[Auth] onAuthStateChanged:",e?e.isAnonymous?"anon:"+e.uid:"real:"+e.uid:"null","firstEvent:",o,"pendingRedirect:",t),e&&!e.isAnonymous){var i=localStorage.getItem("btc_last_auth_uid");i&&i!==e.uid&&(console.log("[Auth] Account switch detected:",i,"->",e.uid,"— clearing localStorage"),clearUserLocalStorage()),localStorage.setItem("btc_last_auth_uid",e.uid)}if(o){if(o=!1,n)return;if(e&&!e.isAnonymous)console.log("[Auth] Real user on first event:",e.uid),sessionStorage.removeItem("btc_redirect_auth"),loadUser(e.uid).then(function(){currentUser&¤tUser.username&&setTimeout(function(){"function"==typeof showToast&&showToast("👋 Welcome back, "+escapeHtml(currentUser.username||"")+"!")},2e3)}).catch(function(){});else if(e&&e.isAnonymous)if(t){console.log("[Auth] Anon user but pending redirect — waiting 8s for real auth...");var a=setTimeout(function(){auth.currentUser&&!auth.currentUser.isAnonymous?(console.log("[Auth] Real user appeared after wait:",auth.currentUser.uid),loadUser(auth.currentUser.uid)):(console.log("[Auth] No real user after 8s — loading anon"),loadUserLocal(e.uid)),localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),localStorage.removeItem("btc_pwa_auth_pending"),sessionStorage.removeItem("btc_redirect_pending")},8e3);redirectResultPromise.then(function(e){e&&clearTimeout(a)})}else loadUserLocal(e.uid);else if(redirectResultResolved&&!t)auth.signInAnonymously().then(()=>{});else{var r=setTimeout(function(){auth.currentUser||(console.log("[Auth] 10s timeout with no user — going anonymous"),localStorage.removeItem("btc_pwa_auth_pending"),auth.signInAnonymously().then(()=>{}))},1e4);redirectResultPromise.then(function(e){clearTimeout(r),e||auth.currentUser||auth.signInAnonymously().then(()=>{})})}}else if(e){if(currentUser&¤tUser.uid===e.uid)return void updateAuthButton();e.isAnonymous?loadUserLocal(e.uid):loadUser(e.uid)}else currentUser=null,redirectResultResolved?auth.signInAnonymously().then(()=>{}):redirectResultPromise.then(function(e){e||auth.currentUser||auth.signInAnonymously().then(()=>{})})})}catch(e){console.error("Ranking init error:",e),setTimeout(function(){"function"==typeof showToast&&showToast("⚠️ Init error: "+(e.message||e))},2e3)}}async function handleEmailSignIn(){var e=window.location.href;let t=null;var o=new URLSearchParams(window.location.search);return o.get("signin_email")&&(t=decodeURIComponent(o.get("signin_email"))),t||(t=localStorage.getItem("btc_signin_email")),t?finishEmailSignIn(t,e):new Promise(function(o){var n=document.createElement("div");n.id="emailConfirmOverlay",n.style.cssText="position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:20px;",n.innerHTML='
    📧
    Confirm Your Email
    It looks like you opened this link on a different device. Enter the email you used to sign up:
    Cancel
    ',document.body.appendChild(n);var i=document.getElementById("crossDeviceEmail");function a(){var a=i.value.trim().toLowerCase();a&&a.includes("@")?(n.remove(),t=a,o(finishEmailSignIn(t,e))):"function"==typeof showToast&&showToast("Please enter a valid email")}document.getElementById("crossDeviceSubmit").onclick=a,i.addEventListener("keydown",function(e){"Enter"===e.key&&a()}),setTimeout(function(){i.focus()},100)})}async function finishEmailSignIn(e,t){if(e)try{const i=auth.currentUser;let a=null,r=null;if(i&&i.isAnonymous){a=i.uid,console.log("[Email Sign-In] Anon user found:",a);try{const e=await db.collection("users").doc(a).get();e.exists&&(r=e.data()),console.log("[Email Sign-In] Anon data loaded:",!!r)}catch(e){console.log("[Email Sign-In] Anon data load failed (non-fatal):",e.code)}}console.log("[Email Sign-In] Starting signInWithEmailLink for:",e);const s=await auth.signInWithEmailLink(e,t);console.log("[Email Sign-In] Sign-in result:",s.user?s.user.uid:"no user"),localStorage.removeItem("btc_signin_email");const l=s.user.uid;console.log("[Email Sign-In] Waiting for auth token propagation...");for(var o=0;o<5;o++){await new Promise(e=>setTimeout(e,200));try{await db.collection("users").doc(l).get(),console.log("[Email Sign-In] Firestore auth ready after",200*(o+1),"ms");break}catch(e){if("permission-denied"===e.code){console.log("[Email Sign-In] Permission denied on retry "+(o+1)+", waiting for token propagation...");continue}throw e}}console.log("[Email Sign-In] Fetching existing user doc:",l);const c=await db.collection("users").doc(l).get();if(console.log("[Email Sign-In] Existing doc exists:",c.exists),!c.exists&&r)r.email=e,await db.collection("users").doc(l).set(r);else if(c.exists&&r){const e=c.data();var n=Math.min(r.points||0,500);!e.mergedAnon&&n>(e.points||0)&&await c.ref.update({points:Math.max(n,e.points||0),channelsVisited:Math.max(r.channelsVisited||0,e.channelsVisited||0),totalVisits:(e.totalVisits||0)+(r.totalVisits||0),mergedAnon:!0})}if(a&&a!==l)try{await db.collection("users").doc(a).delete()}catch(e){}window.history.replaceState(null,"",window.location.pathname+window.location.hash);const d=localStorage.getItem("btc_pending_username"),u=(localStorage.getItem("btc_pending_email"),localStorage.getItem("btc_pending_giveaway"));if(d&&!c.exists){const t={username:d,email:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};if(u){t.lightningAddress=u,t.giveaway={entered:!0,lightningAddress:u,enteredAt:(new Date).toISOString()};try{await db.collection("giveaway_entries").doc(l).set({username:d,lightningAddress:u,email:e,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:l})}catch(e){}}await db.collection("users").doc(l).set(t);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(l)}localStorage.removeItem("btc_pending_username"),localStorage.removeItem("btc_pending_email"),localStorage.removeItem("btc_pending_giveaway"),localStorage.removeItem("btc_wallet_enc"),localStorage.removeItem("btc_wallet_addrs"),loadUser(l),showToast("✅ Email verified! Signed in as "+escapeHtml(d||e)),u&&setTimeout(function(){showToast("🎉 You're entered for the 25,000 sats giveaway! Good luck!")},2e3)}catch(e){console.error("[Email Sign-In] Full error:",e.code,e.message,e.stack),"permission-denied"===e.code?(showToast("⚠️ Permission denied. Try refreshing the page or clearing cache."),console.error("[Email Sign-In] Firestore permission denied - auth state may not be ready")):"auth/invalid-action-code"===e.code||"auth/expired-action-code"===e.code?showToast("⚠️ This sign-in link has expired. Please request a new one."):"auth/invalid-email"===e.code?showToast("⚠️ Email mismatch. Make sure you enter the same email you signed up with."):showToast("Sign-in error ("+(e.code||"unknown")+"). Please try again."),window.history.replaceState(null,"",window.location.pathname+window.location.hash),auth.signInAnonymously()}else showToast("⚠️ Could not determine your email. Please sign in again from the app.")}var GOOGLE_CLIENT_ID="1055248200518-jcn5efjp7vhk0vm8cbmj4mfsgc0edkga.apps.googleusercontent.com";async function signInWithGIS(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){var n=e.anonUid,i=e.anonData;google.accounts.id.initialize({client_id:GOOGLE_CLIENT_ID,callback:async function(e){if(e&&e.credential)try{var a=firebase.auth.GoogleAuthProvider.credential(e.credential),r=await auth.signInWithCredential(a);try{google.accounts.id.cancel()}catch(e){}var s=document.getElementById("gsi-temp-btn");if(s){var l=s.closest('div[style*="position:fixed"]');l?l.remove():s.remove()}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()}),await _handleSignInResultGlobal(r.user,n,i),t(r.user)}catch(e){o(e)}else o(new Error("No credential received"))},auto_select:!1,cancel_on_tap_outside:!0,context:"signin",ux_mode:"popup"}),google.accounts.id.prompt(function(e){(e.isNotDisplayed()||e.isSkippedMoment())&&(console.log("[Auth] One Tap not shown, falling back to Firebase popup"),o(new Error("One Tap unavailable")))})})}function showPWAAuthFallback(e){var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='
    🔐
    '+e+' Sign-In
    '+e+' sign-in requires a browser window. Open the site in your browser to sign in.
    ',document.body.appendChild(t)}window.signInWithGoogle=async function(){if(!/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||"")&&"undefined"!=typeof google&&google.accounts&&google.accounts.id)try{return void await signInWithGIS()}catch(e){console.warn("[Auth] GIS failed, falling back to Firebase popup:",e);try{google.accounts.id.cancel()}catch(e){}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()})}await signInWithProvider(new firebase.auth.GoogleAuthProvider)},window.signInWithTwitter=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.TwitterAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("Twitter")}await signInWithProvider(new firebase.auth.TwitterAuthProvider)},window.signInWithGithub=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.GithubAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("GitHub")}await signInWithProvider(new firebase.auth.GithubAuthProvider)};var FB_APP_ID="1400842698021858";async function signInWithFBSDK(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){FB.login(function(n){if(n.authResponse){var i=firebase.auth.FacebookAuthProvider.credential(n.authResponse.accessToken);auth.signInWithCredential(i).then(async function(o){await _handleSignInResultGlobal(o.user,e.anonUid,e.anonData),t(o.user)}).catch(o)}else o(new Error("Facebook login cancelled"))},{scope:"email,public_profile"})})}function checkRateLimit(){const e=Date.now();return e5&&(signInLockout=e+6e4,signInAttempts=0,showToast("⏳ Too many attempts. Please wait 60 seconds."),1)))}function isInAppBrowser(){var e=navigator.userAgent||"";return/FBAN|FBAV|Instagram|Twitter|Line\/|Snapchat|BytedanceWebview|musical_ly|TikTok|Weibo|MicroMessenger|LinkedInApp|Telegram/i.test(e)}async function _saveAnonDataGlobal(){var e=auth.currentUser,t=null,o=null;if(e&&e.isAnonymous){t=e.uid;try{var n=await db.collection("users").doc(t).get();n.exists&&(o=n.data())}catch(e){}}return{anonUid:t,anonData:o}}async function _handleSignInResultGlobal(e,t,o){var n=await db.collection("users").doc(e.uid).get();if(n.exists){if(o){var i=n.data(),a=Math.min(o.points||0,500);!i.mergedAnon&&a>(i.points||0)&&await n.ref.update({points:Math.max(a,i.points||0),channelsVisited:Math.max(o.channelsVisited||0,i.channelsVisited||0),totalVisits:(i.totalVisits||0)+(o.totalVisits||0),mergedAnon:!0})}!n.data().email&&e.email&&await n.ref.update({email:e.email})}else o?(o.email=e.email||"",o.username||(o.username=e.displayName||"Bitcoiner"),await db.collection("users").doc(e.uid).set(o)):await db.collection("users").doc(e.uid).set({username:e.displayName||"Bitcoiner",email:e.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()});if(t&&t!==e.uid)try{await db.collection("users").doc(t).delete()}catch(e){}if(loadUser(e.uid),n.exists)hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(e.displayName||e.email||"Bitcoiner"));else{"function"==typeof attachReferral&&attachReferral(e.uid),showGiveawayPrompt(e.uid,e.displayName||e.email||"Bitcoiner");try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},1500)}catch(e){}}}async function signInWithProvider(e){if(checkRateLimit()){if(isInAppBrowser()){var t=navigator.userAgent||"",o=/iPhone|iPad/i.test(t)?'Tap the share icon (↑) → "Open in Safari"':/Android/i.test(t)?'Tap ⋮ (menu) → "Open in Browser"':"Open this page in your default browser",n=document.createElement("div");return n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.9);padding:20px;",n.innerHTML='
    🌐

    Open in Browser

    Sign-in doesn\'t work inside apps. '+o+'

    ',void document.body.appendChild(n)}var i=/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||""),a=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(i||a)try{showToast("⏳ Opening sign-in...");const t=auth.currentUser;t&&t.isAnonymous&&(localStorage.setItem("btc_anon_uid",t.uid),db.collection("users").doc(t.uid).get().then(function(e){e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}).catch(function(){}));try{const t=await auth.signInWithPopup(e);if(t&&t.user){const{anonUid:e,anonData:o}=await s();return void await r(t.user,e,o)}}catch(t){return console.log("[Auth] Mobile popup failed, falling back to redirect:",t.code),sessionStorage.setItem("btc_redirect_pending","1"),localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}}catch(e){return console.error("Mobile sign-in error:",e),void showToast("Sign-in failed: "+(e.message||"Unknown error"))}try{const{anonUid:t,anonData:o}=await s(),n=await auth.signInWithPopup(e);await r(n.user,t,o)}catch(t){if(console.error("Provider sign-in error:",t.code,t.message,t),"auth/popup-blocked"===t.code||"auth/cancelled-popup-request"===t.code||"auth/popup-closed-by-user"===t.code||"auth/internal-error"===t.code){try{showToast("⏳ Opening sign-in page...");const t=auth.currentUser;if(t&&t.isAnonymous){localStorage.setItem("btc_anon_uid",t.uid);try{const e=await db.collection("users").doc(t.uid).get();e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}catch(e){}}return localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}catch(e){console.error("Redirect fallback also failed:",e),showToast("Sign-in failed. Please try a different browser.")}return}if("auth/popup-closed-by-user"===t.code)return;"auth/unauthorized-domain"===t.code?showToast("⚠️ This domain is not authorized for sign-in. Please contact support."):"auth/operation-not-allowed"===t.code?showToast("⚠️ This sign-in method is not enabled. Try a different option."):"auth/account-exists-with-different-credential"===t.code?showToast("⚠️ An account with this email exists using a different sign-in method. Try another option."):"auth/network-request-failed"===t.code?showToast("⚠️ Network error. Check your connection and try again."):showToast("Sign-in error ("+(t.code||"unknown")+"). Please try again.")}}async function r(e,t,o){return _handleSignInResultGlobal(e,t,o)}async function s(){return _saveAnonDataGlobal()}}function showGiveawayPrompt(e,t){const o=document.getElementById("usernameModal");o.querySelector(".username-box").innerHTML="

    🎉 Welcome, "+t+'!

    Your account is all set. Want to enter the giveaway?

    Enter a Lightning address so we can send you the sats if you win! 🏆

    ',o.classList.add("open"),document.getElementById("giveawayCheckboxProvider").addEventListener("change",function(){document.getElementById("giveawayLnProvider").parentElement.style.display=this.checked?"flex":"none"})}async function submitGiveawayProvider(e,t){var o=document.getElementById("giveawayCheckboxProvider"),n=document.getElementById("giveawayLnProvider"),i=n?n.value.trim():"";if(o&&o.checked){if(!i)return n&&(n.style.borderColor="#ef4444"),void showToast("⚡ Please enter a Lightning address!");try{await db.collection("users").doc(e).update({lightningAddress:i,giveaway:{entered:!0,lightningAddress:i,enteredAt:(new Date).toISOString()}}),void 0!==currentUser&¤tUser&&(currentUser.lightningAddress=i),await db.collection("giveaway_entries").doc(e).set({username:t,lightningAddress:i,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:e}),showToast("🎉 You're entered for the 25,000 sats giveaway! Good luck!")}catch(e){console.log("Giveaway save error:",e)}}hideUsernamePrompt(),showToast("✅ Signed in as "+t);var a=document.getElementById("giveawayBanner");a&&(a.style.display="none")}async function sendMagicLink(e){const t={url:window.location.origin+window.location.pathname+"?signin_email="+encodeURIComponent(e),handleCodeInApp:!0};try{return await auth.sendSignInLinkToEmail(e,t),localStorage.setItem("btc_signin_email",e),!0}catch(e){return console.log("Magic link error:",e),!1}}function loadUserLocal(e){var t=parseInt(localStorage.getItem("btc_points")||"0"),o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");currentUser={uid:e,points:t,channelsVisited:o.length,readChannels:o,totalVisits:parseInt(localStorage.getItem("btc_total_visits")||"1"),streak:parseInt(localStorage.getItem("btc_streak")||"0"),lastVisit:localStorage.getItem("btc_last_visit")||"",_isLocal:!0},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,restoreVisitedUI(),updateRankUI(),_checkCapOnLoad(),updateAuthButton(),"function"==typeof renderProgressRings&&renderProgressRings(),"function"==typeof renderExplorationMap&&renderExplorationMap(),startReadTimer()}async function loadUser(e,t){const o=t||await db.collection("users").doc(e).get();if(o.exists){currentUser={uid:e,...o.data()},currentUser.visitedChannelsList&¤tUser.visitedChannelsList.forEach(e=>allTimeChannels.add(e));const t=auth.currentUser&&!auth.currentUser.isAnonymous;var n=[...new Set([...Array.isArray(currentUser.visitedChannelsList)?currentUser.visitedChannelsList:[],...Array.isArray(currentUser.readChannels)?currentUser.readChannels:[]])];if(n.length>0){if(t)localStorage.setItem("btc_visited_channels",JSON.stringify(n));else{let e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=[...new Set([...e,...n])];localStorage.setItem("btc_visited_channels",JSON.stringify(t))}restoreVisitedUI()}else t&&(localStorage.setItem("btc_visited_channels","[]"),restoreVisitedUI());if(currentUser.favorites){if(t)localStorage.setItem("btc_favs",JSON.stringify(currentUser.favorites));else{let e=JSON.parse(localStorage.getItem("btc_favs")||"[]"),t=[...new Set([...e,...currentUser.favorites])];localStorage.setItem("btc_favs",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else t&&(localStorage.setItem("btc_favs","[]"),"function"==typeof renderFavs&&renderFavs());if(currentUser.bookmarks){if(t)localStorage.setItem("btc_bookmarks",JSON.stringify(currentUser.bookmarks));else{let e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]"),t=currentUser.bookmarks.concat(e.filter(function(e){return!currentUser.bookmarks.some(function(t){return t.channel===e.channel&&t.idx===e.idx})}));localStorage.setItem("btc_bookmarks",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else if(t){var i=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");i.length>0&&db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({bookmarks:i}).catch(function(){})}if(currentUser.username&&localStorage.setItem("btc_username",currentUser.username),currentUser.streak>0&&!currentUser.bestStreak&&(currentUser.bestStreak=currentUser.streak),rankingReady=!0,updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),awardVisitPoints(),startReadTimer(),auth.currentUser.isAnonymous||db.collection("users").doc(e).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),t){if(currentUser.hiddenBadges){var a=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),r=[...new Set([...a,...currentUser.hiddenBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(r))}if(currentUser.donationBadges&¤tUser.donationBadges.length>0){var s=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),l=[...new Set([...s,...currentUser.donationBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(l))}if(currentUser.visibleBadges){var c=JSON.parse(localStorage.getItem("btc_badges")||"[]"),d=[...new Set([...c,...currentUser.visibleBadges])];localStorage.setItem("btc_badges",JSON.stringify(d))}if(currentUser.spinClosetItems){var u=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]"),p=[...new Set([...u,...currentUser.spinClosetItems])];localStorage.setItem("btc_spin_closet_items",JSON.stringify(p))}if(currentUser.scholarPassed&&localStorage.setItem("btc_scholar_passed","true"),currentUser.nachoMilestones&&localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(currentUser.nachoMilestones)),currentUser.celebratedState){var m=currentUser.celebratedState;m.nachoMilestones&&localStorage.setItem("btc_nacho_milestones",JSON.stringify(m.nachoMilestones)),m.nachoCatComplete&&localStorage.setItem("btc_nacho_cat_complete",JSON.stringify(m.nachoCatComplete)),m.nachoLevelCelebrated&&localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(m.nachoLevelCelebrated)),m.nachoItemsNotified&&localStorage.setItem("btc_nacho_items_notified",JSON.stringify(m.nachoItemsNotified))}if(currentUser.nachoInteractions){var h=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),g=currentUser.nachoInteractions||0;localStorage.setItem("btc_nacho_interactions",Math.max(h,g).toString())}if(currentUser.nachoQuestions){var f=parseInt(localStorage.getItem("btc_nacho_questions")||"0"),y=currentUser.nachoQuestions||0;localStorage.setItem("btc_nacho_questions",Math.max(f,y).toString())}}if(localStorage.setItem("btc_pvp_wins",String(currentUser.pvpWins||0)),localStorage.setItem("btc_pvp_losses",String(currentUser.pvpLosses||0)),currentUser.nachoNickname&&(localStorage.setItem("btc_nacho_nickname",currentUser.nachoNickname),"function"==typeof updateNachoNameUI&&updateNachoNameUI(currentUser.nachoNickname)),t){if(currentUser.lastSpinDate){var b=localStorage.getItem("btc_last_spin")||"";currentUser.lastSpinDate>b&&localStorage.setItem("btc_last_spin",currentUser.lastSpinDate),"function"==typeof updateSpinBanner&&updateSpinBanner()}if(currentUser.prediction&&(localStorage.getItem("btc_prediction")||localStorage.setItem("btc_prediction",JSON.stringify(currentUser.prediction))),currentUser.nachoStoryDays&&Array.isArray(currentUser.nachoStoryDays)){var v=safeJSON("btc_nacho_story_days",[]);currentUser.nachoStoryDays.length>v.length&&localStorage.setItem("btc_nacho_story_days",JSON.stringify(currentUser.nachoStoryDays))}if(currentUser.nachoStoryProgress){var w=parseInt(localStorage.getItem("btc_nacho_story_highest")||"0");currentUser.nachoStoryProgress>w&&localStorage.setItem("btc_nacho_story_highest",currentUser.nachoStoryProgress.toString())}if(currentUser.nachoStoryDate){var x=localStorage.getItem("btc_nacho_story_date")||"";currentUser.nachoStoryDate>x&&localStorage.setItem("btc_nacho_story_date",currentUser.nachoStoryDate)}}window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0;var k=getLevel(currentUser.points||0);lastLevelName=k.name,lastLevelMin=k.min,localStorage.getItem("btc_highest_level_seen")||localStorage.setItem("btc_highest_level_seen",k.min.toString()),setTimeout(function(){levelUpReady=!0},3e3),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showContinueReading&&showContinueReading(),updateAuthButton(),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging()}else{const t=auth.currentUser;if(t&&!t.isAnonymous){const o={username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};await db.collection("users").doc(e).set(o),currentUser={uid:e,...o},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton()}}}window.fbAsyncInit=function(){FB.init({appId:FB_APP_ID,cookie:!0,xfbml:!1,version:"v19.0"})},window.signInWithFacebook=async function(){if("undefined"!=typeof FB)try{return void await signInWithFBSDK()}catch(e){if("Facebook login cancelled"===e.message)return;console.warn("[Auth] FB SDK failed:",e)}await signInWithProvider(new firebase.auth.FacebookAuthProvider)},window.signInWithNostr=async function(){if(checkRateLimit()){var e=!!window.nostr,t=document.createElement("div");t.id="nostrAuthOverlay",t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

    🟣 Sign in with Nostr

    '+(e?'':'
    🔌
    No Extension Detected
    Install Alby or nos2x for one-click login
    ')+'
    or
    🔒 Your nsec is used only in your browser to sign a one-time login event. It is never sent to our servers or stored anywhere.
    or
    ',document.body.appendChild(t)}},window.nostrSignInWithExtension=async function(){if(window.nostr){var e=document.getElementById("nostrAuthStatus");e&&(e.innerHTML='Requesting key from extension...');try{var t=await window.nostr.getPublicKey();if(!t||!/^[a-f0-9]{64}$/.test(t))return void(e&&(e.innerHTML='Could not get public key'));e&&(e.innerHTML='Signing auth event...');var o=await window.nostr.signEvent({kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:t});if(!o||!o.sig)return void(e&&(e.innerHTML='Signing cancelled'));await nostrCompleteAuth(t,o.sig,o)}catch(t){console.error("Nostr extension error:",t),e&&(e.innerHTML='Extension error: '+(t.message||"Unknown")+"")}}else showToast("Extension not found")},window.nostrSignInWithNsec=async function(){var e=(document.getElementById("nostrNsecInput").value||"").trim(),t=document.getElementById("nostrAuthStatus"),o=document.getElementById("nostrNsecBtn");if(e)if(e.startsWith("nsec1")){o.disabled=!0,o.textContent="Loading crypto library...",t&&(t.innerHTML='Loading...');try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.integrity="sha384-GwmNxV/GnZt+zRBR/Hhtu5D4MKfbxeJSApW44ARryGYtj3MFheHMFgiEZ7tVnrln",o.crossOrigin="anonymous",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools;t&&(t.innerHTML='Decoding nsec...'),o.textContent="Signing...";var i=n.nip19.decode(e);if(!i||"nsec"!==i.type)return t&&(t.innerHTML='Invalid nsec'),o.disabled=!1,void(o.textContent="Sign In with nsec");var a=i.data;"string"!=typeof a&&(a=Array.from(new Uint8Array(a)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""));var r=n.getPublicKey(a),s={kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:r};s.id=n.getEventHash(s),s.sig=n.signEvent(s,a),document.getElementById("nostrNsecInput").value="",t&&(t.innerHTML='Verifying signature...'),await nostrCompleteAuth(r,s.sig,s)}catch(e){console.error("Nostr nsec error:",e),t&&(t.innerHTML='Error: '+(e.message||"Failed to sign")+""),o.disabled=!1,o.textContent="Sign In with nsec"}}else t&&(t.innerHTML='Invalid nsec format. Must start with nsec1');else showToast("Please paste your nsec")},window.nostrSignInWithNpub=async function(){var e=(document.getElementById("nostrNpubInput").value||"").trim(),t=document.getElementById("nostrAuthStatus");if(e){var o=e;if(e.startsWith("npub1"))try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools.nip19.decode(e);n&&"npub"===n.type&&"string"!=typeof(o=n.data)&&(o=Array.from(new Uint8Array(o)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""))}catch(e){return void(t&&(t.innerHTML='Invalid npub format'))}if(/^[a-f0-9]{64}$/.test(o)){t&&(t.innerHTML='Linking Nostr identity...');try{auth.currentUser||await auth.signInAnonymously();var i=auth.currentUser.uid;await db.collection("users").doc(i).set({nostr:o,lastLogin:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0}),currentUser&&(currentUser.nostr=o);var a=document.getElementById("nostrAuthOverlay");a&&a.remove(),showToast("🟣 Nostr identity linked! (npub)")}catch(e){t&&(t.innerHTML='Error: '+(e.message||"Unknown")+"")}}else t&&(t.innerHTML='Invalid public key')}else showToast("Please paste your npub")},window.nostrCompleteAuth=async function(e,t,o){var n=document.getElementById("nostrAuthStatus");try{var i=firebase.functions().httpsCallable("nostrAuth"),a=await i({pubkey:e,sig:t,event:o});if(a.data&&a.data.token){await auth.signInWithCustomToken(a.data.token);var r=a.data.uid,s=await db.collection("users").doc(r).get();if(!s.exists||!s.data().username){var l={username:"npub..."+e.substring(0,8),nostr:e,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};s.exists||(l.points=0,l.channelsVisited=0,l.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(r).set(l,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(r),hideUsernamePrompt();var c=document.getElementById("nostrAuthOverlay");c&&c.remove(),showToast("🟣 Signed in with Nostr!")}else n&&(n.innerHTML='Auth failed — no token received')}catch(e){console.error("Nostr auth error:",e),n&&(n.innerHTML='Verification failed: '+(e.message||"Unknown")+"")}},window.signInWithLightning=async function(){if(checkRateLimit()){var e=document.createElement("div");e.id="lnAuthModal",e.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.8);",e.onclick=function(t){t.target===e&&e.remove()},e.innerHTML='

    Lightning Login

    Scan this QR code with your Lightning wallet (Alby, Zeus, Phoenix, BlueWallet, etc.)

    Generating challenge...

    Connecting to server...

    ',document.body.appendChild(e);try{var t=firebase.functions().httpsCallable("lnAuthChallenge"),o=await t();if(!document.getElementById("lnAuthModal"))return;if(!o.data||!o.data.k1||!o.data.lnurl)return"function"==typeof showToast&&showToast("Failed to generate login challenge"),void e.remove();var n=o.data.k1,i=o.data.lnurl,a=document.getElementById("lnAuthQR");if(a)if(a.innerHTML="",a.style.display="inline-block","function"==typeof _renderQRCode)_renderQRCode(a,"lightning:"+i,220);else{var r=document.createElement("img");r.src="https://api.qrserver.com/v1/create-qr-code/?size=220x220&data="+encodeURIComponent("lightning:"+i),r.width=220,r.height=220,r.alt="Lightning Auth QR",r.style.cssText="border-radius:8px;",a.appendChild(r)}var s=document.getElementById("lnAuthCopyWrap");s&&(s.style.display="block",s.innerHTML="");var l=document.getElementById("lnAuthStatus");l&&(l.textContent="Waiting for wallet...",l.style.color="var(--accent)");var c=firebase.functions().httpsCallable("lnAuthVerify"),d=0,u=setInterval(async function(){if(++d>60||!document.getElementById("lnAuthModal"))clearInterval(u);else try{var e=await c({k1:n});if(e.data&&e.data.token){clearInterval(u);var t=document.getElementById("lnAuthStatus");t&&(t.textContent="✅ Authenticated!"),await auth.signInWithCustomToken(e.data.token);var o=e.data.uid,i=await db.collection("users").doc(o).get();if(!i.exists||!i.data().username){var a={username:"⚡anon-"+n.substring(0,8),authMethod:"lightning",totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};i.exists||(a.points=0,a.channelsVisited=0,a.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(o).set(a,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(o),hideUsernamePrompt(),setTimeout(function(){var e=document.getElementById("lnAuthModal");e&&e.remove()},1e3),"function"==typeof showToast&&showToast("⚡ Signed in with Lightning!")}}catch(e){"not-found"!==e.code&&console.log("LN auth poll:",e.message)}},2e3)}catch(e){console.error("Lightning auth error:",e),"function"==typeof showToast&&showToast("Lightning sign-in failed. Try again.");var p=document.getElementById("lnAuthModal");p&&p.remove()}}},window.sendReturningMagicLink=async function(){var e=document.getElementById("returningEmailInput");if(e){var t=e.value.trim();if(!t||!t.includes("@"))return showToast("📧 Please enter a valid email address"),void(e&&(e.style.borderColor="#ef4444"));e.disabled=!0;var o=e.nextElementSibling;o&&(o.disabled=!0,o.textContent="Sending..."),await sendMagicLink(t)?(showToast("📧 Magic link sent! Check your email to sign in."),o&&(o.textContent="✅ Sent!"),hideUsernamePrompt()):(showToast("❌ Could not send magic link. Try again."),e.disabled=!1,o&&(o.disabled=!1,o.textContent="Send Link"))}};var _authBtnSignedIn=!1;function updateAuthButton(){const e=document.getElementById("authBtn");if(e){var t=auth&&auth.currentUser,o=t&&!t.isAnonymous,n=currentUser&¤tUser.username,i=localStorage.getItem("btc_username"),a=n||i||t&&t.displayName||"",r=t&&t.uid&&(t.uid.startsWith("nostr:")||t.uid.startsWith("ln:"));if(o||r||a)_authBtnSignedIn=!0;else{if(_authBtnSignedIn&&t)return;t||(_authBtnSignedIn=!1)}if(_authBtnSignedIn){var s=a||"My Account";e.innerHTML="⚙️ "+("function"==typeof escapeHtml?escapeHtml(s):s)+" — Settings",e.onclick=function(){showSettings()},e.style.display=window.innerWidth<=900?"none":"block",e.style.background="none",e.style.border="2px solid #3b82f6",e.style.color="#3b82f6",e.onmouseover=function(){this.style.background="#3b82f6",this.style.color="#fff"},e.onmouseout=function(){this.style.background="none",this.style.color="#3b82f6"}}else(!t||t&&t.isAnonymous)&&(e.textContent="Create Free Account / Sign In",e.style.display="block",e.style.background="var(--accent)",e.style.border="none",e.style.color="#000",e.onmouseover=function(){this.style.transform="scale(1.02)"},e.onmouseout=function(){this.style.transform="scale(1)"});var l=document.getElementById("guestPointsBanner");l&&_authBtnSignedIn&&(l.style.display="none");var c=document.getElementById("giveawayBanner");c&&_authBtnSignedIn&&(currentUser&¤tUser.giveaway?(c.innerHTML='
    🎉 25,000 SATS GIVEAWAY 🎉
    You\'re entered! Good luck! 🍀
    ✅ Entered
    ',c.onclick=function(){showSettings()}):(c.querySelector("div:last-child")&&(c.querySelector("div:last-child").textContent="⚙️ View Your Profile →"),c.onclick=function(){showSettings()}))}}function sanitizeInput(e){return e.replace(/<[^>]*>/g,"").replace(/[<>"'&]/g,"").trim()}window.sanitizeInput=sanitizeInput,window.syncCelebratedState=function(){if(void 0!==db&&auth&&auth.currentUser){var e={nachoMilestones:safeJSON("btc_nacho_milestones",[]),nachoCatComplete:safeJSON("btc_nacho_cat_complete",[]),nachoLevelCelebrated:safeJSON("btc_nacho_level_celebrated",[]),nachoItemsNotified:safeJSON("btc_nacho_items_notified",[])};db.collection("users").doc(auth.currentUser.uid).update({celebratedState:e}).catch(function(){})}};const PROFANITY_LIST=["fuck","shit","ass","bitch","dick","cock","pussy","cunt","damn","hell","bastard","slut","whore","fag","faggot","nigger","nigga","retard","retarded","penis","vagina","porn","sex","anal","cum","jizz","dildo","tits","boob","nude","naked","hentai","milf","orgasm","erect","molest","rape","pedo","nazi","hitler","kkk","jihad","terrorist","kill","murder","suicide","die","stfu","gtfo","wank","twat","bollocks","arse","shag","piss","crap","douche","skank","thot","incel","simp","onlyfans","xnxx","pornhub","xvideos","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","aroused","erection","erectile","climax","ejaculat","deepthroat","rimjob","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes","twerk","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","zipperhead","jap","paki","wop","dago","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","acab","supremacy","genocide","lynch"];function containsProfanity(e){const t=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g," "),o=t.split(/\s+/);for(const e of o)if(PROFANITY_LIST.includes(e))return!0;const n=t.replace(/\s/g,"");for(const e of PROFANITY_LIST)if(e.length>=4&&n.includes(e))return!0;return!1}async function createUser(e,t,o,n,i){if(void 0===auth||!auth)return showToast("⏳ Loading... please try again in a moment."),void("function"==typeof initRanking&&initRanking());if(!auth.currentUser)try{await auth.signInAnonymously(),auth.currentUser||await new Promise(e=>{const t=auth.onAuthStateChanged(o=>{o&&(t(),e())});setTimeout(()=>{e()},3e3)})}catch(e){return console.log("Anonymous sign-in error:",e),void showToast("Error creating account. Please try again.")}if(!auth.currentUser)return void showToast("Error: Could not authenticate. Please refresh and try again.");const a=auth.currentUser.uid;if(clearUserData(),!(e=(e=sanitizeInput(e)).replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim())||e.length<2)return void showToast("⚠️ Username must be at least 2 characters (letters, numbers, basic symbols only).");if(containsProfanity(e))return void showToast("⚠️ That username is not allowed. Please choose another.");t&&(t=sanitizeInput(t));const r={username:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};if(t&&(r.email=t),i&&(r.country=i),window._signupFaction&&(r.faction=window._signupFaction,window._signupFaction=null),o&&n){r.lightningAddress=n,r.giveaway={entered:!0,lightningAddress:n,enteredAt:(new Date).toISOString()};try{await db.collection("giveaway_entries").doc(a).set({username:e,lightningAddress:n,email:t||null,enteredAt:firebase.firestore.FieldValue.serverTimestamp(),uid:a})}catch(e){console.log("Giveaway entry save error:",e)}}await db.collection("users").doc(a).set(r);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}currentUser={uid:a,...r},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton(),awardPoints(POINTS.visit,"Welcome bonus!"),startReadTimer(),hideUsernamePrompt();try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},800)}catch(e){}var s=document.getElementById("giveawayBanner");s&&(s.style.display="none"),"function"==typeof attachReferral&&attachReferral(a),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging();try{var l=JSON.parse(localStorage.getItem("btc_buddy_pending")||"null");l&&l.goal&&(localStorage.removeItem("btc_buddy_pending"),"function"==typeof _submitBuddyFromOnboarding&&setTimeout(function(){_submitBuddyFromOnboarding(l.level||"beginner",l.goal)},2e3))}catch(e){}}async function awardVisitPoints(){if(!currentUser)return;const e=(new Date).toISOString().split("T")[0],t=new Date(Date.now()-864e5).toISOString().split("T")[0];if(currentUser.lastVisit===e)return;let o=!1,n=0,i=POINTS.visit,a=1;if(currentUser.lastVisit===t)a=(currentUser.streak||0)+1,a%7==0?(n=Math.min(25,5*Math.floor(a/7)),o=!0):a%5==0&&(i+=POINTS.streak,o=!0);else if(currentUser.lastVisit!==e){var r=currentUser.streak||0;currentUser.streakFreezes>0?(a=r+1,currentUser.streakFreezes--,o=!0,setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze ticket was used to save your "+a+"-day streak! ("+(currentUser.streakFreezes||0)+" freezes remaining)")},3e3)):r>1&&setTimeout(function(){showToast("💔 Your "+r+"-day streak was broken! Earn 🧊 Freeze Tickets from the Daily Spin to protect your streak next time.")},3e3)}if(currentUser._isLocal);else{try{var s=firebase.functions().httpsCallable("recordDailyVisit"),l=await s({});if(l.data&&l.data.success&&!l.data.alreadyVisited){a=l.data.streak||1,n=l.data.bonusTickets||0;var c=l.data.bestStreak||a;currentUser.streak=a,currentUser.bestStreak=c,currentUser.lastVisit=e,currentUser.totalVisits=l.data.totalVisits||(currentUser.totalVisits||0)+1,n>0&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+n),l.data.usedFreeze&&(currentUser.streakFreezes=Math.max(0,(currentUser.streakFreezes||0)-1),setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze was used to save your "+a+"-day streak!")},3e3))}}catch(e){console.warn("[VISIT] Cloud Function failed:",e.message)}var d=i+5*n;d>0&&await awardPoints(d,"✅ Daily visit"+(a>1?" ("+a+"-day streak!)":""))}n>0?("function"==typeof notifySelfStreak&¬ifySelfStreak(a),setTimeout(function(){showToast("🔥 STREAK MILESTONE! Day "+a+": Earned +"+n+" Bonus Tickets! 🎟️")},3500)):o&&showToast("🔥 Day "+currentUser.streak+" streak! +"+(POINTS.visit+POINTS.streak)+" XP"),updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen()}async function awardPoints(e,t,o,n,i){if(currentUser&&rankingReady&&(e=parseInt(e),!(isNaN(e)||e<0||e>2200)&&(0!==e||n||i))){window._pointAwardTimes=window._pointAwardTimes||[];var a=Date.now();if(window._pointAwardTimes=window._pointAwardTimes.filter(function(e){return a-e<6e4}),!(window._pointAwardTimes.length>=20)){if(window._pointAwardTimes.push(a),currentUser._isLocal){var r=500,s=(new Date).toISOString().split("T")[0],l="btc_daily_pts_"+s,c=parseInt(localStorage.getItem(l)||"0",10);isNaN(c)&&(c=0);var d={tctv_watch_10m:6e5,daily_spin:864e5,daily_visit:72e6}[t];if(d){var u="btc_cd_"+t,p=parseInt(localStorage.getItem(u)||"0",10);if(p&&Date.now()-p0&&f&&f!==s){g-=y=Math.min(g,r);try{localStorage.setItem(m,String(g))}catch(e){}}var b=e,v=0;if(c>=r?(b=0,v=e):c+e>r&&(v=e-(b=r-c)),(_=b+y)>0){var w=(parseInt(localStorage.getItem("btc_points")||"0",10)||0)+_;try{localStorage.setItem("btc_points",String(w)),b>0&&localStorage.setItem(l,String(c+b))}catch(e){}currentUser.points=w,_showPointsToast(b,t),"function"==typeof notifySelfPoints&¬ifySelfPoints(b,t),y>0&&"function"==typeof showToast&&setTimeout(function(){showToast("♻️ +"+y+" overflow pts redeemed from prior day!",4e3)},1200)}if(v>0){g+=v;try{localStorage.setItem(m,String(g)),localStorage.setItem(h,s)}catch(e){}var x="btc_overflow_notified_"+s;if(!localStorage.getItem(x)){try{localStorage.setItem(x,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap reached (500)! +"+v+" XP banked as overflow — they roll over tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}else if(c+b>=r){var k="btc_daily_cap_notified_"+s;if(!localStorage.getItem(k)){try{localStorage.setItem(k,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}return updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),void("function"==typeof nachoOnPoints&&nachoOnPoints(e))}auth.currentUser.isAnonymous||db.collection("users").doc(auth.currentUser.uid).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),e>0&&t&&"function"==typeof notifySelfPoints&¬ifySelfPoints(e,t);try{var B=firebase.functions().httpsCallable("awardPoints"),S={pts:e,action:t||"",reason:t||""};o&&(S.channelId=o),n&&(S.tickets=n),i&&(S.streakFreezes=i);var T=await B(S);if(T.data&&T.data.dailyActionCapped&&"function"==typeof showToast&&showToast("⏳ "+(T.data.error||"Daily limit reached for this action."),6e3),T.data&&T.data.cooldown&&"function"==typeof showToast&&showToast("⏳ "+(T.data.error||"Slow down a bit."),4e3),T.data&&T.data.success){b=T.data.awarded||0,y=T.data.overflowRedeemed||0,v=T.data.overflowAdded||0;var _,I=T.data.pendingOverflow||0;if((_=b+y)>0&&(currentUser.points=(currentUser.points||0)+_,_showPointsToast(b,t),y>0&&setTimeout(function(){showToast("♻️ +"+y+" overflow pts redeemed from prior day!",4e3)},1200)),v>0){m="btc_overflow_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(m)||(localStorage.setItem(m,"1"),showToast("🎯 Daily cap reached (500)! +"+v+" XP banked as overflow — they roll over tomorrow.",8e3),_updateCapIndicator(!0));try{localStorage.setItem("btc_pts_overflow",String(I))}catch(e){}}else T.data.capped&&(k="btc_daily_cap_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(k)||(localStorage.setItem(k,"1"),showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow.",8e3),_updateCapIndicator(!0)))}}catch(e){console.warn("[POINTS] Cloud Function failed:",e.message),"function"==typeof showToast&&showToast("⏳ XP will sync when connection restores")}updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),"function"==typeof nachoOnPoints&&nachoOnPoints(e)}}}function _showPointsToast(e,t){var o=!1;e>=25?o=!0:t&&t.length>0&&(window._lastPtsToast=window._lastPtsToast||0,Date.now()-window._lastPtsToast>3e4&&(o=!0)),o&&t&&(window._lastPtsToast=Date.now(),showToast("+"+e+" XP — "+t,2500))}function refreshLeaderboardIfOpen(){var e=document.getElementById("leaderboard");if(e&&e.classList.contains("open")&&!e.classList.contains("minimized")){window._lbCache=null,window._lbCacheTime=null;var t=e.querySelector(".lb-me .lb-score");t&¤tUser&&(t.textContent=(currentUser.points||0).toLocaleString()+" XP")}}async function onChannelOpen(e){if("function"==typeof nachoOnChannel&&nachoOnChannel(e),currentUser&&rankingReady){if(!allTimeChannels.has(e)){allTimeChannels.add(e),sessionChannels.add(e);let t=POINTS.openChannel;if(window._dailyBoosts&&window._dailyBoosts.includes(e)&&(t*=2,setTimeout(()=>{showToast("⚡ 2X XP! Daily boost applied! +"+t+" XP")},2e3)),currentUser._isLocal,currentUser.channelsVisited=(currentUser.channelsVisited||0)+1,currentUser.readChannels?-1===currentUser.readChannels.indexOf(e)&¤tUser.readChannels.push(e):currentUser.readChannels=[e],Array.isArray(currentUser.visitedChannelsList)||(currentUser.visitedChannelsList=[]),-1===currentUser.visitedChannelsList.indexOf(e)&¤tUser.visitedChannelsList.push(e),await awardPoints(t,"📖 New channel explored",e),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showToast){const e=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,t=Math.round(allTimeChannels.size/e*100);showToast("🗺️ Exploration Map: "+allTimeChannels.size+" channels reached ("+t+"%)")}10===allTimeChannels.size&&await awardPoints(POINTS.explore10,"Explorer bonus! 10 topics 🎉")}readSeconds=0,lastReadAward=0,syncReadToFirebase(e),"function"==typeof onChannelVisitForQuest&&onChannelVisitForQuest(e)}}async function syncReadToFirebase(e){}async function syncFavsToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_favs")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({favorites:e})}catch(e){}}async function syncBookmarksToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({bookmarks:e})}catch(e){}}function restoreVisitedUI(){JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})})}window.notifySelfPoints=function(e,t){if(e&&!(e<1)&&t&&""!==t){var o={pts:e,reason:t,ts:Date.now(),read:!1};try{var n=JSON.parse(localStorage.getItem("btc_points_log")||"[]");n.push(o),n.length>100&&(n=n.slice(n.length-100)),localStorage.setItem("btc_points_log",JSON.stringify(n))}catch(e){}"function"==typeof _updatePointsBadge&&_updatePointsBadge()}},window.syncBookmarksToFirebase=syncBookmarksToFirebase;let lastActivityTime=Date.now(),lastScrollPos=0,hasScrolledSinceLastAward=!1;function trackActivity(){lastActivityTime=Date.now()}function trackScroll(){const e=document.getElementById("main");e&&Math.abs(e.scrollTop-lastScrollPos)>30&&(lastScrollPos=e.scrollTop,hasScrolledSinceLastAward=!0,lastActivityTime=Date.now())}function startReadTimer(){readTimer&&clearInterval(readTimer),readTimer=setInterval(async()=>{if(currentUser&&rankingReady&&!document.hidden&&!((Date.now()-lastActivityTime)/1e3>45)&&hasScrolledSinceLastAward&&(readSeconds++,sessionStorage.setItem("btc_channel_read_seconds",readSeconds.toString()),readSeconds-lastReadAward>=30)){lastReadAward=readSeconds,hasScrolledSinceLastAward=!1;var e="btc_read_cap_"+(window.currentChannelId||"unknown")+"_"+(new Date).toISOString().split("T")[0],t=parseInt(localStorage.getItem(e)||"0");if(t>=5)return;localStorage.setItem(e,(t+1).toString()),await awardPoints(POINTS.readTime,"")}},1e3)}function getLevel(e){let t=LEVELS[0];for(const o of LEVELS)e>=o.min&&(t=o);const o=LEVELS.indexOf(t)+1,n=o
    '+o.emoji+''+t.toLocaleString()+' XP
    Sign in to keep your XP & get on the leaderboard!
    Sign Up Free →
    ",e.style.display="flex"}}else e&&(e.style.display="none");else e&&(e.style.display="none")}function _updateCapIndicator(e){var t=document.getElementById("userDisplay");if(t){var o,n="btc_daily_pts_"+(new Date).toISOString().split("T")[0],i=parseInt(localStorage.getItem(n)||"0"),a=parseInt(localStorage.getItem("btc_pts_overflow")||"0");e||i>=500?(t.style.borderColor="#ef4444",t.style.boxShadow="0 0 12px rgba(239,68,68,0.3)",t.title="🎯 Daily XP cap reached (500/500)"+(a>0?"\n💫 Overflow: "+a+" pts (rolls over tomorrow)":""),document.getElementById("dailyCapBadge")||((o=document.createElement("span")).id="dailyCapBadge",o.style.cssText="position:absolute;top:-6px;left:-6px;background:#ef4444;color:#fff;font-size:0.55rem;font-weight:800;padding:2px 6px;border-radius:8px;z-index:2;pointer-events:none;",o.textContent="CAP",t.style.position="fixed",t.appendChild(o))):(t.style.borderColor="var(--border)",t.style.boxShadow="0 2px 10px rgba(0,0,0,0.2)",t.title="",(o=document.getElementById("dailyCapBadge"))&&o.remove())}}function _checkCapOnLoad(){var e="btc_daily_pts_"+(new Date).toISOString().split("T")[0];parseInt(localStorage.getItem(e)||"0")>=500&&setTimeout(function(){_updateCapIndicator(!0)},2e3)}function updateRankUI(){if(!currentUser)return;var e=document.getElementById("giveawayBanner");e&¤tUser.username&&(e.style.display="none");const t=getLevel(currentUser.points||0);!lastLevelName&&t.name&&(lastLevelName=t.name,lastLevelMin=t.min),updateGuestPointsBanner(),updateUserDisplay(t);const o=parseInt(localStorage.getItem("btc_highest_level_seen")||"0");if(levelUpReady&&lastLevelName&&lastLevelName!==t.name&&t.min>lastLevelMin&&t.min>o){showLevelUpCelebration(t),localStorage.setItem("btc_highest_level_seen",t.min.toString()),"function"==typeof notifySelfLevelUp&¬ifySelfLevelUp(t.min,t.name,t.emoji);var n=currentUser&¤tUser.username?currentUser.username:null,i=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:"";if(n&&"function"==typeof window.nachoGlobalAnnounce&&window.nachoGlobalAnnounce(t.emoji+" @"+n+" just leveled up to "+t.emoji+" "+t.name+"! Congrats! 🎉",i),"function"==typeof window.contributeSatoshiFavor){var a=t.name||"",r=null;["Pleb","Pleb II","Pleb III","Stacker","Stacker II","Stacker III"].includes(a)?r="level_up":["Maxi","Maxi II","Maxi III"].includes(a)?r="level_up_5":["Papa John","Full Node","Whale","Sovereign","Cypherpunk","Satoshi"].includes(a)&&(r="level_up_10"),r&&window.contributeSatoshiFavor(r,a)}}lastLevelName=t.name,lastLevelMin=t.min;const s=document.getElementById("rankBar");if(!s)return;let l="";t.next&&(l='
    '+(t.next.min-currentUser.points)+" XP to "+t.next.emoji+" "+t.next.name+"
    ");const c=auth.currentUser&&auth.currentUser.isAnonymous&¤tUser.username?'':"",d=currentUser.streak||0,u=d>0&&(d%7==0||30===d||100===d||365===d),p=currentUser.bestStreak||0,m=d>0||p>0?'🔥 '+d+(p>0?"("+p+")":"")+" day streak"+(u?" ✨":"")+"":"",h=(currentUser.orangeTickets||0)>0?''+currentUser.orangeTickets+"":"";s.innerHTML='
    '+t.emoji+" "+t.name+''+escapeHtml(currentUser.username||"Anon")+''+(currentUser.points||0).toLocaleString()+" XP"+m+h+"
    "+l+c,s.style.display="flex"}function getUserDisplayEmoji(e){var t=void 0!==currentUser&¤tUser?currentUser.displayBadge:null;if(t){if(void 0!==BADGE_DEFS)for(var o=0;o0?'🔥'+currentUser.streak+"":"",s=getUserDisplayEmoji(e);let l=document.getElementById("userDisplay");if(l||(l=document.createElement("div"),l.id="userDisplay",document.body.appendChild(l)),n||auth.currentUser&&auth.currentUser.isAnonymous&&!i){if(u=window.innerWidth<=900)return l.setAttribute("data-mob-hidden","1"),void(l.style.display="none");if("1"===sessionStorage.getItem("btc_signin_banner_dismissed"))return l.classList.add("user-hidden"),void(l.style.display="none");l.classList.remove("user-hidden"),l.setAttribute("data-anon","1"),u?l.style.cssText="position:fixed;bottom:70px;left:12px;right:12px;z-index:200;display:flex;align-items:center;gap:10px;padding:10px 16px;background:linear-gradient(135deg,#1a1a2e,#2d1f4e);border:2px solid #f7931a;border-radius:14px;box-shadow:0 4px 20px rgba(247,147,26,0.3);font-size:0.85rem;cursor:pointer;":((c=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((d=document.createElement("div")).id="userDisplayContainer",d.style.padding="0 20px 16px",d.style.borderBottom="1px solid var(--border)",c.parentNode.insertBefore(d,c.nextSibling),d.appendChild(l)),l.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:12px;background:rgba(247,147,26,0.05);border:1px solid rgba(247,147,26,0.2);border-radius:12px;cursor:default;transition:0.3s;width:100%;"),l.onclick=function(e){!u&&e.target.closest("button")||showSettingsPage("account")},l.innerHTML=(u?'':"")+'
    '+e.emoji+'GUEST'+a.toLocaleString()+" XP
    "+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
    ';return e&&(o+='
    $'+Math.round(e).toLocaleString()+"
    "),t&&(o+='⛓️ '+t.toLocaleString()+""),o+"
    "}()+(u?'
    Sign in to keep XP & enter giveaway!
    ':"")+"
    "+(u?"":'
    ')+(u?"":'
    SIGN UP
    ')+(u?'
    Sign Up →
    ':"")}else{l.removeAttribute("data-anon"),l.removeAttribute("data-mob-hidden");var c,d,u=window.innerWidth<=900,p=document.getElementById("dashboardFloatBtn");if(p||((p=document.createElement("div")).id="dashboardFloatBtn",p.className="fab-btn",p.innerHTML="📊",p.title="Bitcoin Metrics",document.body.appendChild(p)),p.onclick=function(){"function"==typeof toggleDashboard&&toggleDashboard()},u)return void(l.style.display="none");if(u)l.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:8px;padding:8px 14px;background:var(--bg-side);border:1px solid var(--border);border-radius:10px;font-size:0.8rem;cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,0.2);";else(c=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((d=document.createElement("div")).id="userDisplayContainer",d.style.padding="0 20px 16px",d.style.borderBottom="1px solid var(--border)",c.parentNode.insertBefore(d,c.nextSibling),d.appendChild(l)),l.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:10px;background:rgba(255,255,255,0.03);border:1px solid var(--border);border-radius:10px;cursor:pointer;width:100%;";l.onclick=function(e){e.target.closest("a")||showSettings()};var m,h=currentUser.username||auth.currentUser&&auth.currentUser.displayName||"Anon";m=currentUser.displayBadge?''+s+' '+e.emoji+"":''+e.emoji+"",l.innerHTML='
    '+m+''+escapeHtml(h)+""+(r?''+r+"":"")+"
    "+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
    ';return e&&(o+='
    $'+Math.round(e).toLocaleString()+"
    "),t&&(o+='⛓️ '+t.toLocaleString()+""),(o+=''+a.toLocaleString()+" XP")+"
    "}()+"
    "+(u?"":'
    ')}l.style.display="flex";const g=document.getElementById("mobileUserInfo");if(g&&window.innerWidth<=900){var f=s;currentUser.displayBadge&&(f+=" "+e.emoji),a=currentUser.points||0;var y=parseFloat(localStorage.getItem("btc_last_price"))||0,b=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(y=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(b=nachoLiveData.blockHeight);var v=''+f+" "+escapeHtml(currentUser.username||(n?"Anonymous":"Anon"))+"";y&&(v+=' $'+Math.round(y).toLocaleString()+""),b&&(v+=' ⛓️ '+b.toLocaleString()+""),v+=' '+a.toLocaleString()+" XP",g.innerHTML=v,g.style.display="inline",g.style.maxWidth="none"}const w=document.getElementById("welcomeBanner");if(w&¤tUser.username){updateAuthButton();const t=currentUser.streak||0,o=currentUser.bestStreak||0,n=t>0||o>0?' · 🔥 '+t+(o>0?"("+o+")":"")+" day streak":"";w.innerHTML=''+e.emoji+' Welcome back, '+escapeHtml(currentUser.username||"Anon")+'! · '+e.name+" · "+(currentUser.points||0).toLocaleString()+" XP"+n+'
    ⚙️ Tap here for Account & Settings
    ',w.style.display="block",w.removeAttribute("data-simplified-hidden")}}document.addEventListener("mousemove",trackActivity),document.addEventListener("keydown",trackActivity),document.addEventListener("touchstart",trackActivity,{passive:!0}),document.addEventListener("click",trackActivity),setInterval(trackScroll,2e3),window.toggleGuestPointsBanner=function(){var e=document.getElementById("guestPointsBanner");if(e){var t=!e.classList.contains("banner-min");e.classList.toggle("banner-min",t);try{localStorage.setItem("btc_signin_banner_min",t?"1":"0")}catch(e){}updateGuestPointsBanner()}};let lbAutoShown=!1;function showLeaderboardAuto(){lbAutoShown||(lbAutoShown=!0,document.getElementById("leaderboard").classList.contains("open")||toggleLeaderboard())}function expandLeaderboard(e){e&&e.stopPropagation(),document.querySelectorAll(".lb-extra").forEach(e=>e.style.display="flex");const t=document.getElementById("lbShowMore");t&&t.remove()}function minimizeLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}function hideLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}function _lbOutsideClose(e){var t=document.getElementById("leaderboard");if(t&&t.classList.contains("open")&&!t.classList.contains("minimized")&&!t.contains(e.target)){var o=document.getElementById("rankBar");if(!o||!o.contains(e.target)){var n=document.getElementById("lbFloatBtn");n&&n.contains(e.target)||document.getElementById("userProfileModal")||(t.classList.remove("open"),t.classList.remove("minimized"),n&&(n.style.display="flex"))}}}function applyOLEDTheme(){const e="true"===localStorage.getItem("btc_theme_oled"),t="light"!==document.body.getAttribute("data-theme");e&&t?document.body.classList.add("oled-theme"):document.body.classList.remove("oled-theme")}function _lbBadgeEmoji(e){var t=[],o="undefined"!=typeof Intl&&Intl.Segmenter?Array.from(new Intl.Segmenter("en",{granularity:"grapheme"}).segment(e)).map(function(e){return e.segment}):null;o?t=o:t=e.match(/\p{Emoji_Presentation}(\u200d\p{Emoji_Presentation})*/gu)||[e];if(t.length<=1)return e;var n=2===t.length?"0.6rem":"0.5rem";return''+t.map(function(e){return""+e+""}).join("")+""}async function toggleLeaderboard(){const e=document.getElementById("leaderboard");if(!e)return;const t=document.getElementById("lbFloatBtn");if(e.classList.contains("open")&&!e.classList.contains("minimized"))return e.classList.remove("open"),e.classList.remove("minimized"),void(t&&(t.style.display="flex"));if(e.classList.remove("minimized"),e.innerHTML='
    Loading leaderboard...
    ',e.classList.add("open"),t&&(t.style.display="none"),("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{window._sharedAudioCtx||(window._sharedAudioCtx=new(window.AudioContext||window.webkitAudioContext));var o=window._sharedAudioCtx;"suspended"===o.state&&o.resume();const e="undefined"!=typeof audioVolume?audioVolume:.5,t=o.currentTime,n=o.createOscillator(),i=o.createGain();n.connect(i),i.connect(o.destination),n.type="sine",n.frequency.setValueAtTime(200,t),n.frequency.exponentialRampToValueAtTime(800,t+.15),i.gain.setValueAtTime(.08*e,t),i.gain.exponentialRampToValueAtTime(.001,t+.2),n.start(t),n.stop(t+.2),[880,1175].forEach((n,i)=>{const a=o.createOscillator(),r=o.createGain();a.connect(r),r.connect(o.destination),a.type="triangle",a.frequency.value=n,r.gain.setValueAtTime(.1*e,t+.1+.08*i),r.gain.exponentialRampToValueAtTime(.001,t+.1+.08*i+.3),a.start(t+.1+.08*i),a.stop(t+.1+.08*i+.3)})}catch(e){}try{var n=Date.now(),i=window._lbCache&&window._lbCacheTime&&n-window._lbCacheTime<12e4;let t=[];i?t=window._lbCache:((await db.collection("users").orderBy("points","desc").limit(150).get()).forEach(e=>{const o=e.data(),n=auth.currentUser&&e.id===auth.currentUser.uid;o.points>0&&(!o.ghostMode||n)&&t.push({id:e.id,...o})}),window._lbCache=t,window._lbCacheTime=n);let o='
    🏆 Leaderboard — tap to expand
    ';o+='

    🏆 Leaderboard

    ',o+='
    ',Math.min(10,t.length),t.forEach((e,t)=>{const n=t+1,i=getLevel(e.points||0),a=auth.currentUser&&e.id===auth.currentUser.uid;a&¤tUser&&(e.points||0)>(currentUser.points||0)&&(currentUser.points=e.points,updateRankUI());const r=1===n?"🥇":2===n?"🥈":3===n?"🥉":"#"+n,s=n>10?' style="display:none;" class="lb-row lb-extra'+(a?" lb-me":"")+'"':' class="lb-row'+(a?" lb-me":"")+'"';var l="function"==typeof onlineStatusDot?onlineStatusDot(e.lastSeen):"";let c="";e.earnedHidden&&e.earnedHidden.includes("cert_scholar")&&(c+=" 🎓"),e.earnedHidden&&e.earnedHidden.includes("cert_tech")&&(c+=" 🛠️");var d=e.profilePic?'':"",u=JSON.stringify({recipientName:e.username||"Anon",recipientUid:e.id,lightningAddress:e.lightningAddress||e.lightning||"",context:"leaderboard",label:"Tip "+(e.username||"Anon")}).replace(/'/g,"'").replace(/"/g,"""),p=e.faction?window._factionNameStyle(e.faction):"";o+="'+r+''+_lbBadgeEmoji(i.emoji)+'"+(d?d+" ":"")+escapeHtml(e.username||"Anon")+l+c+''+(e.points||0).toLocaleString()+' XP
    '}),t.length>10&&(o+='"),o+="","function"==typeof getBadgeHTML&&(o+='

    Your Badges

    '+getBadgeHTML()+"
    "),o+='

    ⚔️ PVP Leaderboard

    Loading PVP rankings...
    ',o+='

    Levels

    ';for(const e of LEVELS)o+='
    '+e.emoji+" "+e.name+""+(0===e.min?"0 XP":e.min+"+ XP")+"
    ";o+="
    ",e.innerHTML=o,_loadPVPLeaderboard()}catch(t){console.error("[Leaderboard] Error:",t),e.innerHTML='
    Error loading leaderboard: '+(t.message||"Unknown error")+"
    "}}async function _loadPVPLeaderboard(){var e=document.getElementById("pvpLeaderboardList");if(e)try{var t,o,n=Date.now();window._pvpLbCache&&window._pvpLbCacheTime&&n-window._pvpLbCacheTime<3e5?(t=window._pvpLbCache.wins,o=window._pvpLbCache.losses):([t,o]=await Promise.all([db.collection("users").where("pvpWins",">",0).orderBy("pvpWins","desc").limit(50).get(),db.collection("users").where("pvpLosses",">",0).orderBy("pvpLosses","desc").limit(50).get()]),window._pvpLbCache={wins:t,losses:o},window._pvpLbCacheTime=n);var i={},a=auth.currentUser?auth.currentUser.uid:null;function r(e){if(!i[e.id]){var t=e.data();if(!t.ghostMode||e.id===a){var o=t.pvpWins||0,n=t.pvpLosses||0,r=o+n;if(0!==r){var s=r>0?o/r*100:0;i[e.id]={id:e.id,username:escapeHtml(t.username||"Anon"),wins:o,losses:n,total:r,winRate:s,isMe:e.id===a,lightningAddress:t.lightningAddress||t.lightning||""}}}}}t.forEach(r),o.forEach(r);var s=Object.values(i);if(0===s.length)return void(e.innerHTML='
    No PVP battles yet — be the first to compete!
    ');s.sort(function(e,t){return t.winRate-e.winRate||t.wins-e.wins});var l="";s.forEach(function(e,t){var o=t+1,n=1===o?"🥇":2===o?"🥈":3===o?"🥉":"#"+o,i=e.wins>=100?"👑":e.wins>=50?"🏆":e.wins>=25?"🏟️":e.wins>=5?"🥊":"⚔️",a=o>10?' style="display:none;" class="lb-row pvp-lb-extra'+(e.isMe?" lb-me":"")+'"':' class="lb-row'+(e.isMe?" lb-me":"")+'"',r=JSON.stringify({recipientName:e.username,recipientUid:e.id,lightningAddress:e.lightningAddress,context:"pvp",label:"Tip "+e.username}).replace(/'/g,"'").replace(/"/g,""");l+="'+n+''+i+''+e.username+''+e.wins+"W – "+e.losses+'L'}),s.length>10&&(l+=""),e.innerHTML=l||'
    No PVP battles yet!
    '}catch(c){e.innerHTML='
    No PVP battles yet — be the first to compete!
    '}}document.addEventListener("mousedown",_lbOutsideClose,!0),document.addEventListener("touchstart",_lbOutsideClose,!0),window.toggleOLEDTheme=function(){const e="true"===localStorage.getItem("btc_theme_oled");localStorage.setItem("btc_theme_oled",!e),applyOLEDTheme(),showSettingsPage("prefs"),showToast(e?"Deep sea mode disabled":"🖤 Midnight OLED enabled!")},document.addEventListener("DOMContentLoaded",applyOLEDTheme),window.showDeleteAccountConfirm=function(){var e=document.createElement("div");e.id="deleteAccountOverlay",e.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;",e.onclick=function(t){t.target===e&&e.remove()};var t=currentUser&¤tUser.username?currentUser.username:"your account",o=currentUser&¤tUser.points||0,n=currentUser&¤tUser.streak||0;e.innerHTML='
    ⚠️

    Delete Your Account?

    This will permanently delete everything associated with '+escapeHtml(t)+':
    '+o.toLocaleString()+" XP and all badges
    "+(n>0?"
    "+n+"-day streak
    ":"")+'
    ❌ All forum posts and replies
    ❌ Marketplace listings
    ❌ DM conversations
    ❌ Nacho chat history
    ❌ Leaderboard ranking
    ❌ Orange Tickets and quest progress
    ⚠️ This action is IRREVERSIBLE. There is no undo.
    ',document.body.appendChild(e)},window.confirmDeleteAccount=async function(){var e=document.getElementById("deleteConfirmInput");if(e&&"DELETE"===e.value){var t=document.getElementById("deleteConfirmBtn");t&&(t.disabled=!0,t.textContent="Deleting...");try{var o=auth.currentUser;if(!o)throw new Error("Not signed in");var n=o.uid;try{await db.collection("users").doc(n).delete()}catch(e){console.warn("User doc delete failed:",e)}try{var i=await db.collection("forum_posts").where("authorId","==",n).get(),a=db.batch();i.forEach(function(e){a.delete(e.ref)}),i.empty||await a.commit()}catch(e){console.warn("Forum posts delete failed:",e)}try{var r=await db.collection("forum_replies").where("authorId","==",n).get(),s=db.batch();r.forEach(function(e){s.delete(e.ref)}),r.empty||await s.commit()}catch(e){console.warn("Forum replies delete failed:",e)}try{var l=await db.collection("marketplace").where("sellerUid","==",n).get(),c=db.batch();l.forEach(function(e){c.delete(e.ref)}),l.empty||await c.commit()}catch(e){console.warn("Marketplace delete failed:",e)}try{var d=await db.collection("conversations").where("participants","array-contains",n).get(),u=db.batch();d.forEach(function(e){u.delete(e.ref)}),d.empty||await u.commit()}catch(e){console.warn("DM delete failed:",e)}try{var p=await db.collection("suggestions").where("uid","==",n).get(),m=db.batch();p.forEach(function(e){m.delete(e.ref)}),p.empty||await m.commit()}catch(e){console.warn("Suggestions delete failed:",e)}for(var h=[],g=0;gclick to ask!'),document.querySelectorAll('[id*="nachoCloset"]').forEach(function(t){var o=t.querySelector('[style*="letter-spacing"]');o&&-1!==o.textContent.indexOf("'s Closet")&&(o.textContent="🦌 "+e+"'s Closet")}),document.querySelectorAll('[style*="font-weight:800"]').forEach(function(t){-1!==t.textContent.indexOf("'s Story")&&(t.textContent=e+"'s Story")})}};var _toastQueue=[];function showToast(e,t){window._directLinkMode||(window._nachoBusy?_toastQueue.push({msg:e,duration:t}):_showToastNow(e,t))}function _showToastNow(e,t){var o=t||2500;const n=document.createElement("div");n.className="rank-toast";var i="object"==typeof e?e.msg:e;n.innerHTML=i.replace(/<(script|svg|img|iframe|object|embed|form|input|link|style|meta|base)[^>]*>/gi,"").replace(/on\w+\s*=/gi,"data-blocked="),"object"==typeof e&&e.duration&&(o=e.duration),document.body.appendChild(n),requestAnimationFrame(()=>n.classList.add("show")),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>n.remove(),400)},o)}function showUsernamePrompt(){try{if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)return void showAccountInfo();if(currentUser&¤tUser.username)return void showAccountInfo();if(!redirectResultResolved)return showToast("⏳ Loading account..."),void redirectResultPromise.then(function(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous||currentUser&¤tUser.username?showAccountInfo():(document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash))});document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash)}catch(e){"function"==typeof showToast&&showToast("Settings error: "+e.message),console.error("showUsernamePrompt error:",e)}}function showAccountInfo(){showSettingsPage("account")}setInterval(function(){!window._nachoBusy&&_toastQueue.length>0&&_showToastNow(_toastQueue.shift())},2e3),window.showSignInOnly=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)showAccountInfo();else{var e=document.getElementById("usernameModal");e&&(e.classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash),setTimeout(function(){var t=e.querySelector(".username-box");if(t){var o=t.querySelector("h2"),n=t.querySelector("p"),i=document.getElementById("usernameInput"),a=document.getElementById("emailInput"),r=document.getElementById("giveawaySection"),s=t.querySelector('button[onclick="submitUsername()"]'),l=a?a.nextElementSibling:null;l&&"P"===l.tagName&&(l.style.display="none"),o&&(o.style.display="none"),n&&(n.style.display="none"),i&&(i.style.display="none"),a&&(a.style.display="none"),r&&(r.style.display="none"),s&&(s.style.display="none");var c=r?r.nextElementSibling:null;c&&"SCRIPT"===c.tagName&&(c.style.display="none");var d=document.getElementById("signInOnlyHeader");d||((d=document.createElement("div")).id="signInOnlyHeader",d.innerHTML='
    🔐

    Welcome Back!

    Sign in to your account

    ',t.insertBefore(d,t.firstChild));var u=document.getElementById("emailSignInSection");if(u){var p=u.querySelector("p");p&&(p.innerHTML='Sign in with your email:')}var m=document.getElementById("signInOnlyNewHere");if(!m){(m=document.createElement("div")).id="signInOnlyNewHere",m.innerHTML='
    ';var h=t.querySelector(".skip");h?t.insertBefore(m,h):t.appendChild(m)}}},50))}},window._restoreSignUpForm=function(){var e=document.getElementById("usernameModal");if(e){var t=e.querySelector(".username-box");if(t){var o=document.getElementById("signInOnlyHeader");o&&o.remove();var n=document.getElementById("signInOnlyNewHere");n&&n.remove();var i=t.querySelector("h2"),a=t.querySelector("p"),r=document.getElementById("usernameInput"),s=document.getElementById("emailInput"),l=document.getElementById("giveawaySection"),c=t.querySelector('button[onclick="submitUsername()"]'),d=s?s.nextElementSibling:null;d&&"P"===d.tagName&&(d.style.display=""),i&&(i.style.display=""),a&&(a.style.display=""),r&&(r.style.display=""),s&&(s.style.display=""),l&&(l.style.display=""),c&&(c.style.display="");var u=document.getElementById("emailSignInSection");if(u){var p=u.querySelector("p");p&&(p.innerHTML="Already have an account? Sign in with your email:")}}}};let settingsTab="account";function shortcutRow(e,t){return'
    '+e+'
    '+t+"
    "}function showSettingsPage(e){try{settingsTab=e||"account";const Ye=document.getElementById("usernameModal"),Xe=Ye.querySelector(".username-box");if(!Ye)return void("function"==typeof showToast&&showToast("Error: modal not found"));if(!Xe)return void("function"==typeof showToast&&showToast("Error: username-box not found"));const Ke=void 0!==auth&&auth?auth.currentUser:null;if(!Ke)return void Ye.classList.add("open");const $e=getLevel(currentUser&¤tUser.points||0);let Ze="";if(Ze+='
    ',["account","scholar","sats","prefs","security","data"].forEach(e=>{const t=settingsTab===e;Ze+=""}),Ze+="
    ","account"===settingsTab){var t=Ke.isAnonymous,o=getUserDisplayEmoji($e),n=currentUser&¤tUser.profilePic||"",i=n?'':'
    '+o+"
    ";Ze+='
    '+i+'
    '+(currentUser&¤tUser.username||"Bitcoiner")+'
    '+$e.name+" · "+(currentUser&¤tUser.points||0).toLocaleString()+" XP"+(currentUser&¤tUser.faction?" · "+("cyber_hornets"===currentUser.faction?"🐝 Cyber Hornets":"🦡 Honey Badgers"):"")+"
    ";var a=currentUser&¤tUser.country||"";Ze+='
    🌍 Country
    Optional · Shown on your public profile
    ';var r=currentUser&¤tUser.faction||"";Ze+='
    ⚔️ Faction
    Choose your allegiance! New faction features coming soon — no competitive advantage to either choice.
    🐝
    Cyber Hornets
    The swarm protects the network
    '+("cyber_hornets"===r?'
    ✓ Joined
    ':"")+'
    🦡
    Honey Badgers
    Honey badger don\'t care
    '+("honey_badgers"===r?'
    ✓ Joined
    ':"")+"
    ",Ze+='
    📷 Profile Picture
    '+(n?'':'
    👤
    ')+'
    "+(n?' ':"")+'
    Square image recommended · Max 2MB
    ';var s="",l='
    Account Details
    ';Ke.email&&(l+='
    Email'+Ke.email+"
    "),Ke.displayName&&(l+='
    Name'+Ke.displayName+"
    ");let et="Anonymous";if(Ke.providerData&&Ke.providerData.length>0){const tt=Ke.providerData[0].providerId;"google.com"===tt?et="Google":"twitter.com"===tt?et="Twitter/X":"github.com"===tt?et="GitHub":"facebook.com"===tt?et="Facebook":"password"===tt&&(et="Email")}if(l+='
    Sign-in method'+et+"
    ",currentUser&¤tUser.created&&(l+='
    Member since'+(currentUser.created.toDate?currentUser.created.toDate().toLocaleDateString():new Date(currentUser.created).toLocaleDateString())+"
    "),s+=l+="
    ",!t){var c=currentUser&¤tUser.displayBadge||"",d=[];void 0!==earnedBadges&&void 0!==BADGE_DEFS&&BADGE_DEFS.forEach(function(e){earnedBadges.has(e.id)&&d.push({id:e.id,emoji:e.emoji,name:e.name})});var u=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]");if(void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){-1!==u.indexOf(e.id)&&d.push({id:e.id,emoji:e.hidden&&e.revealEmoji||e.emoji,name:e.hidden&&e.revealName||e.name})}),d.length>0){var p=$e.emoji+" Rank (default)";if(c){var m=d.find(function(e){return e.id===c});m&&(p=m.emoji+" "+m.name)}var h='
    Choose a badge to show next to your name instead of your rank emoji.
    ';h+='
    '+$e.emoji+'
    '+$e.name+' (Default)
    Your current rank emoji
    '+(c?"":'')+"
    ";for(var g=0;g'+f.emoji+'
    '+f.name+"
    "+(y?'':"")+"
    "}s+="
    🏅 Display Badge
    "+p+'
    ")+"
    "}}s+='
    ✏️ Change Username
    Current username: '+(currentUser&¤tUser.username||"")+'
    ',s+='';var b=currentUser&¤tUser.bio||"",v=[],w=[];[{k:"website",e:"🌐",l:"Website",p:"https://yoursite.com",m:100,t:"url"},{k:"twitter",e:"𝕏",l:"Twitter/X",p:"@yourusername",m:30},{k:"nostr",e:"🟣",l:"Nostr",p:"npub... or NIP-05",m:80},{k:"instagram",e:"📸",l:"Instagram",p:"@yourusername",m:30},{k:"tiktok",e:"🎵",l:"TikTok",p:"@yourusername",m:30},{k:"github",e:"🐙",l:"GitHub",p:"yourusername",m:40},{k:"contactEmail",e:"📧",l:"Email",p:"you@example.com",m:80,t:"email",note:"public"},{k:"lightning",e:"⚡",l:"Lightning",p:"you@walletofsatoshi.com",m:80}].forEach(function(e){currentUser&¤tUser[e.k]?v.push(e):w.push(e)}),Ze+='
    📝 Public Profile
    Visible when someone clicks your name on the leaderboard
    ",Ze+='
    🔗 Links & Socials
    ',Ze+='
    ',v.forEach(function(e){var t=currentUser&¤tUser[e.k]||"";Ze+=''}),Ze+="
    ",w.length>0&&(Ze+='
    "),Ze+='
    ',currentUser&&(currentUser.lightning||currentUser.lightningAddress)||(Ze+='
    Connect a Lightning Wallet
    Tip other users and receive tips from the community!
    '),Ze+="",Ze+='",Ze+=''}else if("_artist_removed"===settingsTab){var x=currentUser&¤tUser.artistProfile||{};void 0!==db&&auth&&auth.currentUser&&auth.currentUser.uid,Ze+='
    🎸
    Artist Profile
    Set up your artist presence on Bitcoin Beats
    ',Ze+='
    🎤 Stage Name
    Shows on your tracks and artist page. Leave blank to use your username.
    ',Ze+='
    📝 Artist Bio
    Music-specific bio. Your general bio is in Account tab.
    ',Ze+='
    🎵 Genres
    Comma-separated. Shows as tags on your artist page.
    ',Ze+='
    🔗 Music Links
    🌊
    🟢
    🎵
    📺
    🔗
    ',Ze+='
    Lightning Tips
    '+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?"✅ Lightning Address set: "+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ No Lightning Address set. Go to Account tab or set up in ⚡ Wallet to receive tips!")+"
    ",Ze+='',Ze+="'}else if("scholar"===settingsTab){Ze+='
    🎓
    Bitcoin Scholar

    Master Bitcoin through quests, certifications, and flashcards.

    ',Ze+='
    Channel Quests

    Test your knowledge on any Bitcoin topic with guided quiz questions.

    ';var k="true"===localStorage.getItem("btc_scholar_prop_passed");Ze+='
    '+(k?"✅":"📜")+'
    Bitcoin Scholar Certification

    25 questions on the economic properties and scarcity of Bitcoin. 80% to pass. One attempt per day.

    ";var B="true"===localStorage.getItem("btc_scholar_tech_passed");Ze+='
    '+(B?"✅":"🛠️")+'
    Bitcoin Protocol Expert

    25 questions on highly technical topics: BIPs, Script, SegWit, Taproot, and Networking.

    ",Ze+="

    Prepare for quests and exams with interactive flashcards.

    ",[{name:"Bitcoin Basics",emoji:"₿"},{name:"Security & Storage",emoji:"🔑"},{name:"Lightning Network",emoji:"⚡"},{name:"Mining & Energy",emoji:"⛏️"},{name:"Economics & Money",emoji:"💰"},{name:"History & Culture",emoji:"📜"},{name:"Privacy & Sovereignty",emoji:"🕵️"},{name:"Nodes & P2P",emoji:"📡"},{name:"Wallets & Tools",emoji:"💼"},{name:"Common Myths",emoji:"🚫"},{name:"Austrian Economics",emoji:"🇦🇹"},{name:"Cypherpunk History",emoji:"🔐"},{name:"Bitcoin Governance",emoji:"🏛️"},{name:"Satoshi Nakamoto",emoji:"🦸"},{name:"Global Impact",emoji:"🌍"},{name:"El Salvador & Adoption",emoji:"🇸🇻"},{name:"Technical Deep Dives",emoji:"🔬"}].forEach(function(e){Ze+=""}),Ze+="
    ",Ze+="",Ze+='"}else if("signal"===settingsTab){var _;Ze+='
    📡
    The Weekly Signal

    Curated Bitcoin insights and site updates.

    ',S=null===(_=localStorage.getItem("btc_ticker_enabled"))?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===_,Ze+="
    📊Live Ticker on Home
    ",Ze+='
    📡 Live Signals
    ',Ze+='
    ',Ze+="",Ze+='
    📚 Featured Deep Dives
    ',[{date:"Feb 26, 2026",title:"Why Proof of Stake is just Fiat 2.0",snippet:"Most cryptos claim to be better than Bitcoin because they use less energy. But Gigi explains why energy IS the point — PoW converts real-world resources into unforgeable security.",channel:"pow-vs-pos"},{date:"Feb 19, 2026",title:"The Great Definancialization",snippet:"Parker Lewis breaks down why we don't need thousands of stocks, bonds, and derivatives if we have one form of hard money that can't be debased.",channel:"problems-of-money"},{date:"Feb 12, 2026",title:"The 21 Million Cap is Inviolate",snippet:"Why even if every miner in the world wanted to change the supply, they couldn't. The users run the rules.",channel:"scarce"},{date:"Feb 5, 2026",title:"Not Your Keys, Not Your Coins",snippet:"After another exchange collapse, the importance of self-custody has never been clearer. Here's how to take control.",channel:"self-custody"},{date:"Jan 29, 2026",title:"The Halving: Scarcity You Can Verify",snippet:"Every 210,000 blocks, the supply issuance gets cut in half. No vote. No committee. Just code.",channel:"difficulty-adjustment"}].forEach(function(e){Ze+='
    '+e.date.toUpperCase()+'
    '+e.title+'
    '+e.snippet+"
    '}),setTimeout(function(){var e=document.getElementById("signalLiveNews");e&&fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=(e.snippet||"").replace(/<[^>]+>/g,""),a=e.link||"";n+='
    SIGNAL #'+(t+1)+''+(e.date||"").toUpperCase()+'
    '+o+"
    "+(i?'
    '+i+"
    ":"")+(a?'
    Read full article →
    ':"")+"
    "}),o.innerHTML=n;var i=function(){var t=document.getElementById("signalArrowL"),o=document.getElementById("signalArrowR");t&&o&&(e.scrollWidth>e.clientWidth+10?(t.style.display=e.scrollLeft>10?"flex":"none",o.style.display=e.scrollLeft+e.clientWidth✅ You\'re subscribed to The Signal!':'
    📧
    Get The Signal via Email

    Weekly curated Bitcoin insights. No spam, pure signal.

    '}else if("tickets"===settingsTab){const ot=!Ke||Ke.isAnonymous;ot?Ze+='
    Orange Tickets
    Sign in with Google, Twitter, or GitHub to start earning Orange Tickets and get your referral link!
    ':(Ze+="function"==typeof renderTicketsSection?renderTicketsSection():"",Ze+="function"==typeof renderReferralSection?renderReferralSection():"",Ze+='
    How to Earn Tickets
    📅 Daily Login: +1 ticket just for visiting.
    🎡 Spin the Wheel: Spin daily for bonus tickets!
    👥 Referrals: Earn 50 tickets per friend who signs up and reaches Maxi rank (2,140+ pts). Verified automatically.
    🏅 Badges: Unlock at 25 🐟, 50 🦈, and 100 🐋 tickets.
    ⭐ Bonus: Each ticket = +5 XP towards your rank.
    🏆 Giveaways: More tickets = higher chance of winning sats!
    '),ot||"function"!=typeof loadReferralStatsUI||setTimeout(loadReferralStatsUI,100)}else if("sats"===settingsTab){var I=window._satsSubTab||"claim",C=(t=Ke.isAnonymous,currentUser&¤tUser.points||0),E=currentUser&¤tUser.pointsClaimed||0,A=currentUser&¤tUser.pointsDonated||0,z=C-E,M=currentUser&¤tUser.satsWithdrawn||0,P=Math.floor(Math.max(0,z)/10),L="function"==typeof getSatCap?getSatCap():1e4,U=Math.max(0,L-M),q=Math.min(P,500,U),N=currentUser&¤tUser.lastSatsClaim||null,H=N?new Date(N.seconds?1e3*N.seconds:N).getTime()+864e5:0,D=Date.now(),O=N&&Dj&&(j=F.length)}catch(nt){}var G=Ke.metadata&&Ke.metadata.creationTime?new Date(Ke.metadata.creationTime):null,V=G?Math.floor((D-G.getTime())/864e5):0,Q=Ke.email&&Ke.emailVerified,J=!t&&Q&&V>=7&&j>=10,Y=P>=100;if(Ze+='
    ',Ze+='',Ze+='',Ze+="
    ","donate"!==I){Ze+='
    ',Ze+='
    ',Ze+='
    Claim Real Sats
    ',Ze+='
    Earn XP → Convert to real Bitcoin over Lightning
    ',Ze+="
    ",Ze+='
    ',Ze+='
    Your Balance
    ',Ze+='
    ⚡ '+P.toLocaleString()+" claimable sats
    ",Ze+='
    '+z.toLocaleString()+" unclaimed XP of "+C.toLocaleString()+" total
    ",Ze+='
    Lifetime withdrawn: '+M.toLocaleString()+" / 10,000 sats
    ",Ze+="
    ",Ze+=!t&&J&&Y&&!O&&q>=100?'":O?'
    ⏳ Next claim in '+W+"
    ":!Y&&J?'
    Need '+(100-P)+" more sats ("+10*(100-P)+" XP) to reach minimum claim
    ":'
    Complete requirements below to claim
    ',Ze+='
    ',Ze+='
    📋 Requirements
    ',[{met:!t,label:"Signed in (not anonymous)",detail:t?"Sign in with email, Google, etc.":"✓ Signed in"},{met:Q,label:"Email verified",detail:Q?"✓ "+Ke.email:"Link & verify your email in Account tab"},{met:V>=7,label:"Account age ≥ 7 days",detail:V>=7?"✓ "+V+" days old":V+"/7 days — "+(7-V)+" more to go"},{met:j>=10,label:"Read ≥ 10 topics",detail:j>=10?"✓ "+j+" topics read":j+"/10 topics — read "+(10-j)+" more"},{met:Y,label:"Minimum 100 sats (1,000 pts)",detail:Y?"✓ "+P+" sats available":P+"/100 sats — earn "+10*(100-P)+" more XP"}].forEach(function(e){Ze+='
    ',Ze+=''+(e.met?"✅":"⬜")+"",Ze+='
    '+e.label+"
    ",Ze+='
    '+e.detail+"
    "}),Ze+="
    ",Ze+='
    ',Ze+='
    ⚡ How It Works
    ',Ze+='
    ',Ze+="• 1,000 XP = 100 sats — earn XP by reading, quests, and daily visits
    ",Ze+="• Min claim: 100 sats (1,000 XP)
    ",Ze+="• Max claim: 500 sats/day
    ",Ze+="• 1 claim per 24 hours
    ",Ze+="• Lifetime max: 10,000 sats per account
    ",Ze+="• Daily XP cap: 500 XP (50 sats worth) to prevent abuse
    ",Ze+="• Unclaimed sats roll over — no expiration
    ",Ze+="• Payouts via Lightning Network ⚡
    ",Ze+="
    ",Ze+='
    ',Ze+="💚 Zero fees for you! We pay all Lightning network fees so you receive the full amount you claim. You earned it!",Ze+="
    ",Ze+='
    ',Ze+="",Ze+='
    ",Ze+='
    ',Ze+='
    📜 Withdrawal History
    ',Ze+='
    Loading...
    ',Ze+="
    ";var K=currentUser&&(currentUser.lightning||currentUser.lightningAddress)||"";Ze+='
    ',Ze+='
    Lightning Address
    For receiving tips from other users
    ',K&&(Ze+='
    '+escapeHtml(K)+"
    "),Ze+='
    ',Ze+='
    ',K||(Ze+='
    💡 Get one from Wallet of Satoshi, Alby, Coinos, or Strike.
    '),Ze+="
    "}else{var $=Math.max(0,C-E-A);r=currentUser&¤tUser.faction||"",Ze+='
    ',Ze+='
    ❤️
    ',Ze+='
    Donate XP for Charity
    ',Ze+='
    1,000 XP = 1,000 sats donated — 10× more impact than claiming
    ',Ze+="
    ",Ze+='
    ',Ze+='
    Available to Donate
    ',Ze+='
    ❤️ '+$.toLocaleString()+" XP
    ",Ze+='
    '+C.toLocaleString()+" total − "+E.toLocaleString()+" claimed − "+A.toLocaleString()+" donated
    ",Ze+="
    ",t?Ze+='
    🔐 Sign in to donate XP
    ':r?(Ze+='
    ',[5,10,25,50,100].forEach(function(e){var t=Math.floor($*e/100);Ze+='"}),Ze+="
    ",Ze+='
    ',Ze+='',Ze+="
    ",Ze+='
    ',Ze+='',Ze+="
    ",Ze+='',A>0&&(Ze+='
    '+A.toLocaleString()+" XP already donated — thank you! ❤️
    ")):(Ze+='
    ',Ze+='
    ⚔️
    ',Ze+='
    Choose Your Faction First
    ',Ze+='
    Your faction’s donation total is tracked for the community leaderboard.
    ',Ze+='',Ze+="
    "),Ze+='
    ',Ze+='',Ze+='',Ze+="
    "}}else if("prefs"===settingsTab){const it="light"!==document.body.getAttribute("data-theme"),at="true"===localStorage.getItem("btc_theme_oled"),rt=localStorage.getItem("btc_font_size")||"medium";Ze+="
    🎨 Appearance
    Theme
    Font Size
    ',["small","medium","large"].forEach(function(e){var t=rt===e,o=e.charAt(0).toUpperCase()+e.slice(1);Ze+=""}),Ze+="
    ",Ze+='
    🌐 Language
    Translate the site to your preferred language
    ',setTimeout(function(){const e=document.getElementById("langSelect"),t=localStorage.getItem("btc_lang")||"";e&&(e.value=t)},50);const st="undefined"==typeof audioEnabled||audioEnabled,lt="undefined"!=typeof audioVolume?audioVolume:.5;Ze+='
    🔊 Sound
    Sound Effects
    Volume
    ',Ze+="",Ze+='"}else Ze+=""}var Fe=localStorage.getItem("btc_nacho_nickname")||"Nacho";if(Ze+='
    🏷️ Name Your Buck
    Currently: '+escapeHtml(Fe)+'
    ',"function"==typeof getNachoStoryProgress){var Ge=getNachoStoryProgress(),Ve=Ge>=10,Qe=escapeHtml(Fe);Ze+='
    📖
    '+Qe+'\'s Story
    '+(Ve?"✅ Complete!":"A new chapter unlocks every day!")+'
    '+Ge+'/10
    "}"function"==typeof renderNachoClosetUI&&(void 0===window._expanded_closet&&(window._expanded_closet=!1),window._pendingClosetScroll&&(window._expanded_closet=!0),Ze+='
    👗 '+escapeHtml(Fe)+'\'s Closet
    '+(window._expanded_closet?"▾":"▸")+"
    ",window._expanded_closet&&(Ze+='
    '),Ze+="
    "),"function"==typeof renderStickerBook&&(Ze+='
    🎨 Sticker Book
    '+(window._expanded_stickers?"▾":"▸")+"
    ",window._expanded_stickers&&(Ze+='
    '+renderStickerBook()+"
    "),Ze+="
    "),Ze+='
    🔒 Privacy
    We do not sell, share, or monetize your data. Ever.
    The only data we store is your username, points, and progress — just enough to power your experience. No tracking, no ads, no third-party analytics. Your data is yours.
    ',Ze+="",Ze+='",Ze+="",Ze+='"}if(Ze+='Close',Xe.innerHTML=Ze,Ye.classList.add("open"),"sats"===settingsTab&&"function"==typeof loadSatsHistory&&setTimeout(loadSatsHistory,100),"sats"===settingsTab&&(window._toggleSatsCharityNote=function(){var e=document.getElementById("satsCharityNote"),t=document.getElementById("satsCharityNoteArrow");if(e){var o="none"!==e.style.display;e.style.display=o?"none":"block",t&&(t.textContent=o?"▼":"▲")}},window._satsCharitySetAmt=function(e){var t=document.getElementById("satsCharityAmtInput");t&&(t.value=e>0?e:"")},window._satsCharitySubmit=function(){if("undefined"!=typeof firebase&&firebase.functions){var e=document.getElementById("satsCharityAmtInput"),t=parseInt(e?e.value:"")||0,o=void 0!==currentUser&¤tUser?Math.max(0,(currentUser.points||0)-(currentUser.pointsClaimed||0)-(currentUser.pointsDonated||0)):0;if(!t||t<1)"function"==typeof showToast&&showToast("Enter a valid amount");else if(t>o)"function"==typeof showToast&&showToast("Not enough available XP ("+o.toLocaleString()+" available)");else{var n=!!document.getElementById("satsCharityAnonToggle")&&document.getElementById("satsCharityAnonToggle").checked,i=document.querySelector('[onclick="window._satsCharitySubmit()"]');i&&(i.disabled=!0,i.textContent="Donating..."),firebase.functions().httpsCallable("donatePoints")({amount:t,anonymous:n}).then(function(e){void 0!==currentUser&¤tUser&&(currentUser.pointsDonated=(currentUser.pointsDonated||0)+t,e.data&&e.data.bonusPts&&(currentUser.points=(currentUser.points||0)+e.data.bonusPts));var o=e.data&&e.data.newBadges&&e.data.newBadges.length>0?" +"+e.data.newBadges.length+" badge"+(e.data.newBadges.length>1?"s":"")+" unlocked!":"";"function"==typeof showToast&&showToast("❤️ Thank you! "+t.toLocaleString()+" XP donated ("+t.toLocaleString()+" sats pledged to charity)."+o,5e3),"function"==typeof window._charityThankYou&&window._charityThankYou(t,e.data&&e.data.newBadges||[],e.data&&e.data.bonusPts||0);var n=e.data&&e.data.newBadges||[];if(n.length>0&&"function"==typeof window.contributeSatoshiFavor){var i={donor_100:"🤷 Giving Pleb",donor_500:"💛 Stack Sharer",donor_1000:"🧡 Community Builder",donor_5000:"❤️ Archive Patron",donor_10000:"🔥 Sats Saint",donor_25000:"⚡ Lightning Philanthropist",donor_50000:"🏆 Satoshi's Steward",donor_100000:"👑 Legend of the Archive"};n.forEach(function(e){i[e]&&window.contributeSatoshiFavor("badge_earned",i[e]).catch(function(){})})}void 0!==window._charityStatsLoaded&&(window._charityStatsLoaded=!1),showSettingsPage("sats")}).catch(function(e){i&&(i.disabled=!1,i.textContent="❤️ Donate XP for Charity"),"function"==typeof showToast&&showToast("❌ "+(e.message||"Donation failed. Try again."),4e3)})}}}),"data"===settingsTab&&"function"==typeof loadReferralStatsUI&&Ke&&!Ke.isAnonymous&&setTimeout(loadReferralStatsUI,100),"data"===settingsTab&&"function"==typeof renderNachoClosetUI){var Je=document.getElementById("nachoClosetContainer");Je&&(renderNachoClosetUI(Je),window._pendingClosetScroll&&setTimeout(function(){Je.scrollIntoView({behavior:"smooth",block:"center"}),window._pendingClosetScroll=!1},300))}}catch(_t){"function"==typeof showToast&&showToast("Settings page error: "+_t.message),console.error("showSettingsPage error:",_t)}}function changeLanguage(e){const t=document.getElementById("langStatus");if(!e){const e=document.querySelector(".goog-te-banner-frame");e&&e.remove();var o=document.querySelector("iframe.goog-te-banner-frame");o&&o.remove();var n=document.querySelector(".skiptranslate");return n&&n.remove(),document.body.style.top="",document.body.style.position="",document.documentElement.style.overflow="",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=."+location.hostname,localStorage.setItem("btc_lang",""),t&&(t.innerHTML='✅ Switched to English'),document.documentElement.classList.remove("translated-ltr","translated-rtl"),document.querySelectorAll('font[style*="vertical-align: inherit"]').forEach(function(e){var t=e.parentNode;t&&t.replaceChild(document.createTextNode(e.textContent),e)}),void setTimeout(function(){showSettingsPage("prefs")},200)}if(localStorage.setItem("btc_lang",e),document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname,t&&(t.innerHTML='Translating...'),document.getElementById("gtranslate"))triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!');else{const o=document.createElement("script");o.id="gtranslate",o.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(o),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget"),setTimeout(()=>{triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!')},1500)};const n=document.createElement("div");n.id="gtranslateWidget",n.style.display="none",document.body.appendChild(n)}}function triggerGoogleTranslate(e){const t=document.querySelector(".goog-te-combo");t&&(t.value=e,t.dispatchEvent(new Event("change")))}function setFontSize(e){localStorage.setItem("btc_font_size",e);const t="small"===e?"14px":"medium"===e?"16px":"18px";document.documentElement.style.fontSize=t,showSettingsPage("prefs")}async function saveProfile(){var e=document.getElementById("profileStatus");if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in with Google, Facebook, Twitter, or email to save your profile!"),e&&(e.innerHTML='🔒 Create a free account to save your profile'),void("function"==typeof showUsernamePrompt&&setTimeout(showUsernamePrompt,1500));var t=auth.currentUser.uid,o=document.getElementById("profileBio")?document.getElementById("profileBio").value.trim():"",n=document.getElementById("countryInput"),i=n?n.value.trim().substring(0,60):"";if(i&&window._countryList&&-1===window._countryList.indexOf(i))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void n.focus();var a={bio:o,country:i};["website","twitter","nostr","instagram","tiktok","github","contactEmail","lightning"].forEach(function(e){var t,o=document.getElementById("profile_"+e);if(o){var n=o.value.trim();"lightning"===e?(n=n.replace(/[\\'"<>]/g,""))&&!n.match(/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)&&(n=""):n="contactEmail"===e||"nostr"===e?n.replace(/[\\'"<>]/g,""):(t=n)?(t=t.trim(),/^(javascript|data|vbscript|blob):/i.test(t)?"":t):"",a[e]=n}else currentUser&&void 0!==currentUser[e]&&(document.querySelector('.pf-link-row[data-key="'+e+'"]')||(a[e]=""))});try{e&&(e.innerHTML='Saving...'),await db.collection("users").doc(t).update(a),Object.assign(currentUser,a),e&&(e.innerHTML='✅ Profile saved!'),"function"==typeof showToast&&showToast("✅ Profile saved successfully!"),setTimeout(function(){e&&(e.innerHTML=""),showSettingsPage("account")},1500)}catch(t){console.error("Error saving profile:",t),e&&(e.innerHTML='❌ Error saving'),"function"==typeof showToast&&showToast("❌ Error saving profile")}}function _pasteFieldFallback(e){e.focus(),e.value="",e.setSelectionRange(0,0);try{document.execCommand("paste")}catch(e){}"function"==typeof showToast&&showToast("📋 Field ready — tap and hold, then tap Paste",5e3)}function clearUserLocalStorage(){for(var e=["btc_theme_oled","btc_font_size","btc_volume","btc_lang","btc_haptic","btc_soundscape","btc_ticker_enabled","btc_ios_a2hs_dismissed","btc_pwa_dismissed","btc_swipe_hint_shown","btc_last_auth_uid","btc_signin_email","btc_pending_email","btc_pending_username","btc_pending_giveaway"],t=[],o=0;o
    Scan this QR code with your authenticator app:
    Or enter this key manually: '+(t.data.secret||"")+'
    ')}}catch(e){showToast("Error setting up authenticator: "+(e.message||"try again"))}}async function verifyTotpSetup(){var e=document.getElementById("totpVerifyCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpVerify");await t({code:e.value.trim()}),showToast("✅ Authenticator app enabled!"),showSettingsPage("security")}catch(e){showToast("Invalid code. Try again.")}else showToast("Enter a 6-digit code")}async function disableTotp(){var e=document.getElementById("totpDisableCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpDisable");await t({code:e.value.trim()}),showToast("Authenticator app disabled"),showSettingsPage("security")}catch(e){showToast("Invalid code")}else showToast("Enter your current code")}function clearUserData(){["btc_visited_channels","btc_favs","btc_hidden_badges","btc_asked_questions","btc_scholar_passed","btc_scholar_attempt_date","btc_badges","btc_last_channel","btc_signin_email","btc_nacho_equipped","btc_nacho_items_notified","btc_points","btc_total_visits","btc_streak","btc_last_visit"].forEach(function(e){localStorage.removeItem(e)}),currentUser=null}function showSignInPrompt(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous?showSettings():showUsernamePrompt()}function _generateDeviceFingerprint(){try{var e=document.createElement("canvas"),t=e.getContext("2d");t.textBaseline="top",t.font="14px Arial",t.fillText("Bitcoin Education 🦌",2,2);for(var o=e.toDataURL(),n=[navigator.userAgent||"",screen.width+"x"+screen.height,screen.colorDepth,(new Date).getTimezoneOffset(),navigator.language||"",navigator.hardwareConcurrency||0,(navigator.deviceMemory||0).toString(),void 0!==window.ontouchstart?"touch":"no-touch",o.substring(o.length-50)].join("|"),i=0,a=0;a{const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.frequency.value=o,i.type=n<3?"sine":"triangle",a.gain.setValueAtTime(.12*e,t.currentTime+.1*n),a.gain.exponentialRampToValueAtTime(.001,t.currentTime+.1*n+.6),i.start(t.currentTime+.1*n),i.stop(t.currentTime+.1*n+.6)})}catch(e){}"function"==typeof launchConfetti&&launchConfetti();const o=document.createElement("div");o.id="levelUpModal",o.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;animation:fadeIn 0.4s;",o.innerHTML='
    '+e.emoji+'
    ⬆️ LEVEL UP!
    '+e.name+'
    You\'ve reached '+e.min.toLocaleString()+'+ XP!
    '+getLevelFlavor(e.name)+'
    ',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function getLevelFlavor(e){return{Curious:"You're starting to see what all the fuss is about.",Pleb:"Welcome to the pleb life. You're one of us now.","Pleb II":"170 — the block height when Satoshi mined the first 1,000 blocks. You're going deeper.","Pleb III":"256 — the number of bits in a private key. You're becoming unbreakable.",Stacker:"Stacking sats and stacking knowledge. Impressive.","Stacker II":"Double stacking! 1913 — the year the Fed was born. You know why that matters.","Stacker III":"Triple stack mode. 2016 — the year the halving changed everything.",Maxi:"2140 — when the last sat is mined. There is no second best. You know it.","Maxi II":"6102 — Executive Order 6102 banned gold. They can't ban Bitcoin. Double the conviction.","Maxi III":"8888 — triple maxi. The signal only gets stronger.","Papa John":"10,000 BTC for two pizzas. Never forget. 🍕 You've earned your slice.","Full Node":"18,333 — port 18333. You verify everything yourself. Don't trust, verify.",Whale:"50,000 strong. You move markets. Unstoppable, just like Bitcoin.",Sovereign:"Self-sovereign. 100K channels deep. No permission needed. You ARE the bank.",Cypherpunk:"133,337 — leet beyond leet. Privacy is a right, not a privilege. Code is law.",Satoshi:"The pinnacle. You've achieved legendary status."}[e]||"You're leveling up!"}window.showSettings=function(){if(void 0===auth||!auth)return"function"==typeof showToast&&showToast("⚠️ Firebase not ready. Retrying..."),"function"==typeof initRanking&&initRanking(),void setTimeout(function(){void 0!==auth&&auth?showUsernamePrompt():"function"==typeof showToast&&showToast("❌ Could not load. Please refresh the page.")},2e3);showUsernamePrompt()},window._countryList=["Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burundi","Cabo Verde","Cambodia","Cameroon","Canada","Central African Republic","Chad","Chile","China","Colombia","Comoros","Congo","Costa Rica","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Eswatini","Ethiopia","Fiji","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Grenada","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Ivory Coast","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","North Korea","North Macedonia","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","Sudan","Suriname","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor-Leste","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Yemen","Zambia","Zimbabwe"],window._filterCountryList=function(){var e=document.getElementById("countryInput"),t=document.getElementById("countryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
    '+l+"
    "}n.length>8&&(i+='
    +'+(n.length-8)+" more — keep typing
    "),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectCountry=function(e){var t=document.getElementById("countryInput"),o=document.getElementById("countryDropdown");t&&(t.value=e),o&&(o.style.display="none")},window._selectFaction=async function(e){try{var t=auth?auth.currentUser:null;if(!t)return void("function"==typeof showToast&&showToast("Sign in to choose a faction"));if(t.isAnonymous)return void("function"==typeof showToast&&showToast("Create an account to choose a faction"));var o=currentUser&¤tUser.faction||null,n=!o;await db.collection("users").doc(t.uid).update({faction:e}),currentUser&&(currentUser.faction=e),"function"==typeof showToast&&showToast("cyber_hornets"===e?"🐝 Welcome to the Cyber Hornets!":"🦡 Welcome to the Honey Badgers!"),showSettingsPage("account"),n&&"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("syncUserFactionPoints")({newFaction:e,previousFaction:o}).then(function(e){e.data&&e.data.pointsSynced>0&&"function"==typeof showToast&&showToast("⚡ "+e.data.pointsSynced+" past SF point"+(1!==e.data.pointsSynced?"s":"")+" credited to your faction!")}).catch(function(e){console.warn("[FACTION] syncUserFactionPoints failed:",e)})}catch(e){console.error("Faction select error:",e),"function"==typeof showToast&&showToast("Error saving faction")}},window._filterSignupCountry=function(){var e=document.getElementById("signupCountryInput"),t=document.getElementById("signupCountryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
    '+l+"
    "}n.length>8&&(i+='
    +'+(n.length-8)+" more — keep typing
    "),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectSignupCountry=function(e){var t=document.getElementById("signupCountryInput"),o=document.getElementById("signupCountryDropdown");t&&(t.value=e),o&&(o.style.display="none")},document.addEventListener("click",function(e){[["countryDropdown","countryAutocomplete"],["signupCountryDropdown","signupCountryAutocomplete"]].forEach(function(t){var o=document.getElementById(t[0]),n=document.getElementById(t[1]);o&&n&&!n.contains(e.target)&&(o.style.display="none")})}),function(){const e=localStorage.getItem("btc_lang");if(e){document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname;const t=document.createElement("script");t.id="gtranslate",t.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(t),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget")};const o=document.createElement("div");o.id="gtranslateWidget",o.style.display="none",document.body.appendChild(o)}}(),window.setSoundscape=function(e){localStorage.setItem("btc_soundscape",e),"function"==typeof updateSoundscape&&updateSoundscape(e),showSettingsPage("prefs")},window._removedProfileLinks={},window.profileLinkRemoved=function(e){window._removedProfileLinks[e]=!0},window.addProfileLink=function(e,t,o,n,i,a){var r=document.getElementById("profileLinksArea");if(r){var s=document.createElement("div");s.className="pf-link-row",s.setAttribute("data-key",e),s.style.cssText="display:flex;align-items:center;gap:12px;margin-bottom:12px;background:rgba(255,255,255,0.02);padding:10px;border-radius:12px;border:1px solid var(--border);",s.innerHTML=''+t+'',r.appendChild(s);var l=document.getElementById("addLinkMenu");l&&(l.style.display="none");var c=document.getElementById("profile_"+e);c&&c.focus()}},window.handleProfilePicUpload=function(e){var t=e.files&&e.files[0];if(t){var o=document.getElementById("pfpUploadStatus");if(t.type.match(/^image\//))if(t.size>2097152)o&&(o.innerHTML='❌ Image too large (max 2MB)');else{o&&(o.innerHTML='Processing...');var n=new FileReader;n.onload=function(e){var t=new Image;t.onload=function(){var e=128,n=document.createElement("canvas");n.width=e,n.height=e;var i,a,r=n.getContext("2d"),s=Math.min(t.width,t.height);i=(t.width-s)/2,a=(t.height-s)/2,r.drawImage(t,i,a,s,s,0,0,e,e);var l=n.toDataURL("image/jpeg",.8);auth&&auth.currentUser?db.collection("users").doc(auth.currentUser.uid).update({profilePic:l}).then(function(){currentUser&&(currentUser.profilePic=l),window._lbCache=null,o&&(o.innerHTML='✅ Profile picture saved!'),"function"==typeof showToast&&showToast("📷 Profile picture updated!"),setTimeout(function(){showSettingsPage("account")},1e3)}).catch(function(e){o&&(o.innerHTML='❌ Save failed: '+e.message+"")}):o&&(o.innerHTML='❌ Not signed in')},t.onerror=function(){o&&(o.innerHTML='❌ Could not load image')},t.src=e.target.result},n.readAsDataURL(t)}else o&&(o.innerHTML='❌ Please select an image file')}},window.removeProfilePic=function(){auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({profilePic:""}).then(function(){currentUser&&(currentUser.profilePic=""),window._lbCache=null,"function"==typeof showToast&&showToast("📷 Profile picture removed"),showSettingsPage("account")}).catch(function(){})},window.showArtistProfileModal=function(){if(auth&&auth.currentUser){var e=document.getElementById("artistProfileModal");e&&e.remove();var t=currentUser&¤tUser.artistProfile||{},o=auth.currentUser.uid,n=document.createElement("div");n.id="artistProfileModal",n.style.cssText="position:fixed;inset:0;z-index:500000;background:rgba(0,0,0,0.85);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",n.onclick=function(e){e.target===n&&n.remove()},n.innerHTML='
    🎸
    Artist Profile
    Set up your artist presence on Bitcoin Beats
    🎤 Stage Name
    Leave blank to use your username.
    📝 Artist Bio
    🎵 Genres
    🔗 Music Links
    🌐
    𝕏
    📸
    '+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?'✅ Lightning: '+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ Set a Lightning Address in Account or Wallet to receive tips!")+'
    ',document.body.appendChild(n)}else"function"==typeof showToast&&showToast("Sign in first")},window.saveArtistProfile=function(){if(auth&&auth.currentUser&&void 0!==db){var e=document.getElementById("artistSaveBtn");e&&(e.disabled=!0,e.textContent="Saving...");var t={stageName:(document.getElementById("artistStageName").value||"").trim().substring(0,40),bio:(document.getElementById("artistBio").value||"").trim().substring(0,500),genres:(document.getElementById("artistGenres").value||"").trim().substring(0,100),website:(document.getElementById("artistLinkWebsite").value||"").trim().substring(0,200),x:(document.getElementById("artistLinkX").value||"").trim().substring(0,50),instagram:(document.getElementById("artistLinkInstagram").value||"").trim().substring(0,50)};db.collection("users").doc(auth.currentUser.uid).update({artistProfile:t}).then(function(){currentUser&&(currentUser.artistProfile=t),"function"==typeof showToast&&showToast("🎸 Artist profile saved!"),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")}).catch(function(t){console.error("Artist profile save error:",t),"function"==typeof showToast&&showToast("Error saving: "+(t.message||"Unknown")),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")})}else"function"==typeof showToast&&showToast("Sign in to save your artist profile")},window.pasteToField=function(e){var t=document.getElementById(e);t&&(navigator.clipboard&&navigator.clipboard.readText?navigator.clipboard.readText().then(function(e){e?(t.value=e.trim(),t.style.borderColor="var(--accent)",t.dispatchEvent(new Event("input",{bubbles:!0})),"function"==typeof showToast&&showToast("📋 Pasted!")):_pasteFieldFallback(t)}).catch(function(){_pasteFieldFallback(t)}):_pasteFieldFallback(t))},window.loadSignalContent=function(){var e=document.getElementById("signalLiveNews");e&&!e.getAttribute("data-loaded")&&(e.setAttribute("data-loaded","1"),fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=e.link||"";n+='
    SIGNAL #'+(t+1)+'
    '+o+"
    "+(i?'
    Read →
    ':"")+"
    "}),o.innerHTML=n}}).catch(function(){}))},window.expandSignUpBanner=function(){sessionStorage.removeItem("btc_signin_banner_dismissed");var e=document.getElementById("mobileSignUpPill");e&&e.remove();var t=document.getElementById("userDisplay");t&&t.classList.remove("user-hidden"),"function"==typeof updateUserDisplay&&updateUserDisplay()},window.minimizeSignUpBanner=function(){sessionStorage.setItem("btc_signin_banner_dismissed","1");var e=document.getElementById("userDisplay");if(window.innerWidth<=900){e&&(e.classList.add("user-hidden"),e.style.display="none");var t=document.getElementById("mobileSignUpPill");t||((t=document.createElement("div")).id="mobileSignUpPill",document.body.appendChild(t)),t.style.cssText="position:fixed;bottom:70px;left:12px;z-index:200;display:flex;align-items:center;gap:6px;padding:8px 12px 8px 16px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",t.innerHTML='🔐 Sign Up',t.onclick=function(){window.expandSignUpBanner()}}else{if(!e)return;e.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:6px;padding:6px 14px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",e.innerHTML='🔐 Sign Up',e.onclick=function(){window.expandSignUpBanner()}}},window.clearUserLocalStorage=clearUserLocalStorage,window.hideUsernamePrompt=function(){const e=document.getElementById("usernameModal");if(e&&e.classList.remove("open"),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn(),"function"==typeof window._onSettingsClose){var t=window._onSettingsClose;window._onSettingsClose=null,setTimeout(t,150)}},window.submitUsername=async function(){try{var e=document.getElementById("usernameInput")||document.getElementById("newUsername");if(!e)return void console.error("[submitUsername] No input found");var t=e.value.trim();if(!t)return void showToast("Please enter a username!");if(t.length<2)return void showToast("Username must be at least 2 characters");if(t.length>20)return void showToast("Username must be 20 characters or less");if(containsProfanity(t))return void showToast("⚠️ That username is not allowed.");if(document.getElementById("usernameInput")){var o=document.getElementById("emailInput"),n=o?o.value.trim():"",i=document.getElementById("signupCountryInput"),a=i?i.value.trim().substring(0,60):"";if(a&&window._countryList&&-1===window._countryList.indexOf(a))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void i.focus();var r=document.getElementById("giveawayCheckbox"),s=document.getElementById("giveawayLnAddress"),l=r&&r.checked,c=s?s.value.trim():"";return l&&!c?(s&&(s.style.borderColor="#ef4444",s.focus()),void showToast("⚡ Enter a Lightning address to enter the giveaway, or uncheck the box to skip.")):n&&await sendMagicLink(n)?(localStorage.setItem("btc_pending_username",t),localStorage.setItem("btc_pending_email",n),l&&c&&localStorage.setItem("btc_pending_giveaway",c),showToast("📧 Check your email for a verification link!"),hideUsernamePrompt(),void await createUser(t,n,l,c,a)):void await createUser(t,n,l,c,a)}if(!currentUser||currentUser._isLocal)return void showToast("Sign in first to change username");var d=document.getElementById("usernameStatus");d&&(d.innerHTML="Saving...");try{await db.collection("users").doc(currentUser.uid).update({username:t,username_lower:t.toLowerCase()}),currentUser.username=t,updateAuthButton(),updateRankUI(),d&&(d.innerHTML="✅ Username updated!"),showToast("✅ Username changed to "+t)}catch(e){d&&(d.innerHTML="❌ Error saving"),showToast("Error updating username. Try again.")}}catch(e){console.error("[submitUsername] Uncaught error:",e),"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown error. Please try again."))}},window.exportUserData=function(){if(!currentUser)return;const e=JSON.stringify(currentUser,null,2),t=new Blob([e],{type:"application/json"}),o=URL.createObjectURL(t),n=document.createElement("a");n.href=o,n.download="bitcoin_archive_user_data.json",n.click()},(!localStorage.getItem("btc_last_price")||Date.now()-parseInt(localStorage.getItem("btc_price_ts")||"0")>3e5)&&fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd&&(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),localStorage.setItem("btc_price_ts",Date.now().toString()))}).catch(function(){}),(!localStorage.getItem("btc_last_height")||Date.now()-parseInt(localStorage.getItem("btc_height_ts")||"0")>3e5)&&fetch("https://mempool.space/api/blocks/tip/height").then(function(e){return e.text()}).then(function(e){var t=parseInt(e);t&&(localStorage.setItem("btc_last_height",t.toString()),localStorage.setItem("btc_height_ts",Date.now().toString()))}).catch(function(){}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",initRanking):initRanking(),void 0!==toggleLeaderboard&&(window.toggleLeaderboard=toggleLeaderboard),void 0!==showUsernamePrompt&&(window.showUsernamePrompt=showUsernamePrompt),window.setDisplayBadge=function(e){if(currentUser){currentUser.displayBadge=e||"",void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({displayBadge:e||""}).catch(function(){}),localStorage.setItem("btc_display_badge",e||""),updateRankUI(),updateAuthButton(),showToast(e?"🏅 Display badge updated!":"🏅 Using default rank emoji");var t=document.getElementById("badgePickerPanel");if(t){var o="function"==typeof getLevel?getLevel(currentUser&¤tUser.points||0):{emoji:"🌱",name:"Newbie"},n=[];void 0!==earnedBadges&&void 0!==BADGE_DEFS&&BADGE_DEFS.forEach(function(e){earnedBadges.has(e.id)&&n.push({id:e.id,emoji:e.emoji,name:e.name})});var i=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]");void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){-1!==i.indexOf(e.id)&&n.push({id:e.id,emoji:e.hidden&&e.revealEmoji||e.emoji,name:e.hidden&&e.revealName||e.name})});var a=e||"",r='
    Choose a badge to show next to your name instead of your rank emoji.
    ';r+='
    '+o.emoji+'
    '+o.name+' (Default)
    Your current rank emoji
    '+(a?"":'')+"
    ",n.forEach(function(e){var t=a===e.id;r+="
    '+e.emoji+'
    '+e.name+"
    "+(t?'':"")+"
    "}),r+="
    ",t.innerHTML=r,t.style.display="block"}}},"undefined"==typeof changeUsername&&(window.changeUsername=async function(e){if(!e){var t=document.getElementById("newUsername");t&&(e=t.value.trim())}if(e&&(e=e.replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim()),!e||e.length<2)showToast("Username must be at least 2 characters (ASCII only)");else if(e.length>20)showToast("Username max 20 characters");else if(containsProfanity(e))showToast("⚠️ That username is not allowed.");else if("function"!=typeof isCleanText||isCleanText(e)){if(localStorage.setItem("btc_username",e),currentUser&&(currentUser.username=e),updateAuthButton(),updateRankUI(),auth&&auth.currentUser&&db)try{await db.collection("users").doc(auth.currentUser.uid).update({username:e,username_lower:e.toLowerCase()})}catch(e){console.warn("Username Firestore save failed:",e)}showToast("✅ Username updated to "+e);var o=document.querySelector('[id="currentUsernameLabel"]');o||document.querySelectorAll("div, span").forEach(function(e){-1===e.textContent.indexOf("Current username:")||o||(o=e)}),o&&(o.innerHTML='Current username: '+("function"==typeof escapeHtml?escapeHtml(e):e)+"");var n=document.querySelector('button[onclick*="changeUsername"]');n&&(n.textContent="✅ Saved!",n.style.background="#22c55e",setTimeout(function(){n.textContent="Save New Username",n.style.background="var(--accent)"},2e3))}else showToast("Username contains inappropriate language")}),window.togglePushNotifications=async function(){try{if(!("Notification"in window))return void showToast("Notifications not supported in this browser");"granted"===await Notification.requestPermission()?(localStorage.setItem("btc_push_enabled","true"),showToast("🔔 Notifications Enabled!")):(localStorage.setItem("btc_push_enabled","false"),showToast("❌ Notification permission denied")),showSettingsPage("prefs")}catch(e){console.error(e)}},"undefined"==typeof sendEmailVerification&&(window.sendEmailVerification=function(){auth&&auth.currentUser&&auth.currentUser.sendEmailVerification&&auth.currentUser.sendEmailVerification().then(function(){showToast("📧 Verification email sent!")}).catch(function(){showToast("Could not send verification email")})}),"undefined"==typeof disable2FA&&(window.disable2FA=function(){showToast("2FA management coming soon")}),"undefined"==typeof startMFAEnroll&&(window.startMFAEnroll=function(){showToast("2FA enrollment coming soon")}),"undefined"==typeof verifyMFACode&&(window.verifyMFACode=function(){showToast("2FA verification coming soon")}),"undefined"==typeof sendPasswordReset&&(window.sendPasswordReset=function(){auth&&auth.currentUser&&auth.currentUser.email&&auth.sendPasswordResetEmail(auth.currentUser.email).then(function(){showToast("📧 Password reset email sent!")}).catch(function(){showToast("Could not send reset email")})}),"undefined"==typeof confirmDeleteAccount&&(window.confirmDeleteAccount=function(){if(confirm("Are you sure you want to delete your account? This cannot be undone.")&&auth&&auth.currentUser){var e=auth.currentUser.uid;db.collection("users").doc(e).delete().then(function(){return auth.currentUser.delete()}).then(function(){localStorage.clear(),location.reload()}).catch(function(e){showToast("Error: "+e.message)})}}),window.saveSatsLnAddress=async function(){var e=document.getElementById("satsLnAddrInput"),t=document.getElementById("satsLnAddrStatus");if(e){var o=e.value.trim();if(o&&(!o.includes("@")||o.length<5))t&&(t.innerHTML='Enter a valid Lightning Address (e.g. you@walletofsatoshi.com)');else if(void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{t&&(t.innerHTML='Saving…'),await db.collection("users").doc(auth.currentUser.uid).update({lightning:o}),void 0!==currentUser&¤tUser&&(currentUser.lightning=o),o?(t&&(t.innerHTML='✅ Lightning Address saved!'),"function"==typeof showToast&&showToast("⚡ Lightning Address saved!"),"true"!==localStorage.getItem("btc_lightning_setup")&&(localStorage.setItem("btc_lightning_setup","true"),"function"==typeof awardPoints&&awardPoints(100,"⚡ Lightning wallet setup!"),"function"==typeof showToast&&setTimeout(function(){showToast("⚡🏅 Lightning Rod badge earned! +100 pts")},1500),"function"==typeof initBadges&&setTimeout(initBadges,2e3))):t&&(t.innerHTML='Lightning Address removed.')}catch(e){t&&(t.innerHTML='Error saving — try again')}else t&&(t.innerHTML='Sign in to save your Lightning Address')}},window.initSatsClaim=function(){if(console.log("[SATS] initSatsClaim called",{currentUser:!!currentUser,auth:!!auth,authUser:!!auth?.currentUser,isAnon:auth?.currentUser?.isAnonymous}),!currentUser||!auth||!auth.currentUser||auth.currentUser.isAnonymous)return console.log("[SATS] BLOCKED: auth check failed"),void showToast("Sign in to claim sats");var e=(currentUser.points||0)-(currentUser.pointsClaimed||0),t=Math.floor(Math.max(0,e)/10),o=currentUser.satsWithdrawn||0,n="function"==typeof getSatCap?getSatCap():1e4,i=Math.max(0,n-o),a=Math.min(t,500,i);if(console.log("[SATS] maxClaim:",a,"| satsBalance:",t,"| lifetimeLeft:",i,"| satsWithdrawn:",o),a<100)return console.log("[SATS] BLOCKED: maxClaim < 100"),void showToast("⚡ Need at least 100 claimable sats (1,000 unclaimed XP) to withdraw. Keep earning!",5e3);console.log("[SATS] Passed all checks, showing overlay");var r=document.createElement("div");r.id="satsClaimOverlay",r.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:10002;display:flex;align-items:center;justify-content:center;padding:16px;",setTimeout(function(){r.onclick=function(e){e.target===r&&r.remove()}},200);var s='
    ';s+='
    Claim Sats
    ',s+='
    ',s+='
    You can claim up to
    ',s+='
    ⚡ '+a+" sats
    ",s+="
    ",s+='',s+='',s+='
    Open your Lightning wallet, create an invoice for the amount you want (100-'+a+' sats), and paste it here.
    💚 Zero fees — we pay all Lightning network fees so you receive the full amount!
    ',s+='',s+='',s+='',s+="
    ",r.innerHTML=s,document.body.appendChild(r)},window._satsClaimInProgress=!1,window.submitSatsClaim=async function(){if(!window._satsClaimInProgress){var e=document.getElementById("satsClaimBtn"),t=document.getElementById("satsClaimInvoice"),o=document.getElementById("satsClaimError");if(e&&t){var n=t.value.trim();if(n&&n.toLowerCase().startsWith("lnbc")){o&&(o.style.display="none"),window._satsClaimInProgress=!0,e.disabled=!0,e.textContent="⏳ Sending sats...",e.style.opacity="0.6";try{var i=firebase.functions().httpsCallable("claimSats"),a=_generateDeviceFingerprint(),r=await i({invoice:n,fingerprint:a});if(r.data&&r.data.success){var s=r.data.amount||0;currentUser.pointsClaimed=(currentUser.pointsClaimed||0)+10*s,currentUser.satsWithdrawn=(currentUser.satsWithdrawn||0)+s,currentUser.lastSatsClaim=new Date,document.getElementById("satsClaimOverlay").remove(),window._satsClaimInProgress=!1,"function"==typeof notifySelfSatsClaim&¬ifySelfSatsClaim(s),"function"==typeof launchConfetti&&launchConfetti();var l=currentUser.satsWithdrawn||s,c="function"==typeof getSatCap?getSatCap():1e4,d=Math.max(0,c-l),u=document.createElement("div");u.id="satsCelebration",u.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.3s;",u.onclick=function(e){e.target===u&&u.remove()},u.innerHTML='
    ⚡🎉

    Sats Claimed!

    '+s+' sats
    sent to your Lightning wallet ⚡
    Check your wallet to confirm!
    ⚡ '+d.toLocaleString()+' sats remaining to claim!
    '+l.toLocaleString()+' / 10,000 lifetime total claimed
    🧡 Thank you for learning Bitcoin with us!
    ',document.body.appendChild(u),setTimeout(function(){showSettingsPage("sats")},500)}else{var p=r.data&&r.data.error?r.data.error:"Claim failed — try again";o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}catch(t){console.error("Sats claim error:",t),p=t.message||"Claim failed — try again",o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}else o&&(o.textContent="Please paste a valid Lightning invoice (starts with lnbc...)",o.style.display="block")}}},window.loadSatsHistory=function(){var e=document.getElementById("satsHistory");e&¤tUser&&db?db.collection("users").doc(currentUser.uid).collection("sats_withdrawals").orderBy("timestamp","desc").get().then(function(t){if(t.empty)e.textContent="No withdrawals yet";else{var o=0,n="function"==typeof getSatCap?getSatCap():1e4,i="";t.forEach(function(e){var t=e.data(),n=parseInt(t.amount)||0;o+=n;var a=t.timestamp?new Date(1e3*t.timestamp.seconds).toLocaleDateString():"—";i+='
    '+a+'⚡ '+n+" sats
    "});var a=Math.max(0,n-o),r=Math.min(100,Math.round(o/n*100)),s=r>=90?"#ef4444":r>=60?"#eab308":"#22c55e",l='
    Lifetime Claimed⚡ '+o.toLocaleString()+" / "+n.toLocaleString()+' sats
    '+r+'% used'+a.toLocaleString()+" sats remaining
    ";e.innerHTML=l+i}}).catch(function(){e.textContent="Could not load history"}):e&&(e.textContent="Sign in to view history")};const BADGE_DEFS=[{id:"pow_first_step",name:"First Step",emoji:"👟",desc:"Synced your first walk via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_marathoner",name:"Marathoner",emoji:"🏃‍♂️",desc:"Hit the 42km daily cap in Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_streak_3",name:"3-Day Streak",emoji:"🔥",desc:"Synced walks 3 days in a row via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_streak_7",name:"7-Day Streak",emoji:"🔥",desc:"Synced walks 7 days in a row via Proof of Walk",check:()=>!1,pts:300,hidden:!1},{id:"pow_streak_30",name:"30-Day Streak",emoji:"💎",desc:"Synced walks 30 days in a row via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_10",name:"10 km Club",emoji:"🥾",desc:"Walked 10 km lifetime via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_km_50",name:"50 km Club",emoji:"🚶",desc:"Walked 50 km lifetime via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_km_100",name:"Century Walker",emoji:"🏅",desc:"Walked 100 km lifetime via Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_km_500",name:"500 km Legend",emoji:"🏔️",desc:"Walked 500 km lifetime via Proof of Walk",check:()=>!1,pts:500,hidden:!1},{id:"pow_km_1000",name:"1,000 km Titan",emoji:"🌍",desc:"Walked 1,000 km lifetime via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_5000",name:"To the Moon",emoji:"🌕",desc:"Walked 5,000 km lifetime via Proof of Walk",check:()=>!1,pts:2500,hidden:!1},{id:"first_channel",name:"First Steps",emoji:"👶",desc:"Opened your first channel",check:e=>e.length>=1,pts:10},{id:"explorer_10",name:"Explorer",emoji:"🧭",desc:"Visited 10 topics",check:e=>e.length>=10,pts:15},{id:"explorer_25",name:"Trailblazer",emoji:"🗺️",desc:"Visited 25 topics",check:e=>e.length>=25,pts:30},{id:"explorer_50",name:"Pathfinder",emoji:"🏕️",desc:"Visited 50 topics",check:e=>e.length>=50,pts:50},{id:"explorer_100",name:"Cartographer",emoji:"🌍",desc:"Visited 100 topics",check:e=>e.length>=100,pts:100},{id:"explorer_all",name:"Completionist",emoji:"🗝️",desc:"Visited every single topic",check:(e,t)=>e.length>=t,pts:500},{id:"foundation_builder",name:"Foundation Builder",emoji:"🧱",desc:"Read all Layer 1 Properties (Orange)",check:e=>["whitepaper","decentralized","scarce","secure","money","peaceful","dominant","organic","supranational","programmable","use-cases"].every(t=>e.includes(t)),pts:75},{id:"experienced_pro",name:"Deep Diver",emoji:"🤿",desc:"Read all Experienced Topics (Purple)",check:e=>["maximalism","problems-of-money","self-custody","privacy-nonkyc","nodes","mining","pow-vs-pos","energy","difficulty-adjustment","layer-2-lightning","fedi-ark","chaumian-mints","ctv-covenants","extension-blocks","op-codes","bitvm","layer-3-sidechains","stablecoins","smart-contracts","blockchain-timechain","regulation","cryptography","core-source-code","developers","investment-strategy","evidence-against-alts","consensus"].every(t=>e.includes(t)),pts:150},{id:"librarian",name:"The Librarian",emoji:"📚",desc:"Read all Resource topics (Blue)",check:e=>["one-stop-shop","faq-glossary","nostr","misconceptions-fud","books","videos","podcasts","articles-threads","informational-sites","curriculum","research-theses","games","music","movies-tv","hardware","poems-stories","apps-tools","projects-diy","art-inspiration","graphics","charts","swag-merch","jobs-earn","social-media","fun-facts","news-adoption","history","international","satoshi-nakamoto","giga-chad","health","web5","memes-funny"].every(t=>e.includes(t)),pts:150},{id:"quest_1",name:"Quester",emoji:"⚔️",desc:"Completed your first Quest",check:(e,t,o)=>o>=1,pts:10},{id:"quest_3",name:"Quest Master",emoji:"📜",desc:"Completed 3 Quests",check:(e,t,o)=>o>=3,pts:25},{id:"quest_5",name:"Quest Legend",emoji:"🏰",desc:"Completed 5 Quests",check:(e,t,o)=>o>=5,pts:50},{id:"bookworm",name:"Bookworm",emoji:"📖",desc:"Saved 5 topics to favorites",check:()=>JSON.parse(localStorage.getItem("btc_favs")||"[]").length>=5,pts:20},{id:"night_owl",name:"Night Owl",emoji:"🦉",desc:"Browsing between midnight and 5am",check:()=>{const e=(new Date).getHours();return e>=0&&e<5},pts:15},{id:"early_bird",name:"Early Bird",emoji:"🐦",desc:"Browsing between 5am and 7am",check:()=>{const e=(new Date).getHours();return e>=5&&e<7},pts:15},{id:"cert_scholar",name:"Bitcoin Scholar",emoji:"🎓",desc:"Passed the Bitcoin Scholar Certification",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed"),pts:50},{id:"tctv_tuned_in",name:"Tuned In",emoji:"📺",desc:"Watched 10 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=10,pts:10},{id:"tctv_couch_potato",name:"Couch Potato",emoji:"🛋️",desc:"Watched 60 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=60,pts:25},{id:"tctv_binge_watcher",name:"Binge Watcher",emoji:"🍿",desc:"Watched 5 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=300,pts:50},{id:"tctv_couch_king",name:"Couch King",emoji:"🛌",desc:"Watched 24 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=1440,pts:100},{id:"tctv_satellite",name:"Satellite",emoji:"🛰️",desc:"Watched 100 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=6e3,pts:750},{id:"cert_tech",name:"Protocol Expert",emoji:"🛠️",desc:"Passed the Technical Protocol Expert Certification",check:()=>"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:100},{id:"nacho_chatterbox",name:"Nacho Chatterbox",emoji:"🦌",desc:"Interacted with Nacho 50+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=50,pts:30},{id:"nacho_bestie",name:"Nacho's Bestie",emoji:"🧡",desc:"Interacted with Nacho 250+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=250,pts:200},{id:"chat_first",name:"First Words",emoji:"💦",desc:"Sent your first message in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=1,pts:10},{id:"chat_10",name:"Chatty",emoji:"🗣️",desc:"Sent 10 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=10,pts:15},{id:"chat_50",name:"Conversationalist",emoji:"💬",desc:"Sent 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=50,pts:25},{id:"chat_100",name:"Town Crier",emoji:"📢",desc:"Sent 100 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=100,pts:50},{id:"chat_500",name:"Chat Legend",emoji:"📯",desc:"Sent 500 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=500,pts:250},{id:"chat_streak_3",name:"Regular",emoji:"📅",desc:"Chatted 3 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=3,pts:20},{id:"chat_streak_7",name:"Devoted Chatter",emoji:"💪",desc:"Chatted 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=7,pts:50},{id:"chat_streak_30",name:"Chat Addict",emoji:"💠",desc:"Chatted 30 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=30,pts:300},{id:"dj_first",name:"First Set",emoji:"🎧",desc:"DJed for the first time in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=1,pts:25},{id:"dj_5",name:"Resident DJ",emoji:"🎛️",desc:"DJed 5 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=5,pts:50},{id:"dj_25",name:"Club Legend",emoji:"🎶",desc:"DJed 25 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=25,pts:300},{id:"dj_songs_10",name:"Playlist Pro",emoji:"📻",desc:"Broadcast 10 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=10,pts:30},{id:"dj_songs_50",name:"Jukebox Hero",emoji:"🎵",desc:"Broadcast 50 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=50,pts:75},{id:"dj_songs_100",name:"Vinyl Master",emoji:"🎼",desc:"Broadcast 100 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=100,pts:400},{id:"dj_listener",name:"Good Listener",emoji:"🔊",desc:"Tuned in to 10 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=10,pts:20},{id:"dj_listener_50",name:"Groupie",emoji:"🤘",desc:"Tuned in to 50 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=50,pts:150},{id:"producer_1",name:"Producer",emoji:"🎤",desc:"Uploaded your first song to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=1,pts:50},{id:"producer_10",name:"Discographer",emoji:"💿",desc:"Uploaded 10 songs to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=10,pts:100},{id:"pvp_first",name:"First Blood",emoji:"🩸",desc:"Won your first PVP battle",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=1,pts:25},{id:"pvp_5",name:"Contender",emoji:"🥊",desc:"Won 5 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=5,pts:50},{id:"pvp_25",name:"Gladiator",emoji:"🏟️",desc:"Won 25 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=25,pts:100},{id:"pvp_50",name:"Champion",emoji:"🏆",desc:"Won 50 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=50,pts:200},{id:"pvp_100",name:"PVP Legend",emoji:"🥇",desc:"Won 100 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=100,pts:1e3},{id:"forum_5",name:"Voice of the People",emoji:"📣",desc:"Made 5 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=5,pts:25},{id:"forum_25",name:"Thought Leader",emoji:"🧠",desc:"Made 25 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=25,pts:75},{id:"article_1",name:"Author",emoji:"✍️",desc:"Published your first article",check:()=>parseInt(localStorage.getItem("btc_articles_published")||"0")>=1,pts:50},{id:"streak_7",name:"Week Warrior",emoji:"🔥",desc:"7-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=7,pts:50},{id:"streak_30",name:"Monthly Maxi",emoji:"🦾",desc:"30-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=30,pts:150},{id:"streak_100",name:"Diamond Hands",emoji:"💎",desc:"100-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=100,pts:1e3},{id:"streak_365",name:"HODLer Supreme",emoji:"🪩",desc:"365-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=365,pts:5e3},{id:"irl_host",name:"Event Host",emoji:"🎪",desc:"Hosted your first IRL event",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=1,pts:50},{id:"irl_host_5",name:"Community Builder",emoji:"🏗️",desc:"Hosted 5 IRL events",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=5,pts:150},{id:"sats_first",name:"First Sats",emoji:"🪙",desc:"Claimed your first sats from the faucet",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1,pts:25},{id:"sats_1k",name:"Stacker",emoji:"📦",desc:"Claimed 1,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e3,pts:100},{id:"sats_5k",name:"Sat Whale",emoji:"🧊",desc:"Claimed 5,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=5e3,pts:250},{id:"predict_1",name:"Oracle",emoji:"🎱",desc:"Made your first price prediction",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.total||0)>=1,pts:10},{id:"predict_correct_5",name:"Crystal Ball",emoji:"🏐",desc:"5 correct predictions",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.correct||0)>=5,pts:75},{id:"first_purchase",name:"Bitcoiner",emoji:"🛒",desc:"Completed the First Bitcoin Purchase guide",check:()=>"true"===localStorage.getItem("btc_fp_completed"),pts:100},{id:"lightning_setup",name:"Lightning Rod",emoji:"⚡",desc:"Set up a Lightning wallet or added a Lightning address",check:()=>"true"===localStorage.getItem("btc_lightning_setup"),pts:100},{id:"trail_meadow",name:"Meadow Walker",emoji:"🌿",desc:"Completed The Meadow trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("meadow")}catch(e){return!1}},pts:200},{id:"trail_mountain",name:"Mountain Climber",emoji:"⛰️",desc:"Completed The Mountain trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("mountain")}catch(e){return!1}},pts:400},{id:"trail_summit",name:"Summit Conqueror",emoji:"🏔️",desc:"Completed The Summit trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("summit")}catch(e){return!1}},pts:750},{id:"trail_all",name:"Trail Master",emoji:"🏁",desc:"Completed all three Nacho's Trails",check:()=>{try{var e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]");return e.includes("meadow")&&e.includes("mountain")&&e.includes("summit")}catch(e){return!1}},pts:500},{id:"tip_first",name:"First Tip",emoji:"💸",desc:"Sent your first Lightning tip",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=1,pts:25},{id:"tip_10",name:"Generous Pleb",emoji:"💛",desc:"Tipped 10 times",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=10,pts:75},{id:"tip_whale",name:"Whale Tipper",emoji:"🐳",desc:"Tipped 1,000+ sats total",check:()=>parseInt(localStorage.getItem("btc_tips_total_sats")||"0")>=1e3,pts:150},{id:"tip_magnet",name:"Tip Magnet",emoji:"🧲",desc:"Received 10 tips from others",check:()=>parseInt(localStorage.getItem("btc_tips_received")||"0")>=10,pts:100},{id:"referral_1",name:"First Referral",emoji:"🔗",desc:"Referred 1 friend who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=1,pts:50},{id:"referral_5",name:"Connector",emoji:"🤝",desc:"Referred 5 friends who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=5,pts:100},{id:"referral_10",name:"Network Effect",emoji:"🌐",desc:"Referred 10 friends to Bitcoin education",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=10,pts:200},{id:"referral_25",name:"Orange Pill Machine",emoji:"💊",desc:"Orange-pilled 25 people via your link",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=25,pts:500},{id:"referral_50",name:"Super Spreader",emoji:"📡",desc:"Referred 50 people — legend status",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=50,pts:1e3},{id:"referral_100",name:"Viral Plebian",emoji:"👑",desc:"Referred 100 people — you are the movement",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=100,pts:2500},{id:"referred",name:"Referred Friend",emoji:"🫂",desc:"Joined Bitcoin Education Archive via a referral link",check:()=>void 0!==currentUser&¤tUser&&!!currentUser.referredBy,pts:25},{id:"dm_first",name:"DM Starter",emoji:"✉️",desc:"Sent your first direct message",check:()=>parseInt(localStorage.getItem("btc_dms_sent")||"0")>=1,pts:15},{id:"react_50",name:"Reaction King",emoji:"❤️",desc:"Reacted to 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_reactions")||"0")>=50,pts:50},{id:"predict_streak_3",name:"Oracle Streak",emoji:"🎯",desc:"3 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=3,pts:50},{id:"predict_streak_10",name:"Nostradamus",emoji:"🔮",desc:"10 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=10,pts:250},{id:"spin_30",name:"Lucky Spinner",emoji:"🎰",desc:"Spun the wheel 30 days total",check:()=>parseInt(localStorage.getItem("btc_spin_count")||"0")>=30,pts:75},{id:"spin_streak_7",name:"Spin Streak",emoji:"🎡",desc:"Spun 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_spin_streak")||"0")>=7,pts:50},{id:"spin_jackpot",name:"Jackpot Winner",emoji:"🌟",desc:"Hit the RARE drop on the spin wheel",check:()=>"true"===localStorage.getItem("btc_spin_hit_rare"),pts:100},{id:"cert_double",name:"Double Scholar",emoji:"🏛️",desc:"Earned both Scholar AND Protocol Expert certifications",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed")&&"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:250},{id:"sf_first_hash",name:"First Hash",emoji:"⛏️",desc:"Generated your first hash during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1,pts:10},{id:"sf_10_hashes",name:"Pickaxe Swinger",emoji:"💥",desc:"Generated 10 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=10,pts:25},{id:"sf_50_hashes",name:"Mine Foreman",emoji:"🪨",desc:"Generated 50 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=50,pts:75},{id:"sf_100_hashes",name:"Hash Machine",emoji:"🔩",desc:"Generated 100 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=100,pts:150},{id:"sf_500_hashes",name:"ASIC Mode",emoji:"🖥️",desc:"Generated 500 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=500,pts:500},{id:"sf_1000_hashes",name:"Mining Rig",emoji:"🏭",desc:"Generated 1,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e3,pts:1e3},{id:"sf_10000_hashes",name:"Hash Lord",emoji:"☄️",desc:"Generated 10,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e4,pts:2100},{id:"sf_low_hash",name:"Lucky Strike",emoji:"⭐",desc:"Mined a hash under 1,000,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e6,pts:50},{id:"sf_ultra_low",name:"Golden Nonce",emoji:"✨",desc:"Mined a hash under 100,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e5,pts:200},{id:"sf_block_solver",name:"Block Solver",emoji:"🌞",desc:"Solved a block! Hash under the difficulty target",check:()=>"true"===localStorage.getItem("btc_sf_solved_block"),pts:1e3},{id:"sf_contributor",name:"Community Miner",emoji:"🤝",desc:"Contributed to activating Satoshi's Favor 3 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=3,pts:50},{id:"sf_contributor_10",name:"Favor Champion",emoji:"🏅",desc:"Contributed to activating Satoshi's Favor 10 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=10,pts:200},{id:"raid_first",name:"Raid Recruit",emoji:"🛡️",desc:"Dealt damage to your first Raid Boss",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=1,pts:10},{id:"raid_5",name:"Raid Warrior",emoji:"🗡️",desc:"Dealt 5 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=5,pts:50},{id:"raid_10",name:"Raid Veteran",emoji:"⚙️",desc:"Dealt 10 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=10,pts:100},{id:"raid_25",name:"Raid Commander",emoji:"⚜️",desc:"Dealt 25 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=25,pts:250},{id:"raid_50",name:"Raid Legend",emoji:"👑",desc:"Dealt 50 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=50,pts:750},{id:"raid_100",name:"Raid Warlord",emoji:"🔱",desc:"Dealt 100 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=100,pts:1500},{id:"raid_boss_slayer",name:"Boss Slayer",emoji:"💀",desc:"Participated in defeating a Raid Boss",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=1,pts:50},{id:"raid_boss_slayer_5",name:"Boss Hunter",emoji:"🐉",desc:"Participated in defeating 5 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=5,pts:150},{id:"raid_boss_slayer_10",name:"Dragon Slayer",emoji:"🐲",desc:"Participated in defeating 10 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=10,pts:500},{id:"raid_winner",name:"Raid Champion",emoji:"🎖️",desc:"Won the sats lottery after a Raid Boss defeat",check:()=>"true"===localStorage.getItem("btc_raid_winner"),pts:250}];let earnedBadges=new Set,badgeCheckInterval=null;function initBadges(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(e=>earnedBadges.add(e)),badgeCheckInterval=setInterval(checkBadges,3e4),setInterval(function(){if(window._visibleBadgeQueue&&0!==window._visibleBadgeQueue.length&&!window._nachoBusy){var e=document.getElementById("nacho-bubble");e&&e.classList.contains("show")||document.getElementById("badgeCelebration")||showBadgeToast(window._visibleBadgeQueue.shift())}},5e3)}function checkBadges(){if(!window._visibleBadgesReady)return;if(window._nachoBusy)return;const e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=void 0!==completedQuests?completedQuests.size:0;for(const a of BADGE_DEFS)if(!earnedBadges.has(a.id))try{if(a.check(e,t,o)){earnedBadges.add(a.id),localStorage.setItem("btc_badges",JSON.stringify([...earnedBadges])),"function"==typeof window._raidOnBadgeEarned&&window._raidOnBadgeEarned(),"function"==typeof window.contributeSatoshiFavor&&(void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username,window.contributeSatoshiFavor("badge_earned",a.emoji+" "+a.name).catch(function(){}));var n=document.getElementById("nacho-bubble");window._nachoBusy||n&&n.classList.contains("show")?(window._visibleBadgeQueue||(window._visibleBadgeQueue=[]),window._visibleBadgeQueue.push(a)):showBadgeToast(a);var i=a.pts||20;if("function"==typeof awardPoints&&awardPoints(i,"Badge: "+a.name+" "+a.emoji),void 0!==db&&void 0!==auth&&auth.currentUser)try{db.collection("users").doc(auth.currentUser.uid).update({visibleBadges:firebase.firestore.FieldValue.arrayUnion(a.id)})}catch(e){}}}catch(e){}}window._visibleBadgesReady=!1,window.markVisibleBadgesReady=function(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(function(e){earnedBadges.add(e)});var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>e.length&&(e=currentUser.readChannels),void 0!==CHANNELS&&Object.keys(CHANNELS).length,void 0!==completedQuests&&completedQuests.size;var t=!1,o=[];void 0!==currentUser&¤tUser&¤tUser.visibleBadges&&(o=currentUser.visibleBadges);for(var n=0;n𝕏 Share on Twitter'),o.innerHTML='
    '+e.emoji+'
    🎉 Badge Earned!
    '+e.name+'
    '+e.desc+'
    +20 XP
    '+r+'
    ',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function copyBadgeLink(e,t){const o="I earned the "+e+" "+t+" badge on Bitcoin Education Archive!\nhttps://bitcoineducation.quest";navigator.clipboard.writeText(o).then(()=>{"function"==typeof showToast&&showToast("📋 Copied to clipboard!")})}function launchConfetti(){const e=document.createElement("canvas");e.id="confettiCanvas",e.style.cssText="position:fixed;inset:0;z-index:500;pointer-events:none;",e.width=window.innerWidth,e.height=window.innerHeight,document.body.appendChild(e);const t=e.getContext("2d"),o=[],n=["#f7931a","#ea580c","#fbbf24","#f59e0b","#ff6b00","#ff9500","#ffb800","#fff"];for(let t=0;t<120;t++)o.push({x:e.width/2+100*(Math.random()-.5),y:e.height/2,vx:16*(Math.random()-.5),vy:16*(Math.random()-1)-4,size:8*Math.random()+3,color:n[Math.floor(Math.random()*n.length)],rotation:360*Math.random(),rotSpeed:12*(Math.random()-.5),gravity:.12+.08*Math.random(),opacity:1,shape:Math.random()>.5?"rect":"circle"});let i=0;requestAnimationFrame(function n(){t.clearRect(0,0,e.width,e.height);let a=!1;o.forEach(o=>{o.x+=o.vx,o.vy+=o.gravity,o.y+=o.vy,o.rotation+=o.rotSpeed,o.vx*=.99,i>40&&(o.opacity-=.015),o.opacity>0&&o.y{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=o,i.type="sine",a.gain.setValueAtTime(.15*t,e.currentTime+.12*n),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.12*n+.5),i.start(e.currentTime+.12*n),i.stop(e.currentTime+.12*n+.5)})}catch(e){}}function getBadgeHTML(){var e={};function t(t,o){var n=t.filter(function(t){return!e[t.id]&&o(t)});return n.forEach(function(t){e[t.id]=!0}),n}const o={"🧭 Discovery":t(BADGE_DEFS,e=>e.id.includes("explorer")||"first_channel"===e.id||"bookworm"===e.id),"🧠 Knowledge":t(BADGE_DEFS,e=>e.id.includes("builder")||e.id.includes("diver")||e.id.includes("librarian")||e.id.includes("quest")||e.id.includes("cert_")),"🦌 Trails":t(BADGE_DEFS,e=>e.id.startsWith("trail_")),"💬 Global Chat":t(BADGE_DEFS,e=>e.id.startsWith("chat_")),"🦌 Nacho":t(BADGE_DEFS,e=>e.id.startsWith("nacho_")),"📺 Timechain TV":t(BADGE_DEFS,e=>e.id.startsWith("tctv_")),"🎧 DJ Mode":t(BADGE_DEFS,e=>e.id.startsWith("dj_")),"🎵 Music":t(BADGE_DEFS,e=>e.id.startsWith("producer")),"⚔️ PVP":t(BADGE_DEFS,e=>e.id.startsWith("pvp_")),"📝 Forum":t(BADGE_DEFS,e=>e.id.startsWith("forum_")||e.id.startsWith("article_")),"🔥 Streaks":t(BADGE_DEFS,e=>e.id.startsWith("streak_")),"🤝 Community":t(BADGE_DEFS,e=>e.id.startsWith("irl_")||e.id.startsWith("referral_")),"⚡ Sats & Lightning":t(BADGE_DEFS,e=>e.id.startsWith("sats_")||"lightning_setup"===e.id||e.id.startsWith("tip_")),"🔮 Predictions":t(BADGE_DEFS,e=>e.id.startsWith("predict_")),"💬 Social":t(BADGE_DEFS,e=>e.id.startsWith("dm_")||"react_50"===e.id),"🎡 Spin Wheel":t(BADGE_DEFS,e=>e.id.startsWith("spin_")),"⛏️ Satoshi's Favor":t(BADGE_DEFS,e=>e.id.startsWith("sf_")),"🐲 Raid Boss":t(BADGE_DEFS,e=>e.id.startsWith("raid_")),"🌙 Fun":t(BADGE_DEFS,e=>"night_owl"===e.id||"early_bird"===e.id),"🏆 Milestones":t(BADGE_DEFS,t=>!e[t.id])};let n='';n+='
    ';var i=0;for(const[e,t]of Object.entries(o)){if(0===t.length)continue;var a="bc_"+ ++i;const o=t.filter(e=>earnedBadges.has(e.id)).length,r=o===t.length;n+='
    ',n+="",n+='
    "}if(void 0!==HIDDEN_BADGES){const e=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),t=HIDDEN_BADGES.filter(function(e){return!e.hidden});if(t.length>0){var r="bc_"+ ++i,s=t.filter(function(t){return e.includes(t.id)}).length,l=s===t.length;n+='
    ',n+="",n+='
    "}const o=HIDDEN_BADGES.filter(function(e){return e.hidden}),a=o.some(function(t){return e.includes(t.id)}),u=o.length,p=o.filter(function(t){return e.includes(t.id)}).length;var c="bc_"+ ++i,d=p===u;if(n+='
    ',n+="",n+='
    "}return n}window._showBadgeTip=function(e,t){e.stopPropagation();var o=document.getElementById("badgeFloatTip");if(o){var n=t.querySelector(".badge-tooltip"),i=n?n.innerHTML:t.getAttribute("title")||"";if(i){if("block"===o.style.display&&o._srcEl===t)return o.style.display="none",o._srcEl=null,void t.classList.remove("tapped");document.querySelectorAll(".badge-item.tapped").forEach(function(e){e.classList.remove("tapped")}),t.classList.add("tapped"),o._srcEl=t,o.innerHTML=i,o.style.display="block";var a=(e.touches?e.touches[0].clientX:e.clientX)||0,r=(e.touches?e.touches[0].clientY:e.clientY)||0;o.style.left="0px",o.style.top="0px";var s=o.offsetWidth||220,l=o.offsetHeight||80,c=window.innerWidth,d=window.innerHeight,u=Math.min(a-s/2,c-s-10);u=Math.max(u,10);var p=r-l-12;p<10&&(p=r+24),p+l>d-10&&(p=d-l-10),o.style.left=u+"px",o.style.top=p+"px"}}},document.addEventListener("click",function(e){var t=document.getElementById("badgeFloatTip");t&&"none"!==t.style.display&&(e.target.closest(".badge-item")||(t.style.display="none",t._srcEl=null,document.querySelectorAll(".badge-item.tapped").forEach(function(e){e.classList.remove("tapped")})))},!0),window._badgeSearch=function(e){var t=(e||"").trim().toLowerCase(),o=document.getElementById("badgeSearchResults");if(o){if(document.querySelectorAll(".badge-item.badge-search-highlight").forEach(function(e){e.classList.remove("badge-search-highlight")}),!t)return o.style.display="none",void(o.innerHTML="");var n=[];void 0!==BADGE_DEFS&&(n=n.concat(BADGE_DEFS)),void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){e.hidden||n.push(e)});var i=n.filter(function(e){return e.name.toLowerCase().includes(t)||(e.desc||"").toLowerCase().includes(t)}).slice(0,8);if(0===i.length)return o.innerHTML='
    No badges found for "'+escapeHtml(e)+'"
    ',void(o.style.display="block");var a="";i.forEach(function(e){var t=earnedBadges.has(e.id)||JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]").includes(e.id);a+="
    '+(t?e.emoji:e.lockedEmoji||"🔘")+'
    '+escapeHtml(e.name)+'
    '+(t?"✅ ":"🔒 ")+escapeHtml(e.desc)+"
    "}),o.innerHTML=a,o.style.display="block"}},window._badgeSearchJump=function(e){var t=document.getElementById("badgeSearchResults"),o=document.getElementById("badgeSearchInput");t&&(t.style.display="none",t.innerHTML=""),o&&(o.value=""),document.querySelectorAll(".badge-item.badge-search-highlight").forEach(function(e){e.classList.remove("badge-search-highlight")});var n=document.querySelector('.badge-item[data-badge-id="'+e+'"]');if(n){var i=n.closest(".badges-grid");if(i&&"none"===i.style.display){i.style.display="grid";var a=i.previousElementSibling;if(a){var r=a.querySelector(".bca");r&&(r.textContent="▼")}}n.classList.add("badge-search-highlight"),setTimeout(function(){n.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(function(){n.classList.remove("badge-search-highlight")},2500)},100)}},setTimeout(initBadges,2e3);const TICKET_CONFIG={dailyLogin:1,referral:50,referralSignupBonus:50,referralPointsThreshold:2140,pointsPerTicket:5};function getReferralCode(){return currentUser&¤tUser.uid?currentUser.uid.substring(0,8):null}function getReferralLink(){const e=getReferralCode();return e?window.location.origin+window.location.pathname+"?ref="+e:""}function captureReferralCode(){const e=new URLSearchParams(window.location.search).get("ref");if(e&&e.length>=6&&(localStorage.setItem("btc_referral_code",e),window.history&&window.history.replaceState)){const e=window.location.pathname+window.location.hash;window.history.replaceState({},"",e)}}async function awardDailyTicket(){try{if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;const e=(new Date).toISOString().split("T")[0];if(currentUser.lastTicketDate===e)return;const t=TICKET_CONFIG.dailyLogin,o=t*TICKET_CONFIG.pointsPerTicket,n=(currentUser.orangeTickets||0)+t;if("function"==typeof awardPoints){const e=await awardPoints(o,"🎟️ Daily tickets",null,t);if(!e||!e.success)return}currentUser.lastTicketDate=e,currentUser.orangeTickets=(currentUser.orangeTickets||0)+t,setTimeout(function(){"function"==typeof showToast&&showToast("🎟️ +1 Orange Ticket — Welcome back! (Total: "+n+")")},2500),"function"==typeof updateRankUI&&updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}catch(e){console.warn("Daily ticket error:",e)}}async function attachReferral(e){const t=localStorage.getItem("btc_referral_code");if(t&&!e.startsWith(t))try{const o=await db.collection("users").where("referralCode","==",t).limit(1).get();let n=null;n=o.empty?null:o.docs[0].id,await db.collection("users").doc(e).update({referredBy:t,referralVerified:!1}),await db.collection("referrals").doc(e).set({referredUser:e,referrerCode:t,referrerUid:n||"",createdAt:firebase.firestore.FieldValue.serverTimestamp(),verified:!1,ticketsAwarded:!1}),localStorage.removeItem("btc_referral_code")}catch(e){console.log("Referral attach error:",e)}}async function checkReferralQualifications(){if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;if(window._referralChecked)return;window._referralChecked=!0;const e=getReferralCode();if(e)try{const t=await db.collection("referrals").where("referrerCode","==",e).where("ticketsAwarded","==",!1).get();if(t.empty)return;let o=0;for(const e of t.docs){const t=e.data().referredUser,n=await db.collection("users").doc(t).get();if(!n.exists)continue;const i=n.data();(i.points||0)>=TICKET_CONFIG.referralPointsThreshold&&(i.totalVisits||0)>=2&&(o+=TICKET_CONFIG.referral,await db.collection("referrals").doc(e.id).update({verified:!0,ticketsAwarded:!0,verifiedAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("users").doc(t).update({referralVerified:!0}))}if(o>0){const e=o*TICKET_CONFIG.pointsPerTicket;currentUser.orangeTickets,"function"==typeof awardPoints&&await awardPoints(e,"🎟️ Referral tickets",null,o),currentUser.orangeTickets=(currentUser.orangeTickets||0)+o,showToast("🎟️ +"+o+" Orange Tickets — Referral"+(o>50?"s":"")+" verified!"),"function"==typeof notifySelfReferral&¬ifySelfReferral(o),updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}}catch(e){console.log("Referral check error:",e)}}async function ensureReferralCode(){if(currentUser&&db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&!currentUser.referralCode){const e=getReferralCode();e&&(await db.collection("users").doc(currentUser.uid).update({referralCode:e}),currentUser.referralCode=e)}}async function getReferralStats(){if(!currentUser||!db)return{total:0,verified:0,pending:0};const e=getReferralCode();if(!e)return{total:0,verified:0,pending:0};try{const t=await db.collection("referrals").where("referrerCode","==",e).get();let o=t.size,n=0,i=0;return t.forEach(e=>{e.data().verified?n++:i++}),{total:o,verified:n,pending:i}}catch(e){return{total:0,verified:0,pending:0}}}function renderTicketsSection(){return'
    Orange Tickets
    '+(currentUser&¤tUser.orangeTickets||0)+'
    Earn tickets by logging in daily (+1), spinning the daily wheel, and referring friends (+50 per verified referral!). Each ticket earned also awards 5 bonus points!

    🏆 The more tickets you have, the higher your chance of winning our 25,000 sats giveaways!
    📅
    Daily Login
    +1 ticket
    🤝
    Referral
    +50 tickets
    '}function renderReferralSection(){const e=getReferralLink();return getReferralCode()?'
    🔗 Referral Program
    Share your link with friends. Earn 50 Orange Tickets for each referral who logs in and earns 2,140+ points (Maxi rank).
    Loading referral stats...
    ':""}function copyReferralLink(){const e=document.getElementById("referralLinkInput");e&&(navigator.clipboard?navigator.clipboard.writeText(e.value).then(function(){showToast("🔗 Referral link copied!")}):(e.select(),document.execCommand("copy"),showToast("🔗 Referral link copied!")))}async function loadReferralStatsUI(){const e=document.getElementById("referralStats");if(!e)return;const t=await getReferralStats();0===t.total?e.innerHTML='No referrals yet. Share your link to start earning!':e.innerHTML='
    👥 Total: '+t.total+'✅ Verified: '+t.verified+'⏳ Pending: '+t.pending+"
    "}async function onUserLoadedTickets(){currentUser&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(await ensureReferralCode(),await awardDailyTicket(),checkReferralQualifications().catch(function(){}))}function getEquippedItems(){try{return JSON.parse(localStorage.getItem("btc_nacho_equipped_multi")||"{}")}catch(e){return{}}}function getEquippedItem(){var e=getEquippedItems();return Object.values(e)[0]||localStorage.getItem("btc_nacho_equipped")||null}window.awardTickets=async function(e,t){if(e&&!(e<1)&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&void 0!==currentUser&¤tUser){currentUser.orangeTickets;var o=e*TICKET_CONFIG.pointsPerTicket;try{"function"==typeof awardPoints&&await awardPoints(o,"🎟️ "+(t||"Orange Tickets"),null,e),currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,"function"==typeof updateRankUI&&updateRankUI()}catch(e){console.warn("[tickets] Award error:",e)}"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Tickets! "+(t||""))}},"undefined"!=typeof window&&captureReferralCode(),function(){const e=function(){const e=(new Date).toISOString().split("T")[0];if(void 0===CHANNELS)return[];const t=Object.keys(CHANNELS),o=[];let n=0;for(let t=0;t{const t=document.querySelector("[onclick*=\"go('"+e+"'\"]");if(t){const e=document.createElement("span");e.style.cssText="position:absolute;top:4px;right:4px;background:#f7931a;color:#fff;font-size:0.55rem;font-weight:900;padding:2px 5px;border-radius:4px;box-shadow:0 0 10px rgba(247,147,26,0.4);",e.textContent="2X PTS",t.style.position="relative",t.appendChild(e)}}),window._dailyBoosts=e}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}(),function(){let e={price:null,blockHeight:null,fees:null,mempoolSize:null,lastFetch:0};const t=3e5;async function o(){const o=Date.now();if(!(o-e.lastFetch900:"true"===e)){var t=document.getElementById("btcTicker");return t&&t.remove(),void document.body.classList.remove("ticker-visible")}var n=document.getElementById("btcTicker");n||((n=document.createElement("div")).id="btcTicker",document.body.prepend(n)),document.body.classList.add("ticker-visible"),n.style.cssText="position:fixed;top:0;left:0;right:0;z-index:10005;background:#030712;border-bottom:1px solid #f7931a;padding:0;height:32px;overflow:hidden;display:flex;align-items:center;font-family:inherit;font-size:0.75rem;color:#94a3b8;line-height:32px;";var i=document.createElement("div");i.id="tickerScroller",i.style.cssText="display:flex;white-space:nowrap;width:max-content;animation:btcTickerScroll 25s linear infinite;will-change:transform;";const a='\n
    \n \n 📡 LOADING SIGNAL...\n \n
    ';i.innerHTML=a+a+a+a,n.innerHTML="",n.appendChild(i);var r=document.getElementById("btcTickerStyle");r||((r=document.createElement("style")).id="btcTickerStyle",document.head.appendChild(r)),r.textContent="\n @keyframes btcTickerScroll { 0% { transform: translateX(0); } 100% { transform: translateX(-50%); } }\n #btcTicker:hover #tickerScroller { animation-play-state: paused; }\n @media(max-width:900px) { \n body.ticker-visible .mobile-bar { top: 32px !important; }\n body.ticker-visible main { padding-top: 130px !important; }\n body.ticker-visible aside { top: 130px !important; z-index: 10006; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n #btcTicker { font-size: 0.65rem; height: 32px; }\n body.ticker-visible .progress-bar { top: 118px !important; }\n }\n @media(min-width:901px) { \n body.ticker-visible aside { padding-top: 32px; }\n body.ticker-visible main { padding-top: 32px; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n body.ticker-visible .progress-bar { top: 32px !important; }\n }",fetch("newsletter-data.json?v="+Date.now()).then(e=>e.json()).then(e=>{const t=n.querySelectorAll(".t-news-items");if(t&&e.news){let o="";e.news.forEach((e,t)=>{var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #'+(t+1)+""+n+""}),t.forEach(e=>e.innerHTML=o)}}).catch(e=>{n.querySelectorAll(".t-news-items").forEach(e=>e.innerHTML="📡 TECHNICAL SIGNAL OFFLINE")}),o(),setInterval(function(){o()},6e4);var s="";setInterval(function(){fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(e){var t=document.querySelectorAll(".t-news-items");if(t.length>0&&e.news&&e.news.length>0){var o="";if(e.news.slice(0,3).forEach(function(e,t){var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #'+(t+1)+""+n+""}),o!==s){s=o;var n=document.getElementById("tickerScroller");t.forEach(function(e){e.innerHTML=o}),n&&(n.style.animation="none",n.offsetHeight,n.style.animation="btcTickerScroll 25s linear infinite")}}}).catch(function(){})},18e5)}function i(e){return e?e>=1e3?"$"+Math.round(e).toLocaleString():"$"+e.toFixed(2):null}window.getNachoLiveData=function(){return e},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",n):n(),window.nachoLiveAnswer=function(t){var o=t.toLowerCase();if(/price|how much is|what.?s bitcoin at|current price|btc price|bitcoin worth|bitcoin cost/.test(o)){var n,a=e.price;if(a||(n=parseFloat(localStorage.getItem("btc_last_price")))&&n>0&&(a=n),!a)return null;var r=i(a),s=["Bitcoin is currently at "+r+"! Still early, {name}. 📈🦌","The current BTC price is "+r+". Number go up technology! 📊","Right now, 1 BTC = "+r+". How many sats are you stacking, {name}? ⚡"];return{answer:s[Math.floor(Math.random()*s.length)],channel:"charts",channelName:"Charts"}}if(/block height|current block|what block|how many blocks|latest block/.test(o))return e.blockHeight?{answer:"We're currently at block "+e.blockHeight.toLocaleString()+"! Every block is history being written, {name}. ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:(n=localStorage.getItem("btc_last_height"))?{answer:"I'm still syncing, but the last block I saw was "+parseInt(n).toLocaleString()+"! ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:null;if(/halving|halvening|next halving|when.*halving|halving countdown/.test(o)){var l=function(){var t=e.blockHeight;if(!t)return null;var o=21e4*Math.ceil(t/21e4),n=o-t;return{nextHalving:o,blocksLeft:n,daysLeft:Math.round(10*n/1440)}}();return l?{answer:"The next halving is at block "+l.nextHalving.toLocaleString()+" -- that's "+l.blocksLeft.toLocaleString()+" blocks away (~"+l.daysLeft+" days). Tick tock, {name}! ⏰",channel:"scarce",channelName:"Scarce"}:null}return null},window.nachoLiveMessage=function(){if(Math.random()>.15)return null;if(o(),!e.price)return null;var t=[];if(e.price){var n=i(e.price);t.push({pose:"cool",text:"BTC is at "+n+" right now, {name}. Just thought you should know. 😎📈"})}return e.blockHeight&&t.push({pose:"brain",text:"We just passed block "+e.blockHeight.toLocaleString()+". Every block is a heartbeat of the network. ⛓️💓"}),0===t.length?null:t[Math.floor(Math.random()*t.length)]},setTimeout(o,3e3),setInterval(o,t),window.toggleTickerSetting=function(){var e=localStorage.getItem("btc_ticker_enabled");if(null===e?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===e){localStorage.setItem("btc_ticker_enabled","false");var t=document.getElementById("btcTicker");t&&t.remove(),document.body.classList.remove("ticker-visible"),"function"==typeof showToast&&showToast("📡 Signal ticker hidden. Refresh to fully apply.")}else localStorage.setItem("btc_ticker_enabled","true"),window._tickerInitialized=!1,n(),"function"==typeof showToast&&showToast("📡 Signal ticker enabled!");"function"==typeof showSettingsPage&&showSettingsPage("prefs")}}(),function(){const e="\"Nacho\"🦌');\">",t='
    🛋️
    🍿
    ';function o(){return"timechain-tv"===window.currentPage||"#timechain-tv"===window.location.hash}const n={default:"🦌",wave:"👋",think:"🤔",celebrate:"🎉",point:"👆",eyes:"👀",fire:"🔥",brain:"🧠",cool:"😎",sleep:"💤",cheese:"🧀",love:"🧡"};window._btcData={price:null,height:null,halvingBlocks:null,lastUpdate:0};const i={whitepaper:{pose:"brain",text:"It looks like you're reading the whitepaper! This is where it all started — 9 pages that changed the world! 📜"},"self-custody":{pose:"point",text:"It looks like you're learning about self-custody! Remember: Nacho keys, nacho cheese. 🧀🔑"},"investment-strategy":{pose:"think",text:"It looks like you're planning your stack strategy! Pro tip: DCA and chill. Time in the market beats timing the market. 📈"},mining:{pose:"fire",text:"It looks like you're exploring mining! Every 10 minutes a new block is born. Beautiful, isn't it? ⛏️"},"privacy-nonkyc":{pose:"eyes",text:"It looks like you value your privacy! Good. A wise buck never reveals his forest location. 🕵️"},"layer-2-lightning":{pose:"celebrate",text:"It looks like you're exploring Lightning! This is how Bitcoin scales to millions of transactions per second! ⚡⚡"},"fun-facts":{pose:"cool",text:"It looks like you're browsing fun facts! This channel is my personal favorite. Don't tell the others. 🤫"},history:{pose:"brain",text:"It looks like you're studying Bitcoin history! Those who don't learn history are doomed to repeat it. 📚"},charts:{pose:"eyes",text:"It looks like you're checking the charts! Number go up technology, am I right? 📊"},"problems-of-money":{pose:"think",text:"It looks like you're learning why fiat is broken! This is where many people get orange-pilled. 🟠"},"giga-chad":{pose:"fire",text:"It looks like you're in the Giga Chad channel! Based and orange-pilled. 💪"},"memes-funny":{pose:"celebrate",text:"It looks like you're looking at memes! A deer of culture, I see. 😏"},"evidence-against-alts":{pose:"cool",text:"It looks like you're reading about altcoins! Spoiler: there's only Bitcoin. 🦌"},scarce:{pose:"brain",text:"It looks like you're learning about scarcity! Only 21 million will ever exist. Even I can't make more. 💎"},decentralized:{pose:"fire",text:"It looks like you're exploring decentralization! No single point of failure. Like a forest — cut one tree, the rest stand strong. 🌲"},secure:{pose:"point",text:"It looks like you're reading about Bitcoin's security! More computing power secures this network than anything else on Earth. 🔒"},money:{pose:"think",text:"It looks like you're learning what money really is! Hint: it's not what the government tells you. 💰"},programmable:{pose:"brain",text:"It looks like you're exploring programmable money! Smart contracts on Bitcoin — the future is being built right here. 🔧"},consensus:{pose:"think",text:"It looks like you're studying consensus! This is how thousands of nodes agree without a boss. Democracy at the protocol level. 🤝"},"difficulty-adjustment":{pose:"brain",text:"It looks like you're learning about the difficulty adjustment! The most elegant part of Bitcoin's design, in my humble deer opinion. ⚙️"},"blockchain-timechain":{pose:"fire",text:"It looks like you're reading about the timechain! Fun fact: many Bitcoiners prefer 'timechain' over 'blockchain.' ⛓️"},"pow-vs-pos":{pose:"cool",text:"It looks like you're comparing PoW vs PoS! Spoiler: Proof of Work wins. Always has. 🏆"},"articles-threads":{pose:"brain",text:"It looks like you're browsing articles! This channel has some of the best Bitcoin writing ever published. Take your time! 📰"},books:{pose:"love",text:"It looks like you're checking out Bitcoin books! The Bitcoin Standard changed my life. Well, my deer life. 📖"},podcasts:{pose:"cool",text:"It looks like you're browsing podcasts! Great for learning while you graze... I mean, commute. 🎧"},"movies-tv":{pose:"celebrate",text:"It looks like you're looking at Bitcoin movies! Grab some popcorn (and cheese). 🍿🧀"},"one-stop-shop":{pose:"point",text:"It looks like you're in the one-stop shop! This is the starter pack — everything a newcomer needs. 🎁"},regulation:{pose:"think",text:"It looks like you're reading about regulation! Governments are slowly figuring out they can't stop Bitcoin. 🏛️"},nodes:{pose:"fire",text:"It looks like you're learning about nodes! Running your own node = verifying everything yourself. Trust no one! 🖥️"},geopolitics___macroeconomics:{pose:"brain",text:"It looks like you're exploring the macro picture! Bitcoin isn't just money — it's a geopolitical shift. 🌍"},"jobs-earn":{pose:"celebrate",text:"It looks like you're checking out Bitcoin jobs! Get paid in sats — the dream! 💼⚡"},"apps-tools-services-models":{pose:"point",text:"It looks like you're browsing Bitcoin tools and apps! So many ways to use the network. 🛠️"},music:{pose:"celebrate",text:"It looks like you're checking Bitcoin music! Yes, there are Bitcoin songs. And yes, they slap. 🎵"},"art-inspiration":{pose:"love",text:"It looks like you're browsing Bitcoin art! Creativity meets sound money. Beautiful. 🎨"},games:{pose:"cool",text:"It looks like you're checking out Bitcoin games! Learn while you play — my kind of strategy. 🎮"},health:{pose:"love",text:"It looks like you're in the health channel! Sound money, sound body, sound mind. 🏋️"},nostr:{pose:"fire",text:"It looks like you're exploring Nostr! Decentralized social media — Bitcoin's best friend. 💜"},curriculum:{pose:"brain",text:"It looks like you're looking at Bitcoin education materials! Perfect for teachers and students! 📝"},"misconceptions-fud":{pose:"cool",text:"It looks like you're fighting FUD! Arm yourself with facts. This channel is your ammo. 🛡️"},cryptography:{pose:"brain",text:"It looks like you're diving into cryptography! This is the math that makes Bitcoin unbreakable. 🔢"},"tail-emission":{pose:"think",text:"It looks like you're reading about tail emission! A big debate in the Bitcoin world. What do you think? 🤔"},stablecoins:{pose:"eyes",text:"It looks like you're reading about stablecoins! Useful on-ramps, but remember — Bitcoin is the exit. 🚪"}},a=[{pose:"brain",text:"📜 Have you read Bitcoin's Whitepaper? It's only 9 pages and it started a revolution! Read it here → 🦌"},{pose:"fire",text:'🔥 Pro tip: Read the Bitcoin Whitepaper — it\'s the Genesis document! Only 9 pages changed the world forever. Check it out →'},{pose:"point",text:"💡 Tip: The sidebar on the left has ALL topics organized by category. Tap a category to expand it!"},{pose:"point",text:"💡 Tip: Click the 🎲 dice button to jump to a random channel — great for discovering new topics!"},{pose:"point",text:"💡 Tip: Use the 🔍 search button to find any subject across all 146+ topics instantly!"},{pose:"point",text:"💡 Tip: Click the Bitcoin logo at the top to return to the homepage anytime!"},{pose:"point",text:"💡 Tip: Hit the ⭐ button on any channel to save it to your favorites for quick access!"},{pose:"point",text:"💡 Tip: Your Exploration Map on the homepage shows every channel you've visited. Try to light them all up! 🗺️"},{pose:"point",text:"💡 Tip: Channels you've already read get a ✓ checkmark in the sidebar. Track your progress!"},{pose:"brain",text:"💡 Tip: You earn XP by visiting daily (+5), opening new topics (+10), and reading (+15 per 30 sec)!"},{pose:"point",text:"💡 Tip: Check the leaderboard to see how you rank against other Bitcoiners! Click your rank bar at the bottom."},{pose:"fire",text:"💡 Tip: Keep a daily streak going! Every 5 days in a row = bonus 100 points! 🔥"},{pose:"point",text:"💡 Tip: There are 9 rank levels from Normie to Satoshi. What level are you? Check Settings → Data!"},{pose:"cheese",text:"💡 Tip: Earn Orange Tickets daily just by logging in! More tickets = higher giveaway chances! 🎟️"},{pose:"point",text:"💡 Tip: Share your referral link (Settings → Tickets) and earn 50 tickets for each verified friend!"},{pose:"celebrate",text:"💡 Tip: Each Orange Ticket also gives you 5 bonus XP! Tickets + points = double reward! 🎟️⭐"},{pose:"brain",text:"💡 Tip: Hit 'Start a Quest' in the sidebar to test your Bitcoin knowledge and earn XP! ⚡"},{pose:"fire",text:"💡 Tip: The Bitcoin Scholar Certification Quest is the ultimate test — pass it to earn the 🎓 badge + 300 points!"},{pose:"eyes",text:"💡 Tip: There are 9 hidden badges to unlock! Each one awards points. Explore the site to discover them all! 🏅"},{pose:"point",text:"💡 Tip: Badges scale in points from 25 to 1,000! The hardest ones are worth the most! 💰"},{pose:"point",text:"💡 Tip: Click your username or the sign-in button to access your Settings — Account, Tickets, Prefs, Security, Data!"},{pose:"point",text:"💡 Tip: You can switch between dark and light theme in Settings → Prefs! 🌙☀️"},{pose:"point",text:"💡 Tip: The site works offline too! Add it to your home screen as an app! 📱"},{pose:"point",text:"💡 Tip: You can export all your data anytime in Settings → Data. Your data is yours! 📥"},{pose:"point",text:"💡 Tip: Don't like me? Long-press to hide me. But I'll miss you. 🥺 (You can bring me back in Settings → Prefs)"},{pose:"brain",text:"💡 Tip: YouTube videos are embedded right in the channels — click to play without leaving the site! 🎬"},{pose:"point",text:"💡 Tip: Tweets are embedded too! Click '▶ Click to display tweet' to expand them. 🐦"},{pose:"fire",text:'📺 Tip: Timechain TV streams 21 curated channels 24/7 — earn 10 pts per 10 min watched! Tune in →'},{pose:"cheese",text:'🛋️ Tip: Couch with me on Timechain TV — I react to every channel you tune into! 🍿 Let\'s chill →'},{pose:"point",text:"💡 Tip: Timechain TV has a global clock — every viewer on the same channel sees the same moment. True synchronized TV! ⏰"},{pose:"celebrate",text:"👑 Tip: Watch 24 hours on Timechain TV to unlock the 👑 Couch King badge + 100 points!"},{pose:"point",text:"💡 Tip: The Quote of the Day on the homepage changes daily — click it to jump to the related channel! 💬"},{pose:"point",text:"💡 Tip: New to Bitcoin? Start with the 'one-stop-shop' channel — it has everything to get you started! 🎯"},{pose:"brain",text:"💡 Tip: Channels are organized into Properties, Experienced Topics, Resources, and Additional Info. Start with Properties!"},{pose:"point",text:"💡 Tip: Post in the PlebTalk to earn the 📣 Town Crier badge + 100 points! Press T or find it in the sidebar."},{pose:"point",text:"💡 Tip: Reply to PlebTalk posts to earn the 💬 Conversationalist badge + 75 points! Join the discussion!"},{pose:"cheese",text:"💡 Tip: LightningMart lets you buy and sell with Bitcoin! List an item to earn the 🏪 Merchant badge! Press S to check it out."},{pose:"point",text:"💡 Tip: Found something cool on LightningMart? Contact the seller to earn the 🛍️ Shopper badge!"},{pose:"celebrate",text:"💡 Tip: Check out my closet in Settings → Nacho! You can dress me up with items you unlock! 🎽🦌"},{pose:"point",text:"💡 Tip: Closet items are colorable! Equip an item, then tap 🎨 Color to customize it! 🌈"},{pose:"fire",text:"💡 Tip: Spin the Daily Wheel every day for free Orange Tickets! Look for the banner at the top of the homepage! 🎡"},{pose:"fire",text:"💡 Tip: Press N to enter Nacho Mode — a full chat experience where I answer your Bitcoin questions with AI! 🦌🧠"},{pose:"point",text:"💡 Tip: In Nacho Mode, press ↑ to recall your previous questions — just like in a chat app!"},{pose:"brain",text:"💡 Tip: Nacho Mode shows the live Bitcoin price in the header! Check it anytime! ₿"},{pose:"point",text:"💡 Tip: Tap the 🧒 button in Nacho Mode to toggle ELI5 mode — I'll explain everything in super simple language!"},{pose:"celebrate",text:"💡 Tip: In Nacho Mode, tap '🗺️ Start Bitcoin Journey' for a guided 10-step learning path from beginner to pro!"},{pose:"point",text:"💡 Tip: Tap '🎮 Quiz Me' in Nacho Mode to test your knowledge and earn XP! 🏆"},{pose:"point",text:"💡 Tip: Nacho Mode has topic chips — tap them if you don't know what to ask! ⚡ Lightning, ⛏️ Mining, and more!"},{pose:"brain",text:"💡 Tip: Every answer in Nacho Mode has 👍👎 buttons — your feedback helps me get smarter!"},{pose:"point",text:"💡 Tip: You can share any Nacho answer with the 📤 Share button — spread the Bitcoin knowledge! 🌍"},{pose:"fire",text:"💡 Tip: Use your voice! Tap 🎙️ in Nacho Mode to ask me questions by speaking! 🗣️"},{pose:"point",text:"💡 Tip: Nacho Mode saves your full chat history — come back anytime to pick up where you left off!"},{pose:"celebrate",text:"💡 Tip: Ask me 10, 25, 50, or 100 questions in Nacho Mode to unlock special milestones! 🎉"},{pose:"fire",text:"💡 Tip: We have a PlebTalk! Press T or click '🗣️ PlebTalk' in the sidebar to discuss Bitcoin! 💬"},{pose:"point",text:"💡 Tip: In PlebTalk, upvote great posts with ⚡ and earn +10 points for posting, +5 for replying!"},{pose:"brain",text:"💡 Tip: PlebTalk posts can include links! Share interesting Bitcoin articles or resources with the community! 🔗"},{pose:"point",text:"💡 Tip: Set up your profile in Settings → Account! Add a bio, website, Twitter, Nostr, and Lightning address! 📝"},{pose:"eyes",text:"💡 Tip: Click any user on the leaderboard to see their profile — including their bio and social links! 👀"},{pose:"fire",text:"💡 Tip: The Scholar Certification awards 2,100 points — that's 21 million in sats! The magic number! 🎓"},{pose:"cheese",text:"💡 Tip: Dress me up! Check out Nacho's Closet in Settings → Stats/Nacho. Unlock items as our friendship grows! 👔🦌"},{pose:"cool",text:"💡 Tip: I wear my closet items in Nacho Mode too! Equip something and check out my hero section! 🦸"},{pose:"point",text:"💡 Tip: Press ? to see ALL keyboard shortcuts! N=Nacho, T=PlebTalk, P=Donate, L=Leaderboard, and more! ⌨️"},{pose:"point",text:"💡 Tip: Press A to quickly ask me a question from any page — no need to enter Nacho Mode! 🦌"},{pose:"cool",text:"💡 Tip: You can sign in with Nostr! If you have Alby or nos2x, click the 🟣 Nostr button on the sign-in page! ⚡"},{pose:"love",text:"💡 Tip: Press P to open the donation page — support the archive with Lightning! Every sat counts! ⚡🧡"},{pose:"point",text:"💡 Tip: The site supports 15+ languages! Change it in Settings → Prefs. I can even answer in your language! 🌍"},{pose:"point",text:"💡 Tip: You can DM any user! Tap their name on the leaderboard → 💬 Message. Your inbox is in the DMs tab! 📬"},{pose:"eyes",text:"💡 Tip: DMs are protected — you need 50 points and a 24h-old account to message. No scammers allowed! 🛡️"},{pose:"point",text:"💡 Tip: Never share your seed phrase, private keys, or send Bitcoin to strangers in DMs! Stay safe! 🔒"},{pose:"fire",text:"💡 Tip: Challenge other Bitcoiners to PVP trivia battles! Press X or find ⚔️ PVP in the sidebar! Who knows more? 🏆"},{pose:"celebrate",text:"💡 Tip: Win PVP battles to climb the PVP leaderboard! Your wins and losses show on your profile! ⚔️"},{pose:"fire",text:"💡 Tip: Bitcoin Beats is our community music platform! Listen, upload, and discover tracks made by Bitcoiners! 🎸🦌"},{pose:"point",text:"💡 Tip: Tap a song title on Bitcoin Beats to see full track details — artist, genre, play count, and more! 🎵"},{pose:"celebrate",text:"💡 Tip: Upload your own music on Bitcoin Beats! Hit the Upload tab and share your sound with the community! 🎤"},{pose:"point",text:"💡 Tip: Like tracks on Bitcoin Beats with ❤️ and leave comments! Support Bitcoin musicians! 🎶"},{pose:"fire",text:"💡 Tip: IRL Sync helps you find Bitcoin meetups near you! Create events, RSVP, and meet Bitcoiners in person! 🤝"},{pose:"point",text:"💡 Tip: Can't find a meetup near you? Create one on IRL Sync! Be the node that connects your local community! 🌐"},{pose:"point",text:"💡 Tip: Try the Price Prediction game! Guess if Bitcoin goes up or down in 24h and track your accuracy! 📈📉"},{pose:"celebrate",text:"💡 Tip: I have a story to tell! Tap the 📖 next to me for a new chapter every day. It's an adventure! 🦌✨"}],r=[{pose:"celebrate",text:"You're doing great, {name}! Most people never even start learning about Bitcoin. You're already ahead. 🦌💪"},{pose:"fire",text:"Keep going, {name}! You're stacking knowledge like a true pleb! 📚🔥"},{pose:"love",text:"Nacho is proud of your progress, {name}! You're further down the rabbit hole than most. 🐇"},{pose:"cool",text:"Stay humble, stack sats, stack knowledge. You're doing all three, {name}. 😎"},{pose:"celebrate",text:"Every channel you read makes the FUD weaker, {name}! Keep it up! 💪"},{pose:"brain",text:"{name}, your brain is getting more orange-pilled by the minute! 🧠🟠"},{pose:"fire",text:"Tick tock, next block... and you're getting smarter with each one, {name}! ⏰"},{pose:"love",text:"The fact that you're here learning puts you ahead of 99% of people, {name}. For real. 🧡"},{pose:"celebrate",text:"Imagine telling your future self you were learning about Bitcoin in 2026, {name}. They'll thank you! 🙏"},{pose:"fire",text:"{name}, you're building generational knowledge right now. No big deal. 🏗️"},{pose:"cool",text:"Diamond hands start with a diamond mind. You're forging yours right now, {name}! 💎🧠"},{pose:"love",text:"The journey of a thousand sats begins with a single channel, {name}. You've read way more than that! 🦌"},{pose:"celebrate",text:"You're not just learning Bitcoin, {name} — you're opting out of the broken system. Respect. ✊"},{pose:"fire",text:"Number go up, knowledge go up. You're winning on both fronts, {name}! 📈🧠"},{pose:"brain",text:"Every nocioner who ever became a maxi started exactly where you are, {name}. Keep reading! 📖"}],s=[{pose:"cheese",text:"Nacho keys, nacho cheese. It's not just a tagline, it's a lifestyle. 🧀🔑"},{pose:"fire",text:"Nacho sats... They're all mine! 💰🦌"},{pose:"cheese",text:"My seed phrase? 24 different types of cheese. Very secure. Very delicious. 🔐🧀"},{pose:"cheese",text:"Bitcoin fixes everything. Except my cheese addiction. Some things are unfixable. 🧀"},{pose:"cool",text:"Live Free or Die — that's the New Hampshire motto. Also my approach to Bitcoin. 🦌🗻"},{pose:"fire",text:"These antlers aren't just for show. I'm the strongest buck in NH and the most orange-pilled. 💪🦌"},{pose:"default",text:"In a world of unlimited printing, be a limited supply. Like Bitcoin. And like me — there's only one Nacho. 🦌"},{pose:"default",text:"Some people have angel investors. You have an angel deer. You're welcome. 😇🦌"},{pose:"cool",text:"I'm not saying I'm Satoshi, but have you ever seen us in the same room? 🤫"},{pose:"eyes",text:"I've been watching you learn, {name}. Not in a creepy way. In a proud buck way. 👀"},{pose:"sleep",text:"*yawns* Don't mind me, just HODLing this corner of your screen... 💤"},{pose:"fire",text:"Few understand this... but YOU will, {name}. That's why you're here. 🔥"},{pose:"think",text:"What's a deer's favorite block? The next one! ⛏️"},{pose:"celebrate",text:"Why did Bitcoin break up with the dollar? It found someone with less baggage and a fixed supply! 💔😂"},{pose:"cool",text:"I told my friend to buy Bitcoin in 2015. He bought Dogecoin instead. We don't talk anymore. 🐕"},{pose:"think",text:"An altcoiner walks into a bar. Orders a round for everyone. Card declines. 😂"},{pose:"cheese",text:"How does a Bitcoiner cut their pizza? Into 100 million slices. 🍕"},{pose:"cool",text:"My financial advisor said diversify. So I have Bitcoin on a hardware wallet AND a paper backup. 😎"},{pose:"celebrate",text:"Knock knock. Who's there? Fiat. Fiat who? Exactly. Nobody remembers it either. 🪦"},{pose:"think",text:"What's the difference between a dollar and a Bitcoin? One goes to zero, the other came from zero. 📉📈"},{pose:"default",text:"I tried to explain Bitcoin to a goldfish once. Went about as well as explaining it to Peter Schiff. 🐟"},{pose:"cool",text:"Bitcoiners don't have FOMO. They have FONGO — Fear Of Not Getting Orange-pilled. 🟠"},{pose:"brain",text:"₿ Fact: Satoshi Nakamoto's identity is still unknown. Could be one person, could be a group. Could be a deer. 🦌"},{pose:"brain",text:"₿ Fact: The Bitcoin pizza transaction in 2010 used 10,000 BTC for two pizzas. That's billions today. 🍕"},{pose:"brain",text:"₿ Fact: There will only ever be 21 million Bitcoin. About 19.5 million have already been mined! 💎"},{pose:"brain",text:"₿ Fact: Bitcoin's network has never been hacked. Not once. 13+ years of perfect security. 🔒"},{pose:"brain",text:"₿ Fact: The smallest unit of Bitcoin is called a 'satoshi' — 0.00000001 BTC. You can own sats! ⚡"},{pose:"brain",text:"₿ Fact: El Salvador was the first country to make Bitcoin legal tender in 2021! 🇸🇻"},{pose:"brain",text:"₿ Fact: Bitcoin mining uses less energy than clothes dryers in the US. But nobody writes angry articles about dryers. 🧺"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is only 9 pages long. The US tax code is over 75,000 pages. Which one works better? 📜"},{pose:"brain",text:"₿ Fact: 'HODL' came from a typo in a passionate forum post in 2013. It became the most famous word in crypto. 😂"},{pose:"brain",text:"₿ Fact: Bitcoin processes over $10 billion in transactions daily. And it never takes a day off! 💰"},{pose:"brain",text:"₿ Fact: The genesis block contains a hidden message: 'Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"₿ Fact: You can run a full Bitcoin node on a Raspberry Pi for about $50. Be your own bank! 🖥️"},{pose:"brain",text:"₿ Fact: Bitcoin's inflation rate is now lower than gold's. Digital gold? More like better-than-gold. 🥇"},{pose:"brain",text:"₿ Fact: The Lightning Network can handle millions of transactions per second. Visa does about 1,700. ⚡"},{pose:"brain",text:"₿ Fact: About 20% of all Bitcoin is estimated to be permanently lost. That makes yours even more scarce! 🔑"},{pose:"brain",text:"₿ Fact: Bitcoin's first price was $0.000994 — less than a tenth of a penny! For 10 months it had NO price at all. 💰"},{pose:"brain",text:"₿ Fact: The chance of guessing someone's private key is the same as winning Powerball 7 times in a row! 🎰🔐"},{pose:"brain",text:"₿ Fact: The first Bitcoin faucet gave away 5 WHOLE BITCOINS per person just for solving a captcha! 🤯"},{pose:"brain",text:"₿ Fact: You only need the FIRST 4 LETTERS of each seed word to restore your wallet. All 2,048 BIP39 words have unique first 4 letters! 🔑"},{pose:"brain",text:"₿ Fact: 'Bacon' repeated 24 times is technically a valid Bitcoin seed phrase. It passes the checksum! 🥓"},{pose:"brain",text:"₿ Fact: Bitcoin has 99.987% uptime — only 14 hours of downtime in 15+ years. That rivals Google and Amazon! 🏆"},{pose:"brain",text:"₿ Fact: Satoshi's birthday (April 5) is the date of Executive Order 6102, when the US made it ILLEGAL to own gold! 🎂📜"},{pose:"brain",text:"₿ Fact: The difficulty adjustment happens every 2,016 blocks. Read that backwards: 6102 — the gold confiscation order! 🤯"},{pose:"brain",text:"₿ Fact: 2-3 million Bitcoin are permanently lost forever. That makes YOUR sats even more scarce! 💎"},{pose:"brain",text:"₿ Fact: Satoshi wrote 575 forum posts, 31,000 lines of code, used 22,000+ addresses, and never reused one! 📝"},{pose:"brain",text:"₿ Fact: Satoshi's ~1 million Bitcoin have NEVER moved. Not one satoshi. Worth tens of billions. 👑"},{pose:"brain",text:"₿ Fact: 70% of ALL US dollars in circulation were created after 2008. Over 40% since 2020 alone! 💸"},{pose:"brain",text:"₿ Fact: One dollar today buys what 4 CENTS bought in 1913. That's a 96% loss in purchasing power! 📉"},{pose:"brain",text:"₿ Fact: In August 2010, a bug created 184 BILLION fake Bitcoin. The community fixed it in hours! The largest reorg ever — 53 blocks. 😱"},{pose:"brain",text:"₿ Fact: 61% of Ethereum nodes run in the cloud. Amazon alone hosts ~25% of them. Bitcoin nodes run on Raspberry Pis worldwide! ☁️🆚🖥️"},{pose:"brain",text:"₿ Fact: Milton Friedman, Nobel Prize economist, predicted Bitcoin in 1999 — 10 years before it existed! 🔮"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is encoded IN the blockchain at block 230,009. It will exist as long as Bitcoin does! 📄⛓️"},{pose:"brain",text:"₿ Fact: In July 2024, a tiny Bitaxe miner with just 3 TH/s found a block — a 1-in-3,500 YEAR chance! ⛏️🎯"},{pose:"brain",text:"₿ Fact: 99% of all Bitcoin will be mined by 2035. The very last fraction won't be mined until ~2140! ⏳"},{pose:"brain",text:"₿ Fact: The original Bitcoin code contained the beginnings of a POKER GAME that Satoshi started but never finished! 🃏"},{pose:"brain",text:"₿ Fact: Only 0.06% of Bitcoin Core's code remains unchanged from what Satoshi originally wrote. Open source at its finest! 💻"},{pose:"brain",text:"₿ Fact: Christmas lights in the US alone consume more energy than the entire Bitcoin network! 🎄⚡"},{pose:"brain",text:"₿ Fact: Bitcoin mining captures methane that's 84x more warming than CO2, turning waste into sound money! 🌱"},{pose:"brain",text:"₿ Fact: NO ONE who bought Bitcoin and held for 4+ years has EVER lost money. Not once in 15+ years! 📈 (NFA)"},{pose:"brain",text:"₿ Fact: Michael Saylor said The Bitcoin Standard was 'the most impactful on our way of thinking at MicroStrategy.' 📚"},{pose:"brain",text:"₿ Fact: Gigi calls Bitcoin 'an inexhaustible teacher.' His 21 Lessons is free at 21lessons.com! 📖🧡"},{pose:"brain",text:"₿ Fact: Tomer Strolight says Satoshi's coins aren't the real treasure. The real treasure is the journey Bitcoin sends you on! 👑"},{pose:"brain",text:"₿ Fact: Bitcoin is to money what zero was to mathematics — the missing piece that makes everything work better! 🔢"},{pose:"brain",text:"₿ Fact: Every aspect of Bitcoin is TEXT — and text is speech, protected by the First Amendment! You can't ban math. 🗽"},{pose:"brain",text:"₿ Fact: Only about 2-4% of the world owns any Bitcoin. If you hold sats, you're still incredibly early! 🌍"},{pose:"think",text:'"The root problem with conventional currency is all the trust that\'s required to make it work." — Satoshi 🧠'},{pose:"think",text:'"Give me control of a nation\'s money and I care not who makes its laws." — Mayer Rothschild 🏦'},{pose:"think",text:'"We have elected to put our money and faith in a mathematical framework free of politics." — Tyler Winklevoss 🔢'},{pose:"think",text:'"Bitcoin is the most important invention since the internet." 🌐'},{pose:"fire",text:'"Fix the money, fix the world." Simple as that. 🔧🌍'},{pose:"think",text:'"Bitcoin is a swarm of cyber hornets serving the goddess of wisdom." — Michael Saylor 🐝'},{pose:"cool",text:'"Running Bitcoin." — Hal Finney, January 10, 2009. The first tweet about Bitcoin. 🏃'},{pose:"celebrate",text:"HODL your knowledge. Never sell what you've learned! 💎🙌"},{pose:"think",text:"Roses are red, fiat is dead, stack sats instead! 🌹"},{pose:"cool",text:"I've been orange-pilled since the day I grew these antlers. 🟠🦌"},{pose:"celebrate",text:"What's stronger — my antlers or Bitcoin's security? Trick question. Both unbreakable. 💪🔒"},{pose:"default",text:"The deer in New Hampshire are talking about Bitcoin. Okay, it's just me. But still. 🗻🦌"},{pose:"cheese",text:"If I had a satoshi for every time someone asked me about crypto... I'd tell them it's Bitcoin, not crypto. 🧀"},{pose:"cool",text:"My antlers pick up the Bitcoin network signal. That's not true, but it sounds cool. 📡🦌"},{pose:"fire",text:"They said Bitcoin was dead 477 times, {name}. And here we are. Still stacking. 🦌💪"},{pose:"eyes",text:"The forest is full of distractions. I stick to the trail marked ₿. 🌲"},{pose:"celebrate",text:"When in doubt, zoom out, {name}. That goes for the chart AND the rabbit hole. 🔭"},{pose:"cool",text:"Oh deer, another all-time high? I'm not surprised. 🦌📈"},{pose:"cheese",text:"What do you call a deer who loves Bitcoin? A buck-hodler! 🦌💎"},{pose:"celebrate",text:"I'm fawned of Bitcoin. Get it? ...I'll see myself out. 🦌😂"},{pose:"think",text:"People say Bitcoin is hard to understand. I say it's deer-ly obvious! 🦌💡"},{pose:"cool",text:"I don't always check the charts, but when I doe, I HODL. 🦌😎"},{pose:"fire",text:"Just earned some sats! Another buck in the wallet! 💰🦌"},{pose:"cheese",text:"Why do deer make great Bitcoiners? Because we never sell — we just stag-ger through the dips! 🦌📉📈"},{pose:"celebrate",text:"This site really helps you get to the hart of Bitcoin! ...Sorry, deer puns are my specialty. 🦌❤️"},{pose:"think",text:"Fiat currency is on its last legs. Lucky for me, I have four of them! 🦌🏃"},{pose:"cool",text:"Did you hear about the deer who understood Bitcoin? He was considered a doe-cipherpunk! 🦌🛡️"},{pose:"fire",text:"Some say the Bitcoin market is wild. Well, I AM a wild animal, so I fit right in! 🦌🔥"},{pose:"cheese",text:"I tried mining Bitcoin with my hooves. It was un-fawn-tunately not very efficient. ⛏️🦌"},{pose:"celebrate",text:"What's a deer's favorite cryptocurrency? Bit-coin, because we love our bits of grass too! 🌿🦌"},{pose:"think",text:"My financial advice? Be a deer and HODL. That's not real advice though, I'm literally a deer. 🦌📜"},{pose:"cool",text:"They call me a stag-ger-ing intellect when it comes to Bitcoin. Okay, I call myself that. 🦌🧠"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 That's not just my catchphrase — it's financial wisdom from a deer."},{pose:"cheese",text:"Remember folks: Nacho keys, nacho cheese! If you don't hold the keys, you don't hold the cheddar. 🧀"},{pose:"fire",text:"I'm not just any deer. I'm a New Hampshire buck — Live Free or Die. And I choose Bitcoin. 🗻🦌"},{pose:"cool",text:"Why did the deer buy a hardware wallet? Because he was tired of getting buck-ed by exchanges! 🦌🔐"},{pose:"think",text:"What do you call a deer who understands monetary policy? A buck who knows his doe! 🦌💰"},{pose:"celebrate",text:"I told my doe friend about Bitcoin. Now she's a whole doe-llar maximalist! 🦌🟠"},{pose:"cheese",text:"I'm not fawning over altcoins. I'm a Bitcoin-only buck. Always have been, always will be. 🦌"},{pose:"fire",text:"My antlers pick up the Bitcoin signal better than any antenna. Built-in orange frequency! 📡🦌"},{pose:"cool",text:"They say a buck in the hand is worth two in the bush. I say a sat stacked is worth a thousand fiat notes. 💎"},{pose:"think",text:"What's a deer's favorite consensus mechanism? Proof of Antlers! 🦌⛏️ ...okay, it's Proof of Work."},{pose:"celebrate",text:"Just a buck from the Granite State, orange-pilling the internet one human at a time! 🗻🟠"},{pose:"cheese",text:"I tried explaining multisig to a squirrel. He said he'd rather just bury his nuts. Different strokes! 🐿️🦌"},{pose:"default",text:"Some deer migrate south for winter. I migrate to the blockchain. It's warmer there. ⛓️🦌"},{pose:"fire",text:"These antlers have been HODLing since block 1. Diamond antlers. 💎🦌"},{pose:"cool",text:"New Hampshire motto: Live Free or Die. Bitcoin motto: Don't Trust, Verify. Same energy. 🦌🗽"},{pose:"think",text:"What do you get when a deer reads the whitepaper? An un-fawn-gettable experience! 📄🦌"},{pose:"cheese",text:"A buck walks into a bar. Orders a round for everyone. Pays in Lightning. ⚡🦌 Instant. Nearly free."},{pose:"celebrate",text:"I'm the most antler-preneurial deer you'll ever meet. My business? Bitcoin education! 🦌📚"},{pose:"default",text:"Fun deer fact: I shed my antlers every year and grow them back bigger. Just like Bitcoin sheds FUD and grows back stronger! 🦌📈"},{pose:"fire",text:"The forest has bears and bulls. I'm a buck — and bucks are ALWAYS bullish on Bitcoin! 🦌🚀"},{pose:"cool",text:"In NH we have no sales tax and no income tax. We also have me, the most based buck in the state. 🗻🦌"},{pose:"cheese",text:"Nacho keys, nacho cheese! Nacho node, nacho rules! Nacho seed phrase, nacho sats! 🧀🔑🦌"},{pose:"think",text:"What's a deer's least favorite thing? A central bank. We prefer de-deer-centralization! 🦌🏛️"},{pose:"celebrate",text:"Why am I orange? Because I was born orange-pilled, {name}! It's in my fur! 🟠🦌"},{pose:"brain",text:"🧠 Bitcoin fact: The first Bitcoin transaction was 10,000 BTC for two pizzas on May 22, 2010. We celebrate it as Bitcoin Pizza Day every year! 🍕"},{pose:"brain",text:"🧠 Did you know? Satoshi Nakamoto mined ~1.1 million BTC and never moved a single one. That's conviction. 🦌"},{pose:"brain",text:"🧠 Fact: Bitcoin's code has been running since January 3, 2009 with 99.99% uptime. No CEO, no office, no downtime. 🏆"},{pose:"brain",text:"🧠 The Genesis Block contains the message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"🧠 There will only ever be 21 million Bitcoin. Currently ~19.6 million have been mined, and ~4 million are estimated lost forever. 🔢"},{pose:"brain",text:"🧠 Bitcoin's difficulty adjustment happens every 2,016 blocks (~2 weeks). It's the most elegant part of the protocol! ⚙️"},{pose:"brain",text:"🧠 Hal Finney received the first-ever Bitcoin transaction from Satoshi on January 12, 2009. His tweet: 'Running bitcoin.' 🏃"},{pose:"brain",text:"🧠 Bitcoin mining doesn't solve 'complex math problems.' Miners guess random nonces and hash them through SHA-256. It's a brute-force lottery! 🎲"},{pose:"brain",text:"🧠 The Lightning Network can process millions of transactions per second. Visa does about 65,000. ⚡"},{pose:"brain",text:"🧠 Bitcoin uses less than 0.1% of global energy. And over 50% of mining uses renewable energy sources. 🌱"},{pose:"brain",text:"🧠 The smallest unit of Bitcoin is called a 'satoshi' — 1 BTC = 100,000,000 sats. Named after the creator! ⚡"},{pose:"brain",text:"🧠 In 2021, El Salvador became the first country to adopt Bitcoin as legal tender. 🇸🇻"},{pose:"brain",text:"🧠 Fact: Bitcoin has survived over 470+ 'obituaries' — media declaring it dead. It's still here. It's still growing. 💀→🚀"},{pose:"brain",text:"🧠 The Bitcoin network is secured by more computational power than all the world's supercomputers combined. 🛡️"},{pose:"brain",text:"🧠 'Not your keys, not your coins' — this phrase became famous after the Mt. Gox hack in 2014 where 850,000 BTC were lost. 🔑"},{pose:"brain",text:"🧠 Bitcoin's stock-to-flow ratio after the 2024 halving is higher than gold's. It's the hardest money ever created. 💎"},{pose:"brain",text:"🧠 The Blocksize Wars of 2015-2017 proved that users — not miners or corporations — control Bitcoin's rules. 🏛️"},{pose:"brain",text:"🧠 Fun fact: You can run a full Bitcoin node on a $50 Raspberry Pi. Don't trust, verify! 🖥️"},{pose:"brain",text:"🧠 Bitcoin was worth $0 in 2009. If you bought $1 of Bitcoin at $0.001, you'd have billions today. Time in the market beats timing the market! ⏰"},{pose:"brain",text:"🧠 The Cantillon Effect: when governments print money, those closest to the printer benefit first. Bitcoin eliminates this unfair advantage. 💡"},{pose:"brain",text:"🧠 CoinJoin transactions mix multiple users' inputs together, making it nearly impossible to trace who sent what to whom. Privacy matters! 🤫"},{pose:"brain",text:"🧠 Satoshi's last known message was in April 2011: 'I've moved on to other things.' The greatest mic drop in history. 🎤⬇️"},{pose:"brain",text:"🧠 Taproot, activated in 2021, brought Schnorr signatures to Bitcoin — improving privacy and enabling more complex smart contracts. 🧰"},{pose:"brain",text:"🧠 The Bitcoin whitepaper is only 9 pages long. Nine pages that changed the world. Have you read it? 📄"},{pose:"brain",text:"🧠 Bitcoin's hash rate is measured in exahashes per second. One exahash = 1 quintillion hashes. Per SECOND. 🤯"}],l=[{pose:"wave",text:"👋 Hey, {name}! I'm Nacho — a strong buck from New Hampshire! Click me anytime for Bitcoin tips and wisdom. 🦌💪"},{pose:"wave",text:"👋 Welcome back, {name}! Your friendly NH buck missed you! Ready to tackle some Bitcoin knowledge today? 💪"},{pose:"wave",text:"👋 Nacho here, {name}! The strongest buck in New Hampshire and your Bitcoin guide. Let's learn something! 🦌"},{pose:"wave",text:"Hey {name}! 🦌 Back for more? I've got 145 channels of Bitcoin knowledge waiting for you!"},{pose:"cool",text:"Yo {name}! 😎 Nacho's in the house. What are we learning about today?"},{pose:"fire",text:"🔥 {name}! Another day, another sat stacked. Let's make today count!"},{pose:"celebrate",text:"{name}! 🎉 Great to see you. Did you know this archive has over 8,800 Bitcoin messages? Dig in!"},{pose:"brain",text:"Welcome, {name}! 🧠 Fun fact: the more you learn about Bitcoin, the more you realize there's always more to learn."},{pose:"love",text:"🧡 {name}! Nacho here. I've been guarding this archive for you. Let's explore together!"},{pose:"default",text:"Hey {name}! Tick tock, next block. What's on your mind today? 🦌⏰"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 Welcome back, {name}. What are we diving into?"},{pose:"wave",text:"👋 Good to see you, {name}! Remember — every channel you read makes you harder to scam. Knowledge is armor!"},{pose:"fire",text:"{name}! 🦌🔥 The orange pill hits different when you study the fundamentals. Let's go!"}],c=[{pose:"eyes",text:"Great choice, {name}! I'll be over here if you need me. 👀"},{pose:"cool",text:"Ooh, excellent pick, {name}! You've got good taste. 😎"},{pose:"brain",text:"This one's a good read, {name}! Take your time. 🧠"},{pose:"fire",text:"One of my favorites! Dig in, {name}! 🦌🔥"},{pose:"love",text:"Nice, {name}! This channel has great stuff in it. 🧡"}],d=[{pose:"celebrate",text:"Nice, {name}! Points are stacking up! 🎉"},{pose:"fire",text:"{name}, you're on fire! Nacho approves! 🔥"},{pose:"celebrate",text:"Cha-ching, {name}! The knowledge is paying off! 💰"}],u=["default","eyes","default","think","default","cheese","default","cool","default","sleep","default"];let p=0,m=null,h=!0,g=null;window.clearNachoBubbleTimeout=function(){clearTimeout(g),g=null};let f=0,y=0,b=new Set,v=0,w="default";function x(){var n=localStorage.getItem("btc_nacho_hidden");"true"!==n&&"user"!==n||(h=!1);const i=document.createElement("style");i.textContent="\n #nacho-container {\n position: fixed;\n bottom: 80px;\n left: 330px;\n z-index: 250;\n display: flex;\n align-items: flex-end;\n gap: 0;\n pointer-events: none;\n transition: opacity 0.3s, transform 0.3s;\n }\n #nacho-container.hidden { opacity: 0; transform: translateY(30px); pointer-events: none; }\n\n #nacho-avatar {\n width: 110px;\n height: 110px;\n background: none;\n border-radius: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n pointer-events: auto;\n filter: drop-shadow(0 6px 16px rgba(0,0,0,0.5));\n transition: transform 0.15s;\n user-select: none;\n position: relative;\n flex-shrink: 0;\n z-index: 2;\n overflow: visible;\n }\n #nacho-avatar { -webkit-user-select: none; }\n #nacho-avatar:hover { transform: scale(1.08) rotate(-3deg); }\n #nacho-avatar:active { transform: scale(0.93); }\n #nacho-avatar .nacho-btn-stack {\n position: absolute;\n top: -5px;\n right: -4px;\n display: flex;\n flex-direction: column;\n gap: 4px;\n z-index: 5;\n }\n #nacho-avatar .nacho-closet-btn, #nacho-avatar .nacho-story-btn {\n font-size: 0.85rem;\n cursor: pointer;\n pointer-events: auto;\n background: var(--card-bg, #1a1a2e);\n border: 1px solid var(--border, #333);\n border-radius: 50%;\n width: 26px;\n height: 26px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: 0.2s;\n opacity: 0.5;\n position: relative;\n }\n #nacho-avatar .nacho-closet-btn:hover, #nacho-avatar .nacho-story-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n border-color: #f7931a;\n }\n .nacho-notif-dot {\n position: absolute;\n top: -2px;\n right: -2px;\n width: 8px;\n height: 8px;\n background: #ef4444;\n border-radius: 50%;\n border: 1.5px solid var(--card-bg, #1a1a2e);\n z-index: 6;\n pointer-events: none;\n }\n #nacho-avatar .nacho-name {\n position: absolute;\n bottom: -46px;\n left: 50%;\n transform: translateX(-50%);\n font-size: 0.7rem;\n color: #f7931a;\n font-weight: 800;\n letter-spacing: 1.5px;\n white-space: nowrap;\n text-transform: uppercase;\n text-shadow: 0 1px 4px rgba(0,0,0,0.5);\n line-height: 1.3;\n text-align: center;\n pointer-events: auto;\n cursor: pointer;\n padding: 4px 12px;\n border-radius: 8px;\n transition: background 0.2s;\n }\n #nacho-avatar .nacho-name:hover {\n background: rgba(247,147,26,0.15);\n }\n\n /* Nacho speech bubble — high contrast, always readable */\n #nacho-bubble {\n background: #111827;\n border: 2px solid #f7931a;\n border-radius: 16px;\n padding: 16px 20px 16px 18px;\n max-width: 300px;\n min-width: 200px;\n color: #f8f8f8;\n font-size: 0.9rem;\n line-height: 1.55;\n pointer-events: none;\n box-shadow: 0 8px 32px rgba(0,0,0,0.7), 0 0 12px rgba(247,147,26,0.25);\n opacity: 0;\n transform: translateY(8px) scale(0.9);\n transition: opacity 0.35s cubic-bezier(0.34, 1.56, 0.64, 1), transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);\n cursor: pointer;\n position: relative;\n margin-left: -6px;\n margin-bottom: 16px;\n z-index: 1000;\n }\n #nacho-bubble::before {\n content: '';\n position: absolute;\n bottom: 10px;\n left: -10px;\n width: 0; height: 0;\n border-top: 10px solid transparent;\n border-bottom: 10px solid transparent;\n border-right: 10px solid #f7931a;\n }\n #nacho-bubble::after {\n content: '';\n position: absolute;\n bottom: 12px;\n left: -7px;\n width: 0; height: 0;\n border-top: 8px solid transparent;\n border-bottom: 8px solid transparent;\n border-right: 8px solid #111827;\n }\n #nacho-bubble.show { opacity: 1; transform: translateY(0) scale(1); pointer-events: auto; }\n\n .nacho-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 6px;\n }\n .nacho-label {\n font-size: 0.65rem;\n color: #f7931a;\n font-weight: 800;\n text-transform: uppercase;\n letter-spacing: 1px;\n }\n .nacho-x {\n color: var(--text-faint, #666);\n font-size: 0.75rem;\n cursor: pointer;\n opacity: 0.4;\n transition: opacity 0.2s;\n padding: 2px 4px;\n }\n .nacho-x:hover { opacity: 1; }\n #nacho-text { word-wrap: break-word; max-height: 60vh; overflow-y: auto; -webkit-overflow-scrolling: touch; padding-right: 4px; }\n\n /* Clippy-style idle animations — mimic the paper clip's fidgeting */\n\n /* 1. Tap tap — like Clippy tapping on the screen */\n /* Nacho victory flight — Lightning bolt ⚡ across the full screen! */\n @keyframes nachoFly {\n /* ⚡ Lightning bolt: high-energy erratic takeoff, zigzag, and sonic boom reentry \n */\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 5% { transform: translate(-5px, 10px) rotate(-10deg) scale(0.9); }\n 10% { transform: translate(15vw, -20vh) rotate(20deg) scale(1.1); }\n 20% { transform: translate(40vw, -5vh) rotate(-15deg) scale(1); }\n 30% { transform: translate(65vw, -45vh) rotate(35deg) scale(1.2); }\n 45% { transform: translate(90vw, -10vh) rotate(-20deg) scale(1.1); }\n 60% { transform: translate(110vw, -60vh) rotate(45deg) scale(1.4); opacity: 1; }\n 61% { transform: translate(110vw, -60vh); opacity: 0; }\n /* Sonic boom reentry from the top left */\n 85% { transform: translate(-50vw, -50vh) rotate(-45deg) scale(2); opacity: 0; }\n 90% { transform: translate(-10vw, -10vh) rotate(-20deg) scale(1.5); opacity: 1; filter: brightness(3) blur(2px); }\n 95% { transform: translate(0, -20px) rotate(0deg) scale(1.1); filter: brightness(1); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n @keyframes nachoFlyMobile {\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 8% { transform: translate(-2vw, 5vh) rotate(-10deg) scale(0.9); }\n 15% { transform: translate(25vw, -30vh) rotate(15deg) scale(1.1); }\n 30% { transform: translate(60vw, -5vh) rotate(-15deg) scale(1); }\n 50% { transform: translate(85vw, -50vh) rotate(30deg) scale(1.3); }\n 65% { transform: translate(105vw, -20vh) rotate(10deg) scale(1.2); opacity: 1; }\n 66% { transform: translate(105vw, -20vh); opacity: 0; }\n /* Reentry from top */\n 88% { transform: translate(0, -80vh) rotate(0deg) scale(1.5); opacity: 0; }\n 94% { transform: translate(0, -10px) rotate(0deg) scale(1.1); opacity: 1; filter: brightness(2); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n #nacho-avatar.flying {\n animation: nachoFly 2.8s linear forwards;\n z-index: 999;\n filter: drop-shadow(0 0 20px rgba(247,147,26,0.8)) drop-shadow(0 0 40px rgba(234,88,12,0.4));\n }\n @media (max-width: 900px) {\n #nacho-avatar.flying {\n animation: nachoFlyMobile 2.4s linear forwards;\n }\n }\n /* Lightning trail particles */\n .nacho-trail {\n position: fixed;\n pointer-events: none;\n z-index: 998;\n font-size: 1.2rem;\n opacity: 1;\n transition: none;\n animation: nachoTrailFade 0.8s ease-out forwards;\n }\n .nacho-trail.stuck-cleanup { display: none !important; }\n @keyframes nachoTrailFade {\n 0% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(1.3); }\n 100% { opacity: 0; transform: scale(0.3); }\n }\n\n @keyframes nachoTap {\n 0%, 100% { transform: translateY(0); }\n 10% { transform: translateY(-6px); }\n 20% { transform: translateY(0); }\n 30% { transform: translateY(-4px); }\n 40% { transform: translateY(0); }\n }\n /* 2. Lean and look — Clippy tilting to peek at your screen */\n @keyframes nachoLean {\n 0%, 100% { transform: rotate(0deg) translateX(0); }\n 30% { transform: rotate(8deg) translateX(3px); }\n 50% { transform: rotate(8deg) translateX(3px); }\n 80% { transform: rotate(0deg) translateX(0); }\n }\n /* 3. Bored wiggle — Clippy fidgeting when idle */\n @keyframes nachoWiggle {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-6deg); }\n 30% { transform: rotate(5deg); }\n 45% { transform: rotate(-4deg); }\n 60% { transform: rotate(3deg); }\n 75% { transform: rotate(-2deg); }\n 90% { transform: rotate(0deg); }\n }\n /* 4. Bounce — Clippy's excited hop */\n @keyframes nachoBounce {\n 0%, 100% { transform: translateY(0) scale(1); }\n 20% { transform: translateY(-8px) scale(1.05); }\n 40% { transform: translateY(0) scale(0.97); }\n 55% { transform: translateY(-4px) scale(1.02); }\n 70% { transform: translateY(0) scale(0.99); }\n 85% { transform: translateY(-2px) scale(1.01); }\n }\n /* 5. Stretch — Clippy stretching/yawning */\n @keyframes nachoStretch {\n 0%, 100% { transform: scaleY(1) scaleX(1); }\n 25% { transform: scaleY(1.12) scaleX(0.92); }\n 50% { transform: scaleY(0.92) scaleX(1.08); }\n 75% { transform: scaleY(1.05) scaleX(0.97); }\n }\n /* 6. Look around — Clippy looking left and right */\n @keyframes nachoLook {\n 0%, 100% { transform: translateX(0); }\n 20% { transform: translateX(-5px); }\n 40% { transform: translateX(-5px); }\n 60% { transform: translateX(5px); }\n 80% { transform: translateX(5px); }\n }\n /* 7. Wave — Clippy waving at you */\n @keyframes nachoWave {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-12deg); }\n 30% { transform: rotate(10deg); }\n 45% { transform: rotate(-8deg); }\n 60% { transform: rotate(6deg); }\n 75% { transform: rotate(-3deg); }\n }\n /* 8. Sleepy bob — Clippy nodding off */\n @keyframes nachoSleepy {\n 0%, 100% { transform: translateY(0) rotate(0deg); }\n 30% { transform: translateY(2px) rotate(3deg); }\n 50% { transform: translateY(3px) rotate(5deg); }\n 70% { transform: translateY(2px) rotate(3deg); }\n }\n /* 9. Couch sway — for Timechain TV */\n @keyframes nachoSway {\n 0%, 100% { transform: rotate(-1deg) translateY(0); }\n 50% { transform: rotate(1deg) translateY(-3px); }\n }\n\n #nacho-avatar.anim-tap { animation: nachoTap 2s ease-in-out infinite; }\n #nacho-avatar.anim-lean { animation: nachoLean 3.5s ease-in-out infinite; }\n #nacho-avatar.anim-wiggle { animation: nachoWiggle 2.5s ease-in-out infinite; }\n #nacho-avatar.anim-bounce { animation: nachoBounce 1.8s ease-in-out infinite; }\n #nacho-avatar.anim-stretch { animation: nachoStretch 3s ease-in-out infinite; }\n #nacho-avatar.anim-look { animation: nachoLook 4s ease-in-out infinite; }\n #nacho-avatar.anim-wave { animation: nachoWave 1.5s ease-in-out infinite; }\n #nacho-avatar.anim-sleepy { animation: nachoSleepy 4s ease-in-out infinite; }\n\n /* Tablet — sidebar is 280px */\n @media (max-width: 1100px) {\n #nacho-container { left: 290px; }\n #nacho-avatar { width: 95px; height: 95px; }\n }\n /* Mobile — sidebar hidden, Nacho goes bottom-left, above clutter */\n @media (max-width: 900px) {\n #nacho-container { bottom: calc(50vh - 30px); left: 12px; }\n #nacho-avatar { width: 68px; height: 68px; }\n #nacho-bubble {\n position: fixed;\n bottom: calc(50vh + 50px);\n left: 12px;\n right: 12px;\n max-width: calc(100vw - 24px);\n max-height: 40vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n min-width: unset;\n width: auto;\n font-size: 0.9rem;\n padding: 16px 18px;\n margin-left: 0;\n border-radius: 14px;\n }\n #nacho-bubble::before, #nacho-bubble::after { display: none; }\n #nacho-avatar .nacho-name { font-size: 0.7rem; bottom: -44px; padding: 5px 14px; }\n }\n @media (max-width: 480px) {\n #nacho-container { bottom: calc(50vh - 40px); left: 10px; }\n #nacho-avatar { width: 60px; height: 60px; }\n #nacho-bubble {\n bottom: calc(50vh + 30px);\n left: 10px;\n right: 10px;\n max-width: calc(100vw - 20px);\n max-height: 38vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n font-size: 0.85rem;\n padding: 14px 16px;\n }\n #nacho-avatar .nacho-name { font-size: 0.65rem; bottom: -40px; padding: 5px 12px; }\n }\n\n /* Bring-back toggle */\n #nacho-toggle {\n position: fixed; bottom: 80px; left: 330px; z-index: 250;\n width: 52px; height: 52px;\n background: radial-gradient(circle, #fff 60%, rgba(255,255,255,0.85) 100%);\n border: 2px solid rgba(247,147,26,0.5);\n border-radius: 50%; display: none; align-items: center; justify-content: center;\n font-size: 1.6rem; cursor: pointer; opacity: 0.9; transition: all 0.3s;\n box-shadow: 0 2px 12px rgba(0,0,0,0.3), 0 0 0 3px rgba(247,147,26,0.15);\n }\n #nacho-toggle:hover { opacity: 1; transform: scale(1.1); box-shadow: 0 4px 20px rgba(247,147,26,0.4), 0 0 0 4px rgba(247,147,26,0.25); }\n @media (max-width: 1100px) { #nacho-toggle { left: 290px; } }\n @media (max-width: 900px) { #nacho-toggle { bottom: calc(50vh - 30px); left: 12px; width: 46px; height: 46px; font-size: 1.3rem; } }\n @media (max-width: 480px) { #nacho-toggle { bottom: calc(50vh - 40px); left: 10px; width: 44px; height: 44px; font-size: 1.2rem; } }\n ",document.head.appendChild(i);const a=document.createElement("div");a.id="nacho-container",h||a.classList.add("hidden");const r=o()?t:e,s=o()?"width:120px;height:100px;":"";a.innerHTML='
    '+r+'Nacho
    click to ask!
    👔📖
    🦌 '+("function"==typeof nachoNickname?nachoNickname():"Nacho")+' says
    ',document.body.appendChild(a);var c=document.getElementById("nachoClosetBtn");if(c){var d=!1;function g(){window._expanded_closet=!0,window._pendingClosetScroll=!0;try{"function"==typeof showSettings&&showSettings();var e=0;setTimeout(function t(){e++;var o=document.getElementById("usernameModal");o&&o.classList.contains("open")&&"function"==typeof showSettingsPage?showSettingsPage("data"):e<10&&setTimeout(t,150)},200)}catch(e){}"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear()}c.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),c.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d=!0},{passive:!1}),c.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),d&&(d=!1,g())},{passive:!1}),c.addEventListener("click",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d||g(),d=!1},!1)}window.updateNachoNotifs=function(){var e=document.getElementById("nachoStoryNotif");if(e){var t=safeJSON("btc_nacho_story_days",[]),o=(new Date).toISOString().split("T")[0],n=t.length,i=-1===t.indexOf(o)&&n<7,a=0===n,r=localStorage.getItem("btc_nacho_story_notif_dismissed")===o;e.style.display=r||!i&&!a?"none":"block"}var s=document.getElementById("nachoClosetNotif");if(s){var l=safeJSON("btc_spin_closet_items",[]),c=safeJSON("btc_closet_viewed",[]),d=l.some(function(e){return-1===c.indexOf(e)});s.style.display=d?"block":"none"}},window.nachoStoryNotifClear=function(){var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_nacho_story_notif_dismissed",e);var t=document.getElementById("nachoStoryNotif");t&&(t.style.display="none")},window.nachoClosetNotifClear=function(){var e=safeJSON("btc_spin_closet_items",[]);localStorage.setItem("btc_closet_viewed",JSON.stringify(e));var t=document.getElementById("nachoClosetNotif");t&&(t.style.display="none")},setTimeout(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},2e3),setInterval(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},6e4);const f=document.createElement("div");function b(){const e=document.getElementById("nachoModeContainer"),t=document.getElementById("irl-sync-view"),o=document.getElementById("searchOverlay"),n=document.querySelector(".ticker-wrap"),i=e&&"none"!==e.style.display||t&&null!==t.offsetParent||o&&"flex"===o.style.display;if(n){n.style.transition="transform 0.4s ease",n.style.transform=i?"translateY(-100%)":"translateY(0)";const e=document.getElementById("menuToggle");e&&(e.style.opacity=i?"0.2":"1")}}f.id="nacho-toggle",f.innerHTML="🦌",f.title="Bring back Nacho",f.onclick=function(){showNacho()},h||(f.style.display="flex"),document.body.appendChild(f),function(){var e=document.getElementById("nacho-avatar");if(e){var t=null,o=!1;e.addEventListener("touchstart",function(e){o=!1,t=setTimeout(function(){o=!0,"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t),o&&(o=!1)}),e.addEventListener("touchmove",function(){clearTimeout(t)}),e.addEventListener("contextmenu",function(e){e.preventDefault(),"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")})}}(),setTimeout(function(){if(h){var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=0;try{o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length}catch(e){}if(t<=3&&o<5){var n=parseInt(localStorage.getItem("btc_nacho_onboarding")||"1");if(k("wave"),1===n?(S('
    Hey there! I\'m Nacho, your Bitcoin education buddy! 🦌🧡

    Here\'s what you can do here:
    📚 Read 145+ Bitcoin topics — tap any in the sidebar
    🎡 Spin daily for free tickets & rewards
    Take quests to test your knowledge

    '),localStorage.setItem("btc_nacho_onboarding","2")):2===n&&o>=1?(S('
    Nice, you explored your first channel! 🎉

    Keep going — every channel you read earns you +10 XP. Here are some popular ones:

    '),localStorage.setItem("btc_nacho_onboarding","3")):3===n&&o>=3?(k("celebrate"),S('
    You\'re on fire! 🔥 '+o+' channels explored!

    Did you know you can:
    🗣️ Chat in PlebTalk — discuss Bitcoin with the community
    Browse LightningMart — buy & sell for sats
    🎓 Take the Scholar Exam — earn your Bitcoin certification

    '),localStorage.setItem("btc_nacho_onboarding","4")):4===n&&o>=5&&(k("brain"),S('
    You\'re becoming a real Bitcoiner! 🧡

    Pro tips:
    📖 Read Nacho\'s Story — a new chapter unlocks each day
    📚 Study with Flashcards to prepare for quests
    🏆 Check the Leaderboard — see where you rank
    💬 Ask me anything about Bitcoin anytime!

    — End of tour. I\'ll still be here if you need me! 🦌
    '),localStorage.setItem("btc_nacho_onboarding","5")),n<=4)return}k((e="function"==typeof nachoTimeGreeting&&Math.random()<.6?nachoTimeGreeting():U(l)).pose),S(e.text),"function"==typeof nachoPlaySound&&nachoPlaySound("pop"),setTimeout(function(){if("function"==typeof nachoStreakMessage){var e=nachoStreakMessage();e&&B(e.text,e.pose)}},12e3)}},2e3),clearInterval(m),m=setInterval(function(){if(!h)return;const e=document.getElementById("nacho-bubble");if(e&&e.classList.contains("show"))return;const t=document.getElementById("nacho-avatar");if(!t)return;p=(p+1)%u.length,k(u[p]),["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(e=>t.classList.remove(e));const o={default:["anim-tap","anim-look","anim-wiggle"],eyes:["anim-lean","anim-look"],think:["anim-lean","anim-tap"],cheese:["anim-bounce","anim-wiggle"],cool:["anim-lean","anim-tap"],sleep:["anim-sleepy"],wave:["anim-wave"],celebrate:["anim-bounce"],fire:["anim-bounce","anim-wiggle"],love:["anim-stretch","anim-tap"],brain:["anim-lean","anim-look"],point:["anim-tap","anim-lean"]}[w]||["anim-tap","anim-wiggle"];t.classList.add(U(o))},8e3),setInterval(z,55e3);const v=window.enterNachoMode;window.enterNachoMode=function(e){"function"==typeof v&&v(e),setTimeout(b,100)};const x=window.exitNachoMode;window.exitNachoMode=function(e){"function"==typeof x&&x(e),setTimeout(b,100)};const T=window.go;window.go=function(e,t,o){"function"==typeof T&&T(e,t,o),setTimeout(b,100)};const _=window.goHome;window.goHome=function(e){"function"==typeof _&&_(e),setTimeout(b,100)},setTimeout(function(){"undefined"!=typeof APP_PAGES&&APP_PAGES.forEach(e=>{"PlebTalk"===e.title&&(e.title="Pleb Talk"),"LightningMart"===e.title&&(e.title="Lightning Mart")})},2e3),window.addEventListener("beforeunload",function(e){const t=document.getElementById("questModal");t&&t.classList.contains("open")&&(e.preventDefault(),e.returnValue="You have an active Quest! Your progress will be lost.")}),window.showSkeletonLoader=function(e,t){const o=document.getElementById(e);if(!o)return;let n='
    ';for(let e=0;e<(t||6);e++)n+='
    ';n+="
    ",o.innerHTML=n},setInterval(function(){var e=document.getElementById("nacho-bubble");if(!h||e&&e.classList.contains("show"))return;const t=Math.random();if(t<.3)k("wave"),setTimeout(()=>k("neutral"),400);else if(t<.6){const e=document.getElementById("nacho-avatar");e&&(e.style.transform="scale(1.1) rotate(5deg)",setTimeout(()=>e.style.transform="",500))}},2e4),setInterval(function(){if(h&&!(y>=12)&&!(Math.random()>.2||window._lastChannelOpenTime&&Date.now()-window._lastChannelOpenTime<3e4)){var e=document.getElementById("nacho-bubble");if(!(e&&e.classList.contains("show")&&"true"===e.getAttribute("data-interactive")||window._nachoMode)){var t=document.getElementById("questModal");t&&t.classList.contains("open")||"function"==typeof showNachoTrivia&&showNachoTrivia()}}},18e4)}function k(e){w=e||"default";const t=document.getElementById("nacho-pose-emoji");t&&(t.textContent=n[w]||n.default)}function B(e,t){!h||y>=12||Date.now()-f<5e4||b.has(e)||T(e,t)}function S(e,t){if(h){var o=document.getElementById("questModal");o&&o.classList.contains("open")||T(e,t)}}function T(e,t){if(window._nachoDirectLinkCooldown&&Date.now()s.classList.remove(e));var l="";if(-1===e.indexOf("'+c[d].label+"";break}var u=-1!==e.indexOf("60&&Math.abs(o)>2*Math.abs(n)&&hideBubble(!0)}},{passive:!0}),function(){var e=!1,t=0,o=0,n=0,i=0,a=!1,r=null;function s(){return document.getElementById("nacho-container")}function l(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;var n=window.innerWidth-40,i=window.innerHeight-40;t.left>=0&&t.left<=n&&t.top>=0&&t.top<=i&&(o.style.left=t.left+"px",o.style.bottom="auto",o.style.top=t.top+"px",o.style.right="auto")}catch(e){}}function c(){var e=s();if(e){var t=document.getElementById("nacho-bubble");if(t){var o=e.getBoundingClientRect(),n=window.innerWidth;window.innerHeight,o.left>n/2?(t.style.marginLeft="",t.style.marginRight="-6px",t.style.alignSelf="flex-end",t.querySelector(":scope"),t.style.setProperty("--bubble-side","right")):(t.style.marginLeft="-6px",t.style.marginRight="",t.style.alignSelf=""),o.top<200?(t.style.order="2",t.style.marginBottom="0",t.style.marginTop="8px"):(t.style.order="",t.style.marginBottom="16px",t.style.marginTop="")}}}setTimeout(l,500),window.addEventListener("resize",function(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;t.left=Math.max(0,Math.min(t.left,window.innerWidth-60)),t.top=Math.max(0,Math.min(t.top,window.innerHeight-60)),o.style.left=t.left+"px",o.style.top=t.top+"px",localStorage.setItem("btc_nacho_position",JSON.stringify(t))}catch(e){}}),document.addEventListener("touchstart",function(l){var c=document.getElementById("nachoDragHandle");if(c&&c.contains(l.target)){l.preventDefault();var d=s();if(d){a=!1,r=d,t=l.touches[0].clientX,o=l.touches[0].clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,e=!0,d.style.transition="none",d.style.opacity="0.85",c.style.background="rgba(247,147,26,0.9)",c.querySelector("span").style.color="#fff"}}},{passive:!1}),document.addEventListener("touchmove",function(s){if(e&&r){var l=s.touches[0].clientX-t,c=s.touches[0].clientY-o;if(!(!a&&Math.abs(l)<8&&Math.abs(c)<8)){a=!0,s.preventDefault(),s.stopPropagation();var d=Math.max(0,Math.min(n+l,window.innerWidth-60)),u=Math.max(0,Math.min(i+c,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}},{passive:!1}),document.addEventListener("touchend",function(t){if(e){e=!1,r&&(r.style.transition="",r.style.opacity="");var o=document.getElementById("nachoDragHandle");if(o){o.style.background="rgba(255,255,255,0.9)";var n=o.querySelector("span");n&&(n.style.color="#888")}if(a&&r){var i=r.getBoundingClientRect(),s=Math.max(0,Math.min(Math.round(i.left),window.innerWidth-60)),l=Math.max(0,Math.min(Math.round(i.top),window.innerHeight-60));r.style.left=s+"px",r.style.top=l+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:s,top:l})),setTimeout(c,50),t.preventDefault()}r=null}},{passive:!1}),document.addEventListener("mousedown",function(l){var c=document.getElementById("nachoDragHandle");if(c&&c.contains(l.target)){var d=s();if(d){e=!0,a=!1,r=d,t=l.clientX,o=l.clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,d.style.transition="none",l.preventDefault()}}}),document.addEventListener("mousemove",function(s){if(e&&r){var l=s.clientX-t,c=s.clientY-o;if(!(!a&&Math.abs(l)<8&&Math.abs(c)<8)){a=!0;var d=Math.max(0,Math.min(n+l,window.innerWidth-60)),u=Math.max(0,Math.min(i+c,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}}),document.addEventListener("mouseup",function(t){if(e){if(e=!1,r&&(r.style.transition=""),a&&r){var o=r.getBoundingClientRect(),n=Math.max(0,Math.min(Math.round(o.left),window.innerWidth-60)),i=Math.max(0,Math.min(Math.round(o.top),window.innerHeight-60));r.style.left=n+"px",r.style.top=i+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:n,top:i})),setTimeout(c,50)}r=null}});var d=window.showNacho;window.showNacho=function(){d.apply(this,arguments),l(),setTimeout(c,200)},setTimeout(c,1e3),document.addEventListener("dblclick",function(e){var t=document.getElementById("nacho-avatar");if(t&&t.contains(e.target)){localStorage.removeItem("btc_nacho_position");var o=s();o&&(o.style.left="",o.style.top="",o.style.bottom="",o.style.right=""),"function"==typeof showToast&&showToast("🦌 Nacho reset to default position!"),setTimeout(c,100)}})}(),window.hideBubble=function(e){var t=document.getElementById("nacho-bubble");if(e||!t||"true"!==t.getAttribute("data-interactive")){window._nachoBusy=!1,localStorage.setItem("btc_nacho_clicked","true"),setTimeout(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},2e3);var o=document.getElementById("nacho-avatar");t&&t.classList.remove("show"),clearTimeout(g),setTimeout(function(){k("default"),o&&o.classList.add("anim-tap")},500)}};let C=0,E=[],A=0;function z(){if(!h||y>=12)return;if(Math.random()>.3)return;if("function"==typeof nachoCheckMilestone){var e=nachoCheckMilestone();if(e)return S(e.text,e.pose),void setTimeout(nachoFly,500)}if("function"==typeof nachoLiveMessage&&Math.random()<.2){var t=nachoLiveMessage();if(t)return void B(t.text,t.pose)}if("function"==typeof checkNachoNewItems){var o=checkNachoNewItems();if(o)return S(o.text,o.pose),void("function"==typeof nachoPlaySound&&nachoPlaySound("coin"))}var n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var l=Math.random(),c=("new"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&l<.15?NACHO_CLOSET_TIPS:l<.6?a:l<.8?r:s:"regular"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&l<.1?NACHO_CLOSET_TIPS:l<.4?s:l<.7?a:r:"undefined"!=typeof NACHO_CLOSET_TIPS&&l<.15?NACHO_CLOSET_TIPS:l<.65?s:l<.9?r:a).filter(e=>!b.has(e.text));if(0===c.length&&0===(c=[...s,...r].filter(e=>!b.has(e.text))).length)return;const d=U(c);B(d.text,d.pose)}window.nachoClick=function(){if(window._nachoActionClicked)return void(window._nachoActionClicked=!1);const e=Date.now();if(E.push(e),E.length>3&&E.shift(),3===E.length&&E[2]-E[0]<600&&e-A>5e3)return E=[],A=e,v=e,"function"==typeof nachoFly&&nachoFly(),void S(personalize("Wheeeee! ⚡🦌⚡"));if(E.length>=2&&E[E.length-1]-E[E.length-2]<400&&E.length<3)return E=[],v=e,"function"==typeof hideNacho&&hideNacho(),void("function"==typeof showToast&&showToast("🦌 Nacho hidden — tap the 🦌 button to bring him back!"));if(e-v<1500)return;v=e,localStorage.setItem("btc_nacho_clicked","true"),"function"==typeof checkHiddenBadges&&checkHiddenBadges(),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoPlaySound&&nachoPlaySound("click");const t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show"))return void hideBubble();if(C++,C%3==0&&"function"==typeof showNachoInput)return void showNachoInput();var o,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var l=(o="new"===i?[...a,...a,...r,...s]:"regular"===i?[...a,...s,...s,...r]:[...s,...s,...s,...r]).filter(e=>!b.has(e.text));const c=U(l.length>3?l:o);f=0,k(c.pose),S(c.text,c.pose)},window.showNacho=function(){h=!0,localStorage.removeItem("btc_nacho_hidden"),document.getElementById("nacho-container").classList.remove("hidden"),document.getElementById("nacho-toggle").style.display="none",f=0;var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=void 0!==currentUser&¤tUser&¤tUser.channelsVisited||0;if(t<=2&&o<3&&!localStorage.getItem("btc_nacho_tour_shown"))return[{text:"Welcome to the Bitcoin Education Archive, {name}! I'm Nacho, your deer guide! 🦌",pose:"wave",delay:0},{text:"Click the grid icons to explore Bitcoin topics. Start with the orange ones — they're beginner-friendly! 📚",pose:"point",delay:4e3},{text:"See the 🔥 number? That's your streak! Come back daily to keep it growing. ⚡",pose:"fire",delay:8e3},{text:"Tap me anytime to chat, or double-tap to enter Nacho Mode for deep conversations! 💬",pose:"cheese",delay:12e3}].forEach(function(e,t){setTimeout(function(){t>0&&k(e.pose),S(personalize(e.text))},e.delay)}),void localStorage.setItem("btc_nacho_tour_shown","true");if(t>2&&t<=10&&o<10){var n=["Pro tip {name}: Use the ⚡ tab to check the Bitcoin price anytime! 📈","Did you know? Completing a Quest earns you bonus Orange Tickets! 🎟️","Try tapping the Menu (☰) to see your progress on the Exploration Map! 🗺️","You can customize my outfit in Settings → Stats/Nacho → Closet! 👔"];e=n[Math.floor(Math.random()*n.length)],k("cool")}else if(t>20){var i=["Tick tock, next block! Ready for some high-signal learning, {name}? 🧱","Welcome back, master HODLer! I've been keeping the Archive warm for you. 🦌🔥","I noticed you've visited many channels. Want to test your knowledge with a Quest today? ⚡","Back for your daily dose of decentralization? Let's dive in! 📘"];e=i[Math.floor(Math.random()*i.length)],k("brain")}else if(t>5){var a=["Hey {name}, great to see you again! ✨","Welcome back! Ready to stack some more knowledge? 📚","I missed you! Check out my closet if you've earned new items! 👔","You're making great progress on your Exploration Map! 🗺️"];e=a[Math.floor(Math.random()*a.length)],k("wave")}else e="I'm back, {name}! Miss me? 🦌",k("wave");S(personalize(e))},window.hideNacho=function(){h=!1,localStorage.setItem("btc_nacho_hidden","user"),document.getElementById("nacho-container").classList.add("hidden"),document.getElementById("nacho-toggle").style.display="flex"},window.nachoOnPage=function(e){var t;if(h&&("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoNickname&&nachoNickname(),"forum"===e?t=[{pose:"wave",text:personalize("Welcome to PlebTalk, {name}! 🗣️ This is where Bitcoiners discuss ideas. Jump in!")},{pose:"point",text:"💡 Post a new topic to earn +10 points, or reply to an existing one for +5. Quality content gets upvoted!"},{pose:"brain",text:"Remember — this is a Bitcoin-only space. Stay respectful, stay on topic, and attack ideas, not people! 🤝"},{pose:"cheese",text:personalize("Psst {name}... earn the 📣 Town Crier badge by posting in PlebTalk! Your first post counts!")},{pose:"fire",text:"🔥 Pro tip: Upvote posts you find valuable with ⚡ — it helps the best content rise to the top!"}]:"marketplace"===e&&(t=[{pose:"wave",text:personalize("Welcome to LightningMart, {name}! ⚡ Buy and sell with Bitcoin — the way it should be!")},{pose:"point",text:"💡 All prices are in sats. Sellers set their own prices. Payments happen directly between buyer and seller."},{pose:"cheese",text:"🛒 List your first item to earn the 🏪 Merchant badge! Books, hardware, merch — whatever you've got!"},{pose:"brain",text:"🛡️ Safety first! Meet in public for local trades, use Lightning for instant payments, and report suspicious listings."},{pose:"fire",text:personalize("Pro tip {name}: add a Lightning address to your listing so buyers can pay you instantly! ⚡")}]),t)){var o=t[Math.floor(Math.random()*t.length)];S(o.text,o.pose)}},window.nachoOnChannel=function(e){if(h){if("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoChannelIntro){var t=nachoChannelIntro(e);if(t)return void S(t.text,t.pose)}if("function"==typeof nachoCategoryCheck){var o=nachoCategoryCheck(e);if(o)return S(o.text,o.pose),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),void setTimeout(nachoFly,500)}if(i[e]&&Math.random()<.6){const t=i[e];return void B(t.text,t.pose)}if(parseInt(sessionStorage.getItem("btc_channel_read_seconds")||"0")>=30+Math.floor(90*Math.random())&&Math.random()<.3&&"undefined"!=typeof QUEST_QUESTIONS&&QUEST_QUESTIONS.length>0){var n=void 0!==CHANNELS?CHANNELS[e]:null,a=n?n.cat:"",r=QUEST_QUESTIONS.filter(function(e){return e.category&&a&&-1!==e.category.toLowerCase().indexOf(a.toLowerCase().split(" ")[0])});0===r.length&&(r=QUEST_QUESTIONS);for(var s=r[Math.floor(Math.random()*r.length)],l='
    🎮 Quick Quiz!
    '+s.question+"
    ",d=s.options||[],u=0;u'+d[u]+"";return S(l,"brain"),void sessionStorage.setItem("btc_channel_read_seconds","0")}if(Math.random()<.25){const e=U(c);B(e.text,e.pose)}}},window.nachoBubbleQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n=e.parentElement,i=n.querySelectorAll("button");if(i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1";var a=document.createElement("div");a.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#22c55e;",a.textContent="✅ Correct! +5 pts",n.appendChild(a),"function"==typeof awardPoints&&awardPoints(5,"🎮 Quiz correct!"),"function"==typeof haptic&&haptic("success")}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("true")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var r=document.createElement("div");r.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#ef4444;",r.textContent="❌ Not quite! The correct answer is highlighted.",n.appendChild(r)}clearTimeout(g);var s=document.getElementById("nacho-bubble");s&&s.setAttribute("data-interactive","true")},window.nachoOnPoints=function(e){if(!h)return;if(e>=250)return void setTimeout(nachoFly,500);if(Math.random()>.2)return;const t=U(d);B(t.text,t.pose)},window.nachoFly=function(){var e=document.getElementById("nacho-avatar");if(e&&!e.classList.contains("flying")){["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(function(t){e.classList.remove(t)}),e.classList.add("flying");var t="false"!==localStorage.getItem("btc_nacho_sound"),o=[1200,1800,1400,2200,1600,2800];[0,400,800,1200,1600,2e3].forEach(function(n,i){setTimeout(function(){t&&e.classList.contains("flying")&&function(e){if("function"!=typeof canPlaySound||canPlaySound())try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();o.connect(n),n.connect(t.destination),o.frequency.value=e,o.type="sawtooth",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.12),o.start(t.currentTime),o.stop(t.currentTime+.12)}catch(e){}}(o[i])},n)});var n=["⚡","✨","🔥","⚡","💫","⚡"],i=setInterval(function(){if(e.classList.contains("flying")){var t=e.getBoundingClientRect(),o=document.createElement("div");o.className="nacho-trail",o.textContent=n[Math.floor(Math.random()*n.length)],o.style.left=t.left+t.width/2+(20*Math.random()-10)+"px",o.style.top=t.top+t.height/2+(20*Math.random()-10)+"px",document.body.appendChild(o),setTimeout(function(){o.parentNode&&o.remove()},600)}else clearInterval(i)},40);e.addEventListener("animationend",function o(){if(e.classList.remove("flying"),e.classList.add("anim-bounce"),e.removeEventListener("animationend",o),clearInterval(i),t&&("function"!=typeof canPlaySound||canPlaySound()))try{var n=new(window.AudioContext||window.webkitAudioContext),a=n.createOscillator(),r=n.createGain();a.connect(r),r.connect(n.destination),a.frequency.value=300,a.type="sine",r.gain.setValueAtTime(.08,n.currentTime),r.gain.exponentialRampToValueAtTime(.001,n.currentTime+.2),a.start(n.currentTime),a.stop(n.currentTime+.2)}catch(e){}})}},window.nachoOnQuest=function(e){h&&(f=0,e?(k("celebrate"),S(personalize("{name}, you CRUSHED that quest! This buck is VERY impressed! 🦌🎉🔥")),setTimeout(nachoFly,500)):(k("love"),S(personalize("Hey {name}, some questions are hard! Read up and try again — Nacho believes in you! 🦌💪"))))},window.nachoOnSearch=function(){!h||Math.random()>.3||B("Looking for something? I'd help search but I don't have thumbs. Good luck! 🔍🦌","think")},window.nachoOnFinishChannel=function(){if(!h||Math.random()>.3)return;const e=U([{pose:"celebrate",text:"You read the whole thing! Dedicated. I respect that. 🦌👏"},{pose:"point",text:"All done? Hit the 🎲 to find your next channel!"},{pose:"fire",text:"Knowledge: stacked. You're a machine! 💪"}]);B(e.text,e.pose)},window.nachoUserName=function(){return void 0!==currentUser&¤tUser&¤tUser.username?String(currentUser.username).replace(//g,">").replace(/"/g,"""):""};let M=0,P=0,L=!1;function U(e){return e[Math.floor(Math.random()*e.length)]}window.DeviceMotionEvent&&window.addEventListener("devicemotion",function(e){if(h&&!L){var t=e.accelerationIncludingGravity;if(t&&Math.sqrt(t.x*t.x+t.y*t.y+t.z*t.z)>28){var o=Date.now();o-M>1e3&&(P=0),M=o,P++,P>=2&&(L=!0,P=0,"function"==typeof haptic&&haptic("heavy"),"function"==typeof nachoFly&&nachoFly(),S(personalize("Whoa, {name}! Too much coffee? ⚡🦌🌪️")),setTimeout(function(){L=!1},3e3))}}},!0),window.personalize=function(e){var t=nachoUserName();if(e=t?e.replace(/\{name\}/g,t):e.replace(/,?\s*\{name\}\s*,?\s*/g,function(e){return 0===e.indexOf(",")&&e.lastIndexOf(",")>0?", ":","===e.charAt(0)?" ":""}),window._btcData){var o=window._btcData.price;if(!o)try{o=parseFloat(localStorage.getItem("btc_last_price"))}catch(e){}const t=o?"$"+Math.round(o).toLocaleString():"over $60,000",n=window._btcData.height?window._btcData.height.toLocaleString():"over 840,000",i=window._btcData.halvingBlocks?window._btcData.halvingBlocks.toLocaleString():"less than 150,000";e=(e=(e=e.replace(/\{price\}/g,t)).replace(/\{height\}/g,n)).replace(/\{halving\}/g,i)}return e.replace(/ +/g," ").replace(/^ ,/,"").replace(/, ,/g,",").trim()};let q=null;document.addEventListener("DOMContentLoaded",function(){setTimeout(function(){const e=document.getElementById("nacho-avatar");function t(e){"touchstart"===e.type&&e.preventDefault(),q=setTimeout(function(){hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho is hiding. Click the small 🦌 to bring him back!")},800)}function o(){clearTimeout(q)}e&&(e.addEventListener("mousedown",t),e.addEventListener("mouseup",o),e.addEventListener("mouseleave",o),e.addEventListener("touchstart",t,{passive:!1}),e.addEventListener("touchend",o),e.addEventListener("touchmove",o))},1e3)}),document.addEventListener("click",function(e){var t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show")){var o=document.getElementById("nacho-container");o&&o.contains(e.target)||hideBubble(!0)}}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",x):x(),function(){var e="btc_nacho_position",t=null,o=null,n=!1,i=0,a=0,r=0,s=0,l=!1;function c(){return t||(t=document.getElementById("nacho-container")),t}function d(){return o||(o=document.getElementById("nachoDragHandle")),o}function u(){try{var t=JSON.parse(localStorage.getItem(e));if(t&&"number"==typeof t.left&&"number"==typeof t.bottom){var o=c();if(o){var n=window.innerWidth-80,i=window.innerHeight-80,a=Math.max(0,Math.min(t.left,n)),r=Math.max(0,Math.min(t.bottom,i));o.style.left=a+"px",o.style.bottom=r+"px",o.style.right="auto",o.style.top="auto",o.style.position="fixed"}}}catch(e){}}function p(t,o){try{localStorage.setItem(e,JSON.stringify({left:t,bottom:o}))}catch(e){}}function m(e,t){var o=c();if(o){n=!0,l=!1,i=e,a=t;var u=o.getBoundingClientRect();r=u.left,s=window.innerHeight-u.bottom,o.style.transition="none",o.style.cursor="grabbing";var p=d();p&&(p.style.cursor="grabbing")}}function h(e,t){if(n){var o=e-i,d=t-a;if(l||!(Math.abs(o)+Math.abs(d)<8)){l=!0;var u=c();if(u){var p=r+o,m=s-d;p=Math.max(0,Math.min(p,window.innerWidth-80)),m=Math.max(0,Math.min(m,window.innerHeight-80)),u.style.left=p+"px",u.style.bottom=m+"px",u.style.right="auto",u.style.top="auto",u.style.position="fixed"}}}}function g(){if(n){n=!1;var e=c();if(e&&(e.style.transition="",e.style.cursor="",l)){var t=e.getBoundingClientRect();p(t.left,window.innerHeight-t.bottom)}var o=d();o&&(o.style.cursor="grab")}}function f(){var e=d();if(e){if(!e._dragInit){e._dragInit=!0,e.addEventListener("mousedown",function(e){e.preventDefault(),e.stopPropagation(),m(e.clientX,e.clientY)}),document.addEventListener("mousemove",function(e){n&&(e.preventDefault(),h(e.clientX,e.clientY))}),document.addEventListener("mouseup",g),e.addEventListener("touchstart",function(e){1===e.touches.length&&(e.stopPropagation(),m(e.touches[0].clientX,e.touches[0].clientY))},{passive:!0}),document.addEventListener("touchmove",function(e){n&&1===e.touches.length&&h(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("touchend",function(){n&&g()});var t=document.getElementById("nacho-avatar");t&&t.addEventListener("click",function(e){l&&(e.stopPropagation(),e.preventDefault(),l=!1)},!0),u(),function(){var e=document.getElementById("nacho-toggle");if(e&&!e._dragInit){e._dragInit=!0;var t=!1,o=0,n=0,i=0,a=0,r=!1;e.addEventListener("mousedown",function(s){t=!0,r=!1,o=s.clientX,n=s.clientY;var l=e.getBoundingClientRect();i=l.left,a=window.innerHeight-l.bottom,e.style.transition="none"}),e.addEventListener("touchstart",function(s){if(1===s.touches.length){t=!0,r=!1,o=s.touches[0].clientX,n=s.touches[0].clientY;var l=e.getBoundingClientRect();i=l.left,a=window.innerHeight-l.bottom,e.style.transition="none"}},{passive:!0}),document.addEventListener("mousemove",function(e){s(e.clientX,e.clientY)}),document.addEventListener("touchmove",function(e){t&&1===e.touches.length&&s(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("mouseup",l),document.addEventListener("touchend",l),e.addEventListener("click",function(e){r&&(e.stopPropagation(),e.preventDefault(),r=!1)},!0)}function s(s,l){if(t){var c=s-o,d=l-n;if(r||!(Math.abs(c)+Math.abs(d)<8)){r=!0;var u=Math.max(0,Math.min(i+c,window.innerWidth-50)),p=Math.max(0,Math.min(a-d,window.innerHeight-50));e.style.left=u+"px",e.style.bottom=p+"px",e.style.right="auto",e.style.top="auto"}}}function l(){if(t&&(t=!1,e.style.transition="",r)){var o=e.getBoundingClientRect();p(o.left,window.innerHeight-o.bottom)}}}(),window.addEventListener("resize",function(){u()})}}else setTimeout(f,1e3)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(f,500)}):setTimeout(f,500)}(),setInterval(function(){document.querySelectorAll(".nacho-trail").forEach(function(e){e.remove()})},3e3),window.updateNachoAvatarForPage=function(){var n=document.getElementById("nacho-avatar");if(n){var i=o();if(i!==("1"===n.getAttribute("data-tctv"))){n.setAttribute("data-tctv",i?"1":"0"),i?(n.style.width="120px",n.style.height="100px",n.innerHTML=t+'Nacho
    click to ask!
    👔📖
    '):(n.style.width="",n.style.height="",n.innerHTML=e+'Nacho
    click to ask!
    👔📖
    ');var a=document.getElementById("nachoClosetBtn");if(a){var r=!1;a.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),a.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),r=!0},{passive:!1}),a.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),r&&(r=!1,window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},200),"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear())},{passive:!1})}}}};var N=window.go;N&&(window.go=function(){var e=N.apply(this,arguments);return setTimeout(window.updateNachoAvatarForPage,100),e})}(),function(){window.nachoTimeGreeting=function(){var e=(new Date).getHours(),t=((new Date).getDay(),"function"==typeof nachoUserName?nachoUserName():""),o=t?", "+t:"";return e>=5&&e<12?{pose:"wave",text:"Good morning"+o+"! ☀️ Ready to learn some Bitcoin today?"}:e>=12&&e<17?{pose:"wave",text:"Good afternoon"+o+"! 🌤️ Let's stack some knowledge!"}:e>=17&&e<21?{pose:"wave",text:"Good evening"+o+"! 🌅 Great time to dive into some Bitcoin education!"}:e>=21||e<2?{pose:"cool",text:"Late night study session"+o+"? 🌙 Respect! The night owl and the night deer, learning together. 🦉🦌"}:{pose:"sleep",text:"Whoa"+o+", it's the middle of the night! 😴 Your dedication is legendary. Most deer would be asleep right now!"}},window.nachoStreakMessage=function(){if(void 0===currentUser||!currentUser)return null;var e=currentUser.streak||0,t="function"==typeof nachoUserName?nachoUserName():"",o=t?", "+t:"";return e>=30?{pose:"fire",text:e+"-day streak"+o+"! You're absolutely unstoppable! 🔥🦌👑"}:e>=14?{pose:"fire",text:e+"-day streak"+o+"! Two weeks straight! You're a machine! 🔥💪"}:e>=7?{pose:"celebrate",text:e+"-day streak"+o+"! A whole week! Nacho is very impressed! 🎉🔥"}:e>=3?{pose:"love",text:e+"-day streak"+o+"! Keep it going! 🔥"}:null};const e=[100,250,500,1e3,2100,5e3,1e4,21e3];window.nachoCheckMilestone=function(){if(void 0===currentUser||!currentUser)return null;for(var t=currentUser.points||0,o=JSON.parse(localStorage.getItem("btc_nacho_milestones")||"[]"),n="function"==typeof nachoUserName?nachoUserName():"",i=n?", "+n:"",a=[],r=0;r=s&&!o.includes(s)&&(a.push(s),o.push(s))}if(0===a.length)return null;localStorage.setItem("btc_nacho_milestones",JSON.stringify(o)),"function"==typeof syncCelebratedState&&syncCelebratedState();var l=a[0],c="function"==typeof getLevel?getLevel(t):null,d=c?" You're now rank: "+c.emoji+" "+c.name+"!":"";if(a.length>1&&"function"==typeof forceShowBubble)for(var u=1;u=3){var s=r.wrong.slice(0,3),l=Math.floor(4*Math.random());s.splice(l,0,r.a),e.push({q:r.q,options:s,correct:l,pts:10,_fromBank:!0})}}}var c=JSON.parse(localStorage.getItem("btc_nacho_trivia_asked")||"[]");c.length>.8*e.length&&(c=[],localStorage.removeItem("btc_nacho_trivia_asked"));var d=e.filter(function(e,t){return!c.includes(e._fromBank?"qb_"+e.q.substring(0,30):t)});if(0===d.length)return null;var u=d[Math.floor(Math.random()*d.length)],p=u._fromBank?"qb_"+u.q.substring(0,30):e.indexOf(u);return c.push(p),localStorage.setItem("btc_nacho_trivia_asked",JSON.stringify(c)),{trivia:u,index:idx}},window.showNachoTrivia=function(){if(window._nachoBusy)return!1;var e=nachoTrivia();if(!e)return!1;var t=e.trivia,o=document.getElementById("nacho-bubble"),n=document.getElementById("nacho-text");if(!o||!n)return!1;"function"==typeof setPose&&setPose("think"),o.setAttribute("data-interactive","true"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout();for(var i='
    🧠 Quick Trivia! (+'+t.pts+' pts)
    '+t.q+"
    ",a=0;a'+String.fromCharCode(65+a)+". "+t.options[a]+"";return n.innerHTML=i,o.classList.add("show"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout(),!0},window.nachoTriviaAnswer=function(e,t,o,n){for(var i=n.parentElement.querySelectorAll("button"),a=0;a","function"==typeof setPose&&setPose("celebrate");else{var d=Math.max(2,Math.floor(o/3));"function"==typeof awardPoints&&awardPoints(d,"🧠 Nice try!"),s.innerHTML+='
    ❌ Not quite'+c+"! The answer was "+String.fromCharCode(65+t)+". +"+d+" pts for trying! 📚
    ","function"==typeof setPose&&setPose("love")}s.innerHTML+='',s.innerHTML+=''},window.getNachoFriendship=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?{level:5,name:"Best Buds",emoji:"💛"}:e>=350?{level:4,name:"Close Friends",emoji:"🧡"}:e>=100?{level:3,name:"Good Friends",emoji:"😊"}:e>=10?{level:2,name:"Getting Acquainted",emoji:"👋"}:e>=1?{level:1,name:"Just Met",emoji:"🦌"}:{level:0,name:"Strangers",emoji:"❓"}},window.trackNachoInteraction=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0")+1;if(localStorage.setItem("btc_nacho_interactions",e.toString()),window._nachoLastInteraction=Date.now(),void 0!==db&&void 0!==auth&&auth.currentUser){var t=parseInt(localStorage.getItem("btc_nacho_questions")||"0");try{db.collection("users").doc(auth.currentUser.uid).update({nachoInteractions:e,nachoQuestions:t})}catch(e){}}"function"==typeof renderProgressRings&&renderProgressRings()};const i={mining:["How does the difficulty adjustment work?","What is a halving?","Is mining bad for the environment?","What is a nonce?","Can I mine at home?","What is an ASIC?"],wallet:["What is a seed phrase?","What is self-custody?","What is a hardware wallet?","How do I back up my wallet?","What is multisig?","Which wallet is best for beginners?"],lightning:["How fast is Lightning?","What are sats?","How do I get a Lightning Address?","What is a payment channel?","What is LNURL?","Can I tip people with Lightning?"],halving:["What is the block reward?","When is the next halving?","Why does the price go up after halving?","How many halvings are left?","What happens when all Bitcoin are mined?"],price:["Is it too late to buy?","What is DCA?","Why is Bitcoin volatile?","How high can Bitcoin go?","What is stock-to-flow?"],"self-custody":["What is a seed phrase?","What wallets do you recommend?","What does HODL mean?","What is cold storage?","What is a passphrase?"],privacy:["What is CoinJoin?","What is non-KYC Bitcoin?","Is Bitcoin anonymous?","What are silent payments?","What is Nostr?"],basics:["How does mining work?","What is the Lightning Network?","Who created Bitcoin?","What is a sat?","Why is there only 21 million?"],fud:["Is Bitcoin bad for the environment?","Can Bitcoin be hacked?","Will governments ban Bitcoin?","What about quantum computers?","Is Bitcoin a Ponzi scheme?"],node:["Why should I run a node?","What is a full node?","How does consensus work?","What is Nakamoto Consensus?"],taproot:["What is Schnorr?","What are covenants?","What is MuSig2?","What is OP_CAT?"],security:["What is a 51% attack?","How secure is Bitcoin?","What is proof of work?","Can Bitcoin be hacked?"],scarcity:["Why only 21 million?","What makes Bitcoin scarce?","What is inflation?","Bitcoin vs gold?"],layer:["What is Lightning Network?","What are sidechains?","What is the Liquid Network?","What are channel factories?"],economics:["What is sound money?","What is the Cantillon Effect?","What is time preference?","Why is fiat bad?"],satoshi:["Why did Satoshi disappear?","Who is Hal Finney?","What is the Genesis Block?","Is Craig Wright Satoshi?"],nostr:["What is Nostr?","How do I use Nostr?","What are Nostr relays?","Can I sign in with Nostr?"],regulation:["Can Bitcoin be banned?","What happened when China banned Bitcoin?","Is Bitcoin legal?","What about the SEC?"],altcoin:["Why is Bitcoin different from altcoins?","What about Ethereum?","Are meme coins worth it?","Why Bitcoin only?"],invest:["What is DCA?","How much should I invest?","Is now a good time to buy?","What is HODL?"],history:["What is Pizza Day?","What are the blocksize wars?","When was the first transaction?","What is the Genesis Block?"],energy:["Does Bitcoin waste energy?","How much energy does mining use?","Is Bitcoin green?","What is stranded energy?"]};var a=[];window.nachoFollowUps=function(e){if(!e)return[];var t=e.toLowerCase(),o=[];for(var n in i)t.includes(n)&&(o=o.concat(i[n]));0===o.length&&(o=["What is Bitcoin?","How do I get started?","What is the Lightning Network?","Who created Bitcoin?","Why is there only 21 million?","What is self-custody?"]);var r=window._nachoAskedQuestions||[],s=o.filter(function(e){return-1===a.indexOf(e)&&-1===r.indexOf(e.toLowerCase())});s.length<3&&(a=[],s=o.filter(function(e){return-1===r.indexOf(e.toLowerCase())})),0===s.length&&(s=o),s.sort(function(){return Math.random()-.5});var l=Math.min(Math.max(3,s.length),5),c=s.slice(0,l);return(a=a.concat(c)).length>30&&(a=a.slice(-15)),c},window.trackNachoQuestion=function(e,t){try{var o=JSON.parse(localStorage.getItem("btc_nacho_analytics")||"[]");o.push({q:e.substring(0,100),matched:t,t:Date.now()}),o.length>100&&(o=o.slice(-100)),localStorage.setItem("btc_nacho_analytics",JSON.stringify(o))}catch(e){}};let r="false"!==localStorage.getItem("btc_nacho_sound");window.nachoPlaySound=function(e){if(("function"!=typeof canPlaySound||canPlaySound())&&r)try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();if(o.connect(n),n.connect(t.destination),n.gain.value=.08,"pop"===e)o.frequency.value=800,o.type="sine",n.gain.setValueAtTime(.08,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.15),o.start(t.currentTime),o.stop(t.currentTime+.15);else if("coin"===e){o.frequency.value=1200,o.type="sine",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.3),o.start(t.currentTime),o.stop(t.currentTime+.3);var i=t.createOscillator();i.connect(n),i.frequency.value=1600,i.type="sine",i.start(t.currentTime+.1),i.stop(t.currentTime+.3)}else"click"===e?(o.frequency.value=600,o.type="triangle",n.gain.setValueAtTime(.05,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.08),o.start(t.currentTime),o.stop(t.currentTime+.08)):"tctv-beep"===e&&(o.frequency.value=2400,o.type="square",n.gain.setValueAtTime(.03,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.06),o.start(t.currentTime),o.stop(t.currentTime+.06))}catch(e){}},window.toggleNachoSound=function(){return r=!r,localStorage.setItem("btc_nacho_sound",r.toString()),r};let s=[];window.nachoAddContext=function(e){s.push(e),s.length>5&&s.shift()},window.nachoGetContext=function(){return s},setTimeout(function(){if("1"!==localStorage.getItem("btc_ln_prompt_dismissed")){var e=void 0!==currentUser?currentUser:null;if(e&&e.username&&!e.lightning&&!e.lightningAddress){var t=[];try{t=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}t.length<5||"function"==typeof forceShowBubble&&(forceShowBubble("⚡ Hey "+(e.username||"friend")+"! Connect a Lightning wallet to tip other users and receive tips! Tap me to learn how. 🦌",function(){go("lightning")}),localStorage.setItem("btc_ln_prompt_dismissed","1"))}}},3e4),function(){var e="btc_smart_nudges";function t(){try{return JSON.parse(localStorage.getItem(e)||"{}")}catch(e){return{}}}function o(e){var o=t();return!o[e]||Date.now()-o[e]>864e5}function n(){if("function"==typeof forceShowBubble&&!(Date.now()-(window._sessionStart||Date.now())<3e4)){var n=document.getElementById("nacho-bubble");if(!(n&&n.classList.contains("show")||window._nachoBusy)){var i,a,r=[];if(void 0!==BADGE_DEFS&&void 0!==earnedBadges){var s=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length;!earnedBadges.has("explorer_10")&&s>=7&&o("near_explorer_10")&&r.push({id:"near_explorer_10",text:"You've visited "+s+" topics — just "+(10-s)+" more to earn the Explorer badge! 🧭 Keep exploring!"}),!earnedBadges.has("explorer_25")&&s>=20&&s<25&&o("near_explorer_25")&&r.push({id:"near_explorer_25",text:"Only "+(25-s)+" more topics to unlock Trailblazer! 🗺️ You're so close!"});var l=void 0!==currentUser&¤tUser&¤tUser.streak||0;!earnedBadges.has("streak_7")&&l>=5&&l<7&&o("near_streak_7")&&r.push({id:"near_streak_7",text:l+"-day streak! 🔥 Just "+(7-l)+" more days for the Week Warrior badge! Don't break it!"}),!earnedBadges.has("streak_30")&&l>=25&&l<30&&o("near_streak_30")&&r.push({id:"near_streak_30",text:l+"-day streak! 💪 "+(30-l)+" more days to Monthly Maxi! That's legendary dedication!"}),!earnedBadges.has("streak_100")&&l>=90&&l<100&&o("near_streak_100")&&r.push({id:"near_streak_100",text:l+"-day streak! 💎 "+(100-l)+" days from Diamond Hands! You're in the top tier!"});var c=parseInt(localStorage.getItem("btc_chat_msgs")||"0");!earnedBadges.has("chat_50")&&c>=40&&c<50&&o("near_chat_50")&&r.push({id:"near_chat_50",text:c+" chat messages! Just "+(50-c)+" more to become a Conversationalist! 🎤 Head to Global Chat!"});var d=parseInt(localStorage.getItem("btc_pvp_wins")||"0");!earnedBadges.has("pvp_5")&&d>=3&&d<5&&o("near_pvp_5")&&r.push({id:"near_pvp_5",text:d+" PVP wins! ⚔️ "+(5-d)+" more to unlock Contender! Ready for a battle?"});var u=void 0!==completedQuests&&completedQuests.size||0;!earnedBadges.has("quest_3")&&u>=2&&u<3&&o("near_quest_3")&&r.push({id:"near_quest_3",text:"You've completed "+u+" quests! One more for the Quest Master badge! ⚔️ Try a quest after reading!"});var p=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0");!earnedBadges.has("tctv_couch_potato")&&p>=45&&p<60&&o("near_tctv_60")&&r.push({id:"near_tctv_60",text:p+" minutes of Timechain TV! 📺 Just "+(60-p)+" more for Couch Potato! Grab some popcorn! 🍿"}),localStorage.getItem("btc_last_spin_date")!==(new Date).toDateString()&&o("daily_spin")&&r.push({id:"daily_spin",text:"You haven't spun the daily wheel yet! 🎡 Free tickets and prizes await!"})}if(r.length>0){var m=r[Math.floor(Math.random()*r.length)];i=m.id,(a=t())[i]=Date.now(),localStorage.setItem(e,JSON.stringify(a)),forceShowBubble(m.text)}}}}setTimeout(function(){n(),setInterval(n,3e5)},12e4),window.checkSmartNudges=n}()}(),window.nachoNickname=function(){return localStorage.getItem("btc_nacho_nickname")||"Nacho"},function(){const e=[{id:"orange_scarf",category:"shirt",name:"Bitcoin Scarf",emoji:"🧣",desc:"A cozy orange scarf with the ₿ symbol.",level:1,overlay:{top:"68%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"sunglasses",category:"glasses",name:"Cool Shades",emoji:"🕶️",desc:"Sunglasses so cool, even the blockchain can't see through them.",level:1,overlay:{top:"43%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"bowtie",category:"shirt",name:"Fancy Bowtie",emoji:"🎀",desc:"A dapper bowtie for a distinguished buck. Class and sats.",level:1,overlay:{top:"64%",left:"50%",transform:"translateX(-50%)",fontSize:"1.3em"},hidden:!1,colorable:!0},{id:"mining_helmet",category:"hat",name:"Mining Helmet",emoji:"⛑️",desc:"A safety helmet for a hardworking miner. Ready to find the next block!",level:2,overlay:{top:"5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"lightning_chain",category:"glasses",name:"Lightning Chain",emoji:"⚡",desc:"A chain necklace with a Lightning bolt pendant.",level:2,overlay:{top:"65%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"party_hat",category:"hat",name:"Party Hat",emoji:"🎉",desc:"Every day is a party when you're stacking sats!",level:2,overlay:{top:"2%",left:"58%",transform:"translateX(-50%) rotate(15deg)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"hodl_hoodie",category:"shirt",name:"HODL Hoodie",emoji:"🧥",desc:"A hoodie that says HODL on the back. For diamond-handed deer.",level:3,overlay:{top:"72%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1,colorable:!0},{id:"laser_eyes",category:"glasses",name:"Laser Eyes",emoji:"🔴",desc:"The legendary Bitcoin laser eyes. Number go up!",level:3,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"0.9em",custom:"🔴 🔴"},hidden:!1,colorable:!0},{id:"wizard_hat",category:"hat",name:"Wizard Hat",emoji:"🪄",desc:"A mystical wizard hat. Nacho casts spells of financial sovereignty!",level:3,overlay:{top:"-5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!1,colorable:!0},{id:"crown",category:"hat",name:"Royal Crown",emoji:"👑",desc:"Fit for the king of cryptocurrency. There is no second best!",level:3,overlay:{top:"3%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"steak",category:"glasses",name:"Proof of Steak",emoji:"🥩",desc:"A juicy steak for a hardworking buck. Proof of Steak > Proof of Stake!",level:4,overlay:{top:"58%",right:"-18%",fontSize:"1.8em",transform:"rotate(20deg)"},hidden:!1},{id:"diamond_hooves",category:"glasses",name:"Diamond Hooves",emoji:"💎",desc:"Diamond hooves for a deer with diamond hands. Never selling!",level:4,overlay:{bottom:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em",custom:"💎💎"},hidden:!1},{id:"astronaut",category:"hat",name:"Moon Helmet",emoji:"🪖",desc:"To the moon! A space helmet for the ultimate HODLer.",level:4,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1},{id:"cape_permanent",category:"shirt",name:"Hero Cape",emoji:"🦸",desc:"A permanent cape for a Bitcoin hero. Earned, not given!",level:4,overlay:{top:"55%",right:"-15%",fontSize:"2.4em",transform:"rotate(-12deg)"},hidden:!1,colorable:!0},{id:"golden_antlers",category:"hat",name:"???",emoji:"✨",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"0.5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Golden Antlers",revealEmoji:"✨",revealDesc:"Antlers plated in pure gold. Only the closest friends get to see these shine!"},{id:"satoshi_cloak",category:"shirt",name:"???",emoji:"🧥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"68%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Satoshi's Cloak",revealEmoji:"🧥",revealDesc:"A mysterious cloak worn by Satoshi himself. Legend says it grants anonymity to any deer who wears it."},{id:"flame_aura",category:"glasses",name:"???",emoji:"🔥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"25%",left:"50%",transform:"translateX(-50%)",fontSize:"3.5em"},hidden:!0,revealName:"Flame Aura",revealEmoji:"🔥",revealDesc:"A blazing aura of pure Bitcoin energy. The ultimate flex for Nacho's best friend!"},{id:"rainbow_antlers",category:"hat",name:"???",emoji:"🌈",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!0,revealName:"Rainbow Antlers",revealEmoji:"🌈",revealDesc:"Prismatic rainbow antlers that shimmer in every color. Legendary!"},{id:"bitcoin_eyes",category:"glasses",name:"???",emoji:"₿",desc:"How do you find this one?",level:1,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.2em",custom:"₿ ₿"},hidden:!0,revealName:"Bitcoin Eyes",revealEmoji:"₿",revealDesc:"Eyes made of pure Bitcoin. You found the secret! Nacho sees everything in sats now."},{id:"santa_hat",category:"hat",name:"Santa Hat",emoji:"🎅",desc:"Ho ho HODL! A festive Santa hat for the holiday season.",level:1,overlay:{top:"1%",left:"54%",transform:"translateX(-50%) rotate(15deg)",fontSize:"2.2em"},hidden:!1,seasonal:"december"},{id:"pumpkin",category:"hat",name:"Pumpkin Head",emoji:"🎃",desc:"Spooky season! A jack-o-lantern for Halloween.",level:1,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1,seasonal:"october"},{id:"halving_pickaxe",category:"glasses",name:"Golden Pickaxe",emoji:"⛏️",desc:"A golden pickaxe to celebrate the halving! Limited edition.",level:1,overlay:{top:"22%",right:"-15%",fontSize:"2.2em",transform:"rotate(30deg)"},hidden:!1,seasonal:"april"}];var t=document.createElement("style");function o(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?5:e>=350?4:e>=100?3:e>=10?2:e>=1?1:0}t.textContent="\n @keyframes nachoEquipPop {\n 0% { transform: scale(0) rotate(-45deg); opacity: 0; }\n 50% { transform: scale(1.5) rotate(10deg); opacity: 1; }\n 70% { transform: scale(0.9) rotate(-5deg); }\n 100% { transform: scale(1) rotate(0deg); opacity: 1; }\n }\n @keyframes nachoEquipGlow {\n 0% { filter: drop-shadow(0 0 0px transparent); }\n 30% { filter: drop-shadow(0 0 12px rgba(247,147,26,0.8)); }\n 100% { filter: drop-shadow(0 0 4px rgba(247,147,26,0.3)); }\n }\n @keyframes nachoUnequip {\n 0% { transform: scale(1); opacity: 1; }\n 40% { transform: scale(1.3) rotate(15deg); opacity: 0.8; }\n 100% { transform: scale(0) rotate(-30deg); opacity: 0; }\n }\n @keyframes nachoItemFloat {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-3px); }\n }\n @keyframes nachoLaserPulse {\n 0%, 100% { opacity: 0.8; filter: drop-shadow(0 0 4px #ff0000); }\n 50% { opacity: 1; filter: drop-shadow(0 0 10px #ff0000) drop-shadow(0 0 20px #ff3300); }\n }\n @keyframes nachoSparkle {\n 0%, 100% { filter: drop-shadow(0 0 4px rgba(255,215,0,0.3)); }\n 50% { filter: drop-shadow(0 0 10px rgba(255,215,0,0.8)) drop-shadow(0 0 20px rgba(255,215,0,0.4)); }\n }\n @keyframes nachoCloakWave {\n 0%, 100% { transform: translateX(-50%) rotate(-2deg); }\n 50% { transform: translateX(-50%) rotate(2deg); }\n }\n .nacho-overlay-item {\n position: absolute;\n pointer-events: none;\n z-index: 3;\n }\n .nacho-overlay-item.equipping {\n animation: nachoEquipPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards,\n nachoEquipGlow 0.8s ease-out forwards;\n }\n .nacho-overlay-item.unequipping {\n animation: nachoUnequip 0.35s ease-in forwards;\n }\n .nacho-overlay-item.idle-float {\n animation: nachoItemFloat 3s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-laser {\n animation: nachoLaserPulse 1.5s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-sparkle {\n animation: nachoSparkle 2s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-wave {\n animation: nachoCloakWave 4s ease-in-out infinite;\n }\n",document.head.appendChild(t),window.equipNachoItem=function(t){if(!t)return localStorage.removeItem("btc_nacho_equipped_multi"),void renderNachoOverlay();var n=o(),i=e.find(function(e){return e.id===t}),a=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]");if(i&&i.level>n&&-1===a.indexOf(t))showToast("🔒 Need a higher friendship level to wear this!");else{var r=getEquippedItems(),s=i&&i.category||"misc";r[s]===t?(delete r[s],"function"==typeof forceShowBubble&&forceShowBubble("Back to natural in the "+s+" department! 🦌")):(r[s]=t,"function"==typeof forceShowBubble&&forceShowBubble({orange_scarf:"Looking cozy! This scarf really brings out my orange. 🧣🦌",mining_helmet:"Safety first! Time to mine some blocks! ⛑️⛏️",lightning_chain:"Bling bling! Fast as Lightning! ⚡🦌",hodl_hoodie:"HODL gang! This hoodie makes me feel unstoppable! 🧥💎",laser_eyes:"LASER EYES ACTIVATED! Number go up! 🔴🔴🚀",steak:"Mmm, Proof of Steak! Way better than Proof of Stake! 🥩😋",golden_antlers:"These golden antlers are MAGNIFICENT! Only for my best friends! 👑✨",satoshi_cloak:"Who am I? Nobody knows... I am Satoshi Nachoamoto! 🧙🦌"}[t]||"Looking fresh with my "+(i.hidden?i.revealName:i.name)+"! 🦌")),localStorage.setItem("btc_nacho_equipped_multi",JSON.stringify(r)),renderNachoOverlay(!0),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),document.getElementById("nachoClosetGrid")&&renderNachoClosetUI(document.getElementById("nachoClosetGrid").parentElement)}},window.renderNachoOverlay=function(t){document.querySelectorAll(".nacho-overlay-item").forEach(e=>e.remove());var o=getEquippedItems(),n=document.getElementById("nacho-avatar");n&&(Object.values(o).forEach(function(o){var i=e.find(function(e){return e.id===o});if(i){var a=i.hidden?i.revealEmoji:i.emoji,r=function(e){switch(e){case"laser_eyes":return"idle-laser";case"golden_antlers":case"diamond_hooves":return"idle-sparkle";case"satoshi_cloak":return"idle-wave";default:return"idle-float"}}(i.id),s=document.createElement("span");for(var l in s.className="nacho-overlay-item"+(t?" equipping":" "+r),s.id="nacho-overlay-"+i.id,s.textContent=i.overlay.custom||a,i.overlay.custom&&(s.style.letterSpacing="-0.1em",s.style.whiteSpace="nowrap"),i.overlay)"filter"!==l&&"custom"!==l&&(s.style[l]=i.overlay[l]);if(i.colorable){var c=localStorage.getItem("btc_closet_color_"+i.id);c&&"0deg"!==c&&(s.style.filter="hue-rotate("+c+")")}t&&s.addEventListener("animationend",function e(){s.classList.remove("equipping"),s.classList.add(r),s.removeEventListener("animationend",e)},{once:!0}),n.appendChild(s)}}),t&&function(e){for(var t=e.getBoundingClientRect(),o=["✨","⭐","💫","🌟"],n=0;n<6;n++)(function(e){setTimeout(function(){var n=document.createElement("div");n.className="nacho-trail",n.textContent=o[e%o.length],n.style.left=t.left+Math.random()*t.width+"px",n.style.top=t.top+Math.random()*t.height+"px",n.style.fontSize=.8+.8*Math.random()+"rem",document.body.appendChild(n),setTimeout(function(){n.parentNode&&n.remove()},800)},80*e)})(n)}(n))},window.getNachoFriendship=function(){const e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[{name:"Stranger",emoji:"🦌",min:0},{name:"Acquaintance",emoji:"🤝",min:10},{name:"Pleb Friend",emoji:"🧡",min:50},{name:"HODL Buddy",emoji:"💎",min:150},{name:"Maxi Mentor",emoji:"👑",min:500}];let o=t[0];for(const n of t)e>=n.min&&(o=n);return o},window.renderNachoClosetUI=function(t){for(var n=o(),i=getEquippedItems(),a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r="function"==typeof getNachoFriendship?getNachoFriendship():{level:0,name:"Strangers",emoji:"❓"},s=[1,10,100,350,750],l="",c=0;cNext level in '+(s[c]-a)+" more interactions";break}var d="",u=[];Object.values(i).forEach(function(t){var o=e.find(function(e){return e.id===t});if(o){var n=o.hidden?o.revealEmoji:o.emoji;o.overlay.custom&&(n=o.overlay.custom);var i="position:absolute;font-size:"+(o.overlay.fontSize||"1.5rem")+";";if(o.overlay.top&&(i+="top:"+o.overlay.top+";"),o.overlay.bottom&&(i+="bottom:"+o.overlay.bottom+";"),o.overlay.left&&(i+="left:"+o.overlay.left+";"),o.overlay.right&&(i+="right:"+o.overlay.right+";"),o.overlay.transform&&(i+="transform:"+o.overlay.transform+";"),i+="z-index:5;pointer-events:none;",o.colorable){var a=localStorage.getItem("btc_closet_color_"+o.id);a&&"0deg"!==a&&(i+="filter:hue-rotate("+a+");")}d+=''+n+"",u.push(o.hidden?o.revealName:o.name)}});var p="function"==typeof nachoNickname?nachoNickname():"Nacho",m='
    🦌 '+escapeHtml(p)+"'s Closet
    ";m+='
    Nacho'+d+'
    '+(u.length>0?'✨ Wearing: '+u.join(", ")+"":"No item equipped — tap one below!")+"
    ",m+='
    Friendship: '+r.emoji+" "+r.name+''+a+" interactions
    "+l,m+='
    ',m+='
    ';for(var h=(new Date).toLocaleString("en",{month:"long"}).toLowerCase(),g=0;g
    '+x+'
    '+w+"
    "+(b?'
    ✓ EQUIPPED
    ':"")+(b&&f.colorable?"
    🎨 Color
    ':"")+(y||v?"":'
    Lvl '+f.level+"
    ")+(v?'
    🔒
    ':"")+(f.seasonal?'
    🗓️ '+f.seasonal+"
    ":"")+"
    "}}m+="",m+='
    '+(Object.keys(i).length>0?function(){var t=e.find(function(e){return e.id===Object.values(i)[0]});if(!t)return"Tap an item to equip it on "+escapeHtml(p)+"!";var o=t.hidden?t.revealDesc:t.desc;return''+(t.hidden?t.revealName:t.name)+": "+o}():"Tap an unlocked item to equip it on "+escapeHtml(p)+"!
    Tap again to unequip.")+"
    ",t.innerHTML=m};var n="function"==typeof nachoNickname?nachoNickname():"Nacho";window.NACHO_CLOSET_TIPS=[{pose:"cool",text:"Did you know I have a whole closet of outfits, {name}? Check Settings → Stats → "+escapeHtml(n)+"'s Closet to dress me up! 👔🦌"},{pose:"celebrate",text:"The more we interact, the more items you unlock for me to wear! Check my closet in Settings! 🧣⚡"},{pose:"eyes",text:"I heard there are some mystery items in my closet that only my closest friends get to see... 👀🔒"},{pose:"fire",text:"Proof of Steak > Proof of Stake. Ask me about it... or better yet, unlock it in my closet! 🥩🦌"},{pose:"cheese",text:"Fashion tip from a deer: orange goes with everything. Especially Bitcoin orange. Check my closet in Settings! 🟠"}],window.checkNachoNewItems=function(){var t=o(),n=JSON.parse(localStorage.getItem("btc_nacho_items_notified")||"[]"),i=e.filter(function(e){return e.level<=t&&!n.includes(e.id)});if(i.length>0){for(var a=0;a
    '+(a?a.name:"Item")+'
    Choose a color
    ';[{name:"Default",hue:"0deg",color:"#f7931a"},{name:"Bitcoin Orange",hue:"25deg",color:"#ff8c00"},{name:"Crimson",hue:"340deg",color:"#dc2626"},{name:"Royal Purple",hue:"270deg",color:"#7c3aed"},{name:"Ocean Blue",hue:"200deg",color:"#0ea5e9"},{name:"Forest Green",hue:"120deg",color:"#16a34a"},{name:"Gold",hue:"45deg",color:"#eab308"},{name:"Hot Pink",hue:"310deg",color:"#ec4899"},{name:"Cyan",hue:"175deg",color:"#06b6d4"},{name:"Lime",hue:"90deg",color:"#84cc16"}].forEach(function(t){var n=o===t.hue;r+=""}),r+='
    ',i.innerHTML=r,n.appendChild(i),document.body.appendChild(n)},window._applyClosetColor=function(e,t){localStorage.setItem("btc_closet_color_"+e,t);var o=document.querySelector("#nacho-overlay");if(o&&(o.style.filter="0deg"===t?"none":"hue-rotate("+t+")"),"function"==typeof showColorPicker&&showColorPicker(e),"function"==typeof renderNachoClosetUI){var n=document.getElementById("nachoClosetContainer");n&&renderNachoClosetUI(n)}};const QUESTION_BANK={whitepaper:[{q:"When was the Bitcoin Whitepaper published?",a:"October 31, 2008",wrong:["January 3, 2009","March 15, 2007","December 25, 2010"]},{q:"How many pages of text is the Bitcoin Whitepaper?",a:"8 pages",wrong:["20 pages","50 pages","2 pages"]},{q:"The Whitepaper was published on:",a:"A cryptography mailing list",wrong:["Twitter","A Bitcoin forum","The New York Times"]},{q:"What is the title of the Bitcoin Whitepaper?",a:"Bitcoin: A Peer-to-Peer Electronic Cash System",wrong:["Digital Gold: The Future","How to Mine Cryptocurrency","The Blockchain Revolution"]},{q:"The Whitepaper proposed a solution to:",a:"The double-spending problem",wrong:["Climate change","Internet speed","Social media addiction"]}],whitepaper_pt2:[{q:"Who is credited as the author of the Whitepaper?",a:"Satoshi Nakamoto",wrong:["Vitalik Buterin","Elon Musk","Hal Finney"]},{q:"The Whitepaper describes Bitcoin as:",a:"A peer-to-peer electronic cash system",wrong:["A stock trading platform","A social network","A video game currency"]},{q:"What concept does the Whitepaper use to timestamp transactions?",a:"A chain of hashed blocks",wrong:["A central database","Email timestamps","GPS coordinates"]},{q:"The Bitcoin whitepaper solved what previously unsolvable problem?",a:"Digital scarcity without a trusted third party",wrong:["Faster internet speeds","Quantum-proof encryption","Free worldwide communication"]},{q:"What did Satoshi embed in the Genesis Block's coinbase transaction?",a:"A newspaper headline about bank bailouts",wrong:["Their real name","A mathematical formula","Instructions for miners"]}],decentralized:[{q:'How many people are "in charge" of Bitcoin?',a:"No one",wrong:["Satoshi Nakamoto","A board of directors","The Bitcoin Foundation"]},{q:"What is needed for code updates to Bitcoin?",a:"Deep consensus from the network",wrong:["A CEO decision","A government vote","Permission from miners only"]},{q:"Bitcoin is described as:",a:"A protocol, not a company",wrong:["A company based in Japan","A government project","A bank product"]},{q:"Bitcoin nodes are run by:",a:"Anyone who wants to, worldwide",wrong:["Only by miners","Only in the United States","Only by approved operators"]},{q:"If one country shuts down all Bitcoin mining:",a:"The network continues in other countries",wrong:["Bitcoin dies","All coins are lost","The price goes to zero permanently"]}],decentralized_pt2:[{q:"Bitcoin has no:",a:"Central point of failure",wrong:["Users","Transactions","Value"]},{q:"Decentralization means:",a:"No single entity controls the network",wrong:["One company runs everything","The government manages it","Only banks can use it"]},{q:"What happens to Bitcoin if one country bans it?",a:"The network continues operating globally since no single country controls it",wrong:["Bitcoin shuts down in that country","All nodes worldwide go offline","Miners must relocate to that country"]},{q:"How many Bitcoin full nodes are estimated to run worldwide?",a:"Tens of thousands across dozens of countries",wrong:["About 100 in the United States","One per continent","Only miners run nodes"]},{q:"Why is geographic distribution of nodes important?",a:"It prevents any single jurisdiction from shutting down the network",wrong:["It makes Bitcoin faster","It reduces electricity costs","It increases the block size"]}],scarce:[{q:"What is the maximum supply of Bitcoin?",a:"21 million",wrong:["100 million","1 billion","Unlimited"]},{q:"How many Bitcoin are estimated to be lost forever?",a:"2-3 million",wrong:["None","10 million","100,000"]},{q:"Bitcoin's code is:",a:"Open source and auditable by anyone",wrong:["Private and closed","Only visible to developers","Controlled by a company"]},{q:"What event cuts Bitcoin's new supply in half?",a:"The halving",wrong:["The merge","The split","The fork"]},{q:"How often does the halving occur?",a:"Approximately every 4 years",wrong:["Every year","Every 10 years","Every month"]}],scarce_pt2:[{q:"Bitcoin is often compared to which precious metal?",a:"Gold",wrong:["Silver","Platinum","Copper"]},{q:"The last Bitcoin will be mined around the year:",a:"2140",wrong:["2030","2050","2025"]},{q:"Bitcoin scarcity is enforced by:",a:"Math and code",wrong:["Government regulations","A central bank","Mining companies"]},{q:"What is the smallest unit of Bitcoin called?",a:"A satoshi (0.00000001 BTC)",wrong:["A bit (0.01 BTC)","A wei","A gwei"]},{q:"How does Bitcoin's stock-to-flow ratio compare to gold after the 2024 halving?",a:"Bitcoin's stock-to-flow surpassed gold's",wrong:["Gold's is still much higher","They are identical","Stock-to-flow doesn't apply to Bitcoin"]}],secure:[{q:"Bitcoin has been under attack since gaining significant value around:",a:"2013",wrong:["2020","2009","2017"]},{q:"How many potential Bitcoin wallets exist?",a:"2^160",wrong:["21 million","A few billion","2^16"]},{q:"Bitcoin's monetary policy is:",a:"Set in stone and immutable",wrong:["Changed annually","Decided by miners","Flexible based on market"]},{q:"A 51% attack would require:",a:"More computing power than the rest of the network combined",wrong:["A password","Government approval","Hacking one computer"]},{q:"Bitcoin has experienced how many hours of downtime since 2013?",a:"Zero",wrong:["Hundreds","A few days each year","One week"]}],secure_pt2:[{q:"Bitcoin uses which hashing algorithm?",a:"SHA-256",wrong:["MD5","RSA","AES"]},{q:"The cost to attack Bitcoin's network is:",a:"Billions of dollars",wrong:["A few hundred dollars","Free","A few thousand dollars"]},{q:"What is Bitcoin's uptime percentage since launch in 2009?",a:"Over 99.98% - virtually no downtime",wrong:["About 95%","Around 80% due to attacks","100% with zero interruptions"]},{q:"Why does higher hashrate make Bitcoin more secure?",a:"More computational power means an attacker needs proportionally more resources to overpower the network",wrong:["Higher hashrate makes transactions free","It allows more coins to be mined","It reduces the block time to seconds"]},{q:"What makes a 51% attack on Bitcoin impractical?",a:"The enormous cost of acquiring more mining power than all honest miners combined",wrong:["The government protects Bitcoin","Satoshi can reverse any attack","Bitcoin uses a firewall"]}],money:[{q:"How many satoshis are in one Bitcoin?",a:"100,000,000",wrong:["1,000,000","1,000","10,000"]},{q:"Bitcoin payments are compared to:",a:"Email - anyone with your address can send",wrong:["Fax machines","Phone calls","Physical mail"]},{q:"Bitcoin's distribution was fair because:",a:"There was no premine",wrong:["A company sold coins early","The government distributed it","Only miners got coins"]},{q:"A satoshi is named after:",a:"Bitcoin's creator, Satoshi Nakamoto",wrong:["A Japanese emperor","A type of sushi","A programming language"]},{q:"Bitcoin is divisible to how many decimal places?",a:"8",wrong:["2","4","16"]}],money_pt2:[{q:"Bitcoin can function as:",a:"A store of value, medium of exchange, and unit of account",wrong:["Only a store of value","Only for payments","Only for speculation"]},{q:'What makes Bitcoin "sound money"?',a:"Fixed supply and predictable issuance",wrong:["Government backing","Bank guarantees","Corporate ownership"]},{q:"Which property of money does Bitcoin's 21 million cap satisfy?",a:"Scarcity - it cannot be inflated or debased",wrong:["Acceptability - everyone must use it","Portability - it weighs nothing","Cognizability - it looks like gold"]},{q:"Why are satoshis important for Bitcoin as money?",a:"They allow micropayments and make Bitcoin divisible enough for everyday transactions",wrong:["They increase the total supply","They are a separate cryptocurrency","They can only be used on Lightning"]},{q:"What gives Bitcoin its monetary value according to Austrian economics?",a:"Subjective value from its useful properties: scarcity, portability, divisibility, and censorship resistance",wrong:["Government decree","Gold backing","The electricity used to mine it"]}],peaceful:[{q:"When China banned Bitcoin:",a:"Bitcoin just moved and kept going",wrong:["Bitcoin shut down","The price went to zero","The code was deleted"]},{q:"What happened to Bitcoin transactions during the 2021 China mining ban?",a:"The network kept running - hash rate dipped then recovered within months",wrong:["Transactions slowed severely as hash rate took over a year to fully recover","The difficulty adjustment failed and blocks stopped confirming for several weeks","The network split into two chains — one with and one without Chinese nodes"]},{q:"Bitcoin enables protest by:",a:"Allowing people to transact without government permission",wrong:["Sending angry emails","Blocking websites","Hacking banks"]},{q:'Bitcoin is called "peaceful" because:',a:"It opts out of the existing system without force",wrong:["It prevents all crime","It eliminates wars","It makes everyone rich"]},{q:"Bitcoin helps people in authoritarian regimes by:",a:"Providing censorship-resistant money",wrong:["Overthrowing governments","Hacking military systems","Printing local currency"]}],peaceful_pt2:[{q:"Bitcoin adoption is described as:",a:"Voluntary and organic",wrong:["Mandatory and forced","Government-mandated","Corporate-controlled"]},{q:"How does Bitcoin function as a peaceful protest tool?",a:"It allows people to opt out of inflationary monetary systems without violence",wrong:["It funds protest organizations","It blocks government websites","It replaces voting systems"]},{q:'Why is Bitcoin described as "opt-in" money?',a:"Nobody is forced to use it - participation is entirely voluntary",wrong:["You must opt in through a bank","Governments assign Bitcoin to citizens","Mining is mandatory for users"]},{q:"How did Bitcoin help protestors in authoritarian regimes?",a:"It allowed them to receive donations that could not be frozen by the government",wrong:["It gave them free internet access","It replaced their national ID systems","It provided encrypted phone calls"]},{q:'What makes Bitcoin "permissionless"?',a:"Anyone can send, receive, or hold Bitcoin without needing approval from any authority",wrong:["You need a license to own it","Only approved wallets can transact","Miners must approve each transaction manually"]}],dominant:[{q:"∞/21M means:",a:"All world wealth funneling into 21 million coins",wrong:["Bitcoin is infinite","There are infinite users","21 million blockchains"]},{q:"Bitcoin's growth pattern resembles:",a:"A J-shaped curve",wrong:["A straight line","A bell curve","A flat line"]},{q:"Bitcoin is said to change you by:",a:"Lowering your time preference",wrong:["Making you rich instantly","Increasing spending","Nothing changes"]},{q:"Bitcoin's market dominance refers to:",a:"Its share of total cryptocurrency market cap",wrong:["How many users it has","Its mining speed","Its block size"]},{q:"Bitcoin's ∞/21M meme represents:",a:"All the world's wealth eventually stored in a 21M coin supply",wrong:["Bitcoin has infinite users","Mining never ends","There are infinite blockchains"]}],dominant_pt2:[{q:"Bitcoin is considered dominant because:",a:"It has the strongest network effect and security",wrong:["It was the cheapest","A government chose it","It has the most features"]},{q:'What is the "Lindy effect" as applied to Bitcoin\'s dominance?',a:"The longer Bitcoin survives and grows, the more likely it is to continue dominating",wrong:["Old technology always fails eventually","Bitcoin dominance decreases with age","Lindy only applies to physical goods"]},{q:"Why do network effects favor Bitcoin over altcoins?",a:"More users, miners, developers, and infrastructure create a self-reinforcing cycle that's hard for competitors to match",wrong:["Bitcoin has the best marketing team","Altcoins are illegal","Network effects only apply to social media"]},{q:'What does Bitcoin\'s "dominance" metric measure?',a:"Bitcoin's share of total cryptocurrency market capitalization",wrong:["The number of Bitcoin nodes vs altcoin nodes","Bitcoin's hash rate compared to all others","The percentage of merchants accepting Bitcoin"]},{q:"Why has no altcoin overtaken Bitcoin despite thousands of attempts?",a:"Bitcoin's first-mover advantage, network effects, decentralization, and brand recognition create an insurmountable moat",wrong:["The government protects Bitcoin specifically","Altcoins are all scams with no technology","Satoshi prevents forks from succeeding"]}],"use-cases":[{q:"Bitcoin is described as better than gold because:",a:"It can be sent across the planet instantly",wrong:["It's heavier","It's shinier","It's backed by gold"]},{q:"How do Bitcoin remittance fees compare to Western Union?",a:"Much cheaper, nearly free",wrong:["About the same","More expensive","Double the cost"]},{q:"Credit card merchants pay about what fee?",a:"3%",wrong:["0%","10%","25%"]},{q:"Bitcoin can help the unbanked because:",a:"You only need a phone and internet to use it",wrong:["Banks distribute it","The government gives it away","You need a credit score"]},{q:"Bitcoin as a hedge against inflation means:",a:"Its fixed supply protects purchasing power",wrong:["It always goes up","The government guarantees its value","It pays interest"]}],"use-cases_pt2":[{q:"Micropayments on Bitcoin are possible through:",a:"The Lightning Network",wrong:["Visa","PayPal","Wire transfer"]},{q:"Bitcoin enables financial sovereignty by:",a:"Letting you be your own bank",wrong:["Requiring a bank account","Needing government ID","Using credit scores"]},{q:"Why is Bitcoin especially valuable for international remittances?",a:"It settles in minutes with low fees compared to days and high fees with traditional wire transfers",wrong:["It automatically converts to local currency","Banks process Bitcoin remittances for free","It requires no internet connection"]},{q:'How does Bitcoin serve as a "savings technology"?',a:"Its fixed supply and deflationary nature preserve purchasing power over time",wrong:["It pays interest like a savings account","Banks guarantee Bitcoin deposits","It automatically grows by 10% annually"]},{q:"What makes Bitcoin useful for micropayments via Lightning?",a:"Sub-penny transaction fees and instant settlement enable payments too small for traditional systems",wrong:["Lightning removes the need for Bitcoin","Micropayments require on-chain transactions","Only amounts over $1 can be sent"]}],mining:[{q:"What do miners do?",a:"Secure the network and process transactions",wrong:["Create Bitcoin from nothing","Print digital money","Delete old transactions"]},{q:"Miners are paid in:",a:"New Bitcoin and transaction fees",wrong:["US dollars","Ethereum","Company stock"]},{q:"Mining difficulty adjusts approximately every:",a:"2 weeks (2016 blocks)",wrong:["Every day","Every hour","Never"]},{q:"A mining pool is:",a:"A group of miners combining computing power",wrong:["A swimming pool for tech workers","A single powerful computer","A government facility"]},{q:"The mining reward after the 2024 halving is:",a:"3.125 BTC per block",wrong:["6.25 BTC","50 BTC","12.5 BTC"]}],mining_pt2:[{q:"ASIC miners are:",a:"Specialized hardware designed only for mining",wrong:["Regular laptops","Gaming consoles","Smart phones"]},{q:"What prevents miners from cheating?",a:"Other nodes verify their work",wrong:["The honor system","Government oversight","Nothing"]},{q:"What milestone did Bitcoin hash rate reach in September 2025?",a:"1 Zettahash per second",wrong:["500 Exahash","10 Petahash","100 Terahash"]},{q:"Pleb Pool and Atlas Pool are examples of:",a:"Solo Bitcoin mining pools",wrong:["Lightning wallets","Bitcoin exchanges","Hardware wallets"]},{q:"D-Central Technologies specializes in:",a:"Home mining equipment and support",wrong:["Bitcoin trading","Lightning channels","Cold storage"]}],mining_pt3:[{q:"Constellation Heating combines mining with:",a:"Heating swimming pools",wrong:["Cooling data centers","Wind power","Solar panels"]},{q:'What is a "nonce" in Bitcoin mining?',a:'A "number used once" that miners change to find a valid hash',wrong:["A type of mining hardware","A fee paid to nodes","The total number of Bitcoins"]},{q:"Mining pools allow small miners to:",a:"Receive more frequent, smaller payouts",wrong:["Control the entire network","Mine without using electricity","Change the supply of Bitcoin"]},{q:"Bitcoin difficulty adjusts every how many blocks?",a:"2,016 blocks (roughly 2 weeks)",wrong:["210,000 blocks","Only during halvings","Every single block"]},{q:"Bitcoin mining is best described as:",a:"A brute-force lottery of guessing nonces until a valid hash is found",wrong:["Solving complex mathematical equations","Running an algorithm that factors large prime numbers","Decrypting encrypted transaction data"]}],mining_pt4:[{q:"What happens when a miner finds a valid block hash?",a:"They broadcast the block to the network, collect the block reward and transaction fees",wrong:["They must wait for government approval before adding it","The block is sent to Satoshi for verification","All other miners must restart their hardware"]},{q:"Why does Bitcoin mining use so much energy?",a:"Energy expenditure is what gives Bitcoin its security - it makes attacks prohibitively expensive",wrong:["The code is poorly optimized","Miners are required to run 24/7 by law","Each transaction requires its own mining operation"]},{q:'What is "hash rate" in Bitcoin mining?',a:"The total computational power being used to process transactions and secure the network",wrong:["The speed at which new coins are printed","The rate at which transactions are deleted","The number of miners currently online"]},{q:'What is "stranded energy" and why do Bitcoin miners seek it?',a:"Energy produced in remote locations with no local demand - miners can monetize it at low cost",wrong:["Energy that has been stored in batteries","Solar power generated at night","Electricity from decommissioned plants only"]},{q:'What is a mining "share" in a pool?',a:"Proof that a miner contributed valid work toward finding a block, used to split rewards proportionally",wrong:["A stock in the mining company","A partial Bitcoin sent to the miner","A vote on which transactions to include"]}],nodes:[{q:"Running a node lets you:",a:"Verify transactions independently",wrong:["Mine Bitcoin","Print money","Control the network"]},{q:'What does it mean to say Bitcoin has "no leader"?',a:"No single person or organization controls the protocol rules",wrong:["Satoshi still runs it anonymously","The Bitcoin Foundation is in charge","Core developers vote on all changes"]},{q:"A full node stores:",a:"The entire blockchain history",wrong:["Only your transactions","Just the latest block","Nothing"]},{q:"How many Bitcoin nodes exist approximately?",a:"Tens of thousands worldwide",wrong:["Only 5","Exactly 21 million","One per country"]},{q:"Running a node requires:",a:"A regular computer with enough storage",wrong:["A supercomputer","Government permission","A mining rig"]}],nodes_pt2:[{q:"Nodes enforce:",a:"The consensus rules of Bitcoin",wrong:["Government laws","Company policies","Social media rules"]},{q:"Clark Moody dashboard is useful for tracking:",a:"Bitcoin network stats and Knots adoption",wrong:["Altcoin prices","Social media followers","Email subscribers"]},{q:"Matt Hill is the founder and CEO of:",a:"Start9 (node-in-a-box solution)",wrong:["Bitcoin Magazine","Coinbase","Blockstream"]},{q:"The Bitcoin Commons governance model proposes:",a:"Coordination without authority for Bitcoin implementations",wrong:["Central planning of upgrades","Voting on block size","Government oversight"]},{q:"A pruned node saves space by:",a:"Deleting old block data after validating it",wrong:["Only downloading headers","Charging other nodes for storage","Reducing the frequency of blocks"]}],nodes_pt3:[{q:"A full node is different from a miner because:",a:"It enforces all rules but doesn't create new blocks",wrong:["It is faster than a miner","It requires more electricity","It is only for experts"]},{q:"How does your node know if a transaction is valid?",a:"It checks the signatures and inputs against the consensus rules",wrong:["It asks a central server","It votes with other nodes","It waits for a tweet from Satoshi"]},{q:"What is the main benefit of running your own Bitcoin node?",a:"You verify all transactions and blocks yourself without trusting any third party",wrong:["You earn Bitcoin rewards for running it","You can mine Bitcoin more efficiently","You get faster transaction speeds"]},{q:'What does "initial block download" (IBD) mean?',a:"The process of downloading and validating the entire blockchain when first setting up a node",wrong:["The time it takes to mine the first block","Downloading the Bitcoin software installer","Syncing your wallet with an exchange"]},{q:"How does a Bitcoin node protect you from accepting fake transactions?",a:"It independently validates every transaction against consensus rules before accepting it",wrong:["It contacts Satoshi for verification","It checks with three other nodes and takes a vote","It uses AI to detect fraud patterns"]}],"pow-vs-pos":[{q:"Bitcoin uses which consensus mechanism?",a:"Proof of Work",wrong:["Proof of Stake","Proof of Authority","Proof of Space"]},{q:"In Proof of Work, security comes from:",a:"Computational work and electricity",wrong:["Staking coins","Voting","Government approval"]},{q:"Proof of Stake has been criticized for:",a:"Favoring wealthy holders (the rich get richer)",wrong:["Using too much energy","Being too decentralized","Being too slow"]},{q:"Proof of Work connects Bitcoin to:",a:"The physical world through energy expenditure",wrong:["The stock market","Social media","Government databases"]},{q:"In PoW, you can't fake:",a:"The energy spent to mine a block",wrong:["Your username","Your IP address","The current time"]}],"pow-vs-pos_pt2":[{q:"Proof of Work was chosen because:",a:"It provides unforgeable costliness",wrong:["It was the cheapest option","Satoshi had no other ideas","The government required it"]},{q:"What real-world resource does Proof of Work consume that Proof of Stake does not?",a:"Energy (electricity used for computation)",wrong:["Hard drive space","Internet bandwidth","RAM memory"]},{q:'What is the "nothing at stake" problem in Proof of Stake?',a:"Validators can sign multiple competing chain forks at no cost, weakening consensus",wrong:["Stakers lose all their tokens if they validate","There is no block reward in PoS","Validators must buy mining hardware"]},{q:"Why do PoW proponents argue it provides stronger security guarantees?",a:"Attacking PoW requires massive ongoing real-world energy expenditure that can't be faked",wrong:["PoW has more developers working on it","PoW chains are always faster","PoW was invented first so it must be better"]},{q:"How does Proof of Stake differ from Proof of Work in block producer selection?",a:"PoS selects validators based on the amount of coins they lock up, while PoW requires solving computational puzzles",wrong:["PoS uses random lottery tickets purchased with fiat","PoW lets the richest miner always win","There is no difference in selection mechanism"]}],"layer-2-lightning":[{q:"Lightning is which layer of Bitcoin?",a:"Layer 2",wrong:["Layer 1","Layer 3","Layer 0"]},{q:"Lightning uses what for privacy?",a:"Onion routing",wrong:["GPS tracking","Public ledger","Email verification"]},{q:"Opening a Lightning channel is like:",a:"Opening a bar tab",wrong:["Buying a car","Getting a loan","Opening a bank account"]},{q:"Lightning transactions are:",a:"Nearly instant and very cheap",wrong:["Slow and expensive","Free but take hours","Only for large amounts"]},{q:"Lightning channels are settled on:",a:"The Bitcoin base layer",wrong:["Ethereum","A separate blockchain","A bank ledger"]}],"layer-2-lightning_pt2":[{q:"Lightning enables:",a:"Micropayments as small as 1 satoshi",wrong:["Only large transactions","Only fiat payments","Only international transfers"]},{q:"Lightning capacity refers to:",a:"The total Bitcoin locked in payment channels",wrong:["Internet bandwidth","Mining power","Number of nodes"]},{q:"Satogram allows you to:",a:"Send messages across the Lightning network",wrong:["Mine Bitcoin","Create NFTs","Swap altcoins"]},{q:"Lightning Cats and Lightning Goats let you:",a:"Feed real animals using Lightning payments",wrong:["Trade animal NFTs","Mine with animal power","Buy pets with Bitcoin"]},{q:"Pay With Flash is a service for:",a:"Businesses to accept Bitcoin payments",wrong:["Mining Bitcoin","Cold storage","Coin mixing"]}],"layer-2-lightning_pt3":[{q:"LNgigs is a Bitcoin-powered:",a:"Freelance marketplace",wrong:["Mining pool","Exchange","Hardware wallet"]},{q:"The Lightning Network whitepaper was written by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto","Vitalik Buterin","Adam Back"]},{q:"Lightning Network payment channels work by:",a:"Opening a channel with an on-chain transaction, then transacting off-chain instantly",wrong:["Creating a separate blockchain for each payment","Sending Bitcoin through email servers","Using proof of stake instead of proof of work"]},{q:"Why is Lightning considered a Layer 2 solution?",a:"It builds on top of Bitcoin's base layer without changing the protocol",wrong:["Because it is the second cryptocurrency ever created","Because it requires two confirmations per transaction","Because only two people can use it at a time"]},{q:"A Lightning invoice is:",a:"A payment request containing the amount, destination, and expiry time",wrong:["A monthly bill for using the Lightning Network","A receipt showing your mining rewards","A document required by tax authorities"]}],"self-custody":[{q:'"Not your keys, not your..."',a:"Bitcoin",wrong:["Wallet","Password","Account"]},{q:"The most secure long-term storage is:",a:"Hardware wallet",wrong:["Exchange account","Phone app","Email attachment"]},{q:"A seed phrase is typically:",a:"12 or 24 words that recover your wallet",wrong:["Your email password","A website URL","A phone number"]},{q:"You should store your seed phrase:",a:"On paper or metal in a secure location",wrong:["In a screenshot on your phone","In your email drafts","On social media"]},{q:"Multi-sig means:",a:"Multiple keys required to authorize a transaction",wrong:["Multiple Bitcoin addresses","Multiple blockchains","Multiple exchanges"]}],"self-custody_pt2":[{q:"When an exchange holds your Bitcoin:",a:"You have an IOU, not actual Bitcoin",wrong:["It's completely safe","You own it fully","The government insures it"]},{q:"Cold storage means:",a:"Keeping keys offline, disconnected from the internet",wrong:["Storing Bitcoin in a freezer","A cold climate mining facility","An inactive exchange account"]},{q:"A hardware wallet provides security by:",a:"Keeping private keys on a dedicated device that never exposes them to the internet",wrong:["Storing Bitcoin inside the physical device","Encrypting the blockchain so only you can read it","Requiring government approval for each transaction"]},{q:"If you lose your hardware wallet but have your seed phrase, you can:",a:"Recover all your Bitcoin on a new wallet using the seed phrase",wrong:["Nothing - the Bitcoin is permanently lost","Contact the wallet manufacturer for a replacement","File a claim with Bitcoin insurance"]},{q:"Multisig (multi-signature) wallets require:",a:"Multiple keys to authorize a transaction (e.g., 2-of-3)",wrong:["Multiple Bitcoin addresses to send from","Multiple confirmations from the same key","Multiple mining pools to verify"]}],"privacy-nonkyc":[{q:"KYC stands for:",a:"Know Your Customer",wrong:["Keep Your Coins","Keys You Control","Knowledge Yields Crypto"]},{q:"CoinJoin is used for:",a:"Mixing transactions for privacy",wrong:["Joining mining pools","Merging blockchains","Creating altcoins"]},{q:"Non-KYC Bitcoin means:",a:"Bitcoin acquired without identity verification",wrong:["Stolen Bitcoin","Fake Bitcoin","Government Bitcoin"]},{q:"Bitcoin's blockchain is:",a:"Public - anyone can see transactions",wrong:["Completely private","Only visible to miners","Encrypted and hidden"]},{q:"Why do some people prefer non-KYC Bitcoin?",a:"To maintain financial privacy",wrong:["To pay lower fees","To mine faster","To get a better price"]}],"privacy-nonkyc_pt2":[{q:"A Bitcoin address should ideally be:",a:"Used only once for privacy",wrong:["Shared with everyone","Used for all transactions","Posted on social media"]},{q:"The first recorded address poisoning attack on Bitcoin happened in:",a:"2025",wrong:["2021","2013","2009"]},{q:"Shielded CSV on Bitcoin promises:",a:"Better than Zcash-level privacy as an L1.5",wrong:["Faster mining","Bigger blocks","More altcoins"]},{q:"Briar messenger is engineered for:",a:"Privacy in hostile environments using Tor",wrong:["Fast video calls","Social media sharing","Cloud storage"]},{q:'What is a "Dust Attack"?',a:"Tiny amounts of BTC sent to addresses to track the owner's movement",wrong:["A network overload","A type of mining hardware failure","Deleting your private keys by accident"]}],"privacy-nonkyc_pt3":[{q:'"WabiSabi" and "Whirlpool" are types of:',a:"CoinJoin coordination protocols",wrong:["Mining hardware","Wallet brand names","Bitcoin address formats"]},{q:"KYC (Know Your Customer) in Bitcoin refers to:",a:"Identity verification required by regulated exchanges",wrong:["A type of encryption algorithm","A consensus mechanism used by altcoins","The name of a Bitcoin wallet"]},{q:"Why do some Bitcoiners prefer non-KYC acquisition?",a:"To protect financial privacy and avoid linking identity to Bitcoin holdings",wrong:["Because it is cheaper than using exchanges","Because KYC Bitcoin is worth less","Because non-KYC Bitcoin mines faster"]},{q:'What is "address reuse" and why is it a privacy concern?',a:"Using the same Bitcoin address multiple times lets observers link all those transactions to one entity",wrong:["It causes transactions to fail","It increases mining fees","It violates Bitcoin consensus rules"]},{q:'What does "non-KYC Bitcoin" mean?',a:"Bitcoin acquired without providing identity documents, such as through peer-to-peer trades or mining",wrong:["Bitcoin that has never been in a wallet","Bitcoin mined before 2013","Bitcoin stored on a hardware wallet"]}],"problems-of-money":[{q:'Why is inflation described as a "hidden tax"?',a:"It silently erodes the purchasing power of savings without a formal vote",wrong:["It is an unofficial surcharge added by central banks on top of existing income taxes","Banks secretly deposit hidden service fees into government accounts disguised as price rises","Only people in the highest tax bracket are actually subject to the effects of inflation"]},{q:"Fractional reserve banking means:",a:"Banks hold only a fraction of deposits",wrong:["Banks hold all deposits","Bitcoin is fractional","Miners keep fractions"]},{q:"Inflation is often called:",a:"A hidden tax on savings",wrong:["A bonus for savers","A mining reward","A blockchain feature"]},{q:"Fiat currency is backed by:",a:"Government decree and trust",wrong:["Gold reserves","Bitcoin","Real estate"]},{q:"The US dollar has lost what percentage of purchasing power since 1913?",a:"Over 96%",wrong:["About 10%","None","About 50%"]}],"problems-of-money_pt2":[{q:"Money printing causes:",a:"Devaluation of existing currency",wrong:["Deflation","Higher savings rates","Stronger currency"]},{q:"Sound money historically meant:",a:"Money that couldn't be easily debased",wrong:["Money that makes noise","Digital currency","Credit cards"]},{q:"The Cantillon Effect describes how:",a:"Those closest to new money benefit most from inflation",wrong:["Bitcoin mining gets harder","Banks lose money","Gold prices drop"]},{q:"ShadowStats.com tracks:",a:"Real inflation rates vs official government numbers",wrong:["Bitcoin mining difficulty","Lightning channel capacity","Altcoin prices"]},{q:'"The Four Horsemen" documentary (2013) exposes:',a:"The fiat monetary system scam",wrong:["Bitcoin mining farms","Social media dangers","Space exploration"]}],"problems-of-money_pt3":[{q:'"Nixon Shock" in 1971 refers to:',a:"The US ending the dollar's convertibility into gold",wrong:["The launch of Bitcoin","A global stock market crash","The creation of the first bank"]},{q:"Gresham's Law states that:",a:'"Bad money drives out good money"',wrong:['"Bitcoin will replace fiat"','"Gold is always better than silver"','"Taxes are voluntary"']},{q:"What happened in 1971?",a:"Nixon ended the gold standard, allowing unlimited fiat money printing",wrong:["Bitcoin was invented","The first digital computer was built","The Euro was introduced"]},{q:'Inflation is often called a "hidden tax" because:',a:"It silently erodes the purchasing power of your savings",wrong:["The IRS taxes Bitcoin gains at a hidden rate","Banks charge fees that are not disclosed","Governments print money in secret locations"]},{q:"What is seigniorage?",a:"The profit a government makes by issuing currency that costs less to produce than its face value",wrong:["A tax on gold mining","Interest earned on savings accounts","The fee banks charge for wire transfers"]}],"investment-strategy":[{q:"DCA stands for:",a:"Dollar Cost Averaging",wrong:["Digital Currency Account","Decentralized Crypto Asset","Direct Coin Access"]},{q:"A common Bitcoin investment strategy is:",a:"Buy regularly and hold long-term",wrong:["Day trade constantly","Sell every week","Only buy at the top"]},{q:"HODL originated from:",a:'A misspelled forum post saying "I AM HODLING"',wrong:["A financial textbook","A government document","A bank term"]},{q:"Bitcoin's 4-year cycle is often tied to:",a:"The halving events",wrong:["US elections","Solar cycles","Stock market seasons"]},{q:"The best time to buy Bitcoin according to Bitcoiners is:",a:"Always - time in the market beats timing the market",wrong:["Only at all-time highs","Only on Mondays","Only in December"]}],"investment-strategy_pt2":[{q:"Stacking sats means:",a:"Accumulating small amounts of Bitcoin over time",wrong:["Building satellite dishes","Stacking physical coins","Creating smart contracts"]},{q:"The biggest drawdown in Bitcoin history was:",a:"94% decline from $32 to $2 in July 2011",wrong:["50% in 2018","70% in 2022","80% in 2014"]},{q:"MNAV.com tracks:",a:"Bitcoin treasury companies and their metrics",wrong:["Lightning channels","Mining pools","Altcoin prices"]},{q:"Lump-sum investing means:",a:"Buying a large amount of Bitcoin all at once",wrong:["Buying a fixed amount every week","Selling all your holdings","Trading only on weekends"]},{q:"Dollar Cost Averaging (DCA) means:",a:"Buying a fixed amount of Bitcoin at regular intervals regardless of price",wrong:["Only buying when the price drops below a target","Investing your entire savings at once","Selling Bitcoin every time it rises 10%"]}],"investment-strategy_pt3":[{q:'The Bitcoin phrase "zoom out" means:',a:"Look at the long-term price trend instead of daily volatility",wrong:["Reduce your Bitcoin position size","Use a magnifying glass to read the whitepaper","Exit the market during a downturn"]},{q:'What does "stacking sats" mean in Bitcoin culture?',a:"Regularly accumulating small amounts of Bitcoin (satoshis) over time",wrong:["Building a stack of physical Bitcoin coins","Storing Bitcoin on multiple exchanges","Running multiple mining rigs simultaneously"]},{q:'Why do Bitcoiners say "time in the market beats timing the market"?',a:"Long-term holders historically outperform those trying to buy dips and sell tops",wrong:["Because Bitcoin's price never goes down","Because exchanges charge timing fees","Because mining rewards increase over time"]},{q:'What is the "HODL" strategy?',a:"Buying Bitcoin and holding it long-term regardless of short-term price volatility",wrong:["A day-trading technique for quick profits","An automated trading bot strategy","Holding exactly 1 Bitcoin at all times"]},{q:"Why is cold storage recommended for long-term Bitcoin holdings?",a:"Keeping private keys offline eliminates the risk of remote hacking or exchange failure",wrong:["Cold storage earns interest on your Bitcoin","It makes transactions faster","Cold wallets automatically back up to the cloud"]}],cryptography:[{q:"Bitcoin uses cryptography that has been:",a:"Used for decades in other applications",wrong:["Invented specifically for Bitcoin","Never tested before","Made by AI"]},{q:"A private key is:",a:"A secret number that controls your Bitcoin",wrong:["Your email password","A physical key","Your bank PIN"]},{q:"A public key is derived from:",a:"The private key using one-way math",wrong:["Your name","Random chance","The blockchain"]},{q:"Digital signatures prove:",a:"You own the private key without revealing it",wrong:["Your identity","Your location","Your bank balance"]},{q:"Hashing is:",a:"Converting data into a fixed-length fingerprint",wrong:["Deleting data","Encrypting emails","Mining Bitcoin"]}],cryptography_pt2:[{q:"Elliptic curve cryptography is used for:",a:"Generating Bitcoin key pairs",wrong:["Mining blocks","Sending emails","Browsing the web"]},{q:"What type of cryptography does Bitcoin use for digital signatures?",a:"Elliptic Curve Digital Signature Algorithm (ECDSA) on the secp256k1 curve",wrong:["RSA 2048-bit encryption","AES-256 symmetric encryption","Triple DES block cipher"]},{q:"What is a hash function's role in Bitcoin?",a:"It creates a fixed-size, unique digital fingerprint of any input data, used for block headers, addresses, and mining",wrong:["It encrypts all Bitcoin transactions end-to-end","It compresses the blockchain to save space","It converts Bitcoin to other cryptocurrencies"]},{q:"Why can't you derive a private key from a public key?",a:"Elliptic curve math is a one-way function - easy to compute forward, computationally infeasible to reverse",wrong:["Because private keys are longer than public keys","Because the blockchain deletes private keys","Because Satoshi encrypted all key pairs"]},{q:"What does SHA-256 stand for and where is it used in Bitcoin?",a:"Secure Hash Algorithm 256-bit - used in mining (proof of work) and creating transaction IDs",wrong:["Super Hash Accelerator - used in wallet encryption only","Satoshi Hash Algorithm - used in signature verification","Shared Hash Array - used in peer-to-peer networking"]}],regulation:[{q:"Bitcoin's response to bans has been:",a:"Moving to friendlier jurisdictions",wrong:["Shutting down","Complying immediately","Becoming illegal forever"]},{q:"El Salvador made Bitcoin:",a:"Legal tender in 2021",wrong:["Illegal in 2020","A national secret","Only for tourists"]},{q:"Bitcoin regulation varies by:",a:"Country - each has different rules",wrong:["There are no rules anywhere","One global law covers it","Bitcoin regulates itself"]},{q:"A Bitcoin ETF allows:",a:"Traditional investors to get Bitcoin exposure through stock markets",wrong:["Free Bitcoin for everyone","Government-controlled mining","Printing new Bitcoin"]},{q:"The SEC has classified Bitcoin as:",a:"A commodity, not a security",wrong:["A security","A currency","Illegal"]}],regulation_pt2:[{q:'What is a "Self-Custody" regulation attempt?',a:"Rules that try to force users to use custodial services",wrong:["Laws that guarantee free Bitcoin","Mining equipment safety standards","Bitcoin price caps"]},{q:"Can a government effectively ban Bitcoin?",a:"They can restrict fiat on-ramps but cannot stop peer-to-peer transactions",wrong:["Yes - turning off the internet kills Bitcoin permanently","Yes - all nodes can be identified and shut down simultaneously","No bans have ever been attempted by any country"]},{q:"China has banned Bitcoin mining multiple times, yet:",a:"Miners relocated and the network hash rate recovered within months",wrong:["Bitcoin permanently lost 50% of its value","All Chinese Bitcoin was confiscated","The Bitcoin network was offline for weeks"]},{q:"How is Bitcoin classified for tax purposes in most jurisdictions?",a:"As property or a capital asset, meaning gains are subject to capital gains tax",wrong:["As currency, exempt from all taxes","As a commodity with no reporting requirements","As digital cash with no tax implications"]},{q:'What does the "Travel Rule" require for crypto transactions?',a:"Regulated exchanges must share sender and receiver identity information for transfers above a threshold",wrong:["Users must physically travel to an exchange to withdraw","Bitcoin can only be sent within your home country","Miners must verify passport numbers for each block"]}],energy:[{q:"Bitcoin mining and energy:",a:"Promotes renewable energy and uses wasted energy",wrong:["Only uses coal","Wastes all energy","Uses no energy"]},{q:"Stranded energy refers to:",a:"Energy produced in remote locations with no buyers",wrong:["Electricity outages","Solar panels at night","Wind on calm days"]},{q:"Bitcoin miners often locate near:",a:"Cheap renewable energy sources",wrong:["Shopping malls","Government buildings","Residential areas"]},{q:"Bitcoin mining can help stabilize:",a:"Electrical grids by acting as a flexible load",wrong:["The stock market","Internet speeds","Political systems"]},{q:"Compared to traditional banking, Bitcoin's energy use is:",a:"Debatable but often comparable or less",wrong:["1000x more","Zero","Exactly the same"]}],energy_pt2:[{q:"Methane flaring and Bitcoin mining:",a:"Miners can capture and use flared gas productively",wrong:["They are unrelated","Mining increases flaring","Flaring powers all mining"]},{q:"Bitcoin mining primarily uses which type of energy?",a:"Over 50% renewable - often stranded or wasted energy",wrong:["100% coal and natural gas","Nuclear power exclusively","Solar panels attached to mining rigs"]},{q:"Bitcoin mining can actually help the environment by:",a:"Monetizing flared methane that would otherwise be released into the atmosphere",wrong:["Reducing the total electricity consumed worldwide","Creating new renewable energy out of thin air","Cooling the planet through heat dissipation"]},{q:"How do Bitcoin miners contribute to grid stability?",a:"They can instantly power down during peak demand, acting as flexible load that balances the grid",wrong:["They generate excess electricity for the grid","They replace power plants entirely","They only mine during off-peak hours by law"]},{q:"What percentage of Bitcoin mining uses renewable energy sources according to recent estimates?",a:"Over 50% and growing, driven by miners seeking the cheapest energy",wrong:["Less than 5%","Exactly 100% - all mining is renewable","About 10%, mostly nuclear"]}],"core-source-code":[{q:"Changes to Bitcoin Core require:",a:"Careful testing and peer review",wrong:["One person's approval","A company decision","Government permission"]},{q:"What is a Bitcoin Improvement Proposal (BIP)?",a:"A formal document proposing changes or standards for the Bitcoin protocol",wrong:["A mandatory software update all Bitcoin nodes must immediately install","A formal funding request submitted by miners to the Bitcoin Foundation","A signed petition from major exchanges required before protocol changes occur"]},{q:"Anyone can:",a:"Read, review, and propose changes to Bitcoin's code",wrong:["Change Bitcoin without review","Delete the blockchain","Add more coins"]},{q:"A BIP is:",a:"A Bitcoin Improvement Proposal",wrong:["A Bitcoin Investment Plan","A Block Information Protocol","A Banking Integration Process"]},{q:"Bitcoin's code repository is hosted on:",a:"GitHub",wrong:["Facebook","A secret server","The dark web"]}],"blockchain-timechain":[{q:"A new Bitcoin block is produced approximately every:",a:"10 minutes",wrong:["1 second","1 hour","1 day"]},{q:"Each block contains:",a:"A list of transactions and a reference to the previous block",wrong:["Just one transaction","Pictures","Email addresses"]},{q:"The blockchain is often called:",a:"An immutable ledger",wrong:["A cloud server","A website","A database that can be edited"]},{q:"Satoshi originally called it:",a:"A timechain",wrong:["A blockchain","A datachain","A coinchain"]},{q:"The Genesis Block contains a message about:",a:"A newspaper headline about bank bailouts",wrong:["A recipe","A love letter","A stock tip"]}],"blockchain-timechain_pt2":[{q:"Block height refers to:",a:"The sequential number of a block in the chain",wrong:["How tall a server rack is","The size of the block","Mining difficulty"]},{q:"Satoshi originally called the blockchain the:",a:"Timechain",wrong:["Hashchain","Blockweb","Cryptoledger"]},{q:"Each Bitcoin block contains a reference to:",a:"The hash of the previous block, creating an unbreakable chain",wrong:["The next block that will be mined","All future transactions that will occur","A backup of the entire blockchain"]},{q:"The mempool is:",a:"A waiting area where unconfirmed transactions sit until miners include them in a block",wrong:["A type of Bitcoin storage device","The total amount of memory used by Bitcoin nodes","A pool of memory shared between mining hardware"]},{q:'Why did Satoshi originally call it a "timechain" rather than "blockchain"?',a:"Because each block timestamps transactions in chronological order, creating a chain of time-stamped records",wrong:["Because blocks are mined at exactly 10-minute intervals","Because it tracks time zones for each transaction",'Because the name "blockchain" was already trademarked']}],analogies:[{q:"In the airport analogy, Lightning is like:",a:"A bicycle courier in the terminal",wrong:["The runway","A cargo plane","Air traffic control"]},{q:"Bitcoin is often compared to:",a:"Digital gold",wrong:["Digital silver","Digital stocks","Digital bonds"]},{q:"The Bitcoin network is sometimes compared to:",a:"The internet protocol (TCP/IP)",wrong:["A single website","A phone call","A TV channel"]},{q:"Holding Bitcoin is compared to:",a:"Holding property in cyberspace",wrong:["Renting a movie","Subscribing to a service","Opening a bank account"]},{q:"Nick Szabo's pre-Bitcoin proposal for digital scarce money was called:",a:"Bit Gold",wrong:["Digital Cash","E-Gold","Digi-Buck"]}],byzantine_generals__problem:[{q:"The Byzantine Generals Problem is about:",a:"Reaching agreement when some participants may be dishonest",wrong:["Building castles","Trading gold","Sending emails"]},{q:"Bitcoin solved the Byzantine Generals Problem using:",a:"Proof of Work consensus",wrong:["A voting system","A trusted mediator","Encryption alone"]},{q:"In the analogy, the generals need to:",a:"Coordinate an attack without a trusted messenger",wrong:["Build a wall","Trade horses","Sign a peace treaty"]},{q:"Before Bitcoin, the Byzantine Generals Problem was considered:",a:"Unsolvable in a trustless digital environment",wrong:["Easy to solve","Irrelevant","Already solved by banks"]},{q:"The Byzantine Generals Problem asks how dispersed parties can reach consensus without trusting each other. What mechanism did Bitcoin invent to solve this?",a:"Nakamoto Consensus (proof-of-work + longest chain)",wrong:["Voting by validator nodes","Centralized coordinator server","Proof of stake randomization"]}],game_theory:[{q:"Bitcoin's incentive structure uses:",a:"Game theory to align participants",wrong:["Threats of punishment","Legal contracts","Trust alone"]},{q:"Miners are incentivized to be honest because:",a:"Cheating costs more than playing by the rules",wrong:["They sign contracts","The government watches them","There are no incentives"]},{q:"Nash Equilibrium in Bitcoin means:",a:"No participant benefits from changing their strategy alone",wrong:["Everyone mines equally","Prices never change","All nodes are identical"]},{q:"The prisoner's dilemma relates to Bitcoin because:",a:"Cooperation is more profitable than defection",wrong:["Miners are in prison","Bitcoin is illegal","Users are trapped"]},{q:"What game theory concept explains why Bitcoin miners are incentivized to stay honest rather than attack the network?",a:"Nash equilibrium - attacking costs more than honest mining",wrong:["Prisoner\\'s dilemma","Zero-sum game","Pareto inefficiency"]}],elevator_pitches:[{q:"A good Bitcoin elevator pitch should be:",a:"Simple and compelling in under a minute",wrong:["A 2-hour lecture","Only about price","As technical as possible"]},{q:"When explaining Bitcoin to beginners, start with:",a:"The problem it solves (broken money)",wrong:["Mining algorithms","Cryptographic proofs","Exchange trading"]},{q:"The simplest Bitcoin pitch is often:",a:"Digital money that no one can print or confiscate",wrong:["A get-rich-quick scheme","Internet points","A new bank"]},{q:"How would you explain Bitcoin to a complete newcomer in one sentence?",a:"A digital form of money that no government or company can print, freeze, or control",wrong:["A speculative investment to get rich quick","A credit card for online shopping","A bank account with higher interest"]},{q:"What is the most important feature for Bitcoin newcomers to understand first?",a:"Nobody can confiscate or freeze your bitcoin if you hold your own keys",wrong:["The price will always go up","It\\'s anonymous like cash","Transactions are free"]}],taproot:[{q:"Taproot is a Bitcoin:",a:"Upgrade that improves privacy and smart contracts",wrong:["New cryptocurrency","Mining algorithm","Exchange platform"]},{q:"Taproot was activated in:",a:"November 2021",wrong:["January 2009","March 2015","June 2023"]},{q:"Taproot uses Schnorr signatures which:",a:"Make multi-sig transactions look like regular ones",wrong:["Speed up mining","Create new coins","Delete old blocks"]},{q:"Taproot improves:",a:"Privacy, efficiency, and smart contract capabilities",wrong:["Mining speed only","Block size only","Transaction fees only"]},{q:"What type of signature scheme did Taproot introduce to Bitcoin?",a:"Schnorr signatures",wrong:["RSA signatures","Ring signatures","Lamport signatures"]}],taproot_pt2:[{q:"Taproot improves Bitcoin by:",a:"Enhancing privacy, efficiency, and smart contract capabilities using Schnorr signatures",wrong:["Increasing the total supply above 21 million","Removing the need for mining","Making all transactions completely anonymous"]},{q:"When was the Taproot upgrade activated on Bitcoin?",a:"November 2021 at block 709,632",wrong:["August 2017 with SegWit","January 2009 at genesis","June 2023 with Ordinals"]},{q:"What is MAST (Merkelized Abstract Syntax Trees) in Taproot?",a:"A structure that reveals only the executed spending condition, hiding unused conditions for privacy",wrong:["A new mining algorithm that replaces SHA-256","A type of Lightning channel","A database for storing smart contract state"]},{q:"How does Taproot improve multi-signature transactions?",a:"Schnorr signatures allow multiple signers to produce a single compact signature indistinguishable from a regular one",wrong:["It removes the need for multiple signatures entirely","It stores each signature in a separate block","It requires all signers to be online simultaneously"]},{q:"What is Tapscript?",a:"An updated version of Bitcoin Script that enables new opcodes and improved scripting with Taproot",wrong:["A programming language for building altcoins","A tool for writing Bitcoin Core patches","The scripting language used in Lightning Network"]}],scalability:[{q:"Bitcoin base layer processes roughly:",a:"7 transactions per second",wrong:["7 million per second","1 per minute","100,000 per second"]},{q:"Bitcoin scales primarily through:",a:"Layer 2 solutions like Lightning",wrong:["Making blocks bigger forever","Removing the block limit","Using faster internet"]},{q:"The block size limit exists to:",a:"Keep node requirements low and maintain decentralization",wrong:["Slow down transactions","Limit Bitcoin's value","Help miners make more money"]},{q:"The Blocksize Wars were about:",a:"Whether to increase block size or use Layer 2",wrong:["Mining profitability","Bitcoin's name","Which exchange to use"]},{q:"Bitcoin's block size is limited to approximately:",a:"1-4 MB (with SegWit)",wrong:["100 MB","Unlimited - it grows with demand","1 KB"]}],scalability_pt2:[{q:"What did SegWit (Segregated Witness) do for Bitcoin scalability?",a:"Separated signature data from transaction data, effectively increasing block capacity to ~2 MB equivalent",wrong:["Doubled the block size to 2 MB","Removed the block size limit entirely","Moved all transactions to a sidechain"]},{q:"What is transaction batching?",a:"Combining multiple payments into a single on-chain transaction to save block space and fees",wrong:["Sending the same transaction multiple times for reliability","Grouping transactions by sender country","Waiting until a block is full before broadcasting"]},{q:"Why did the Bitcoin community reject simply raising the block size limit?",a:"Larger blocks increase node operating costs, risking centralization and reducing censorship resistance",wrong:["Larger blocks would break all existing wallets","Satoshi explicitly forbade any block size changes","Larger blocks would reduce the total Bitcoin supply"]},{q:"How does the Lightning Network improve Bitcoin's throughput?",a:"By processing millions of transactions off-chain and only settling final balances on the Bitcoin blockchain",wrong:["By replacing Bitcoin's blockchain with a faster one","By increasing the block size to 100 MB","By reducing the time between blocks to 1 second"]},{q:"What is payment channel batching on Lightning?",a:"Opening or closing multiple channels in a single on-chain transaction to save fees and block space",wrong:["Sending the same payment to multiple recipients","Mining multiple blocks at once","Compressing transaction data for faster processing"]}],utxos:[{q:"UTXO stands for:",a:"Unspent Transaction Output",wrong:["Universal Token Exchange Order","Unified Transaction eXecution Object","Ultra-fast Transfer of eXchange Operations"]},{q:"A UTXO is like:",a:"A specific bill in your wallet that you spend whole",wrong:["A bank balance","A credit limit","An account number"]},{q:"When you spend a UTXO:",a:"It's consumed entirely and change is returned as a new UTXO",wrong:["Part of it disappears","It stays in your wallet","It's deleted from the blockchain"]},{q:"UTXO management matters for:",a:"Privacy and minimizing future transaction fees",wrong:["Mining speed","Block creation","Node operation"]},{q:"What is a UTXO in Bitcoin?",a:"Unspent Transaction Output - the amount of bitcoin remaining after a transaction",wrong:["A type of digital signature","A mining reward token","A user transaction ID"]}],dust:[{q:'Bitcoin "dust" is:',a:"An amount too small to spend because the fee exceeds the value",wrong:["Deleted Bitcoin","A type of mining waste","A security attack"]},{q:"Dust attacks are used to:",a:"Track and deanonymize wallet owners",wrong:["Steal Bitcoin directly","Mine faster","Create new blocks"]},{q:"To avoid dust issues:",a:"Consolidate small UTXOs when fees are low",wrong:["Delete your wallet","Stop using Bitcoin","Only use exchanges"]},{q:'What is a "dust attack" in Bitcoin?',a:"Sending tiny amounts of bitcoin to wallets to track and de-anonymize users",wrong:["Overloading the network with large transactions","Physical dirt damaging mining hardware","A bug in the Bitcoin software"]},{q:"Why should users consolidate small UTXOs when fees are low?",a:"To reduce future transaction costs, as each UTXO adds to transaction size",wrong:["To increase bitcoin value","To improve privacy","To earn mining rewards"]}],rbf:[{q:"RBF stands for:",a:"Replace-By-Fee",wrong:["Really Big Fee","Rapid Block Finality","Return Bitcoin Fast"]},{q:"RBF allows you to:",a:"Bump a stuck transaction's fee to speed confirmation",wrong:["Cancel any transaction","Send Bitcoin for free","Mine your own block"]},{q:"RBF is useful when:",a:"Your transaction is stuck because the fee was too low",wrong:["You want to mine","You need a new wallet","You want to buy altcoins"]},{q:"What does RBF (Replace-by-Fee) allow users to do?",a:"Replace an unconfirmed transaction with a higher-fee version",wrong:["Reverse a confirmed transaction","Increase their total bitcoin balance","Prevent double spending"]},{q:"What is CPFP (Child Pays for Parent) used for?",a:"Accelerating confirmation by spending an unconfirmed output with a high-fee transaction",wrong:["Splitting bitcoin for children","Creating child wallets","Reducing transaction size"]}],time_preference:[{q:"Low time preference means:",a:"Saving for the future instead of spending now",wrong:["Spending everything today","Not caring about money","Only day trading"]},{q:"Bitcoin encourages low time preference because:",a:"Its value tends to increase over time due to scarcity",wrong:["It loses value quickly","It pays interest","The government mandates savings"]},{q:"High time preference leads to:",a:"Overconsumption and debt",wrong:["Wealth building","Better savings","Financial freedom"]},{q:"Fiat currency encourages:",a:"Spending now because money loses value over time",wrong:["Long-term saving","Low time preference","Financial responsibility"]},{q:'What is "low time preference" in Bitcoin culture?',a:"Prioritizing long-term saving over short-term spending",wrong:["Trading Bitcoin frequently for quick profits","Spending all your Bitcoin before the next halving","Checking the price every 5 minutes"]}],time_preference_pt2:[{q:"A Bitcoin standard encourages low time preference because:",a:"Saving is rewarded since the money appreciates over time",wrong:["Bitcoin transactions are extremely slow","The government mandates holding periods","You can only sell Bitcoin once per year"]},{q:'What does "low time preference" mean in the context of Bitcoin?',a:"Prioritizing long-term value and future rewards over immediate gratification",wrong:["Preferring to spend Bitcoin quickly before it loses value","Setting a time limit on how long you hold Bitcoin","Trading Bitcoin on short timeframes"]},{q:"How does fiat money encourage high time preference?",a:"Inflation erodes purchasing power, incentivizing spending now rather than saving for later",wrong:["Fiat money expires after a certain date","Banks charge fees for holding money too long","Governments tax savings but not spending"]},{q:'Why do Bitcoiners say Bitcoin "fixes" time preference?',a:"A deflationary hard money incentivizes saving and long-term thinking since purchasing power increases over time",wrong:["Bitcoin automatically invests your savings","Bitcoin transactions are slower, forcing patience","Bitcoin wallets lock funds for a minimum of one year"]},{q:"How does time preference relate to civilization building?",a:"Lower time preference leads to more capital accumulation, investment, and long-term infrastructure development",wrong:["Higher time preference builds civilizations faster","Time preference has no relationship to economic development","Only governments can lower society's time preference"]}],soft_vs_hard_forks:[{q:"A soft fork is:",a:"Backward-compatible upgrade",wrong:["A completely new blockchain","Deleting Bitcoin","A type of altcoin"]},{q:"A hard fork creates:",a:"A permanent chain split if not everyone upgrades",wrong:["A temporary pause","More Bitcoin","A faster network"]},{q:"Bitcoin Cash was created by:",a:"A hard fork of Bitcoin in 2017",wrong:["Satoshi Nakamoto in 2009","The US government","Ethereum developers"]},{q:"SegWit was activated as:",a:"A soft fork",wrong:["A hard fork","A new blockchain","An altcoin"]},{q:"The key difference between a soft fork and a hard fork is:",a:"Soft forks are backwards-compatible; hard forks are not",wrong:["Soft forks are temporary; hard forks are permanent","Soft forks require less code; hard forks need more","Soft forks are approved by vote; hard forks by mining"]}],soft_vs_hard_forks_pt2:[{q:"The Blocksize Wars resulted in:",a:"Bitcoin Cash splitting off as a hard fork while Bitcoin kept small blocks + SegWit",wrong:["Bitcoin doubling its block size to 2 MB","All miners switching to Bitcoin Cash","The creation of Ethereum"]},{q:"What is a soft fork in Bitcoin?",a:"A backward-compatible protocol upgrade where old nodes still accept new blocks",wrong:["A complete restart of the blockchain","A split that creates a new cryptocurrency","An update that requires all nodes to upgrade immediately"]},{q:"What is a hard fork?",a:"A non-backward-compatible change that requires all nodes to upgrade or they'll follow a different chain",wrong:["A bug fix that doesn't change consensus rules","A minor update to wallet software","A temporary network outage"]},{q:"What was the Bitcoin Cash (BCH) hard fork about?",a:"A disagreement over scaling - BCH proponents wanted larger blocks while Bitcoin kept the 1 MB base limit with SegWit",wrong:["A dispute over who created Bitcoin","A fix for a critical security bug","A change to Bitcoin's monetary policy"]},{q:"Why are soft forks generally preferred over hard forks for Bitcoin upgrades?",a:"They maintain backward compatibility, don't force upgrades, and don't risk splitting the network",wrong:["They are faster to implement","They don't require any code changes","Hard forks are illegal in most countries"]}],fedimints:[{q:"Fedimint helps with:",a:"Community custody with privacy",wrong:["Solo mining","Creating altcoins","Government reporting"]},{q:"A Fedimint uses:",a:"Federated guardians who jointly custody Bitcoin",wrong:["A single custodian","Government vaults","Exchange accounts"]},{q:"Fedimint provides privacy through:",a:"Chaumian eCash tokens",wrong:["Public blockchain","KYC verification","IP tracking"]},{q:"Fedimints are designed for:",a:"Communities that trust each other but want privacy",wrong:["Individual use only","Government agencies","Large corporations"]},{q:"A Fedimint (Federated Mint) provides:",a:"Community-custodial privacy through Chaumian ecash on Bitcoin",wrong:["A new type of Bitcoin mining pool","A government-approved Bitcoin exchange","A way to increase Bitcoin's supply above 21 million"]}],fedimints_pt2:[{q:"Fedimints improve Bitcoin privacy by:",a:"Using blinded signatures so the mint cannot link deposits to withdrawals",wrong:["Deleting transaction data from the blockchain","Requiring all users to share their identity","Converting Bitcoin into a different cryptocurrency"]},{q:"What is a Fedimint?",a:"A federated Chaumian eCash mint where a group of guardians custody Bitcoin and issue private eCash tokens",wrong:["A government-run Bitcoin exchange","A type of Bitcoin mining pool","A centralized bank built on Lightning"]},{q:"How do Fedimints provide privacy?",a:"Using blind signatures so the mint cannot link who deposited Bitcoin with who redeems eCash tokens",wrong:["By encrypting the blockchain","By hiding all transactions from the public","By requiring users to use VPNs"]},{q:"What is the trust model of a Fedimint?",a:"Users trust a federation of guardians (e.g., 3-of-5 multisig) rather than a single custodian",wrong:["Completely trustless like on-chain Bitcoin","Users trust a single company","The government guarantees deposits"]},{q:"How do Fedimints interact with the Lightning Network?",a:"They can send and receive Lightning payments, allowing private transactions with the broader Bitcoin network",wrong:["They replace Lightning entirely","Lightning cannot connect to Fedimints","Fedimints require their own separate payment network"]}],books:[{q:"The Bitcoin Standard is a popular book about:",a:"Sound money and Bitcoin economics",wrong:["Bitcoin mining hardware","How to day trade","Building websites"]},{q:"Mastering Bitcoin by Andreas Antonopoulos is:",a:"A technical deep-dive into how Bitcoin works",wrong:["A children's book","A cookbook","A fitness guide"]},{q:"The Sovereign Individual predicted:",a:"Digital money and the decline of nation-states",wrong:["Social media","Electric cars","Space travel"]},{q:"21 Lessons by Gigi explores:",a:"Philosophical lessons learned from going down the Bitcoin rabbit hole",wrong:["21 mining techniques","21 trading strategies","21 altcoins to buy"]},{q:'"The Bitcoin Standard" by Saifedean Ammous primarily argues:',a:"Bitcoin is the hardest money ever invented and will replace fiat",wrong:["Bitcoin is a useful technology but too volatile to be money","Gold is still superior to Bitcoin as a store of value","Central banks should adopt Bitcoin as a reserve currency"]}],books_pt2:[{q:'Gigi\'s "21 Lessons" is structured around:',a:"21 philosophical, economic, and technical lessons learned from Bitcoin",wrong:["A 21-day guide to becoming a Bitcoin trader","The 21 richest Bitcoin holders and their strategies","The history of 21 failed cryptocurrencies"]},{q:'Who wrote "The Bitcoin Standard"?',a:"Saifedean Ammous",wrong:["Andreas Antonopoulos","Satoshi Nakamoto","Michael Saylor"]},{q:"What book by Jimmy Song teaches Bitcoin programming and development?",a:"Programming Bitcoin",wrong:["The Bitcoin Standard","Digital Gold","Cryptoassets"]},{q:"What book by Lyn Alden provides a broad investment perspective including Bitcoin?",a:"Broken Money",wrong:["The Bitcoin Standard","Digital Gold","The Internet of Money"]},{q:'What is "The Blocksize War" by Jonathan Bier about?',a:"The history of Bitcoin's scaling debate, SegWit activation, and the BCH fork",wrong:["How to increase your Bitcoin block rewards","A fiction novel about cryptocurrency battles","Military applications of blockchain technology"]}],"misconceptions-fud":[{q:"FUD stands for:",a:"Fear, Uncertainty, and Doubt",wrong:["Fully Unified Database","First User Downloaded","Financial Update Daily"]},{q:'"Bitcoin is used by criminals" ignores that:',a:"Cash is used far more for crime and Bitcoin is traceable",wrong:["Bitcoin is untraceable","There are no criminals","Crime doesn't exist"]},{q:'"Bitcoin has no intrinsic value" ignores:',a:"Its network security, scarcity, and utility",wrong:["Its physical weight","Its smell","Its color"]},{q:'"Bitcoin is too volatile" ignores:',a:"Its long-term upward trend and decreasing volatility over time",wrong:["That it never moves","That it only goes down","Government price controls"]},{q:'"Bitcoin wastes energy" ignores:',a:"Its use of stranded/renewable energy and the value it secures",wrong:["That it uses no energy","Solar panels","Wind turbines only"]}],"satoshi-nakamoto":[{q:"Satoshi Nakamoto:",a:"Stepped down and disappeared",wrong:["Is currently the CEO of Bitcoin","Was arrested","Sold all Bitcoin"]},{q:"Satoshi's last known communication was around:",a:"2011",wrong:["2020","2015","2009"]},{q:"Satoshi's Bitcoin holdings are estimated at:",a:"About 1 million BTC that have never moved",wrong:["Zero","100 BTC","All 21 million"]},{q:"Satoshi's disappearance is seen as:",a:"A feature - it made Bitcoin truly decentralized",wrong:["A bug","A crime","A marketing strategy"]},{q:"Satoshi's true identity is:",a:"Unknown - it could be one person or a group",wrong:["Confirmed to be Elon Musk","A CIA agent","The President"]}],"satoshi-nakamoto_pt2":[{q:"Why is it important that Satoshi Nakamoto disappeared?",a:"Bitcoin has no leader who can be arrested, corrupted, or pressured",wrong:["Because they were wanted by law enforcement","So they could secretly accumulate more Bitcoin","Because the code was finished and needed no more work"]},{q:"What evidence suggests Satoshi Nakamoto was likely one person rather than a team?",a:"Consistent writing style, coding patterns, and posting times across years of activity",wrong:["A signed confession published on the Bitcoin Talk forum","DNA evidence found on the original Bitcoin server hardware","A government investigation that confirmed a single identity"]},{q:"When did Satoshi Nakamoto stop posting publicly?",a:"Around December 2010, with a final known post in April 2011",wrong:["January 2009 right after launching Bitcoin","They never stopped and still post today","In 2015 during the block size debate"]},{q:"How many Bitcoin did Satoshi Nakamoto reportedly mine?",a:"Approximately 1 million BTC based on analysis of early mining patterns",wrong:["Exactly 21 million (the entire supply)","Zero - Satoshi never mined","About 100 BTC from the genesis block only"]},{q:"What famous message did Satoshi embed in the Bitcoin genesis block?",a:'"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"',wrong:['"Hello World - Bitcoin is born"','"In code we trust"','"The revolution will not be centralized"']}],history:[{q:"The Bitcoin Genesis Block was mined in:",a:"January 2009",wrong:["October 2008","June 2010","December 2007"]},{q:"The first real-world Bitcoin transaction was:",a:"10,000 BTC for two pizzas",wrong:["1 BTC for a car","100 BTC for a house","1 BTC for a coffee"]},{q:"Bitcoin Pizza Day is celebrated on:",a:"May 22",wrong:["January 3","October 31","December 25"]},{q:"Mt. Gox was:",a:"An early Bitcoin exchange that was hacked and collapsed",wrong:["A mining company","A Bitcoin wallet","A government agency"]},{q:"The first Bitcoin block is called:",a:"The Genesis Block (Block 0)",wrong:["The Alpha Block","Block One","The Origin Block"]}],history_pt2:[{q:"Hal Finney received:",a:"The first Bitcoin transaction from Satoshi",wrong:["The last Bitcoin ever","A medal from the government","The Bitcoin trademark"]},{q:"Laszlo's famous pizza order was called from:",a:"London (Laszlo was in Florida)",wrong:["New York","San Francisco","Tokyo"]},{q:"The Bitcoin Wiki has been online since:",a:"2010",wrong:["2015","2009","2013"]},{q:"Tim Draper is known in Bitcoin for:",a:"Buying seized Silk Road Bitcoin at US Marshals auction",wrong:["Creating the Lightning Network","Writing the whitepaper","Mining the genesis block"]},{q:'The "Lightning Torch" was:',a:"A Lightning payment passed between notable Bitcoiners",wrong:["A mining competition","A hardware wallet","A documentary"]}],_general:[{q:"One Bitcoin equals how many satoshis?",a:"100,000,000 (one hundred million)",wrong:["1,000,000 (one million)","10,000,000 (ten million)","1,000,000,000 (one billion)"]},{q:"Bitcoin was launched in which year?",a:"2009",wrong:["2008","2010","2012"]},{q:"Bitcoin transactions are recorded on:",a:"A public distributed ledger",wrong:["A private server","A bank database","An email chain"]},{q:"Who can send you Bitcoin?",a:"Anyone who knows your address",wrong:["Only your bank","Only verified users","Only people in your country"]},{q:"Bitcoin operates on:",a:"24/7, 365 days a year",wrong:["Banking hours only","Weekdays only","It shuts down for maintenance"]},{q:"The total number of Bitcoins that will ever exist is:",a:"Exactly 21 million",wrong:["Unlimited","100 million","It changes yearly"]},{q:"Bitcoin is often abbreviated as:",a:"BTC",wrong:["BTN","BCN","BIT"]},{q:"A Bitcoin wallet stores:",a:"Private keys, not actual Bitcoin",wrong:["Physical coins","Digital files of Bitcoin","Pictures of Bitcoin"]},{q:"To receive Bitcoin you need:",a:"A Bitcoin address",wrong:["A bank account","A social security number","A credit card"]},{q:"The Bitcoin network is maintained by:",a:"Thousands of volunteers running nodes worldwide",wrong:["A company in California","The United Nations","A single supercomputer"]},{q:"Bitcoin confirmation time depends on:",a:"Network congestion and fee paid",wrong:["Time of day","Your internet speed","Which country you are in"]},{q:"A mempool is:",a:"Where unconfirmed transactions wait to be included in a block",wrong:["A mining pool","A type of wallet","A cryptocurrency exchange"]},{q:"Bitcoin difficulty adjustment ensures:",a:"Blocks are found roughly every 10 minutes regardless of hash power",wrong:["Prices stay stable","Miners earn the same amount","Transactions are free"]},{q:"SegWit stands for:",a:"Segregated Witness",wrong:["Secure Widget","Sequential Witness","Segment Width"]},{q:"A Bitcoin address starts with:",a:"1, 3, or bc1",wrong:["0x","BTC","Any letter"]},{q:"The Lightning Network whitepaper was published by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto","Vitalik Buterin","Elon Musk"]},{q:"Bitcoin hash rate measures:",a:"The total computing power securing the network",wrong:["Transaction speed","Number of users","Price changes"]},{q:"A nonce in mining is:",a:"A number miners change to find a valid block hash",wrong:["A type of fee","A wallet address","A block reward"]},{q:'The term "NGMI" in Bitcoin culture means:',a:"Not Gonna Make It",wrong:["New Global Money Index","Next Generation Mining Interface","Network Growth Metric Indicator"]},{q:"Hyperbitcoinization refers to:",a:"Mass voluntary adoption of Bitcoin as money",wrong:["A Bitcoin price crash","A mining difficulty spike","A new altcoin launch"]},{q:"Strike, Cash App, and River are all:",a:"Apps that let you buy Bitcoin",wrong:["Mining pools","Altcoins","Bitcoin forks"]},{q:"Nostr is:",a:"A decentralized social protocol popular in the Bitcoin community",wrong:["A mining algorithm","A Bitcoin fork","An exchange"]},{q:'The phrase "fix the money, fix the world" means:',a:"Sound money leads to better societal outcomes",wrong:["Print more money","Ban all currencies","Use only credit cards"]},{q:"A timelock in Bitcoin allows:",a:"Locking funds until a specific block height or time",wrong:["Freezing the blockchain","Stopping mining","Deleting transactions"]},{q:"Block reward plus transaction fees equals:",a:"The total miner revenue per block",wrong:["The Bitcoin price","The network speed","The difficulty level"]},{q:"Ordinals on Bitcoin are:",a:"A way to inscribe data on individual satoshis",wrong:["A ranking system for miners","A type of wallet","A government regulation"]},{q:"A paper wallet is:",a:"A printed private key for cold storage",wrong:["A paper receipt from an ATM","A bank statement","A type of fiat currency"]},{q:"The Lightning Network can theoretically handle:",a:"Millions of transactions per second",wrong:["7 per second","100 per second","1 per minute"]},{q:"A watch-only wallet lets you:",a:"Monitor a balance without being able to spend",wrong:["Mine Bitcoin","Create new coins","Edit the blockchain"]},{q:"Pleb is a term of endearment in Bitcoin meaning:",a:"An everyday Bitcoiner, not wealthy but committed",wrong:["A professional trader","A mining executive","A government official"]},{q:"What is the total number of satoshis that will ever exist?",a:"2.1 quadrillion (2,100,000,000,000,000)",wrong:["21 million","100 billion","21 quadrillion"]},{q:"Bitcoin's first confirmed exchange rate (in 2010) was roughly:",a:"1,309 BTC per US dollar",wrong:["1 BTC per US dollar","100 BTC per US dollar","0.01 BTC per US dollar"]},{q:"The first Bitcoin exchange rate was established at approximately:",a:"$0.00099 per BTC (less than one penny)",wrong:["$1.00 per BTC","$0.10 per BTC","$100 per BTC"]},{q:"Dollar-cost averaging (DCA) into Bitcoin means:",a:"Buying a fixed amount regularly regardless of price",wrong:["Borrowing dollars to buy Bitcoin all at once","Selling Bitcoin when the dollar strengthens","Converting Bitcoin profits back into dollars"]},{q:'The phrase "Not your keys, not your coins" warns against:',a:"Keeping Bitcoin on exchanges where you don't control the private keys",wrong:["Using physical Bitcoin coins instead of digital","Sharing your public key with other people","Using hardware wallets instead of software"]}],risks__threats__attack_vectors__weaknes:[{q:"Which Bitcoin address type is better for quantum resistance?",a:"SegWit (bc1q) because Taproot exposes the public key",wrong:["Taproot (bc1p)","Legacy (1...)","All are equally vulnerable"]},{q:"BIP 360 proposes:",a:"Pay to Quantum Resistant Hash",wrong:["Bigger blocks","Faster mining","New altcoin support"]},{q:"Why is a 51% attack economically irrational against Bitcoin?",a:"The cost of acquiring that hash rate would far exceed any attainable reward",wrong:["Because Bitcoin's code blocks it automatically","Because Satoshi holds 51% of hash rate as a safeguard","Because 51% of miners have agreed never to attack"]},{q:"What can a successful 51% attacker actually do to Bitcoin?",a:"Double-spend their own recent transactions and block some new transactions",wrong:["Create new Bitcoin out of thin air beyond the 21M cap","Steal coins from other users' wallets","Delete the entire blockchain history"]},{q:"Quantum computing threatens Bitcoin by potentially:",a:"Breaking ECDSA signatures used to authorize spending",wrong:["Mining all remaining Bitcoin in seconds","Deleting the entire blockchain","Creating unlimited new Bitcoin addresses"]}],"evidence-against-alts":[{q:"Ethereum's original sale page reveals that ETH was:",a:"Pre-sold as a security to fund development",wrong:["Mined fairly like Bitcoin","Distributed equally","Created by Satoshi"]},{q:"What fundamental difference exists between Bitcoin and altcoins regarding decentralization?",a:"Altcoin founders often hold large pre-mines or centralized control",wrong:["Altcoins are too cheap","Bitcoin has better marketing","Altcoins use different blockchains"]},{q:'Why do Bitcoiners say "there is no second best"?',a:"No other crypto achieves Bitcoin's decentralization, security, and immutability",wrong:["Bitcoin was the first, so it automatically wins","The SEC has declared all other cryptos illegal","Satoshi patented the blockchain concept"]},{q:'What is a "pre-mine" and why is it concerning?',a:"Founders allocate coins to themselves before public launch - unfair distribution",wrong:["A technique to speed up transaction processing","A security measure that protects the network","A method of testing the blockchain before launch"]},{q:"Most altcoins are considered securities because:",a:"They have identifiable teams profiting from token sales with promises of returns",wrong:["They use the same code as Bitcoin","The SEC approves them as securities automatically","They are traded on stock exchanges"]}],"smart-contracts":[{q:"Bitcoin's scripting language has supported smart contracts:",a:"Since the beginning - Bitcoin always had them",wrong:["Only after Taproot in 2021","Only after SegWit in 2017","Never - only Ethereum has them"]},{q:"OP_RETURN is used in Bitcoin to:",a:"Embed small amounts of data in transactions",wrong:["Return sent Bitcoin","Cancel transactions","Mine faster"]},{q:"What is Bitcoin\\'s native scripting language called?",a:"Bitcoin Script",wrong:["Solidity","Python Script","JavaScript"]},{q:"What does OP_RETURN allow users to do on Bitcoin?",a:"Embed up to 80 bytes of arbitrary data in a transaction",wrong:["Execute Ethereum-style smart contracts","Change transaction amounts","Create new bitcoins"]},{q:"What are DLCs (Discreet Log Contracts) on Bitcoin?",a:"Smart contracts that settle based on external oracle data without revealing details",wrong:["Private keys stored in logs","Debug contracts for developers","Decentralized lending contracts on Ethereum"]}],"chaumian-mints":[{q:"Cashu is an implementation of:",a:"Chaumian ecash on Bitcoin/Lightning",wrong:["A new blockchain","An altcoin","A mining algorithm"]},{q:"Who invented the blind signature technology used in Chaumian eCash?",a:"David Chaum in 1982",wrong:["Satoshi Nakamoto in 2008","Adam Back in 1997","Hal Finney in 2004"]},{q:"What modern Bitcoin layer implements Chaumian eCash for minting privacy-preserving tokens?",a:"Cashu and Fedimint protocols",wrong:["Lightning Network","Liquid Network","Ethereum ERC-20"]},{q:"Cashu is:",a:"An ecash protocol built on Bitcoin using Chaumian blind signatures",wrong:["A competing cryptocurrency to Bitcoin","A hardware wallet manufacturer","A type of Bitcoin mining software"]},{q:'What are "blind signatures" in ecash?',a:"The mint signs tokens without knowing which user they belong to",wrong:["Signatures that expire after 24 hours","A way to sign transactions without a private key","Signatures that can only be verified by the government"]}],"swag-merch":[{q:"BTCAccepted.org helps you find:",a:"Businesses that accept Bitcoin payments",wrong:["Mining pools","Lightning nodes","Altcoin exchanges"]},{q:"Sats.host offers:",a:"Bitcoin-powered static website hosting",wrong:["Mining services","Cold storage","KYC verification"]},{q:'What annual Bitcoin conference is often called "the Super Bowl of Bitcoin"?',a:"Bitcoin Conference (formerly Miami/Bitcoin 2021)",wrong:["Consensus","DevCon","ETHDenver"]},{q:"What is the significance of wearing an orange pill at Bitcoin conferences?",a:'Signifies being "orange pilled" - awakened to Bitcoin\\\'s importance',wrong:["Medical supplement promotion","Conference staff identifier","VIP pass indicator"]},{q:"What popular Bitcoin merchandise item satirizes central banking?",a:'"End the Fed" t-shirts and posters',wrong:["Bitcoin gaming chairs","Satoshi action figures","Mining rig keychains"]}],"apps-tools":[{q:"PPQ.ai lets you use AI models and pay with:",a:"Bitcoin per prompt - no subscription needed",wrong:["Monthly credit card subscription","Ethereum gas fees","Free but with ads"]},{q:"Angor is a platform for:",a:"Non-custodial Bitcoin crowdfunding",wrong:["Bitcoin mining","Coin mixing","Hardware wallets"]},{q:"What website provides real-time visualization of the Bitcoin mempool?",a:"mempool.space",wrong:["blockchain.com","coinmarketcap.com","bitcoincharts.com"]},{q:"What popular hardware wallet supports both Bitcoin and Lightning?",a:"Coldcard and BitBox02",wrong:["PayPal Card","Venmo Wallet","Apple Pay"]},{q:"What full node implementation is the most widely used for running Bitcoin?",a:"Bitcoin Core",wrong:["Bitcoin Cash","Ethereum Classic","Ripple Node"]}],games:[{q:"Timechain Arcade offers:",a:"Free Bitcoin-themed video games",wrong:["Mining services","Trading tools","Hardware wallets"]},{q:"CanYouBeatBitcoin.com is:",a:"An investing simulator comparing your picks to Bitcoin",wrong:["A mining difficulty calculator","A Bitcoin wallet","A trading bot"]},{q:"What type of Bitcoin games reward players with satoshis?",a:"Play-to-earn Lightning games",wrong:["Casino-style gambling","Console RPGs","Mobile ad games"]},{q:"What popular Bitcoin trivia app lets users earn sats for answering questions?",a:"THNDR Games (like Bitcoin Bounce, Bitcoin Bay)",wrong:["Fortnite","Candy Crush","Minecraft"]},{q:"What is Zebedee known for in the Bitcoin gaming space?",a:"A platform enabling Lightning payments in games",wrong:["Hardware mining rigs","Altcoin exchange","NFT marketplace"]}],"difficulty-adjustment":[{q:"How often does Bitcoin's difficulty adjustment occur?",a:"Every 2,016 blocks (approximately 2 weeks)",wrong:["Every 1,000 blocks","Every month","Every day"]},{q:"What does the difficulty adjustment ensure?",a:"Blocks are found roughly every 10 minutes regardless of hash power changes",wrong:["Transaction fees stay constant","Mining rewards increase","Block size adjusts automatically"]},{q:"Bitcoin's difficulty adjusts every:",a:"2,016 blocks (roughly every 2 weeks)",wrong:["Every single block","Once per year","Every 210,000 blocks (at each halving)"]},{q:"If miners leave the network, difficulty adjustment:",a:"Lowers the difficulty so blocks are found at the target rate",wrong:["Increases difficulty to punish remaining miners","Has no effect - blocks just take longer forever","Automatically doubles the block reward"]},{q:"The target time between Bitcoin blocks is approximately:",a:"10 minutes",wrong:["1 minute","1 hour","30 seconds"]}],nostr:[{q:"What does the Nostr acronym stand for?",a:"Notes and Other Stuff Transmitted by Relays",wrong:["Network of Secured Transactions and Relays","New Open Source Transaction Relay","Node-Operated Social Trust Registry"]},{q:"What makes Nostr unique from typical social media?",a:"Your identity is uncensorable and no single entity controls the platform",wrong:["It automatically pays users in Bitcoin proportional to the engagement they receive","It functions exclusively on mobile devices with no desktop interface available","It requires government-issued identity verification before any content can be published"]},{q:"What is a NIP in the Nostr ecosystem?",a:"A Nostr Implementation Possibility - a protocol specification for how clients and relays behave",wrong:["A Nostr Identity Protocol mapping public keys to verified human-readable usernames","A standardised encryption layer securing private direct messages between Nostr users","A subscription fee structure charged by premium relay operators for event publishing"]},{q:"Nostr uses cryptographic keys to:",a:"Allow users to own their identity without a central authority",wrong:["Mine new coins on the Nostr blockchain","Encrypt all messages so no one can read them","Create smart contracts between users"]},{q:"How is Nostr connected to Bitcoin?",a:"Many clients integrate Lightning for tips and payments",wrong:["Nostr runs on the Bitcoin blockchain directly","You must own Bitcoin to create a Nostr account","Nostr mining validates Bitcoin transactions"]}],network_effects:[{q:"Bitcoin's network effect means:",a:"Each new user increases the value and utility for all existing users",wrong:["The internet gets faster","Mining gets easier","Fees decrease to zero"]},{q:"Why is Bitcoin's network effect considered a strong moat?",a:"It creates a self-reinforcing cycle of liquidity, security, and adoption that competitors cannot easily replicate",wrong:["Because Bitcoin has patents","Because the government protects it","Because the code is encrypted"]},{q:"What economic principle explains Bitcoin\\'s value increasing as more people use it?",a:"Metcalfe\\'s Law - network value proportional to connected users squared",wrong:["Moore\\'s Law","Murphy\\'s Law","Pareto Principle"]},{q:"Metcalfe's Law applied to Bitcoin suggests:",a:"Its value grows proportionally to the square of its users",wrong:["The price will always increase linearly","Only the first users receive any benefit","Network effects only apply to social media"]},{q:"What is the flywheel effect in Bitcoin adoption?",a:"More users attract more developers, merchants, and infrastructure, which attracts even more users",wrong:["Mining gets easier as more people join","Transaction fees decrease as the network grows","Bitcoin price always goes up with more users"]}],governance:[{q:"Bitcoin governance is best described as:",a:"Rough consensus among users, developers, miners, and node operators",wrong:["A CEO makes all decisions","Miners vote on everything","A foundation sets the rules"]},{q:"The Blocksize Wars demonstrated that:",a:"Users and node operators ultimately control Bitcoin's rules, not miners alone",wrong:["Miners have absolute power","Developers can force any change","Bitcoin cannot be upgraded"]},{q:"What is the BIP process in Bitcoin?",a:"Bitcoin Improvement Proposals for suggesting protocol changes",wrong:["Bitcoin Investment Plan","Blockchain IP Protection","Banking Integration Protocol"]},{q:"How is Bitcoin governed?",a:"Through rough consensus among users, developers, miners, and node operators",wrong:["By a board of directors at the Bitcoin Foundation","Through shareholder voting like a corporation","By whoever owns the most Bitcoin"]},{q:"A BIP (Bitcoin Improvement Proposal) is:",a:"A formal document proposing changes to Bitcoin's protocol or processes",wrong:["A mandatory update that all nodes must accept","A financial investment in Bitcoin development","A bug report filed to the Bitcoin support team"]}],human_rights__social_justice_and_freedo:[{q:"Bitcoin supports human rights by:",a:"Providing censorship-resistant money that cannot be confiscated by authoritarian regimes",wrong:["Replacing all governments","Eliminating all poverty instantly","Being controlled by the UN"]},{q:"Alex Gladstein advocates for Bitcoin because:",a:"It empowers people living under authoritarian regimes with financial freedom",wrong:["It makes trading stocks easier","It replaces the need for banks in wealthy countries","It was designed as a protest tool"]},{q:"How has Bitcoin helped activists in authoritarian regimes?",a:"By enabling uncensorable fundraising and protecting wealth from seizure",wrong:["By hiding their identity completely","By earning interest from banks","By creating new currencies"]},{q:"How does Bitcoin help people under authoritarian regimes?",a:"It provides censorship-resistant money that governments cannot freeze",wrong:["It automatically reports suspicious activity to authorities","It requires government ID to transact","It only works in democratic countries"]},{q:"Alex Gladstein of the Human Rights Foundation argues that:",a:"Bitcoin is the most important tool for financial freedom globally",wrong:["Only wealthy nations benefit from Bitcoin","Bitcoin should be controlled by human rights organizations","Proof of Stake is better for human rights than Proof of Work"]}],market_cap:[{q:"Bitcoin's market cap is calculated by:",a:"Current price multiplied by total coins in circulation",wrong:["Total transaction volume per day","Number of wallets times average balance","Mining revenue times block height"]},{q:"Why can Bitcoin's market cap potentially exceed gold's?",a:"Bitcoin is more portable, divisible, verifiable, and scarce than gold",wrong:["Because governments will mandate it","Because gold will be banned","Because Bitcoin mining produces gold"]},{q:"What metric compares Bitcoin\\'s market value to all other cryptocurrencies combined?",a:"Bitcoin Dominance Index",wrong:["Coin Market Gap","Crypto Index Fund","Volatility Ratio"]},{q:"Bitcoin's market capitalization represents:",a:"The total value of all existing Bitcoin at the current price",wrong:["The maximum number of coins that can ever exist","The amount of money invested in Bitcoin mining","The total transaction volume over the past year"]},{q:"If Bitcoin captured gold's market cap, each coin would be worth approximately:",a:"Over $500,000",wrong:["$100,000","$50,000","$10,000"]}],the_future:[{q:'What hypothetical event do Bitcoiners call "hyperbitcoinization"?',a:"A voluntary tipping point where Bitcoin displaces fiat as the world's dominant money",wrong:["A coordinated government transition where nations simultaneously adopt a Bitcoin standard","A planned protocol upgrade that makes Bitcoin the only globally compatible payment rail","A forced redenomination where central banks exchange fiat reserves for Bitcoin at par"]},{q:"Bitcoin is described as 'generational wealth' because:",a:"Its fixed supply and growing adoption may increase its value over decades",wrong:["Only family members can legally inherit and access a deceased holder's Bitcoin wallet","Bitcoin wallets automatically expire and reset to zero after 25 years of inactivity","Central banks officially guarantee Bitcoin's face value for 100 years as a reserve asset"]},{q:'What is the "digital scarcity" argument for Bitcoin\'s long-term value?',a:"Unlike any prior asset, Bitcoin's supply cap is enforced by math rather than human institutions",wrong:["Scarcity is irrelevant because Bitcoin can be subdivided infinitely","Bitcoin's value comes from government backing similar to gold reserves","Digital files can always be copied so Bitcoin cannot truly be scarce"]},{q:"What happens when the last Bitcoin is mined (~2140)?",a:"Miners will be compensated solely through transaction fees",wrong:["The network will shut down permanently","A new supply of 21 million coins will be created","Mining will become free with no reward"]},{q:'Who coined the term "hyperbitcoinization"?',a:"Daniel Krawisz in a 2014 Nakamoto Institute essay",wrong:["Satoshi Nakamoto in the Bitcoin whitepaper","Michael Saylor during a 2020 conference","Andreas Antonopoulos in Mastering Bitcoin"]}],"orange-pilling":[{q:"'Orange-pilling' someone means:",a:"Convincing them to understand and adopt Bitcoin",wrong:["Selling them altcoins","Giving them free Bitcoin","Signing them up for an exchange"]},{q:"The most effective way to orange-pill someone is often:",a:"Starting with the problem Bitcoin solves (broken money) rather than technical details",wrong:["Showing them price charts","Explaining SHA-256 hashing","Telling them to buy immediately"]},{q:'What does "orange pilling" someone mean?',a:"Educating them about Bitcoin until they understand its importance",wrong:["Giving them actual pills","Selling them mining equipment","Creating a Bitcoin wallet for them"]},{q:"What is the best approach when orange-pilling a skeptic?",a:"Start with their specific pain point (inflation, remittances, censorship) rather than technical details",wrong:["Show them price charts and promise guaranteed returns","Pressure them into buying immediately before the next halving","Explain the full UTXO model and Merkle trees first"]},{q:"The most effective orange-pilling strategy is:",a:"Meeting people where they are and addressing their specific concerns",wrong:["Posting price predictions on social media","Telling people they are stupid for not buying","Promising guaranteed financial returns"]}],maximalism:[{q:"Bitcoin maximalism is the belief that:",a:"Bitcoin is the only cryptocurrency that truly matters as sound money",wrong:["You should invest everything in Bitcoin","Bitcoin should replace all technology","Only developers should use Bitcoin"]},{q:"Maximalists argue altcoins are unnecessary because:",a:"Bitcoin's base layer plus additional protocol layers can serve all use cases",wrong:["Because altcoins are illegal","Because Satoshi said so","Because there can only be one blockchain"]},{q:"What is Bitcoin maximalism?",a:"The belief that Bitcoin will be the only cryptocurrency to achieve long-term dominance",wrong:["Investing only in altcoins","Maximizing one\\'s bitcoin holdings at all costs","Running multiple full nodes"]},{q:"Why do deep Bitcoin researchers tend to become maximalists?",a:"They realize no other project achieves true decentralization and immutability",wrong:["They are paid by Bitcoin companies to promote it","They lack knowledge of other technologies","It is required to participate in the Bitcoin community"]},{q:"What is the core argument of Bitcoin maximalists?",a:"Only Bitcoin achieves true decentralization and sound money; altcoins compromise on critical aspects",wrong:["Bitcoin should be the only legal currency","All other technology besides Bitcoin is useless","Maximalists refuse to use the internet"]}],developers:[{q:"Bitcoin Core is primarily written in:",a:"C++",wrong:["Python","JavaScript","Rust"]},{q:"Contributing to Bitcoin open source requires:",a:"Anyone can propose changes - no permission needed",wrong:["A computer science degree","Approval from the Bitcoin Foundation","Purchasing a developer license"]},{q:"Who is considered Bitcoin\\'s lead maintainer as of recent years?",a:"There is no formal leader; Bitcoin Core has multiple maintainers",wrong:["Satoshi Nakamoto","Vitalik Buterin","Elon Musk"]},{q:"What organization has historically funded Bitcoin Core development?",a:"MIT Digital Currency Initiative, Chaincode Labs, Brink, Spiral",wrong:["World Bank","Federal Reserve","Goldman Sachs"]},{q:"Which version control system hosts Bitcoin Core's source code?",a:"Git",wrong:["SVN","Mercurial","Bazaar"]}],ham_radio:[{q:"Bitcoin transactions can be sent via ham radio, which means:",a:"Bitcoin can work without an internet connection",wrong:["Bitcoin requires satellite dishes","Only miners can use radio","Radio transactions are free"]},{q:"How can Bitcoin transactions be sent without internet?",a:"Via ham radio operators broadcasting signed transactions",wrong:["Via postal mail","Via telephone calls","Via satellite TV only"]},{q:"What mesh network protocol has been used to broadcast Bitcoin transactions?",a:"Blockstream Satellite and goTenna mesh networks",wrong:["Bluetooth Classic","NFC payments","Zigbee home network"]},{q:"What is the benefit of Bitcoin over ham radio?",a:"Censorship resistance even when governments shut down internet",wrong:["Faster than fiber internet","Lower transaction fees","Better for large file transfers"]},{q:"Who demonstrated sending Bitcoin via ham radio in 2019?",a:"Rodolfo Novak co-founder of Coinkite",wrong:["Elon Musk","Jack Dorsey","Andreas Antonopoulos"]}],lightning_node:[{q:"Running a Lightning node allows you to:",a:"Route payments and earn fees while supporting the network",wrong:["Mine Bitcoin faster","Create new Bitcoin","Access the dark web"]},{q:"What is a Lightning node?",a:"Software that routes payments on the Lightning Network using payment channels",wrong:["A physical Bitcoin ATM","A mining rig","A Bitcoin exchange server"]},{q:"What do node operators lock up to open payment channels?",a:"Bitcoin as liquidity for routing payments",wrong:["Ethereum tokens","Fiat currency","Computing power"]},{q:"What fee do Lightning routing nodes typically charge?",a:"Routing fees measured in milli-satoshis (very small fraction of a cent)",wrong:["1% of transaction amount","$5 per payment","No fees allowed"]},{q:"What is inbound liquidity for a Lightning node?",a:"The ability to receive payments based on funds others have locked with you",wrong:["Money coming from bank deposits","Mining rewards","Exchange trading profits"]}],stablecoins:[{q:"Stablecoins in the Bitcoin ecosystem are typically:",a:"Tokens pegged to fiat currency values, sometimes built on Bitcoin layers",wrong:["A type of mining reward","Bitcoins that never change price","Government-issued digital dollars"]},{q:"What backs the majority of USDT (Tether)?",a:"Commercial paper, cash equivalents, and other reserves (historically controversial)",wrong:["100% US dollars in bank","Gold reserves","Bitcoin collateral"]},{q:"What major risk do centralized stablecoins pose?",a:"Issuer can freeze funds or fail to maintain peg",wrong:["They mine too slowly","High transaction fees","Private key loss"]},{q:"What caused USDC to depeg temporarily in March 2023?",a:"Exposure to failed Silicon Valley Bank",wrong:["Bitcoin price crash","Lightning Network bug","Satoshi selling coins"]},{q:"Stablecoins are NOT a threat to Bitcoin because:",a:"They are centralized IOUs that can be frozen, while Bitcoin is permissionless",wrong:["Stablecoins use the same technology as Bitcoin","Bitcoin automatically converts to stablecoins during crashes","Stablecoins have a higher market cap than Bitcoin"]}],consensus:[{q:"Bitcoin consensus means:",a:"All nodes agree on the state of the blockchain without a central authority",wrong:["Everyone votes on transactions","Miners decide which transactions are valid alone","The government approves each block"]},{q:"What is Nakamoto Consensus?",a:"The combination of proof-of-work, longest chain rule, and economic incentives",wrong:["Voting by coin holders","Consensus by the Bitcoin Foundation","Agreement between exchanges"]},{q:"Why does Bitcoin use the longest chain as the valid chain?",a:"Most proof-of-work indicates most energy/computational investment",wrong:["Random selection","Shortest chains are invalid","User voting"]},{q:"Nakamoto Consensus achieves agreement by:",a:"Having nodes follow the longest valid proof-of-work chain",wrong:["Requiring all nodes to vote on each transaction","Letting the wealthiest node decide which blocks are valid","Using a central server to broadcast the correct chain"]},{q:"What happens if two miners find a valid block at nearly the same time?",a:"A temporary fork occurs and resolves when the next block is found",wrong:["Both blocks are permanently added to the chain","The network shuts down until the conflict is resolved","The older miner's block always wins"]}],open_source:[{q:"Bitcoin being open source means:",a:"Anyone can read, audit, and propose changes to the code",wrong:["The code is secret but free to use","Only approved developers can view it","It costs nothing to mine"]},{q:"What license is Bitcoin Core released under?",a:"MIT License (open source)",wrong:["Proprietary commercial license","GPL v3 only","Patent-encumbered license"]},{q:"How can anyone contribute to Bitcoin Core?",a:"Submit pull requests on GitHub after code review",wrong:["Pay a developer fee","Get hired by a bank","Apply for a license"]},{q:"What is the purpose of code review in Bitcoin development?",a:"To catch bugs and security issues before deployment",wrong:["To slow down development","To charge developers money","To keep the code secret"]},{q:"Why is peer review critical in Bitcoin Core development?",a:"It catches bugs and vulnerabilities before they reach production, since changes affect billions in value",wrong:["It is just a formality required by the MIT license","Only one reviewer is needed for minor patches","Peer review slows down development unnecessarily"]}],coin_mixing_coinjoin_coin_control_utxo:[{q:"CoinJoin improves privacy by:",a:"Combining multiple users' transactions so individual spending is hard to trace",wrong:["Encrypting the blockchain","Deleting transaction history","Creating fake transactions"]},{q:"What is CoinJoin?",a:"A privacy technique combining multiple users\\' transactions to break heuristics",wrong:["A cryptocurrency mixer token","A type of hardware wallet","An exchange withdrawal method"]},{q:"What does coin control allow Bitcoin users to do?",a:"Manually select which UTXOs to spend in a transaction",wrong:["Control the price of bitcoin","Limit mining difficulty","Set transaction speed"]},{q:"What privacy benefit does proper UTXO management provide?",a:"Preventing address clustering and transaction graph analysis",wrong:["Increasing mining rewards","Reducing transaction fees","Speeding up confirmations"]},{q:'What is "coin control" in a Bitcoin wallet?',a:"The ability to manually select which UTXOs to spend in a transaction for better privacy",wrong:["A government program to regulate Bitcoin spending","Software that limits how much Bitcoin you can buy","A mining feature that controls block production"]}],environment___energy:[{q:"Bitcoin mining's relationship with renewable energy is:",a:"Miners actively seek cheap renewable and stranded energy, incentivizing green energy development",wrong:["Mining only uses coal","Renewable energy cannot power mining","Mining has no relationship with energy markets"]},{q:"What percentage of Bitcoin mining comes from renewable energy (estimates)?",a:"Estimates range from 50-60% using renewable or stranded energy",wrong:["0% - all coal","100% renewable","Less than 10%"]},{q:'What is "stranded energy" in Bitcoin mining?',a:"Energy that would otherwise go to waste due to lack of transmission infrastructure",wrong:["Energy from broken solar panels","Leftover battery power","Natural gas used for heating"]},{q:"How does Bitcoin mining help stabilize electrical grids?",a:"Miners can rapidly reduce load during peak demand (demand response)",wrong:["By storing electricity in batteries","By donating profits to utilities","By building more coal plants"]},{q:"What common criticism about Bitcoin energy use is often misrepresented?",a:"Per-transaction energy cost (Bitcoin uses same energy regardless of transaction count)",wrong:["It uses no energy at all","All energy comes from coal","Mining makes computers explode"]}],austrian_school_of_economics:[{q:"The Austrian School of Economics relates to Bitcoin because:",a:"It advocates for sound money with limited supply, which Bitcoin embodies",wrong:["It was founded by Satoshi Nakamoto","It requires government-controlled currency","It predicts Bitcoin will fail"]},{q:"Which Austrian economist emphasized the importance of sound money and criticized fiat?",a:"Ludwig von Mises and Friedrich Hayek",wrong:["John Maynard Keynes","Karl Marx","Milton Friedman"]},{q:"The Austrian School of Economics emphasizes:",a:"Sound money, free markets, and the dangers of central banking",wrong:["Government control of all monetary systems","That inflation is beneficial for economic growth","That central banks should print unlimited money"]},{q:'Who wrote "The Theory of Money and Credit"?',a:"Ludwig von Mises",wrong:["John Maynard Keynes","Paul Krugman","Adam Smith"]},{q:'Saifedean Ammous\' book "The Bitcoin Standard" argues that Bitcoin is the best form of money because:',a:"It is the hardest money ever created — no authority can inflate its supply",wrong:["It provides higher investment returns than gold over any comparable 10-year period","It is the only payment network capable of achieving true instant global settlement","A global coalition of central banks has adopted it as their primary reserve asset"]}],lindy_effect:[{q:'The term "Lindy Effect" was coined and popularized in its modern form by:',a:"Nassim Nicholas Taleb in his 2012 book Antifragile",wrong:["Satoshi Nakamoto in the Bitcoin whitepaper","Albert Goldman originally in 1964","Benoît Mandelbrot in The Fractal Geometry of Nature"]},{q:"What is the Lindy Effect?",a:"The longer something survives, the longer its remaining life expectancy",wrong:["A statistical model measuring how quickly Bitcoin mining difficulty adjusts to hash rate","A type of cryptographic hash function used to verify Bitcoin block headers on-chain","An industry certification that labels hardware wallet firmware as officially secure"]},{q:"The Lindy Effect applies to non-perishable things. Which of these would it NOT apply to?",a:"A human being - biological organisms have decreasing life expectancy with age",wrong:["Bitcoin, which has survived and strengthened over 15+ years of relentless stress-testing","The concept of sound money, which has persisted across thousands of years of civilisation","The C++ programming language, widely used on critical systems since the early 1980s"]},{q:"What concept is closely related to Lindy Effect in Bitcoin?",a:"Antifragility - stress makes the system stronger",wrong:["Inflation targeting","Proof of stake","Central banking"]},{q:"Why is Bitcoin's 15+ year survival significant for the Lindy Effect?",a:"Demonstrates resilience to attacks, bugs, and regulatory pressure",wrong:["Proves the codebase is now too rigid and entrenched to accept meaningful future upgrades","Makes it technically obsolete compared to newer blockchain protocols built after 2018","Shows that its energy consumption has compounded past any level that society can sustain"]}],softwar:[{q:"Jason Lowery's Softwar thesis argues that:",a:"Proof-of-work is a form of digital power projection analogous to military power in the physical world",wrong:["Bitcoin is a weapon system","Software replaces all hardware","Bitcoin was created by the military"]},{q:'Who authored the "Softwar" thesis about Bitcoin?',a:"Major Jason Lowery of the US Space Force",wrong:["Michael Saylor","Nick Szabo","Elizabeth Warren"]},{q:"What is the core argument of the Softwar thesis?",a:"Proof-of-work is a form of kinetic power projection for cyberspace",wrong:["Bitcoin should be banned","Proof of stake is superior","Bitcoin is a company"]},{q:"What does Softwar compare Bitcoin\\'s hash rate to?",a:"Physical military power projection and deterrence",wrong:["Social media likes","Stock market volume","Bank transaction counts"]},{q:"How does the Softwar thesis view Bitcoin mining in terms of national security?",a:"As a strategic asset that projects power in cyberspace, similar to how militaries project power in physical space",wrong:["As a threat to national security that should be banned","As purely an economic activity with no geopolitical significance","As a replacement for nuclear deterrence"]}],sidechains:[{q:"A Bitcoin sidechain is:",a:"A separate blockchain that is pegged to Bitcoin, enabling additional features while settling back to the main chain",wrong:["A backup copy of the Bitcoin blockchain","A faster version of Bitcoin Core","An altcoin that replaced Bitcoin"]},{q:"What is the Liquid Network?",a:"A federated sidechain enabling faster confidential Bitcoin transactions",wrong:["An Ethereum scaling solution","A mining pool","A hardware wallet"]},{q:"What is RSK (Rootstock)?",a:"A Bitcoin sidechain supporting smart contracts with merged mining",wrong:["A Russian Bitcoin exchange","A hardware wallet brand","A Lightning wallet"]},{q:"How are assets secured when moving to a sidechain?",a:"Through a federated peg locking bitcoin on mainchain",wrong:["By burning bitcoin permanently","By trusting a single company","No security is provided"]},{q:"What is a downside of federated sidechains compared to Bitcoin mainchain?",a:"Less decentralization due to reliance on federation members",wrong:["Higher transaction fees","Slower block times","No programming capabilities"]}],submarine_swap:[{q:"A submarine swap allows you to:",a:"Exchange on-chain Bitcoin for Lightning Bitcoin (or vice versa) trustlessly",wrong:["Mine Bitcoin using specialised deep-sea cooling rigs for better thermal efficiency","Send Bitcoin transactions without the internet using a mesh radio relay network","Convert Bitcoin into Ethereum through a cross-chain atomic bridge smart contract"]},{q:'Why is it called a "submarine" swap?',a:'On-chain is "above water" and Lightning off-chain is "below water" - you swap between the two',wrong:["The swap conceals funds below the blockchain visible layer before resurfacing on-chain","On-chain funds are submerged in a time-locked escrow vault beneath the mempool layer","The name comes from the HTLC diving beneath regular channel capacity during the swap"]},{q:"What enables submarine swaps to be trustless?",a:"HTLCs (Hash Time Locked Contracts)",wrong:["Centralized exchange custody","Bank wire confirmation","Social media verification"]},{q:"What problem do submarine swaps solve?",a:"Moving funds between on-chain and Lightning without closing channels",wrong:["Automatically rebalancing mining pool difficulty when large hash rate enters or exits","Stabilising the exchange rate between on-chain BTC and Lightning-denominated sats","Recovering wallet access when a user loses their hardware device or written seed phrase"]},{q:"Alex Bosworth and Olaoluwa Osuntokun created submarine swaps while at which company?",a:"Lightning Labs",wrong:["Blockstream","Chaincode Labs","River Financial"]}],supranational:[{q:'What does "supranational" mean in the context of Bitcoin?',a:"It transcends national borders and governments",wrong:["It is backed by the United Nations","It requires international approval to use","It can only be used between countries"]},{q:'What does it mean that Bitcoin is "supranational" money?',a:"It operates beyond any single nation's jurisdiction or control",wrong:["It is owned by the United Nations","Only governments can use it","It requires international banking licenses"]},{q:"Bitcoin settlement finality means:",a:"Once confirmed, transactions cannot be reversed",wrong:["Transactions can be disputed within 30 days","A central authority must approve each transaction","Only miners can verify if a transaction is final"]},{q:"Which of these best demonstrates Bitcoin's supranational nature?",a:"A citizen of any country can hold Bitcoin without a bank or government permission",wrong:["The UN officially recognized Bitcoin as legal tender in 2021","Bitcoin miners must register with their national government","Cross-border Bitcoin payments require a SWIFT code"]},{q:"What makes Bitcoin different from national currencies like the dollar or euro?",a:"No central bank can print more or manipulate its supply",wrong:["It is backed by gold reserves","It requires government approval","It only works online"]}],organic:[{q:"Bitcoin grew organically because:",a:"It had no pre-mine, no ICO, and no marketing budget",wrong:["A major corporation funded its development","Governments agreed to adopt it simultaneously","Social media algorithms promoted it automatically"]},{q:"What makes Bitcoin's distribution unique among cryptocurrencies?",a:"Fair launch - no coins were pre-allocated to founders",wrong:["Satoshi kept 50% of all coins before launch","Venture capitalists funded the initial distribution","Coins were distributed based on national GDP"]},{q:"How has Bitcoin grown without traditional marketing?",a:"Through grassroots adoption and word-of-mouth from users",wrong:["Massive advertising budgets","Celebrity endorsements","Government subsidies"]},{q:"What drives Bitcoin\\'s organic adoption in developing countries?",a:"Real need for inflation protection and remittance savings",wrong:["Central bank mandates","Corporate marketing campaigns","Mandatory school education"]},{q:"What is the role of Bitcoin\\'s open source community?",a:"Volunteer developers contribute code without corporate hierarchy",wrong:["They control Bitcoin Foundation","They receive government salaries","They own all bitcoins"]}],programmable:[{q:"Bitcoin Script is intentionally limited because:",a:"Simplicity reduces attack surface and increases security",wrong:["Satoshi was not a skilled programmer","The blockchain cannot process complex instructions","It was a temporary design meant to be upgraded"]},{q:'What does "Turing-incomplete" mean for Bitcoin Script?',a:"It cannot run arbitrary programs or infinite loops",wrong:["It cannot process any transactions at all","It requires a separate computer to verify","It can only handle one transaction per block"]},{q:"What makes Bitcoin programmable money?",a:"Bitcoin Script enables conditional spending and smart contracts",wrong:["Only banks can program it","It runs Python code directly","Central programmers control all transactions"]},{q:"What are timelocks in Bitcoin?",a:"Conditions preventing spending until a specific time or block height",wrong:["Physical locks on hardware wallets","Password requirements","Banking hours restrictions"]},{q:"What is a multisig (multi-signature) transaction?",a:"Requires multiple private keys to authorize spending",wrong:["Multiple transactions combined","Multiple miners confirming","Multiple exchanges involved"]}],ordinals:[{q:"Bitcoin Ordinals allow:",a:"Inscribing data (images, text) directly on individual satoshis",wrong:["Creating new tokens on the Bitcoin network","Speeding up transaction confirmation times","Reducing the total supply of Bitcoin"]},{q:"Why are Ordinals controversial in the Bitcoin community?",a:"They increase block space demand and fees for financial transactions",wrong:["They change the 21 million supply cap","They require a hard fork to implement","They give miners control over which transactions are valid"]},{q:"What are Bitcoin Ordinals?",a:"A numbering system for satoshis enabling inscription of arbitrary data",wrong:["A type of altcoin token","A mining algorithm","A Lightning channel type"]},{q:"What controversial use case emerged from Ordinals?",a:"BRC-20 tokens creating fungible tokens on Bitcoin",wrong:["Instant payment settlement","Hardware wallet security","Private key encryption"]},{q:"What is the debate around Ordinals inscriptions?",a:"They use block space, potentially raising fees for regular transactions",wrong:["They steal bitcoin from wallets","They hack the blockchain","They prevent mining from working"]}],geopolitics___macroeconomics:[{q:"Why is Bitcoin relevant to geopolitics?",a:"It provides a neutral monetary system outside any nation's control",wrong:["Major governments collectively control Bitcoin's code","Bitcoin mining is only legal in 5 countries","The UN regulates Bitcoin's international transfers"]},{q:'What is the "petrodollar" system?',a:"Oil is priced in US dollars, forcing global demand for the dollar",wrong:["A cryptocurrency backed by oil reserves","A Bitcoin mining technique using petroleum","A tax imposed on Bitcoin by oil-producing nations"]},{q:"Which country was the first to adopt Bitcoin as legal tender?",a:"El Salvador in September 2021",wrong:["United States","Japan","Germany"]},{q:"How do sanctions-evading nations view Bitcoin?",a:"As a way to circumvent SWIFT restrictions and frozen reserves",wrong:["As a threat to their currencies","As a US surveillance tool","As illegal everywhere"]},{q:"What macro trend drives Bitcoin adoption during inflation?",a:"Currency debasement making bitcoin\\'s fixed supply attractive",wrong:["Lower interest rates on bitcoin","Government bitcoin subsidies","Bank account requirements"]}],"op-codes":[{q:"Bitcoin OP_CODES are:",a:"Instructions in Bitcoin's scripting language that define spending conditions",wrong:["Error codes returned when a transaction fails","Codes used to communicate between mining pools","Secret backdoor commands for Bitcoin developers"]},{q:"OP_RETURN allows:",a:"Embedding small amounts of arbitrary data in the blockchain",wrong:["Reversing a confirmed transaction","Returning stolen Bitcoin to its owner","Increasing the block size limit"]},{q:"What is OP_CHECKSIG in Bitcoin Script?",a:"Verifies a digital signature against a public key",wrong:["Creates new bitcoins","Encrypts transaction data","Connects to mining pools"]},{q:"What was the OP_RETURN controversy?",a:"Its limit was reduced to prevent blockchain bloat from non-financial data",wrong:["It was used to hack exchanges","It created unlimited bitcoins","It stopped all transactions"]},{q:"What did Taproot enable for Bitcoin opcodes?",a:"More flexible scripting through Schnorr signatures and Merkle branches",wrong:["Removal of all previous scripts","Conversion to Ethereum compatibility","Centralized script approval"]}],public_key_vs_private_key:[{q:"Your Bitcoin public key is like:",a:"Your email address - you share it so people can send you Bitcoin",wrong:["Your password - never share it with anyone","Your bank PIN number - used to authorize spending","Your social security number - it proves your identity"]},{q:"If someone has your private key, they can:",a:"Spend all the Bitcoin controlled by that key",wrong:["Only view your transaction history","Reset your password and lock you out","Create new Bitcoin out of thin air"]},{q:"What is the relationship between private and public keys?",a:"Public keys are derived from private keys via one-way cryptographic function",wrong:["Private keys are given to everyone","Public keys encrypt private keys","They are identical numbers"]},{q:"What should you do with your private keys?",a:"Keep them secret and secure, never share with anyone",wrong:["Publish them online","Email them to exchanges","Print them on merchandise"]},{q:"What is the purpose of a public key?",a:"To receive bitcoin and verify signatures without revealing the private key",wrong:["To spend bitcoin alone","To mine new blocks","To create private keys"]}],transaction_fees:[{q:"Bitcoin transaction fees are determined by:",a:"The size of the transaction in bytes and current network demand",wrong:["A fixed percentage of the transaction amount","The number of Bitcoin being sent","The geographic distance between sender and receiver"]},{q:"When the mempool is full:",a:"Transactions with higher fees get confirmed first",wrong:["All transactions are rejected until it clears","The block size automatically increases","Transaction fees are refunded to senders"]},{q:"What determines Bitcoin transaction fees?",a:"Transaction size in bytes and current network demand (mempool congestion)",wrong:["Transaction amount in bitcoin","Sender\\'s reputation","Government regulation"]},{q:"What is the mempool?",a:"A waiting area for unconfirmed transactions held by nodes",wrong:["A mining hardware pool","A cryptocurrency exchange","A type of Bitcoin wallet"]},{q:"Why do fees spike during network congestion?",a:"Users compete for limited block space by bidding higher fees",wrong:["Miners arbitrarily raise prices","Exchanges charge extra","Bitcoin supply decreases"]}],philosophy:[{q:'"Don\'t trust, verify" means:',a:"Run your own node to independently verify all Bitcoin rules",wrong:["Never use Bitcoin because it cannot be trusted","Only trust exchanges that are government-regulated","Verify your identity before making transactions"]},{q:'The concept "Bitcoin is Time" by Gigi suggests:',a:"Bitcoin creates a decentralized clock through proof of work",wrong:["Bitcoin transactions can travel back in time","Bitcoin was invented to save people time","Bitcoin mining uses atomic clocks"]},{q:"What is the cypherpunk movement that birthed Bitcoin?",a:"Advocates for privacy through cryptography and code over trust",wrong:["Bankers wanting digital currency","Gamers creating virtual money","Governments tracking transactions"]},{q:'What does it mean that Bitcoin had a "fair launch"?',a:"No pre-mine, no ICO - anyone could mine from day one on equal terms",wrong:["The government approved it before launch","Satoshi distributed coins equally to all users","A committee reviewed and certified the genesis block"]},{q:'What does Bitcoin\\\'s "monetary policy" refer to?',a:"Fixed supply schedule with predictable issuance rate until 21 million",wrong:["Central bank interest rates","Government fiscal policy","Investment fund strategies"]}],halving:[{q:"The Bitcoin halving occurs every:",a:"210,000 blocks (approximately every 4 years)",wrong:["Every calendar year on January 3","Every 100,000 blocks","Whenever the price doubles"]},{q:"After the 2024 halving, the block reward is:",a:"3.125 BTC per block",wrong:["6.25 BTC per block","1.5625 BTC per block","50 BTC per block"]},{q:"The halving is significant because it:",a:"Mathematically enforces Bitcoin's decreasing supply issuance",wrong:["Doubles the total supply of Bitcoin","Reduces the number of active miners by half","Changes Bitcoin's consensus mechanism"]},{q:"What happens during a Bitcoin halving?",a:"Block reward paid to miners is cut in half",wrong:["Transaction fees double","Bitcoin supply doubles","Mining difficulty halves"]},{q:"When will the final bitcoin be mined?",a:"Around year 2140 when all 21 million are issued",wrong:["2025","2040","Never - mining continues forever"]}],bitcoin_vs_real_estate:[{q:"What key property rights advantage does Bitcoin have over real estate?",a:"It cannot be seized, taxed annually, or confiscated via eminent domain",wrong:["Real estate has stronger rights because it is protected by law","Bitcoin and real estate have identical property rights protections","Bitcoin ownership is not recognized by any major legal system"]},{q:"How do maintenance costs compare between Bitcoin and real estate?",a:"Bitcoin has near-zero costs; real estate requires taxes, insurance, and repairs",wrong:["Bitcoin requires expensive monthly server fees to maintain ownership","Real estate has no maintenance costs once the mortgage is paid off","Both assets have roughly equivalent ongoing maintenance expenses"]},{q:"Why is Bitcoin considered superior to real estate in terms of portability?",a:"A seed phrase can be memorized and carried across any border instantly",wrong:["Real estate deeds can be memorized and are just as portable","Bitcoin is less portable because it always requires internet access","Portability is irrelevant when comparing long-term stores of value"]},{q:"How does Bitcoin's divisibility compare to real estate?",a:"Bitcoin divides into 100 million satoshis; real estate cannot be micro-divided",wrong:["Real estate is more divisible because you can rent individual rooms","Bitcoin cannot be divided at all - you must buy a whole coin","Both assets offer identical divisibility through financial derivatives"]},{q:"What risk does real estate face that Bitcoin does not, related to government power?",a:"Eminent domain seizure, property tax liens, and government confiscation",wrong:["Governments can easily confiscate Bitcoin but not real estate","Neither asset faces any confiscation risk in democratic nations","Bitcoin faces greater government risk because it can be fully banned"]}],bitvm:[{q:"What does BitVM enable on Bitcoin without requiring a protocol change?",a:"Arbitrary computation verification through fraud proofs",wrong:["Turing-complete smart contracts executed by miners","On-chain virtual machine execution like the EVM","Zero-knowledge proof generation inside Bitcoin Script"]},{q:"BitVM uses which computational model to verify off-chain computation?",a:"An optimistic model with prover claims and verifier challenges",wrong:["A zero-knowledge model where proofs are posted each block","A consensus model where all nodes re-execute computation","A federated model where trusted signers attest to results"]},{q:"In BitVM, what is the fundamental logic gate used to represent any computable function?",a:"NAND gates",wrong:["AND gates","XOR gates","NOR gates"]},{q:"Who proposed the original BitVM whitepaper?",a:"Robin Linus",wrong:["Peter Todd","Jeremy Rubin","Andrew Poelstra"]},{q:"How does BitVM2 improve upon the original BitVM design?",a:"It reduces on-chain transactions needed for dispute resolution",wrong:["It adds Turing-complete execution directly on base layer","It eliminates the need for a verifier role entirely","It requires a soft fork to enable several new opcodes"]}],"block_time-block-size":[{q:"Why did Satoshi choose approximately 10 minutes for Bitcoin's target block time?",a:"It balances throughput with time needed for global block propagation",wrong:["It was arbitrary with no real technical justification behind it","Faster blocks would make mining unprofitable due to power costs","It matches the average time needed for international wire transfers"]},{q:"What is the difference between block weight and block size in Bitcoin?",a:"Weight counts witness bytes at a discount versus non-witness bytes",wrong:["Block weight and block size are identical with different names","Block weight measures computational effort to validate a block","Block weight only applies to Lightning Network transactions"]},{q:"What is the maximum block weight allowed by Bitcoin's consensus rules?",a:"4 million weight units (4 MWU)",wrong:["1 megabyte of raw data","8 million weight units (8 MWU)","2 million weight units (2 MWU)"]},{q:"Why does SegWit give witness data a discount in the block weight calculation?",a:"Witness data costs less for nodes to process, incentivizing adoption",wrong:["Witness data is encrypted and takes up less physical storage","The discount was a political compromise with no technical basis","Witness data is stored temporarily then deleted after 100 blocks"]},{q:'What is "blockspace economics" in Bitcoin?',a:"The fee market where users bid for limited space in each block",wrong:["A government program subsidizing mining in renewable energy zones","The cost of running a full node in electricity and bandwidth","A pricing model used for Lightning Network channel capacity"]}],burn_bitcoin:[{q:"What is the maximum amount of data that can be stored in an OP_RETURN output?",a:"80 bytes",wrong:["40 bytes","160 bytes","1000 bytes"]},{q:"What does it mean for Bitcoin to be provably unspendable through OP_RETURN?",a:"The output has no valid script path to spend it",wrong:["It requires a special private key to spend","It can only be spent after 100 confirmations","It is temporarily locked until a timelock expires"]},{q:"Roughly how many Bitcoin are estimated to be permanently lost or burned?",a:"Between 3-4 million BTC",wrong:["Less than 1 million BTC","Over 10 million BTC","Exactly 1 million BTC"]},{q:"What type of Bitcoin address output is provably unspendable with no script?",a:"Bare multisig with invalid pubkeys",wrong:["Standard P2PKH addresses","Wrapped P2SH addresses","Native P2WPKH addresses"]},{q:"What is proof of burn in the context of cryptocurrency?",a:"Demonstrating coins were sent to an unspendable address",wrong:["Mining blocks without ever receiving any block rewards","Permanently deleting the private keys to a wallet","Sending coins to a wallet whose owner has died"]}],consensus_pt2:[{q:"What does finality mean in Nakamoto Consensus?",a:"Reversals become exponentially harder with each confirmation",wrong:["Transactions are instantly and permanently irreversible","Miners hold a formal vote on transaction validity","The longest chain is always guaranteed to be correct"]},{q:"What are orphan blocks in Bitcoin?",a:"Valid blocks not included in the main chain",wrong:["Invalid blocks rejected by network nodes","Blocks that contain zero transactions inside","Alternative variants of the genesis block"]},{q:"What is selfish mining in Bitcoin?",a:"Withholding found blocks to gain unfair advantage",wrong:["Mining solo without joining any mining pool","Using only renewable energy sources for mining","Deliberately refusing to validate any transactions"]},{q:"What is the typical Bitcoin block propagation time?",a:"1-10 seconds globally",wrong:["About 60 seconds on average","Nearly instantaneous at all times","Approximately 10 full minutes"]},{q:"What was the FIBRE network designed to improve?",a:"Block propagation speed between miners",wrong:["Lightning Network payment routing","Wallet synchronization with nodes","Mining difficulty adjustment calculations"]}],cryptography_pt3:[{q:"What advantage do Schnorr signatures provide over ECDSA in Bitcoin?",a:"Key aggregation for efficient multi-signature transactions",wrong:["Quantum resistance that ECDSA fundamentally lacks","Smaller size in all cases regardless of signers","Available since day one but never actually used"]},{q:"What is MuSig2 in Bitcoin?",a:"A Schnorr-based multi-sig scheme producing one standard-looking signature",wrong:["A second version of the Bitcoin music streaming protocol","A next-generation mining algorithm replacing SHA-256 hashing","A Lightning Network routing protocol for two-hop payments"]},{q:"What are adaptor signatures used for in Bitcoin?",a:"Conditional payments where signing reveals a secret value",wrong:["Converting old formats to be Taproot-compatible ones","Signing transactions using multiple keys simultaneously","Adapting Script to support Turing-complete contracts"]},{q:"What is a Pedersen commitment?",a:"A commitment that hides a value while allowing math verification",wrong:["A legal agreement between developers to maintain the protocol","A type of fee commitment that is included in every block","A signed pledge by miners to always follow consensus rules"]},{q:"What is the current status of zero-knowledge proofs on Bitcoin?",a:"Being explored via projects like BitVM and validity rollups",wrong:["Fully implemented in Bitcoin Core since the Taproot upgrade","Impossible on Bitcoin due to fundamental Script limitations","Removed from Bitcoin in 2015 due to critical security risks"]}],"ctv-covenants":[{q:"What does BIP-119 (CheckTemplateVerify) allow a Bitcoin output to do?",a:"Commit to a specific future transaction template for spending",wrong:["Execute arbitrary smart contract code when it is spent","Lock funds until a specific block height has been reached","Require multiple signatures from different keys to spend"]},{q:'What is a "covenant" in the context of Bitcoin?',a:"A restriction on how a UTXO can be spent in the future",wrong:["A multisig arrangement between federation member nodes","A legal agreement between Lightning channel counterparties","A time-locked contract that expires after a set period"]},{q:'What Bitcoin use case does CTV enable through "congestion control"?',a:"Batching many payments into one transaction claimable later",wrong:["Auto-adjusting fees based on current mempool congestion","Throttling transactions a wallet can send within a block","Limiting block size during periods of high network load"]},{q:"What is OP_VAULT designed to provide using covenants?",a:"Time-delayed withdrawals with an emergency clawback option",wrong:["A decentralized exchange built for trustless atomic swaps","Cold storage that auto-moves funds to hardware wallets","Multi-party escrow designed for marketplace transactions"]},{q:"Why are covenants considered controversial by some Bitcoiners?",a:"They could enable coin censorship or spending blacklists",wrong:["They require a hard fork that would split the network","They make all transactions public and remove user privacy","They increase block size beyond what nodes can handle"]}],cycles:[{q:"What drives Bitcoin's historically observed ~4-year market cycle?",a:"The halving, which cuts new supply in half every ~4 years",wrong:["Government regulations that shift with 4-year election cycles","A scheduled software update that resets the network state","Random market psychology with no underlying structural driver"]},{q:"How does the Gartner Hype Cycle apply to each Bitcoin halving era?",a:"Each cycle shows trigger, peak hype, disillusionment, then recovery to a plateau",wrong:["Bitcoin skips disillusionment because the price only goes up long-term","The Gartner Hype Cycle only applies to new tech products, not currencies","Each Bitcoin cycle follows the exact same price pattern as the last one"]},{q:'What is the "lengthening cycles" debate in Bitcoin?',a:"The theory that each bull run takes longer to peak with smaller percentage gains",wrong:["The theory that mining cycles get shorter as hardware gets faster","A proposal to extend the halving interval from four years to eight","The idea that transaction confirmation times increase every year"]},{q:"Which on-chain metrics are commonly used to analyze Bitcoin market cycles?",a:"MVRV, NUPL, and the Pi Cycle Top indicator",wrong:["GDP growth, unemployment, and consumer price index","Twitter followers, Google Trends, and Reddit subs","Block size, node count, and developer commit stats"]},{q:'What is the "diminishing returns" theory in Bitcoin cycles?',a:"Each cycle's percentage gain shrinks, though absolute highs keep rising",wrong:["Returns are accelerating each cycle with larger percentage gains","Bitcoin will eventually produce negative returns in every cycle","It refers to decreasing energy efficiency of mining each cycle"]}],derivation_path:[{q:"What does a BIP-32 HD (Hierarchical Deterministic) wallet allow you to do?",a:"Generate unlimited key pairs from a single master seed",wrong:["Store multiple cryptocurrencies in one single private key","Recover funds without a seed phrase using only email","Connect directly to the network without running a node"]},{q:"In the derivation path m/84'/0'/0'/0/0, what does the \"84\" represent?",a:"BIP-84, the Native SegWit (bech32) address standard",wrong:["The year 1984 when public key crypto was standardized","The 84th account stored inside this particular wallet","The total number of addresses that can be derived"]},{q:"Which BIP defines the derivation path standard for Taproot (bc1p) addresses?",a:"BIP-86",wrong:["BIP-84","BIP-49","BIP-44"]},{q:"Why is sharing an xpub (extended public key) a privacy concern?",a:"It lets anyone see all addresses and balances from that account",wrong:["It allows someone to spend your Bitcoin without the private key","It broadcasts your seed phrase to every node on the network","It reveals your real-world name and identity on the blockchain"]},{q:'What is the "gap limit" in HD wallet address discovery?',a:"How many consecutive unused addresses are checked before stopping",wrong:["The maximum number of addresses a wallet can generate total","The time delay required between generating new addresses","The minimum spacing between two UTXOs in a transaction"]}],"difficulty-adjustment_pt2":[{q:"What algorithm does Bitcoin use for difficulty adjustment?",a:"Direct calculation based on actual vs target time",wrong:["PID controller algorithm with feedback loops","Neural network prediction of future hash rate","Moving average of recent hash rate samples"]},{q:"How many blocks is the difficulty retarget period?",a:"2,016 blocks",wrong:["1,008 blocks","4,032 blocks","10,080 blocks"]},{q:"What causes hash rate oscillation between mining pools?",a:"Miners chasing short-term luck variance",wrong:["Scheduled Bitcoin Core software update cycles","Daily difficulty adjustment recalculations","Network communication delays between nodes"]},{q:"What variance measure describes pool mining luck?",a:"Statistical variance around expected block discovery",wrong:["Fixed reward percentage distributed to miners","Difficulty share ratio across pool participants","Network propagation delay between peer nodes"]},{q:"How long does a difficulty epoch typically last?",a:"Approximately 2 weeks",wrong:["Exactly 1 week","About 1 month","Approximately 4 days"]}],dlcs:[{q:"In a Discreet Log Contract (DLC), what role does an oracle play?",a:"It signs a real-world outcome that determines how the contract pays out",wrong:["It holds the funds in escrow until both parties agree on the result","It executes smart contract code on a sidechain to settle the bet","It mines the specific transaction that settles the contract on-chain"]},{q:'What cryptographic technique makes DLCs "discreet" - invisible to the oracle?',a:"Adaptor signatures that use the oracle's attestation privately",wrong:["Zero-knowledge proofs that hide the contract from participants","Ring signatures that mix the contract with unrelated transactions","Homomorphic encryption that processes data without decrypting it"]},{q:"What is a common real-world use case for Discreet Log Contracts?",a:"Financial derivatives and betting settled by price or event data",wrong:["Decentralized file storage using the Bitcoin network as a backend","Privacy-preserving identity verification on the Bitcoin blockchain","Automated market making for Lightning Network liquidity pools"]},{q:"Why is the oracle in a DLC considered more trustworthy than traditional smart contract oracles?",a:"The oracle doesn't know the contract exists or what depends on it",wrong:["The oracle stakes Bitcoin collateral that is slashed if it lies","Multiple oracles must all agree before any payout can occur","The oracle runs inside a trusted execution environment on-chain"]},{q:"DLC.Link enables Discreet Log Contracts to be used primarily for what purpose?",a:"Bridging Bitcoin as collateral into DeFi without giving up custody",wrong:["Mining pool payout distribution based on individual hash rate","Decentralized DNS registration on the Bitcoin base layer","Cross-chain atomic swaps between Bitcoin and Ethereum directly"]}],"dollar-bitcoin_milkshake_theory":[{q:'Who originated the "Dollar Milkshake Theory"?',a:"Brent Johnson of Santiago Capital",wrong:["Ray Dalio of Bridgewater Associates","Michael Saylor of MicroStrategy","Saifedean Ammous of The Bitcoin Standard"]},{q:"What is the core thesis of the Dollar Milkshake Theory?",a:"The dollar strengthens by sucking up global liquidity while other fiat currencies weaken",wrong:["All fiat currencies collapse simultaneously and get replaced by Bitcoin","The dollar weakens as other currencies collectively strengthen against it","Central banks coordinate to create and adopt a single global currency"]},{q:'What is the "dollar strength paradox" in the Milkshake Theory?',a:"The dollar gets stronger vs other currencies while losing purchasing power vs hard assets",wrong:["A strong dollar always means the Bitcoin price will go down in tandem","Dollar strength is a reliable signal that the US economy is healthy","Nobody wants dollars but everyone needs them to service their debts"]},{q:"How does Bitcoin fit into the Dollar Milkshake Theory's endgame?",a:"After the dollar absorbs global liquidity, Bitcoin becomes the ultimate fiat exit",wrong:["Bitcoin is irrelevant to the theory because it isn't a fiat currency","Bitcoin collapses alongside other currencies during the dollar's rise","The theory predicts Bitcoin gets banned and replaced by state CBDCs"]},{q:"Why does global dollar demand play a central role in the Milkshake Theory?",a:"Trillions in dollar-denominated debt forces nations to buy dollars, strengthening it",wrong:["Global dollar demand is declining rapidly as nations actively de-dollarize","Dollar demand only matters for US domestic transactions and trade","The theory says dollar demand is irrelevant - only money supply matters"]}],"el-salvador":[{q:"What was the Chivo wallet in El Salvador's Bitcoin adoption?",a:"A government-issued Lightning wallet that gave citizens $30 in Bitcoin",wrong:["A private hardware wallet manufactured locally in El Salvador","An exchange platform where Salvadorans could trade altcoins","A banking app that only supported US dollar-based transactions"]},{q:'What is "Bitcoin Beach" and why is it significant to El Salvador\'s Bitcoin story?',a:"El Zonte - a village that built a grassroots Bitcoin economy before the national law",wrong:["A luxury resort in San Salvador that exclusively accepts Bitcoin payments","A government-built tourist attraction designed to promote Bitcoin adoption","A cryptocurrency exchange headquartered on the Salvadoran coastal region"]},{q:"What was President Bukele's core strategy behind making Bitcoin legal tender?",a:"Financial inclusion for the unbanked, foreign investment, and cheaper remittances",wrong:["Replacing the US dollar entirely with Bitcoin as the sole currency","Mining Bitcoin profitably using El Salvador's untapped oil reserves","Creating a government-controlled cryptocurrency to replace Bitcoin"]},{q:"How did the World Bank and IMF respond to El Salvador's Bitcoin law?",a:"They pushed back - the World Bank refused help and the IMF warned of risks",wrong:["Both organizations fully endorsed and helped fund the entire initiative","The IMF designed and helped build the Chivo wallet infrastructure","The World Bank provided a $500 million loan specifically for adoption"]},{q:"How did Lightning Network adoption benefit El Salvador's economy?",a:"It enabled fast, near-free payments and remittances, cutting out costly services",wrong:["Lightning was not used - only on-chain Bitcoin transactions were supported","Lightning made transactions faster but significantly more expensive overall","El Salvador banned Lightning in favor of on-chain-only Bitcoin payments"]}],"evidence-against-alts_pt2":[{q:'What is a "premine" and why is it a red flag for altcoins?',a:"Founders create and keep tokens before public launch, giving insiders an unfair edge",wrong:["A premine is a security feature that helps blockchains launch more quickly","A premine means the coin was tested before release, which is good practice","A premine is when miners validate the genesis block without earning fees"]},{q:"Why are many altcoin tokens considered securities under US law?",a:"They pass the Howey Test - buyers expect profits from a centralized team's efforts",wrong:["The SEC automatically classifies every digital asset as a regulated security","Any token traded on a cryptocurrency exchange is legally a security by default","Only tokens with market caps above $1 billion can qualify as securities"]},{q:'What is "VC token dumping" in the altcoin market?',a:"VCs invest early at a discount, then sell their tokens on retail investors at launch",wrong:["VCs donate their discounted tokens to charity projects after launch","VCs permanently lock their tokens to show support for the project","VCs use their tokens to fund open-source Bitcoin core development"]},{q:'Why do Bitcoiners argue that "decentralized governance tokens" are an oxymoron?',a:"Token voting concentrates power with whales and VCs, recreating inequality",wrong:["Governance tokens are too technically complex to ever implement properly","Bitcoin already uses governance tokens internally for protocol upgrades","Governance tokens have been declared illegal in every jurisdiction"]},{q:"What key evidence do Bitcoiners cite about Ethereum's centralization?",a:"A massive premine to insiders, repeated monetary policy changes, and known leadership",wrong:["Ethereum runs on a single server that is controlled by Vitalik Buterin","Ethereum transactions require explicit government approval before processing","Ethereum has fewer active nodes than a typical corporate cloud database"]}],"extension-blocks":[{q:"What are extension blocks in Bitcoin?",a:"Additional block space running alongside the main chain without changing it",wrong:["Larger blocks created by increasing the block size limit via a hard fork","Blocks reserved exclusively for Lightning Network channel operations","Compressed blocks that store only transaction hashes to save space"]},{q:"How do extension blocks differ from a traditional soft fork upgrade?",a:'Old nodes see extension transactions as "anyone-can-spend" outputs',wrong:["Extension blocks require all nodes to upgrade or be forked off the network","Extension blocks reduce the block size to improve network decentralization","Extension blocks are identical to soft forks but use a different label"]},{q:'What is the "space chain" concept related to extension blocks?',a:"A separate chain whose block space is auctioned via the main chain",wrong:["A satellite network that broadcasts Bitcoin blocks from orbit","A virtual reality environment where Bitcoin nodes operate in 3D","A specialized blockchain optimized for storing files over 4MB"]},{q:"What is a key trade-off of extension blocks?",a:"Non-upgraded nodes cannot fully validate extension block transactions",wrong:["All miners must upgrade their hardware simultaneously to participate","The main block size permanently increases for all future blocks","Lightning Network channels become incompatible with the base layer"]},{q:"Why have extension block proposals historically been controversial in Bitcoin development?",a:"They risk creating a second-class zone that weakens full node security",wrong:["They were proposed by altcoin developers trying to undermine Bitcoin","They would eliminate the need for the Lightning Network entirely","They require replacing SHA-256 with a completely different hash algorithm"]}],feedback_loops:[{q:"What is the price-hashrate-security feedback loop in Bitcoin?",a:"Higher price attracts miners, boosting hashrate, security, and confidence in a rising cycle",wrong:["Higher price causes miners to shut down, reducing hashrate and network security","Hashrate and price are completely independent with no meaningful connection","Security drops as price rises because more hackers are attracted to attack"]},{q:"How does the adoption-liquidity-utility feedback loop work in Bitcoin?",a:"More users deepen liquidity, making Bitcoin more useful, which attracts even more users",wrong:["More users raise fees, which drives away users and decreases overall liquidity","Liquidity falls as adoption grows because the total supply is permanently fixed","Adoption and liquidity have an inverse relationship in the Bitcoin network"]},{q:"How does the Lindy Effect create a reinforcing feedback loop for Bitcoin?",a:"Each day Bitcoin survives boosts confidence in its longevity, drawing more adoption",wrong:["The Lindy Effect means Bitcoin gets less reliable as its codebase ages","Older technology always gets replaced, so the Lindy Effect hurts Bitcoin","The Lindy Effect only applies to physical objects, not digital protocols"]},{q:"What is reflexivity in the context of Bitcoin market cycles?",a:"Perceptions influence fundamentals, which reinforce perceptions, creating self-amplifying cycles",wrong:["Reflexivity means Bitcoin's price always reflects its true fundamental value","It describes the tendency of Bitcoin to always revert to the same price","Reflexivity is a mining technique that increases block production speed"]},{q:"Why are Bitcoin's feedback loops considered among the most powerful in economics?",a:"Multiple self-reinforcing loops in price, hashrate, adoption, and security amplify together",wrong:["Bitcoin has only one feedback loop but it happens to be extremely strong","Bitcoin's feedback loops are actually weak compared to traditional market loops","Feedback loops only work in bull markets and reverse completely in bear runs"]}],first_principles:[{q:'What does "first principles thinking" mean when applied to Bitcoin?',a:"Breaking money down to fundamental properties and reasoning up from there",wrong:["Copying the design of existing currencies and then improving them","Following the majority opinion of mainstream economists on money","Starting with government approval and working backward from there"]},{q:"Which philosopher is most associated with the first principles method of reasoning from fundamental truths?",a:"Aristotle",wrong:["Plato","Socrates","Descartes"]},{q:"When reasoning from first principles about what makes good money, which set of properties matters most?",a:"Scarcity, portability, durability, divisibility, and fungibility",wrong:["Government backing, legal enforcement, and central bank control","Physical weight, aesthetic beauty, and historical tradition","Ease of printing, widespread banking, and inflation targeting"]},{q:"First principles thinking reveals what fundamental connection between energy and money?",a:"Money should represent stored energy - unforgeable costliness gives it value",wrong:["Money has no relationship to energy since it is purely a social construct","Only physical commodities can serve as money because they contain atoms","Energy is irrelevant to money if a government declares it legal tender"]},{q:"Why does first principles reasoning tend to lead people toward Bitcoin rather than altcoins?",a:"Bitcoin best satisfies the fundamental properties of sound money from first principles",wrong:["Bitcoin was the first cryptocurrency so it wins by default over altcoins","Altcoins are illegal in most countries so Bitcoin is the only legal option","Bitcoin has the best marketing team and strongest brand awareness overall"]}],foss:[{q:"What type of software license does Bitcoin Core use?",a:"MIT License",wrong:["GPL v3","Apache License 2.0","Creative Commons"]},{q:"Why is it important that Bitcoin Core is free and open-source software (FOSS)?",a:"Anyone can audit the code to verify no backdoors or hidden rules exist",wrong:["It makes Bitcoin free to use with zero transaction fees for users","It allows developers to create unlimited Bitcoin through the code","It means no one actually needs to run the Bitcoin software"]},{q:"What is the Guix build system used for in Bitcoin Core?",a:"Producing reproducible, auditable binaries so anyone can verify the software",wrong:["Automatically deploying Bitcoin Core updates to all nodes across the network","Managing the peer-review and merge workflow for Bitcoin Core pull requests","Cross-compiling Bitcoin Core binaries optimised for different CPU architectures"]},{q:'"Linus\'s Law" states that "given enough eyeballs, all bugs are shallow." How does this apply to Bitcoin?',a:"Thousands of developers review Bitcoin's code, so vulnerabilities get found and fixed faster",wrong:["Linux servers are the only machines capable of running Bitcoin full nodes properly","Linus Torvalds personally reviews and audits every Bitcoin Core release himself","Bitcoin can only run on open-source operating systems like Linux and FreeBSD"]},{q:"Why does open-source matter specifically for money/monetary software like Bitcoin?",a:"Users must verify the rules of their money - no hidden inflation or secret changes",wrong:["Open-source software is always faster and more efficient than proprietary code","It allows banks to freely copy Bitcoin and make their own branded version","It makes Bitcoin significantly easier for governments to regulate and control"]}],geopolitics___macroeconomics_pt2:[{q:"What is the BRICS de-dollarization movement and how does it relate to Bitcoin?",a:"BRICS nations are reducing dollar dependence, creating demand for neutral reserves like Bitcoin",wrong:["BRICS is a Bitcoin mining pool that is jointly operated by five nations","BRICS nations have collectively banned Bitcoin to protect local currencies","BRICS de-dollarization means these countries adopted Bitcoin as legal tender"]},{q:'What is the "strategic Bitcoin reserve" concept that multiple nations are exploring?',a:"Nations accumulating Bitcoin as a reserve asset alongside gold for its scarcity and hedge value",wrong:["A requirement for all nations to back their fiat currency reserves with Bitcoin","A UN mandate requiring every country to hold at least one thousand Bitcoin","A program where central banks replace all existing gold reserves with Bitcoin"]},{q:'What is the "nation-state game theory" argument for Bitcoin adoption?',a:"Early adopter nations gain a massive strategic edge, pressuring others to follow or fall behind",wrong:["Nations banning Bitcoin grow stronger because they fully control their money supply","Game theory proves that no nation will ever voluntarily adopt Bitcoin as a reserve","Nation-state game theory only applies to countries that possess nuclear weapons"]},{q:"How do proponents respond to critics who say Bitcoin is used for sanctions evasion?",a:"Bitcoin's transparent public ledger makes transactions easier to trace than physical cash",wrong:["Bitcoin supporters agree that sanctions evasion is its primary real-world use case","Bitcoin transactions are completely invisible and undetectable to all governments","Sanctions don't apply to digital assets under any current international law"]},{q:"How do institutions like the IMF and World Bank view Bitcoin?",a:"Generally hostile - they've pressured nations like El Salvador to drop Bitcoin legal tender status",wrong:["The IMF and World Bank are actually the largest institutional Bitcoin holders today","Both organizations have publicly endorsed Bitcoin as the future of global finance","The IMF created Bitcoin as a planned replacement for Special Drawing Rights"]}],governance_pt2:[{q:"Who can submit a Bitcoin Improvement Proposal (BIP)?",a:"Anyone in the Bitcoin community",wrong:["Only Bitcoin Core maintainers","Only miners with enough hash rate","Only officially registered developers"]},{q:"What activation method does BIP 9 use?",a:"Miner signaling with version bits during a defined window",wrong:["Node operators vote directly without miner input","Core developers set a flag day with no miner input","Miners and the SEC jointly approve the activation"]},{q:"BIP 8 improves on BIP 9 by adding what option?",a:'A "lock-in on timeout" (LOT=true) that forces activation even without miner majority',wrong:["A mandatory 95% node upgrade threshold that must be met before version bit signaling","An emergency pause mechanism letting any single mining pool block the activation","A two-thirds supermajority developer vote required before version bit signaling begins"]},{q:"What does UASF stand for?",a:"User-Activated Soft Fork",wrong:["Unified Active Soft Fork","Universal Auto Soft Fork","User Approval Soft Fork"]},{q:"What was Speedy Trial used for in Bitcoin?",a:"Taproot activation with a shortened signaling period",wrong:["SegWit activation with extended miner coordination","Lightning Network deployment across mainnet nodes","Difficulty adjustment algorithm changes and updates"]}],hardware:[{q:"What makes the Coldcard hardware wallet stand out among Bitcoin hardware wallets?",a:"It's air-gapped, Bitcoin-only, and supports NFC signing",wrong:["It supports thousands of altcoins and NFTs","It connects directly to the internet for speed","It's the cheapest hardware wallet available"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction) and why is it important for hardware wallets?",a:"A format for building transactions on one device and signing on another",wrong:["A Bitcoin address type exclusive to hardware wallets","A protocol for sending Bitcoin over Bluetooth","A backup format for storing seed phrases digitally"]},{q:"What is SeedSigner?",a:"A DIY, open-source, air-gapped wallet built on a Raspberry Pi",wrong:["A cloud service that generates seed phrases for you","A proprietary hardware wallet made by Ledger","An app that signs transactions via phone fingerprint"]},{q:'What is a "secure element" chip in hardware wallets?',a:"A tamper-resistant chip that stores keys and blocks extraction",wrong:["A chip that connects the wallet to Wi-Fi securely","A component that speeds up transaction processing","A GPS module that tracks the wallet for recovery"]},{q:'What does "air-gapped" mean when describing a hardware wallet like Coldcard or Foundation Passport?',a:"It never connects to internet - data moves via SD card, QR, or NFC",wrong:["The wallet is sealed in a vacuum to prevent tampering","The wallet uses satellite connections instead of Wi-Fi","The wallet can only be used outdoors for security"]}],history_pt3:[{q:"Approximately how many BTC did Mt. Gox lose in its collapse?",a:"850,000 BTC",wrong:["100,000 BTC","2 million BTC","50,000 BTC"]},{q:"What year did the Silk Road marketplace get seized?",a:"2013",wrong:["2011","2015","2017"]},{q:"How many Bitcoins were exchanged for two pizzas on Bitcoin Pizza Day?",a:"10,000 BTC",wrong:["1,000 BTC","100,000 BTC","1,000,000 BTC"]},{q:"What was the main conflict of the Blocksize War?",a:"Whether to increase block size limit",wrong:["Changing Bitcoin to proof of stake","Adding privacy features to Bitcoin","Changing the halving schedule"]},{q:"What was SegWit2x?",a:"Failed agreement to double block size after SegWit",wrong:["Successful hard fork increasing block size","A new proof-of-work mining algorithm","A second layer scaling protocol"]}],improved_incentive_structure:[{q:'How does Bitcoin "fix broken incentives" in the current monetary system?',a:"By removing money printing, it forces honest accounting and ends inflation of debt",wrong:["It gives governments better tools to manage the economy","It doesn't change incentives - just moves them to digital","It fixes incentives by making all transactions government-traceable"]},{q:'What does "low time preference society" mean in the context of a Bitcoin standard?',a:"People plan long-term and save more because their money gains value over time",wrong:["A society that doesn't care about time and works fewer hours","A society where transactions must complete within strict time limits","A society that only uses Bitcoin for short-term speculation"]},{q:'Why is proof of work considered a "fair distribution" mechanism for new Bitcoin?',a:"Anyone can mine by spending real energy - no pre-mines or insider allocations",wrong:["Proof of work gives equal Bitcoin to every person on Earth","Early miners got special privileges that later miners don't","Proof of work distributes Bitcoin based on geographic location"]},{q:"How does sound money (like Bitcoin) change savings and investment behavior?",a:"People save more and only invest in projects with real returns above deflation",wrong:["Sound money discourages saving because money becomes too valuable","Investment behavior stays the same regardless of monetary system","Sound money causes everyone to hoard and collapse the economy"]},{q:"What broken incentive does fiat money create that Bitcoin eliminates?",a:"Fiat rewards borrowing over saving because inflation erodes purchasing power",wrong:["Fiat incentivizes too much saving, which Bitcoin fixes","Fiat money has no broken incentives - it works as designed","Bitcoin creates the same borrow incentive since rates exist"]}],"investment-strategy_pt4":[{q:"What is UTXO management for tax optimization?",a:"Choosing specific UTXOs with known cost bases to minimize capital gains taxes",wrong:["Automatically hiding Bitcoin transactions from the IRS","Converting all UTXOs to altcoins before tax season","Splitting Bitcoin into $600 transactions to avoid reporting"]},{q:'What does "step-up in cost basis" mean for inherited Bitcoin?',a:"Cost basis resets to market price at owner's death, erasing prior gains",wrong:["Inherited Bitcoin is always taxed at the original purchase price","There is no tax on inherited Bitcoin in any jurisdiction","The cost basis doubles each year after inheritance"]},{q:"What is a Bitcoin IRA?",a:"A self-directed retirement account holding Bitcoin with tax advantages",wrong:["A government program that pays retirees in Bitcoin","An insurance policy replacing lost or stolen Bitcoin","A bank savings account that earns interest in Bitcoin"]},{q:"Why do experienced Bitcoiners warn against lending out your Bitcoin?",a:"Lending platforms like Celsius and BlockFi collapsed, losing depositor funds",wrong:["Bitcoin code prevents any form of lending or borrowing","Lending Bitcoin causes the network to slow down significantly","Bitcoin interest rates are always negative so you lose money"]},{q:"Why is cost basis tracking important for Bitcoin investors?",a:"Each purchase creates a separate tax lot needed for capital gains calculations",wrong:["Cost basis tracking is only needed for exchange-held Bitcoin","The IRS uses a flat tax rate on all Bitcoin regardless of price","Cost basis is irrelevant since Bitcoin is classified as currency"]}],laws_of_thermodynamics:[{q:"How does the First Law of Thermodynamics (conservation of energy) relate to Bitcoin mining?",a:"Miners convert electricity into computational work securing the ledger",wrong:["Bitcoin mining creates energy from nothing to power the network","The First Law means Bitcoin can only exist in cold climates","Energy is destroyed during mining, explaining the high usage"]},{q:'What does "unforgeable costliness" mean in Bitcoin\'s thermodynamic context?',a:"Real energy must be spent to produce Bitcoin and this cost can't be faked",wrong:["Bitcoin transactions are free because the network is decentralized","The cost of mining is purely artificial with no security purpose","Unforgeable costliness means Bitcoin wallets cannot be hacked"]},{q:"How does the Second Law of Thermodynamics (entropy always increases) connect to Bitcoin?",a:"Proof of work creates order in the ledger by increasing entropy via energy use",wrong:["Bitcoin violates the Second Law by creating value from nothing","Entropy has no connection to digital systems like Bitcoin","The Second Law means Bitcoin will eventually stop working"]},{q:'Why do some physicists describe proof of work as "thermodynamic security"?',a:"Reversing the chain would require re-spending all the energy that built it",wrong:["Because Bitcoin mining rigs get very hot during operation","Because proof of work requires cooling systems to function","Because thermodynamic equations are used to set transaction fees"]},{q:'What is the "Maxwell\'s Demon" analogy sometimes applied to Bitcoin?',a:"You can't sort molecules or secure a ledger without real energy expenditure",wrong:["Maxwell's Demon is the name of the first Bitcoin mining software","It describes a theoretical AI attack that takes over the network","It refers to Bitcoin price randomness being like particle motion"]}],"layer-2-lightning_pt4":[{q:"What does Lightning Labs' Loop service do?",a:"It moves funds between on-chain and Lightning using submarine swaps",wrong:["It mines Bitcoin directly from a Lightning node","It converts Bitcoin to altcoins through atomic swaps","It syncs the Lightning channel graph to the Bitcoin timechain"]},{q:"What is Multi-Path Payments (MPP) on Lightning?",a:"Splitting a payment across multiple routes to exceed single-channel limits",wrong:["Making multiple payments to different recipients simultaneously","A backup payment method used only if Lightning is offline","Sending the same payment through multiple channels for redundancy"]},{q:"What privacy advantage does AMP have over basic MPP on Lightning?",a:"Each shard has a different payment hash, making it harder for routing nodes to link shards",wrong:["AMP wraps each shard in an extra onion layer completely invisible to intermediate nodes","AMP routes every shard through Tor by default, concealing the sender's network identity","AMP uses zero-knowledge proofs so routing nodes cannot observe any payment metadata"]},{q:"What is trampoline routing on the Lightning Network?",a:"Delegating route calculation to intermediate nodes for lighter clients",wrong:["Bouncing payments off satellites for wider global coverage area","A routing method that always prioritizes the fastest available path","A security protocol that encrypts all payment amounts in transit"]},{q:"What are channel factories in the Lightning Network?",a:"Opening many channels among multiple parties in one on-chain transaction",wrong:["Physical facilities where Lightning network nodes are manufactured","Automated systems that create channels based on user demand levels","Software that converts on-chain wallets into Lightning-ready wallets"]}],"layer-2-lightning_pt5":[{q:"What is liquidity management on the Lightning Network?",a:"Balancing inbound and outbound capacity to reliably route payments",wrong:["Converting Lightning Bitcoin back to regular on-chain Bitcoin","Managing the total circulating supply of Bitcoin on Lightning","Keeping Lightning nodes continuously connected to the internet"]},{q:"What is channel rebalancing on Lightning?",a:"Moving funds between your own channels to redistribute liquidity",wrong:["Closing and reopening channels with updated funding parameters","Resetting all channel state back to the initial funding amount","Transferring full channel ownership to a different Lightning node"]},{q:"What is a Lightning Service Provider (LSP)?",a:"A service offering liquidity and channel management for easy onboarding",wrong:["An internet service provider that specializes in Bitcoin traffic","A government-licensed operator required to run Lightning nodes","A cloud service that mines Bitcoin using collected Lightning fees"]},{q:"What are zero-conf channels on Lightning?",a:"Channels usable immediately without waiting for on-chain confirmation",wrong:["Channels that require zero Bitcoin as a deposit to open them","Channels that provide completely zero-fee routing for payments","Channels that are permanent and cannot be closed once opened"]},{q:"How do Lightning routing nodes earn revenue?",a:"By charging small fees for forwarding payments through their channels",wrong:["By mining new Bitcoin on the Lightning Network second layer","By collecting a percentage of all Lightning transactions globally","By selling their channel and routing data to analytics companies"]}],"layer-3-sidechains":[{q:"How does the Liquid Network secure its two-way peg to Bitcoin?",a:"Through a federation of functionaries managing the peg via multisig",wrong:["Through merge-mining where Bitcoin miners also validate Liquid","Through a trustless smart contract deployed on Bitcoin's base layer","Through proof-of-stake consensus among Liquid token holder nodes"]},{q:"How does RSK (Rootstock) secure its sidechain?",a:"Through merge-mining where Bitcoin miners also validate RSK blocks",wrong:["Through a federation of trusted companies that collectively sign","Through proof-of-stake where RSK token holders vote on blocks","Through BitVM fraud proofs posted to Bitcoin's main base layer"]},{q:"What consensus mechanism does Stacks use to connect to Bitcoin?",a:"Proof of Transfer (PoX), where miners spend BTC to produce blocks",wrong:["Proof of Work using the same SHA-256 algorithm as Bitcoin mining","Delegated Proof of Stake with community-elected block producers","Proof of Authority using a fixed and permissioned validator set"]},{q:"What are drivechains (BIP-300) designed to enable?",a:"Permissionless sidechains with miner-voted withdrawals to mainchain",wrong:["Faster block times on Bitcoin by reducing difficulty adjustment","A new Lightning channel type that skips on-chain funding steps","Decentralized mining pools that auto-distribute block rewards"]},{q:"What is the primary security concern with federated sidechains like Liquid?",a:"Users must trust federation members not to collude and steal funds",wrong:["The sidechain can reverse Bitcoin base layer transactions at will","Federated sidechains consume more energy than Bitcoin's proof-of-work","The federation has the power to change Bitcoin's 21 million cap"]}],maximalism_pt2:[{q:'What do Bitcoiners mean when they call "toxic maximalism" an immune response?',a:"Aggressive pushback against scams protects newcomers like an immune system",wrong:["Maximalists spread computer viruses to attack competing altcoin networks","Toxic maximalism is a disease Bitcoin developers are actively trying to cure","It means Bitcoin's code automatically rejects transactions from altcoins"]},{q:'What is the "altcoin opportunity cost" argument made by Bitcoin maximalists?',a:"Money spent on altcoins could have gone to Bitcoin, which outperforms long-term",wrong:["Altcoins are free to create so there is no real opportunity cost at all","Bitcoin maximalists believe altcoin trading increases Bitcoin's overall value","Opportunity cost is a fiat concept that does not apply to digital assets"]},{q:"Why do Bitcoin-only companies (like Swan, River, and Unchained) choose not to support altcoins?",a:"They see promoting altcoins as ethically wrong since most will fail and harm users",wrong:["They lack the technical capability needed to support other cryptocurrency tokens","Government regulations currently prohibit companies from offering multiple cryptos","Supporting altcoins would make their exchange and wallet software too slow"]},{q:'What is the "ethical case" for Bitcoin maximalism?',a:"Promoting risky altcoins to unsophisticated investors causes real financial harm",wrong:["Bitcoin maximalists believe they have a religious duty to spread adoption","Ethics demand that all financial technologies be treated equally by default","The ethical case is that Bitcoin miners deserve all cryptocurrency profits"]},{q:'How does Gresham\'s Law ("bad money drives out good") apply to the Bitcoin maximalism argument?',a:"People spend weak fiat and altcoins while hoarding Bitcoin as the hardest money",wrong:["Gresham's Law proves that cheaper altcoins will eventually replace Bitcoin","It means governments will ultimately force citizens to use Bitcoin only","Gresham's Law only applies to physical coins and not digital currencies"]}],mining_pt5:[{q:"What does Stratum V2 allow individual miners to do that Stratum V1 does not?",a:"Choose their own transactions for block templates",wrong:["Mine without needing any internet connection","Bypass the network difficulty adjustment algorithm","Mine multiple different coins at the same time"]},{q:"What is a block template in Bitcoin mining?",a:"A candidate block with selected transactions awaiting a valid hash",wrong:["A design blueprint for building new ASIC mining hardware","A backup copy of the entire Bitcoin blockchain ledger","A reusable template for creating new cryptocurrency mining pools"]},{q:"What is a selfish mining attack?",a:"Withholding discovered blocks to gain an unfair chain advantage",wrong:["Refusing to share mining profits with other pool members","Mining only low-fee transactions for the miner's personal gain","Using stolen electricity to illegally power Bitcoin mining rigs"]},{q:"What is ASICBoost?",a:"A technique that optimizes SHA-256 to reduce energy per hash",wrong:["A specific brand of mining hardware manufactured by Bitmain","A firmware update that automatically doubles any miner's hashrate","A method to cool ASIC miners using advanced liquid nitrogen"]},{q:"What is the difference between overt and covert ASICBoost?",a:"Overt is visible in block headers; covert is hidden from view",wrong:["Overt is legal in all jurisdictions while covert is illegal","Overt uses significantly more energy per hash than covert does","Overt works on any ASIC while covert is Bitmain hardware only"]}],mining_pt6:[{q:'What is "hash price" in Bitcoin mining economics?',a:"Revenue earned per unit of hash rate per day",wrong:["Cost to purchase a single ASIC miner","Bitcoin's price divided by total hash rate","Electricity cost per hash computation"]},{q:"What typically happens to less efficient miners shortly after a Bitcoin halving?",a:"They become unprofitable and may shut down",wrong:["They automatically receive double the reward","Their hash rate doubles to compensate","They permanently switch to mining altcoins"]},{q:"What is the typical operational lifespan of an ASIC miner before it becomes obsolete?",a:"Approximately 3 to 5 years",wrong:["About 6 months on average","Over 20 years with maintenance","Exactly one halving cycle"]},{q:"What is the breakeven electricity cost for Bitcoin mining?",a:"The kWh price where revenue equals costs",wrong:["A fixed rate set by Bitcoin developers","The average electricity cost worldwide","The minimum power to run one ASIC"]},{q:"As block subsidies decrease over time, what must replace them to incentivize miners?",a:"Transaction fees paid by users",wrong:["Government subsidies for miners","Increased mining difficulty","New coins from hard forks"]}],"misconceptions-fud_pt2":[{q:'How do Bitcoiners respond to "Bitcoin is too volatile to be money"?',a:"Every 4-year period has been profitable and volatility decreases over time",wrong:["They agree volatility makes Bitcoin unsuitable as money","They say volatility doesn't exist if you ignore the price","They claim Bitcoin's price is actually fixed by miners"]},{q:'Why is the claim "quantum computers will break Bitcoin" misleading?',a:"Such computers don't exist yet and Bitcoin can upgrade before they do",wrong:["Bitcoin already uses quantum-resistant encryption algorithms","Quantum computers actually strengthen Bitcoin's security","Satoshi designed Bitcoin to be immune to all future computing"]},{q:'What is the rebuttal to "Tether (USDT) props up Bitcoin\'s price"?',a:"Bitcoin grew for years before Tether and kept rising through its controversies",wrong:["Tether holds 100% of its reserves in Bitcoin directly","Bitcoin's price is determined solely by mining costs","Tether was created by Satoshi as part of Bitcoin's design"]},{q:'Why is "Bitcoin is a pyramid scheme" factually wrong?',a:"It has no company, no CEO, no return promises, and no recruitment profits",wrong:["Because early adopters are guaranteed profits by the protocol","Because Satoshi Nakamoto still runs the company behind Bitcoin","Because the Bitcoin protocol pays dividends to long-term holders"]},{q:'What is the strongest argument against "governments will ban Bitcoin"?',a:"China banned it multiple times yet it kept growing, and the US approved ETFs",wrong:["Governments lack the technology to detect Bitcoin transactions","International law prevents any country from banning crypto","Bitcoin automatically shuts down in countries where it's banned"]}],nodes_pt4:[{q:"What is the key difference between a pruned node and an archival (full) node?",a:"A pruned node deletes old block data after verifying it",wrong:["A pruned node skips transaction verification entirely","An archival node only stores the UTXO set","A pruned node cannot validate new transactions"]},{q:"What does BIP 152 (Compact Block Relay) do?",a:"Sends short transaction IDs instead of full transactions",wrong:["Compresses the entire blockchain into smaller files","Allows nodes to skip blocks during initial sync","Encrypts block data for privacy between nodes"]},{q:"What is the Erlay protocol designed to improve?",a:"Transaction relay efficiency between nodes",wrong:["Block mining speed via nonce optimization","Lightning Network channel capacity","Wallet synchronization for mobile devices"]},{q:"What is the UTXO set and why does its size matter for nodes?",a:"All unspent outputs nodes must keep in memory for validation",wrong:["A list of all transactions ever made on Bitcoin","A record of all mining rewards ever distributed","A backup of private keys stored across the network"]},{q:"What is a major concern about running a Bitcoin full node related to bandwidth?",a:"Relaying transactions and blocks uses significant upload bandwidth",wrong:["Nodes must pay per-megabyte fees to the network","Bandwidth usage is zero after initial block download","Only mining nodes consume significant bandwidth"]}],nodes_pt5:[{q:"What programming language is Bitcoin Core primarily written in?",a:"C++",wrong:["Rust","Python","Java"]},{q:"What is btcd?",a:"An alternative Bitcoin full node written in Go",wrong:["A Bitcoin wallet for desktop computers","A command-line tool for Bitcoin mining","A testing framework for Bitcoin Core"]},{q:"What are reproducible builds in the context of Bitcoin Core?",a:"Anyone can compile source and get an identical binary",wrong:["A system where Bitcoin Core auto-updates itself","A method to restore a node from a backup","A way to compile Bitcoin Core faster on CPUs"]},{q:"What is Guix used for in Bitcoin Core development?",a:"A build system for reproducible, verifiable builds",wrong:["A graphical interface for running a Bitcoin node","A security scanner for checking vulnerabilities","A package manager for installing Bitcoin wallets"]},{q:"Why is it important to be able to build Bitcoin Core from source?",a:"To verify the code and ensure your binary matches it",wrong:["Because pre-built binaries aren't available","To get access to hidden developer features","Because source builds make the node faster"]}],"op-codes_pt2":[{q:"What would OP_CAT enable if re-enabled?",a:"Concatenation of data values in script",wrong:["Comparison of timestamp values","Multiplication of numeric values","Direct verification of signatures"]},{q:"What does OP_CHECKSIGFROMSTACK verify?",a:"Arbitrary message signatures on the stack",wrong:["Only standard transaction signatures","Block signatures submitted by miners","Lightning Network commitment signatures"]},{q:"What is Simplicity designed for in Bitcoin?",a:"Formal verification of smart contracts",wrong:["Faster transaction processing speeds","Simplified wallet address formats","Reduced overall block sizes"]},{q:"What is a major limitation of Bitcoin Script?",a:"No loops or complex control flow",wrong:["Maximum of 100 opcodes per script","Cannot handle any signatures","Requires active internet access"]},{q:"Which script type was introduced with Taproot?",a:"P2TR (Pay to Taproot)",wrong:["P2SH (Pay to Script Hash)","P2WSH (Pay to Witness Script)","P2PKH (Pay to Pub Key Hash)"]}],"orange-pilling_pt2":[{q:'What is the "Socratic method" approach to orange-pilling someone about Bitcoin?',a:"Asking questions that lead them to discover Bitcoin's value themselves",wrong:["Quoting ancient Greek philosophers who predicted digital money","Having the person read the Bitcoin whitepaper out loud to you","Debating them aggressively until they agree Bitcoin is good"]},{q:'What is "progressive disclosure" when introducing someone to Bitcoin?',a:"Starting with simple concepts they care about, then going deeper",wrong:["Showing them Bitcoin's full transaction history from genesis","Revealing your entire Bitcoin portfolio to build their trust","Disclosing all of Bitcoin's technical flaws upfront to seem honest"]},{q:"When orange-pilling family members, what is generally the most effective approach?",a:"Focus on what they care about - savings, retirement, their future",wrong:["Send them a 3-hour technical podcast about mining and hashing","Buy them Bitcoin without asking and surprise them with it later","Bring it up at every family dinner until they finally agree"]},{q:"What is one of the biggest mistakes people make when trying to orange-pill someone?",a:"Information overload - dumping too much detail at once",wrong:["Being too patient and waiting for them to ask questions","Starting with how Bitcoin helps people in other countries","Recommending they read a book about the history of money"]},{q:"Which book is widely considered the best starting point for orange-pilling someone interested in economics and sound money?",a:"The Bitcoin Standard by Saifedean Ammous",wrong:["Mastering Bitcoin by Andreas Antonopoulos","Programming Bitcoin by Jimmy Song","The Blocksize War by Jonathan Bier"]}],ordinals_inscriptions:[{q:"Who proposed the Ordinal Theory for Bitcoin?",a:"Casey Rodarmor",wrong:["Adam Back","Pieter Wuille","Satoshi Nakamoto"]},{q:"How are individual satoshis numbered in Ordinal Theory?",a:"Sequentially based on mining order",wrong:["Randomly assigned by the network","By their transaction ID hash","By the receiving wallet address"]},{q:"What do inscriptions attach to specific satoshis?",a:"Arbitrary data like images or text",wrong:["Private keys for spending them","Their full transaction history","Multisig spending conditions"]},{q:"What token standard emerged from Ordinals functionality?",a:"BRC-20",wrong:["ERC-20","RGB","Omni Layer"]},{q:"What was a major criticism of Ordinals regarding block space?",a:"They use limited block space for non-monetary data",wrong:["They significantly reduce mining reward amounts","They break Bitcoin's core consensus rules","They allow theft of other users' funds"]}],philosophy_pt2:[{q:"Who wrote the Cypherpunk Manifesto?",a:"Eric Hughes",wrong:["Timothy May","Julian Assange","Nick Szabo"]},{q:"What concept did Timothy May advocate for in the Crypto-Anarchist Manifesto?",a:"Using cryptography to protect individual privacy",wrong:["Building centralized digital currency systems","Government regulation of all encryption tools","Corporate ownership of communication networks"]},{q:"What was Nick Szabo's Bit Gold concept?",a:"A digital collectible using proof of work",wrong:["A stablecoin backed by physical gold","A centralized government digital currency","A Lightning-style payment channel design"]},{q:"What did Wei Dai propose with b-money?",a:"Anonymous digital cash with decentralized minting",wrong:["A blockchain with standard mining rewards","A central bank controlled digital currency","A system of gold-backed certificates"]},{q:"What was Hal Finney's famous contribution to Bitcoin?",a:"Received the first Bitcoin transaction from Satoshi",wrong:["Wrote the original Bitcoin whitepaper himself","Created the SHA-256 based mining algorithm","Founded the first Bitcoin trading exchange"]}],"privacy-nonkyc_pt4":[{q:"What is a PayJoin (P2EP) transaction?",a:"Both sender and receiver contribute inputs, obscuring who paid whom",wrong:["A payment split equally between two participating parties","A transaction requiring two separate network confirmations","A joint mining operation shared between two mining pools"]},{q:"What are Silent Payments (BIP 352)?",a:"One static address generates a unique on-chain address per payment",wrong:["Transactions that are hidden from the public mempool entirely","Payments delayed until network activity drops to low levels","A method to send Bitcoin without paying any transaction fees"]},{q:"What is the Boltzmann entropy score used for in Bitcoin privacy?",a:"Measuring ambiguity of a transaction's input-output linkages",wrong:["Calculating the thermodynamic energy cost of a transaction","Rating the randomness quality of a wallet's seed phrase","Scoring how quickly a transaction will get confirmed"]},{q:"What does Whirlpool do for Bitcoin privacy?",a:"Mixes UTXOs via CoinJoin to break transaction history links",wrong:["Provides a VPN service designed specifically for Bitcoin nodes","Encrypts Bitcoin transactions end-to-end before broadcast","Runs a privacy coin layer on top of the Bitcoin blockchain"]},{q:"What is CoinSwap and how does it differ from CoinJoin?",a:"Uses atomic swaps so mixing is invisible on-chain, unlike CoinJoin",wrong:["Converts Bitcoin to privacy coins and back for mixing purposes","Is faster but provides less privacy protection than CoinJoin","Requires a trusted third party while CoinJoin does not need one"]}],"problems-of-money_pt4":[{q:"The Cantillon Effect describes how newly printed money benefits those closest to its creation. Who benefits MOST from money printing?",a:"Banks and the politically connected who receive new money first",wrong:["Average workers who receive higher wages from inflation","Retirees on fixed incomes who get cost-of-living adjustments","Small business owners who can raise their prices immediately"]},{q:"What is Quantitative Easing (QE)?",a:"A central bank creating new money to buy bonds, expanding supply",wrong:["A method of reducing government debt by printing less money","A technique for making international trade easier between nations","A system where banks lend to each other at zero percent interest"]},{q:'What is the "repo market" and why does it matter for understanding fiat fragility?',a:"Overnight lending market using bonds as collateral - its 2019 crisis exposed systemic fragility",wrong:["A marketplace where banks sell repossessed homes and vehicles for profit","A government repository that stores and audits physical gold reserves","A database where central banks track and monitor all global transfers"]},{q:'What is the "Eurodollar system"?',a:"US dollars held and created by banks outside the US, forming a shadow system",wrong:["The system that converts Euros to Dollars at European exchange desks","A European Central Bank program to replace the Dollar with the Euro","A cryptocurrency project backed equally by both Euros and US Dollars"]},{q:'What does the decline of the "petrodollar" system mean for global finance?',a:"Oil nations moving away from dollar pricing weakens its reserve status",wrong:["Oil companies are switching from drilling to mining Bitcoin instead","The petrodollar decline means that oil is becoming nearly worthless","European nations are being forced to buy all their oil with gold"]}],regulation_pt3:[{q:"In the US, what is the key difference between SEC and CFTC jurisdiction over digital assets?",a:"SEC regulates securities (most altcoins); CFTC regulates Bitcoin as a commodity",wrong:["SEC handles Bitcoin while CFTC handles all altcoins separately","Both agencies share identical authority over all digital assets","CFTC only regulates physical commodities, not any digital assets"]},{q:"What is the Howey Test and how does it apply to Bitcoin?",a:"A legal test for securities - Bitcoin fails to qualify since it has no central enterprise",wrong:["A technical test that measures a blockchain's degree of decentralization","Bitcoin fails the Howey Test, making it an SEC-regulated security asset","A test that determines the appropriate tax rate on crypto investments"]},{q:'What is the "Travel Rule" in cryptocurrency regulation?',a:"A FATF rule requiring institutions to share sender/receiver identity above a threshold",wrong:["A regulation that limits Bitcoin transfers to within a single country","A requirement for Bitcoin miners to register their physical locations","A law that bans carrying hardware wallets across international borders"]},{q:"What is the FATF and why is it significant for Bitcoin privacy?",a:"An international body pushing KYC/AML standards that threaten self-custodial privacy",wrong:["A global mining consortium that coordinates difficulty adjustment levels","A nonprofit organization promoting Bitcoin adoption in developing nations","A technology standard designed for faster Bitcoin transaction processing"]},{q:"How have US states approached Bitcoin regulation differently from the federal government?",a:"Several states passed pro-Bitcoin laws like reserve bills and transmitter exemptions",wrong:["All 50 states enforce identical cryptocurrency regulations matching federal law","States are constitutionally prohibited from creating crypto-related legislation","Most states have banned Bitcoin mining operations due to energy concerns"]}],rollups:[{q:"What is a validity rollup on Bitcoin?",a:"A system that bundles off-chain transactions and posts a ZK proof to Bitcoin",wrong:["A sidechain that copies Bitcoin's consensus rules exactly as written","A Lightning Network channel that batches together multiple payments","A mining pool feature that combines block templates from miners"]},{q:"How do sovereign rollups differ from validity rollups?",a:"Users verify rollup state themselves rather than relying on the base layer",wrong:["Sovereign rollups use a central authority; validity rollups are decentralized","Sovereign rollups use proof-of-stake; validity rollups use proof-of-work","Sovereign rollups are limited to only seven transactions per second"]},{q:"How could BitVM enable rollups on Bitcoin?",a:"By allowing fraud proofs to verify rollup state without needing new opcodes",wrong:["By adding a Turing-complete VM directly into Bitcoin's consensus layer","By creating a dedicated sidechain specifically for validating rollup data","By replacing Bitcoin's existing Script language with Solidity contracts"]},{q:"How do Bitcoin rollups differ from sidechains?",a:"Rollups post proofs or data to Bitcoin, inheriting its security guarantees",wrong:["Rollups use a separate token for gas while sidechains use native BTC","Rollups need a federation of signers while sidechains are fully trustless","Rollups are faster than sidechains but limited to simple transfers only"]},{q:"What is the main trust assumption difference between a validity rollup and an optimistic rollup?",a:"Validity rollups prove correctness upfront; optimistic rollups assume it until challenged",wrong:["Validity rollups trust a federation of signers; optimistic rollups trust miners","Validity rollups need a soft fork to work; optimistic rollups work on Bitcoin today","Validity rollups are run centrally; optimistic rollups are always fully decentralized"]}],"self-custody_pt3":[{q:"What is Sparrow Wallet known for in multisig coordination?",a:"Deep UTXO management and easy multisig setup with hardware signers",wrong:["A mobile-only wallet with cloud-based multisig coordination","A hardware wallet that stores multiple seed phrases internally","A browser extension designed primarily for Lightning payments"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction)?",a:"A standard format letting a transaction be built and signed by multiple parties",wrong:["A special Bitcoin transaction type that only sends partial amounts","A privacy protocol that hides the identity of a transaction sender","A transaction format exclusively used by mining pool operators"]},{q:"What are output descriptors in Bitcoin?",a:"A standard way to describe how a wallet derives addresses for reliable recovery",wrong:["Labels attached to individual transaction outputs for bookkeeping purposes","A complete list of all outputs ever created on the Bitcoin blockchain","Metadata that mining pools attach to the transactions they broadcast"]},{q:"Why is multisig generally preferred over Shamir Secret Sharing (SSS) for Bitcoin custody?",a:"Multisig never reconstructs the full private key in one place; SSS does when signing",wrong:["Multisig transactions cost significantly less in fees than SSS schemes","SSS requires more hardware devices to operate than multisig setups","Multisig predates SSS and has substantially better documentation available"]},{q:"What is Nunchuk known for in the Bitcoin wallet space?",a:"Easy collaborative multisig setup and built-in inheritance planning",wrong:["Being the first wallet to natively support Lightning payments","A hardware-only wallet designed exclusively for cold storage use","A privacy wallet that uses CoinJoin mixing transactions by default"]}],"self-custody_pt4":[{q:"Why is titanium preferred over stainless steel for seed phrase backup plates?",a:"Higher melting point and better corrosion resistance in extreme conditions",wrong:["Titanium is significantly cheaper and more widely available worldwide","Titanium plates can fit more seed words than steel backup plates","Titanium is the only metal undetectable by standard metal detectors"]},{q:"What is a passphrase (25th word) in Bitcoin seed phrase security?",a:"An extra user-chosen word that generates an entirely different wallet",wrong:["The password you enter to unlock your hardware wallet device","A recovery phrase issued to you by the wallet manufacturer","An encryption key used to protect the local blockchain data"]},{q:"Why is geographic distribution important for Bitcoin seed phrase storage?",a:"It protects against localized disasters destroying all backup copies at once",wrong:["It speeds up the wallet by routing through the nearest Bitcoin nodes","It is a legal requirement enforced in most regulatory jurisdictions","It mathematically increases the entropy of the generated seed phrase"]},{q:"What is a dead man's switch in Bitcoin inheritance planning?",a:"A mechanism that triggers key release if the owner fails to check in",wrong:["A physical switch on hardware wallets that wipes them if tampered","A transaction that auto-sends all Bitcoin to a burn address on a timer","A self-destruct feature built directly into the Bitcoin Core software"]},{q:"What is the biggest risk of not having a Bitcoin inheritance plan?",a:"Your Bitcoin could be permanently lost since no one else has the keys",wrong:["The government will automatically seize all of your Bitcoin holdings","Your Bitcoin gets redistributed among other active network participants","Your Bitcoin will steadily lose value without an actively managed wallet"]}],softwar_pt2:[{q:"What military rank is Jason Lowery?",a:"Major",wrong:["Colonel","Lieutenant","Captain"]},{q:"What university did Jason Lowery work with on his thesis?",a:"MIT",wrong:["Harvard","Stanford","Caltech"]},{q:"According to Softwar, what does proof of work project?",a:"Physical power through cyberspace",wrong:["Financial return on investment","Social consensus via voting","Network speed and throughput"]},{q:"How does Softwar view Bitcoin for nation-states?",a:"A strategic defense technology",wrong:["A replacement for fiat currency","A consumer payment system","An unregulated security asset"]},{q:"What energy concept is central to the Softwar thesis?",a:"Using energy to secure cyberspace property",wrong:["Reducing global carbon emissions","Accelerating solar power adoption","Profiting from energy arbitrage"]}],spv:[{q:"What does SPV (Simplified Payment Verification) allow a lightweight client to do?",a:"Verify transaction inclusion using block headers and Merkle proofs",wrong:["Mine Bitcoin blocks using minimal computing power","Send transactions without paying any network fees","Run a full node on a mobile phone with limited storage"]},{q:"What privacy problem did the original SPV bloom filters (BIP-37) have?",a:"They leaked which addresses the wallet cared about to the server",wrong:["They revealed the user's IP address to every network node","They broadcast the user's seed phrase as part of filter data","They required users to share real names with node operators"]},{q:"What do BIP-157 and BIP-158 (compact block filters) improve over bloom filters?",a:"Clients download pre-computed filters without revealing their addresses",wrong:["They compress the entire blockchain into a single downloadable file","They allow nodes to verify transactions without any network access","They replace Merkle proofs with zero-knowledge proofs for speed"]},{q:"What is Neutrino in the context of Bitcoin light clients?",a:"A light client protocol using BIP-157/158 compact block filters",wrong:["A privacy coin built as a Bitcoin sidechain project","A mining algorithm designed for mobile phone hardware","A wallet that runs a full node in the cloud for you"]},{q:"What is the main security tradeoff of SPV compared to running a full node?",a:"SPV clients trust miners produce valid blocks without full verification",wrong:["SPV clients cannot receive Bitcoin, they can only send it","SPV clients must pay higher transaction fees than full nodes","SPV clients can only connect to one peer node at a time"]}],submarine_swap_pt2:[{q:"What is a Loop Out in Lightning?",a:"Moving funds from Lightning back to on-chain",wrong:["Opening a new payment channel","Receiving inbound Lightning payments","Closing all channels at once"]},{q:"What is Boltz Exchange known for?",a:"Trustless on-chain and Lightning swaps",wrong:["Running a Bitcoin mining pool","Operating a centralized exchange","Selling Bitcoin hardware wallets"]},{q:"What makes submarine swaps trustless?",a:"Atomic hash time-locked contracts",wrong:["Multi-signature escrow wallets","Trusted third-party verification","Proof of stake consensus rules"]},{q:"How do submarine swaps differ from atomic swaps?",a:"They move between layers of the same chain",wrong:["Submarine swaps always require trust","Atomic swaps are significantly faster","Submarine swaps use different coins"]},{q:"What enables cross-chain atomic swaps without intermediaries?",a:"HTLCs combining hashlock and timelock",wrong:["Trusted custodial escrow services","Centralized exchange order books","Smart contract platforms only"]}],tail_emission:[{q:'What is "tail emission" in the context of cryptocurrency monetary policy?',a:"A small perpetual block reward ensuring miners always get some subsidy",wrong:["The final Bitcoin expected to be mined around the year 2140","The process of burning unsold Bitcoin to reduce total supply","A mechanism that increases block rewards over time for miners"]},{q:"Which major cryptocurrency implements tail emission as part of its monetary policy?",a:"Monero, with a permanent minimum reward of 0.6 XMR per block",wrong:["Bitcoin, which added tail emission in the Taproot upgrade","Ethereum, which introduced it during the merge to proof of stake","Litecoin, which activated it after its third halving event"]},{q:"What concern about Bitcoin's long-term security does the tail emission debate address?",a:"Whether fees alone can incentivize miners after block rewards end",wrong:["Whether Bitcoin's encryption can withstand quantum computers","Whether the 21 million supply cap should be raised over time","Whether nodes will have enough storage for the growing chain"]},{q:"What is the main argument AGAINST adding tail emission to Bitcoin?",a:"It would break the 21 million cap and destroy sound money credibility",wrong:["Tail emission would make mining too profitable and attract too many","It would speed up transaction confirmation times excessively","Tail emission is technically impossible to implement on Bitcoin"]},{q:'What is the "fee market sufficiency" argument against the need for tail emission?',a:"Growing adoption and scarce block space will naturally raise fee revenue",wrong:["Miners will voluntarily work for free because they believe in Bitcoin","The government will subsidize mining to keep the network running","New Bitcoin will be discovered on the network like finding new gold"]}],time_preference_pt3:[{q:'According to Saifedean Ammous in "The Bitcoin Standard," what is the relationship between sound money and time preference?',a:"Sound money lowers time preference, encouraging saving and long-term investment",wrong:["Sound money raises time preference because people rush to spend currency","There is no meaningful relationship between money type and time preference","Sound money eliminates time preference, making people totally indifferent"]},{q:"How does Ammous argue that low time preference connects to civilization building?",a:"People invest in long-term projects when money reliably holds its value",wrong:["Civilizations advance fastest when people spend money as quickly as possible","Low time preference leads to stagnation because nobody takes any risks","Civilization building is completely unrelated to the monetary system"]},{q:"What behavioral effect does fiat money have on time preference according to the Austrian economics perspective?",a:"Fiat raises time preference - inflation punishes savers and rewards debtors",wrong:["Fiat lowers time preference because stable inflation aids long-term planning","Fiat has no effect on time preference, which is determined by culture","Fiat encourages saving because interest rates compensate for inflation"]},{q:"How does the concept of delayed gratification relate to Bitcoin and sound money?",a:"Sound money rewards patience by preserving purchasing power over time",wrong:["Delayed gratification is irrelevant to any monetary system design","Bitcoin punishes patience because its price is far too volatile","Sound money discourages waiting by making everything too expensive"]},{q:"What is the key difference between how fiat and Bitcoin influence personal financial behavior?",a:"Fiat incentivizes consumption and debt; Bitcoin incentivizes saving",wrong:["Both systems produce identical behavior - spending stays the same","Bitcoin makes people spend more as they feel wealthy from gains","Fiat encourages saving; Bitcoin encourages spending due to deflation"]}],vbyte:[{q:"What is a virtual byte (vbyte) in Bitcoin?",a:"A unit where 1 vbyte equals 4 weight units, used for fee calculation",wrong:["A compressed byte format that reduces transaction size by 75%","The amount of data a Bitcoin node can process per second","A unit measuring the electricity cost of validating transactions"]},{q:"How did SegWit change the way Bitcoin transaction fees are calculated?",a:"Fees use weight units or vbytes, giving witness data a discount",wrong:["SegWit made all transactions free for the first year after launch","SegWit replaced fee priority with a first-come-first-served queue","SegWit doubled the base fee rate for all transaction types"]},{q:"What is the witness discount ratio in SegWit?",a:"Witness data costs 1 weight unit per byte; non-witness costs 4",wrong:["Witness data is free; non-witness data costs 2 weight units","Both witness and non-witness data cost 2 weight units per byte","Witness data costs 3 weight units; non-witness data costs 4"]},{q:"Why is understanding vbytes important for optimizing Bitcoin transaction costs?",a:"Using SegWit addresses moves data into the discounted witness section",wrong:["Vbytes determine how many confirmations a transaction needs","Using fewer vbytes increases the mining reward for the block","Transactions with more vbytes get higher priority in mempool"]},{q:"A typical single-input, single-output SegWit transaction is approximately how many vbytes?",a:"About 110 vbytes",wrong:["About 500 vbytes","About 10 vbytes","About 1,000 vbytes"]}],blockchain_timechain:[{q:'Why do some Bitcoiners prefer the term "timechain" over "blockchain"?',a:"It emphasizes chronological ordering — each block is permanently anchored in time, not merely linked by shared data hashes",wrong:['It was Satoshi\'s original preferred name in the whitepaper before "blockchain" became the mainstream term later',"It highlights that Bitcoin blocks have timestamps while most other blockchains completely omit block time information","It refers to the fixed 10-minute block interval creating a reliable and predictable sequence of time-indexed records"]},{q:"What date was the Bitcoin genesis block mined, and what was embedded in it as proof-of-time?",a:'January 3, 2009; the Times headline "Chancellor on brink of second bailout for banks" proving no coins predate that block',wrong:['October 31, 2008; the text "Bitcoin: A Peer-to-Peer Electronic Cash System" matching the title of the whitepaper exactly','January 9, 2009; the headline "US Federal Reserve cuts interest rates to near zero" referencing the ongoing financial crisis','November 1, 2008; the phrase "The Times 01/Nov/2008 Global markets near total collapse" embedded as political commentary']},{q:"How does Bitcoin track ownership differently from a traditional bank account?",a:"Bitcoin uses UTXOs (Unspent Transaction Outputs) — discrete coin-like objects — rather than maintaining a running account balance",wrong:["Bitcoin maintains a shared ledger of named accounts with balances updated atomically by each confirmed transaction on the chain","Bitcoin stores ownership in a global identity table where each public key maps to a single cumulative spendable balance amount","Bitcoin assigns each wallet address a unique balance field that miners update when new blocks are added to the chain"]},{q:"What role do Merkle trees play in Bitcoin's design?",a:"They allow SPV wallets to verify a transaction exists in a block without downloading the entire blockchain at all",wrong:["They compress raw transaction bytes so each block can store more transactions within the standard 1 MB block size limit","They link blocks together unforgeable by hashing all transactions directly into the previous block's header field","They prevent double-spending by organizing transactions into a sorted tree that all miners must validate on confirmation"]},{q:"What happens when two miners simultaneously find valid blocks at the same block height?",a:"Both are briefly valid; this is called an orphan or stale block situation — only one survives once the chain extends further",wrong:["Both blocks are merged by the network into a combined super-block containing all transactions from each competing version","The network pauses for 10 minutes and nodes vote on which block to accept based on total transaction fees included","Both miners split the block reward equally and every node permanently accepts whichever block it received first"]},{q:"Which six fields appear in a standard Bitcoin block header?",a:"Version, previous block hash, Merkle root, timestamp, nBits difficulty target, and nonce — the six canonical header fields",wrong:["Version, miner address, transaction count, Merkle root, timestamp, and block height as specified in the protocol spec","Previous block hash, coinbase reward amount, timestamp, nBits target, nonce, and the winning miner's signature field","Block height, previous hash, Merkle root, transaction list hash, nonce, and the miner's public key identifier field"]},{q:'How does Bitcoin settlement compare to the "instant" transfers promoted by retail banking?',a:"Bank transfers are IOUs between institutions; Bitcoin achieves irreversible on-chain settlement in roughly 10 minutes",wrong:["Both achieve true final settlement instantly; the only difference is Bitcoin's settlement is public while bank transfers are private","Bitcoin settlement takes 3–5 business days like wire transfers; the 10-minute block time is only for initial confirmation","Fiat transfers settle on delivery while Bitcoin requires a 72-hour grace period for large transactions over 1 BTC value"]},{q:"What is the Bitcoin mempool and how do miners interact with it?",a:"It's the waiting room for unconfirmed transactions; miners select from it and prioritize higher-fee transactions for inclusion",wrong:["It's a permanent archive of all confirmed transactions that nodes must query to validate each new incoming spending attempt","It's a shared pool where miners deposit newly minted coins before distributing them back to senders as transaction change","It's a registry of known peer node addresses used to discover and connect to other participants on the Bitcoin network"]},{q:"How does Bitcoin's transaction finality compare to SWIFT international bank transfers?",a:"Bitcoin reaches practical finality in about 1 hour (6 confirmations); SWIFT international transfers take 1–5 business days",wrong:["Bitcoin finality takes 24 hours for large transactions; SWIFT now settles in under 2 hours for standard bank-to-bank wires","Both systems achieve finality in roughly the same timeframe; the meaningful difference is in cost rather than settlement speed","Bitcoin reaches finality in under 1 minute with Taproot active; SWIFT settles same-day under the ISO 20022 standard"]},{q:"Why is altering a historical Bitcoin block effectively impossible once buried under sufficient work?",a:"Changing any block invalidates every subsequent block's hash, forcing an attacker to redo all downstream proof-of-work",wrong:["Changing a block triggers a cryptographic alarm that immediately alerts all nodes causing automatic rejection of the edit","Each block is countersigned by a quorum of miners who must all re-sign any proposed modifications to historical records","Historical blocks are stored in read-only memory on every Bitcoin node, making any write operation physically impossible"]}],layer_2_lightning:[{q:"What is the fundamental on-chain mechanism that makes Lightning Network payment channels possible?",a:"Two parties lock funds in a 2-of-2 multisig UTXO on-chain, then exchange signed balance updates off-chain without broadcasting",wrong:["Two parties create a shared custodial wallet hosted by a Lightning Service Provider who settles batches periodically on-chain","Two parties send micropayments through a trusted routing hub that accumulates them and settles on-chain once per day","Two parties lock funds with a single-signature escrow contract and route payments outward through Lightning Service Providers"]},{q:"What cryptographic primitive enables trustless multi-hop routing through intermediate Lightning Network nodes?",a:"HTLCs (Hash Time-Locked Contracts): payment releases when the recipient reveals a preimage, or refunds after a timeout expires",wrong:["Schnorr threshold signatures: three-of-five quorums authorize each hop and prevent intermediate nodes from stealing funds","Zero-knowledge proofs: each routing node proves it forwarded funds without learning the source or destination of the payment","Pedersen commitments: each hop commits to the forwarded amount and reveals it only after the full route successfully completes"]},{q:"What information does a standard Lightning Network BOLT11 invoice contain?",a:"Payment amount, payment hash, expiry time, and destination public key — all encoded in a compact BOLT11 string format",wrong:["Sender's node ID, payment amount, full routing path, and a cryptographic commitment to the sender's current channel balance","Recipient's Bitcoin address, invoice amount, expiry time, and an ordered list of acceptable intermediate routing node IDs","Payment hash, a UTXO reference, expiry time, and the maximum routing fee the payer will accept per hop along the route"]},{q:'What is "inbound liquidity" on the Lightning Network and why is it required to receive payments?',a:"It's capacity to receive funds; someone else must open and fund a channel directed toward your node before you can receive",wrong:["It's the total BTC you have locked across all outgoing channels; more inbound capacity increases your maximum outgoing send limit","It's a routing score assigned by the network based on how reliably your node has historically forwarded other people's payments","It's the reserved on-chain balance your Lightning wallet holds as collateral before you can open any new payment channel"]},{q:"How are routing fees structured on the Lightning Network?",a:"A flat base fee in satoshis per payment plus a proportional fee rate charged in parts per million of the payment amount",wrong:["A uniform percentage fee set globally by the Bitcoin protocol and charged identically by every node along every payment route","Fees equal the hop count multiplied by the node operator's published hourly rate, capped at 0.5% of total payment value","Routing fees are negotiated bilaterally between each pair of nodes before every payment using a real-time fee auction system"]},{q:'What key advantage do BOLT12 "offers" provide over standard BOLT11 Lightning invoices?',a:"Offers are static reusable payment codes; unlike BOLT11 single-use invoices, the same offer can be paid repeatedly by anyone",wrong:["Offers include mandatory KYC fields that make Lightning payments compliant with financial regulations in regulated jurisdictions","Offers embed a complete routing path to the recipient, eliminating pathfinding work in the sender's wallet software entirely","Offers encode pre-negotiated channel paths that bypass normal routing, making payments confirm faster than standard BOLT11 invoices"]},{q:"What is LNURL and what categories of interaction does it enable in Lightning wallets?",a:"LNURL is a set of HTTP-based protocols enabling QR-driven Lightning interactions: pay-to-link, withdraw, and auth flows",wrong:["LNURL is a Bitcoin Improvement Proposal defining a universal address format for cross-chain Lightning payment routing globally","LNURL is a routing protocol that enables Lightning nodes to discover the lowest-fee multi-hop path to any global destination","LNURL is a Lightning wallet sync standard that replicates channel states across multiple devices belonging to one user"]},{q:'What is a Lightning Network "force-close" and what protection exists against fraud after one is broadcast?',a:"A unilateral broadcast of the last signed channel state; a CSV timelock gives the counterparty time to contest any cheating attempt",wrong:["A force-close is a cooperative mutual settlement where both parties co-sign an on-chain transaction dividing the balance evenly","A force-close triggers automatic reimbursement to both parties from the Lightning Service Provider's dedicated insurance fund","A force-close broadcasts a penalty transaction that burns the cheating party's funds and credits the honest party in full"]},{q:"How does Lightning Network improve payment privacy compared to base-layer Bitcoin transactions?",a:"Lightning payments are not recorded on-chain at all; only channel open and close transactions appear in the public ledger",wrong:["Lightning uses stealth addresses so each payment routes to a freshly generated one-time destination hiding the recipient identity","Lightning payments are logged on a private sidechain visible only to the two channel partners and their direct routing nodes","Lightning improves privacy because routing nodes are legally required to delete all payment records within 24 hours of routing"]},{q:"How does Lightning Network's theoretical transaction throughput compare to Bitcoin's base layer?",a:"Lightning can theoretically handle millions of transactions per second at near-zero cost; base layer manages only about 7 TPS",wrong:["Lightning handles up to 1,000 TPS with current node software; the base layer handles ~7 TPS but provides stronger settlement finality","Lightning doubles effective base-layer capacity to about 14 TPS; the primary advantage is lower fees rather than raw throughput","Lightning processes up to 100,000 TPS in ideal conditions with capacity bounded by the weakest routing node's available bandwidth"]}],pow_vs_pos:[{q:"Why do Bitcoin advocates argue Proof-of-Work is a stronger security foundation than Proof-of-Stake?",a:"PoW links digital security to real-world energy expenditure — you cannot fake or virtualize the physical cost of mining blocks",wrong:["PoW uses more electricity, which signals that all participants are financially committed to the network's long-term success","PoW produces a public record of miner identities so the community can penalize dishonest participants after any attack occurs","PoW requires specialized hardware purchases that effectively deanonymize miners, creating legal accountability for any attack"]},{q:"How are validators selected to produce blocks in a Proof-of-Stake system?",a:"Validators are chosen based on the size of their token stake; those with more tokens staked gain proportionally more block rights",wrong:["Validators are elected by token-holder votes each epoch and then share block rewards equally with their supporting voters","Validators are selected by a verifiable random function with absolutely no weighting by stake size or prior token holdings","Validators are chosen by a committee of existing validators who review each candidate's historical performance and uptime record"]},{q:'What is the "nothing at stake" problem that affects naive Proof-of-Stake designs?',a:"Validators can vote on multiple competing chain forks simultaneously at zero cost because no real resource is being consumed",wrong:["Validators can pledge the same tokens to multiple chains at once because there is no on-chain registry of all staked assets","Validators have no incentive to stay online because the penalty for downtime costs less than the reward for staying connected","New participants can't accumulate stake because established validators monopolize block production without expending any resources"]},{q:"When did Ethereum complete its switch from Proof-of-Work to Proof-of-Stake consensus?",a:'September 2022, in an event called "The Merge" that replaced Ethereum\'s PoW mining with a Proof-of-Stake validator set',wrong:["March 2021, when the Ethereum Foundation completed deployment of the Beacon Chain mainnet consensus upgrade on schedule","December 2023, when Ethereum's final sharding upgrade replaced the remaining PoW elements with Proof-of-Stake validation","June 2020, when Ethereum 2.0 Phase 0 launched and the Proof-of-Work chain was simultaneously deprecated in the upgrade"]},{q:"How do the thresholds for a successful attack differ between Bitcoin's PoW and a typical PoS network?",a:"A Bitcoin 51% attack requires over half of total global hashrate; a typical PoS attack requires acquiring over 33% of staked tokens",wrong:["A PoW attack requires 67% of mining power while PoS needs only 10% of staked capital, making PoS actually more attack-resistant","Both systems require exactly 51% of their respective resources; the cost difference depends solely on the current token price","PoW is attacked by controlling 25% of ASIC manufacturers; PoS requires 51% of staked tokens for an equivalent disruption"]},{q:"What did Saifedean Ammous write about Proof-of-Work's uniquely fair property in The Bitcoin Standard?",a:'"PoW is the only mechanism that does not confer explicit power on any subset of participants" — Saifedean Ammous, The Bitcoin Standard',wrong:['"PoW guarantees equal returns on investment for all miners regardless of pool size or geographic cost of electricity access"','"PoW creates a perfectly merit-based network where each participant\'s contribution is measured objectively by work performed"','"PoW eliminates all insider advantages by requiring every participant to solve the same cryptographic puzzle each block epoch"']},{q:"Does Proof-of-Stake slashing fully resolve the security weaknesses inherent in stake-based consensus?",a:"No — slashing punishes detectable misbehavior but cannot prevent long-range attacks where an attacker rewrites old chain history",wrong:["Yes — slashing penalizes all forms of validator dishonesty and provides demonstrably stronger security guarantees than PoW mining","Yes — slashing combined with finality gadgets eliminates all known attack vectors including long-range history rewriting attacks","No — slashing creates severe centralization pressure by making it prohibitively risky for small validators to run nodes at all"]},{q:"What was Bitcoin's approximate network hashrate in the 2024–2025 timeframe?",a:"Over 700 exahashes per second (EH/s), making a successful 51% attack require more hardware than currently exists on Earth",wrong:["Over 100 exahashes per second (EH/s), a figure comparable to Ethereum's peak PoW hashrate just before The Merge in 2022","Approximately 200 terahashes per second (TH/s), reflecting the dominance of next-generation 7nm ASIC mining hardware farms","Around 500 petahashes per second (PH/s), representing roughly 40% annual growth sustained since the May 2020 halving event"]},{q:"How does access to Bitcoin mining compare to participation in Proof-of-Stake validation?",a:"Anyone with hardware and cheap electricity can mine Bitcoin; PoS compounds advantages for those who already hold large wealth",wrong:["Bitcoin mining requires a license from the Bitcoin Foundation; PoS is fully open to anyone willing to make a small token deposit","Both systems offer equivalent access barriers; entry cost is roughly comparable between mining rigs and major PoS token deposits","PoS is far more accessible because anyone can stake tiny amounts; Bitcoin mining requires millions of dollars minimum investment"]},{q:"What is the fundamental difference in the nature of costs between PoW and PoS security models?",a:"PoW requires external real-world energy cost to attack; PoS only requires internal tokens the attacker may already own and hold",wrong:["PoW security comes from miner coordination costs; PoS security relies on smart contract audits and formal verification proofs","PoW security depends on hardware scarcity; PoS security relies entirely on the irreversibility of slashing penalties post-attack","PoW costs are paid by miners and passed to users through fees; PoS costs are socialized across all token holders proportionally"]}],evidence_against_alts:[{q:"How was Ethereum's initial token supply structured at its 2014 crowdsale?",a:"About 72 million ETH were pre-mined; roughly 70% of the initial supply was allocated to founders and early insiders",wrong:["All 72 million ETH were sold in a fully public fair launch with zero allocation reserved for the founding team or investors","Roughly 20 million ETH were pre-mined with the remainder distributed through a public sale open to any retail investor globally","100 million ETH were created and divided equally: one third to founders, one third to an R&D reserve, one third to the public"]},{q:"What does research reveal about the infrastructure running Ethereum's validator nodes?",a:"About 61% of Ethereum nodes run in cloud data centers; AWS alone hosts roughly 25% making centralization a severe concern",wrong:["Only about 15% of Ethereum nodes run in the cloud; the vast majority are home validators run by individual stakers globally","Nearly 95% of Ethereum nodes run on dedicated bare-metal servers; cloud hosting is actively discouraged by the foundation","Roughly 40% of nodes are cloud-hosted, a level considered acceptable within Ethereum's published decentralization targets"]},{q:"What action did Ethereum take after the DAO hack in 2016, and what principle did it violate?",a:'Ethereum rolled back its blockchain to reverse the hack, proving its "code is law" and immutability claims were overrideable',wrong:["Ethereum implemented a smart contract patch to freeze hacker funds without altering any already-confirmed on-chain state","Ethereum hard forked to add new security rules but preserved all historical transactions, maintaining full ledger immutability","Ethereum's core developers sued the attacker in Swiss court and recovered the funds without touching or altering the chain"]},{q:"What are the key concerns about XRP's token distribution and Ripple's legal status?",a:"Ripple pre-created ~100 billion XRP, controls its scheduled release, and was sued by the SEC for an unregistered securities offering",wrong:["XRP has a capped supply of 21 million tokens like Bitcoin, but Ripple Labs retains permanent veto power over all protocol upgrades","Ripple distributed XRP through open mining but faces legal challenges because its founders hold United States banking licenses","XRP has no maximum supply cap and Ripple can mint new tokens freely; the SEC sued over undisclosed token minting activities"]},{q:"What is notable about Solana's track record of network availability since its mainnet launch?",a:"Solana has suffered over 10 major network outages since launch, including a single outage lasting approximately 17 hours",wrong:["Solana has maintained a perfect uptime record since launch thanks to its Proof-of-History consensus and strong validator incentives","Solana experienced one brief 2-hour outage in 2021 that was rapidly resolved via a coordinated validator restart procedure","Solana's network undergoes scheduled maintenance windows twice per year, which critics sometimes mischaracterize as full outages"]},{q:"Why can't a competing cryptocurrency simply copy Bitcoin's open-source code and achieve equivalent security and value?",a:"Code is easily copied but network effects are not: Bitcoin's liquidity, hashrate security, deep trust, and developer talent are irreplaceable",wrong:["Bitcoin's source code is proprietary and protected under copyright law, making direct copies illegal in most global jurisdictions","Bitcoin's cryptographic algorithms are patented by the Satoshi Nakamoto estate, blocking forks from using the same security scheme","Bitcoin's code can be copied but all forks share the UTXO set, preventing any fork from maintaining independent ownership records"]},{q:"What has happened to nearly all altcoins throughout Bitcoin's history when evaluated in BTC-denominated terms?",a:"Over 99% of altcoins ever launched have declined toward zero when priced against Bitcoin, regardless of their initial hype cycles",wrong:["About 50% of altcoins outperform Bitcoin over five-year windows; the rest decline, making broad diversification a rational strategy","Altcoins have collectively outperformed Bitcoin since 2017 on a volume-weighted basis when adjusted for total market capitalization","Roughly 30% of altcoins launched before 2018 still trade above their original ICO price when measured in BTC-denominated terms"]},{q:'What happened to major corporate "blockchain not Bitcoin" initiatives at firms like JPMorgan, IBM, and Maersk?',a:"JPMorgan, IBM, and Maersk all launched enterprise blockchain projects with great fanfare and then quietly abandoned each of them",wrong:["JPMorgan's blockchain now processes $10 trillion daily and IBM's Food Trust actively tracks 25 billion food supply chain records","The corporate blockchain era succeeded in creating interoperable networks that now settle cross-border payments in real time","IBM and JPMorgan merged their blockchain platforms into a single enterprise network now operating across 500 Fortune 500 companies"]},{q:"What makes Bitcoin's origin uniquely different from every other major cryptocurrency ever launched?",a:'Bitcoin has an "immaculate conception": no founder enrichment, no premine, no ICO, and an anonymous creator who then disappeared',wrong:["Bitcoin is unique because its consensus rules have never changed since genesis; no other network has achieved this full stability","Bitcoin's origin is unique because it was launched by a publicly known academic team who donated all profits back to a foundation","Bitcoin is the only cryptocurrency launched before 2015 that still runs its original completely unmodified consensus algorithm"]},{q:"Why does launching a new Proof-of-Work coin present a fundamental and unavoidable security problem?",a:"Any new PoW chain starts with near-zero hashrate, meaning an attacker with modest hardware could 51% attack it from day one",wrong:["New PoW coins are insecure because ASIC manufacturers refuse to supply hardware to chains below the 1 EH/s threshold hashrate","New PoW chains are vulnerable because they must use Bitcoin's SHA-256 algorithm, enabling cheap merged mining attack exploits","Launching a new PoW coin requires regulatory approval in most countries, creating legal barriers that deter legitimate honest miners"]}],cryptography:[{q:"Why did Satoshi choose the secp256k1 elliptic curve for Bitcoin instead of the more widely used NIST P-256?",a:"secp256k1's parameters have no known backdoor; NIST P-256's constants were generated through an opaque process lacking transparency",wrong:["secp256k1 produces shorter 48-byte signatures versus NIST P-256's 72-byte signatures, saving meaningful space per transaction","secp256k1 was the only elliptic curve with an existing open-source implementation available when Bitcoin was being actively developed","secp256k1 enables faster signature verification on commodity CPUs, which was critical for Satoshi's constrained 2009 launch timeline"]},{q:"Which digital signature algorithm did Bitcoin use to authorize transactions before the Taproot upgrade activated?",a:"ECDSA (Elliptic Curve Digital Signature Algorithm) was used to sign and authorize all Bitcoin transactions before Taproot activated",wrong:["EdDSA (Edwards-curve Digital Signature Algorithm), a Schnorr-based variant used widely across modern cryptography since the 1990s","RSA-2048, which was replaced by ECDSA in a 2012 BIP update to reduce transaction signature size and improve overall verification speed","DSA (Digital Signature Algorithm), the original NIST standard adapted for Bitcoin's secp256k1 elliptic curve in the genesis block"]},{q:"What is the key mathematical property of Schnorr signatures that makes them especially valuable for Bitcoin?",a:"Schnorr signatures are linear and additive — multiple parties' signatures can be aggregated into one compact signature via MuSig",wrong:["Schnorr signatures are 256 bytes shorter than equivalent ECDSA signatures, significantly reducing the on-chain footprint of all transactions","Schnorr signatures operate on a different elliptic curve that is provably harder to attack than the secp256k1 curve used by ECDSA","Schnorr signatures are non-deterministic by design, which prevents the timing-based side-channel attacks that can affect ECDSA"]},{q:"What are the key security properties of the SHA-256 hash function as used in Bitcoin?",a:"256-bit fixed output, deterministic, pre-image resistant, and avalanche effect: one changed input bit completely alters the output",wrong:["128-bit variable output, probabilistic, collision-resistant only, designed for high speed on the hardware-accelerated Bitcoin ASICs","512-bit fixed output, deterministic, fully reversible using the corresponding private key, and exhibits a strong avalanche effect","256-bit fixed output, non-deterministic due to an internal random salt, collision-resistant only, and tied to the secp256k1 curve"]},{q:"What is the step-by-step process for deriving a Bitcoin address from a public key?",a:"SHA-256 the public key, then RIPEMD-160 to get a 20-byte hash, then apply Base58Check encoding to produce the final address",wrong:["RIPEMD-160 the private key directly, then SHA-256 it twice, producing a 32-byte output encoded in hexadecimal as the address","SHA-512 the public key then truncate to 20 bytes, then apply Base64 encoding with a 4-byte checksum appended to the result","SHA-256 the compressed public key twice, take the final 20 bytes, then encode using standard Base64 plus a 4-byte checksum"]},{q:'Why are cryptographic hash functions described as "one-way" functions?',a:"Given hash output H(x), finding the original input x is computationally infeasible — you can compute forward but never reverse it",wrong:["Hash functions are one-way because they discard excess information via bitwise truncation performed during the internal hashing rounds","Hash functions are one-way by law only; reversing them without authorization qualifies as a federal computer intrusion crime globally","Hash functions are one-way in hardware only; software implementations of SHA-256 can theoretically be reversed with sufficient RAM"]},{q:"Why does Bitcoin's Base58Check encoding omit certain characters from its alphabet?",a:"It removes visually ambiguous characters — 0, O, I, and l — to prevent costly transcription errors when addresses are copied manually",wrong:["It removes alphabetically late characters x, y, and z to keep all encoded strings short enough to fit on a single paper backup","It excludes special symbols and all uppercase letters to ensure compatibility with every Unicode keyboard and QR code scanner","It removes vowels entirely to prevent encoded addresses from accidentally spelling dictionary words that users might confuse with keys"]},{q:"What is the discrete logarithm problem and how does it protect Bitcoin private keys?",a:"Given a public key (a curve point), deriving the private key (scalar multiplier) is computationally infeasible on the secp256k1 curve",wrong:["Given a private key expressed as a large prime, factoring it into two component primes is computationally infeasible on modern hardware","Given a hash of the public key, reversing SHA-256 to recover the original elliptic curve point is computationally infeasible always","Given an AES-encrypted wallet file, brute-forcing the decryption key is computationally infeasible without the user's original passphrase"]},{q:"How are cryptographic commitment schemes used within Lightning Network HTLCs?",a:"A hash of a secret preimage is shared first; the preimage is revealed upon payment, atomically unlocking funds across all hops",wrong:["A time-locked commitment to a routing fee is published on-chain first; revealing it later proves the payment was properly delivered","Each routing node commits to holding forwarded funds for a fixed timelock period and reveals its commitment to prevent double-spend","A cryptographic commitment to the exact payment amount is shared with all hops; revealing it triggers simultaneous on-chain settlement"]},{q:"What is P2PKH and what security advantage does it offer over the earlier Pay-to-Public-Key output type?",a:"P2PKH (Pay-to-Public-Key-Hash) hashes the public key before use, providing protection if ECDSA is ever weakened or compromised",wrong:["P2PKH locks outputs behind a 2-of-2 multisig requirement, making theft completely impossible without access to both signing keys","P2PKH encrypts the output script with the sender's public key so only the intended recipient can decode the locking conditions","P2PKH uses RIPEMD-256 instead of RIPEMD-160, producing a longer hash that offers significantly stronger collision-resistance guarantees"]}],austrian_economics:[{q:'What did Ludwig von Mises formalize in "Human Action" (1949)?',a:"Praxeology — the study of purposeful human action under scarcity, establishing economics as a deductive science of individual choice",wrong:["Econometrics — the statistical measurement of market outcomes using regression models and aggregate national income data","Macroeconomics — the study of unemployment, inflation, and national output using demand-side analytical frameworks and policy models","Behaviorism — the empirical study of how psychological biases cause individuals to systematically deviate from classically rational decision-making"]},{q:'What was Hayek\'s core argument in "The Use of Knowledge in Society" (1945)?',a:"Prices are decentralized information signals encoding dispersed local knowledge that no central planner could ever collect or replicate",wrong:["Wages are collective bargaining outcomes that government intervention can optimize to achieve full employment across all economic sectors","Capital is best allocated by expert technocrats who can model aggregate market behavior using national statistical databases","Markets fail to coordinate information efficiently whenever monopolies or asymmetric information distort the natural price discovery process"]},{q:'What did Hayek propose in "Denationalization of Money" (1976)?',a:"Competitive private currencies issued and managed entirely outside government control, a concept Bitcoin made real 35 years later",wrong:["A global reserve currency jointly managed by central banks under an international treaty with binding monetary supply rules","A commodity basket standard linking currency values to weighted indices of gold, silver, and key agricultural commodity prices","Full public ownership of the money supply administered by democratically elected monetary boards with transparent policy rules"]},{q:"According to Austrian Business Cycle Theory, what causes boom-bust cycles?",a:"Artificially low central bank interest rates that encourage malinvestment and unsustainable credit expansion, inevitably followed by a painful bust",wrong:["Excessive consumer spending fueled by rising wages that outpaces underlying productivity growth in the manufacturing and services sectors","Trade imbalances caused by currency manipulation that distort the natural flow of global capital across national borders and industries","Monopolistic corporate pricing that suppresses marketplace competition and prevents efficient capital reallocation across the broader economy"]},{q:"How does sound money affect time preference across society according to Austrian theory?",a:"Sound money lowers time preference, encouraging saving and long-term investment over immediate consumption and short-term debt-fueled spending",wrong:["Sound money raises time preference by making future purchasing power uncertain, discouraging multi-year planning among investors and consumers","Sound money has no measurable effect on time preference, which is entirely determined by individual psychology and genetic disposition","Sound money temporarily lowers time preference but eventually promotes excessive hoarding that collapses demand and deflates the broader economy"]},{q:"What is the Austrian subjective theory of value, in contrast to Marxist labor theory?",a:"Value is determined solely by individual actors based on personal preferences and scarcity, not by labor hours embedded in production",wrong:["Value is determined by the collective social utility of a good as measured through democratic consensus and community price-setting processes","Value is established at market equilibrium when aggregate supply matches aggregate demand at a mutually acceptable price level","Value is a function of raw material scarcity measured objectively by the replacement cost of producing the good under current market conditions"]},{q:"What is the Cantillon Effect in monetary economics?",a:"Newly created money benefits those who receive it first — banks and government contractors — before rising prices erode everyone else's purchasing power",wrong:["Currency devaluation benefits exporters first by making their goods cheaper abroad, before domestic wage growth fully catches up to new price levels","Tax cuts benefit large corporations first because they can immediately reinvest capital gains before smaller firms or wage earners see any benefit","Interest rate reductions benefit institutional borrowers first since they can refinance cheaply before retail lending rates are fully adjusted downward"]},{q:"How did Hayek and Keynes fundamentally disagree about recessions?",a:"Keynes argued government spending cures recessions; Hayek argued forced stimulus generates malinvestment that makes the inevitable correction far worse",wrong:["Keynes supported a gold-backed currency to anchor inflation expectations; Hayek argued fiat money was essential for flexible countercyclical policy","Keynes blamed monopolistic corporations for downturns; Hayek argued recessions stemmed purely from insufficient consumer spending and weak aggregate demand","Keynes viewed free markets as naturally self-correcting over time; Hayek argued central bank intervention was essential to stabilize employment and output"]},{q:'How did Saifedean Ammous connect Austrian economics to Bitcoin in "The Bitcoin Standard"?',a:"He applied Mises and Hayek's sound money theory directly to Bitcoin, arguing it restores low time preference and the hard money properties lost under fiat",wrong:["He applied Keynesian demand-side economics to argue Bitcoin's fixed supply would prevent deflationary spirals in modern post-industrial economies","He adapted Modern Monetary Theory to show Bitcoin's decentralized issuance could replace central bank open market operations in a digital economy","He combined behavioral economics with game theory to prove Bitcoin would inevitably displace fiat through pure network adoption incentives"]},{q:'What is "high time preference" in Austrian economic terms?',a:"A strong preference for present consumption over future saving, leading to debt-fueled spending, short-term thinking, and underinvestment in capital formation",wrong:["A preference for investments with rapid compounding returns rather than patient accumulation of slower long-term capital appreciation strategies","An economic condition where rising inflation expectations cause consumers to accelerate purchases before prices increase any further","A deliberate preference for holding liquid assets to preserve maximum optionality in periods of high economic and market uncertainty"]}],bitcoin_vs_real_estate:[{q:"What are the inflation-adjusted annual returns of US real estate over a full century?",a:"Approximately 0–2% real annual returns after accounting for inflation, far below the impressive nominal figures typically advertised by the industry",wrong:["Approximately 6–8% real annual returns after inflation, making residential property the most reliable long-term wealth preservation asset available","Approximately 4–5% real annual returns after inflation, driven primarily by land scarcity in growing metropolitan and coastal urban areas","Approximately 3–4% real annual returns after inflation, compounding consistently across all US regional markets over every significant historical period"]},{q:"What ongoing costs does real estate ownership typically impose on investors?",a:"1–4% of property value annually in maintenance costs alone, plus additional property taxes, insurance premiums, and management fees on top of that",wrong:["Less than 0.5% of property value annually, making residential real estate the most cost-efficient long-term store of value among all asset classes","Exactly 2% of property value annually, standardized by industry actuarial formulas and applied uniformly across all residential property types","5–10% of property value annually for commercial properties only; well-maintained residential homes carry negligible operating costs once fully paid off"]},{q:"How does Bitcoin's liquidity compare to real estate when investors need to exit a position?",a:"Bitcoin trades 24/7 globally with settlement in minutes; real estate typically requires 30–90 days to sell and incurs 5–10% in transaction costs",wrong:["Real estate sells faster than Bitcoin in most markets because institutional buyers routinely complete off-market transactions within 48 business hours","Both assets have similar liquidity profiles since Bitcoin's extreme volatility makes it practically impossible to exit large positions at fair market value","Bitcoin and real estate carry comparable transaction costs since major crypto exchanges charge 5–7% fees on high-value liquidation orders"]},{q:"How does real estate use leverage, and what risk does that introduce?",a:"Real estate commonly uses mortgage leverage to amplify gains, but this equally amplifies losses during price downturns and can wipe out equity entirely",wrong:["Real estate leverage is capped by regulation at 20% of property value, making catastrophic leveraged losses virtually impossible under normal conditions","Real estate leverage always benefits owners long-term because national property values have never declined over any rolling 10-year historical period","Leverage risk applies only to commercial real estate; owner-occupied residential mortgages are federally insured against any significant loss of principal"]},{q:"Can Bitcoin be transferred internationally as easily as real estate can be conveyed between parties?",a:"Bitcoin settles globally across borders in minutes with no intermediaries required; real estate is geographically immovable and cannot cross borders at all",wrong:["Both assets are equally difficult to transfer internationally due to strict capital controls and harmonized anti-money-laundering regulations worldwide","Real estate transfers more easily across some international jurisdictions because standardized legal frameworks exist under international property law treaties","Bitcoin international transfers face the same title verification and escrow delays as real estate due to mandatory blockchain finality confirmation periods"]},{q:"How does Bitcoin differ from real estate when it comes to government seizure risk?",a:"Property can be seized through eminent domain, tax liens, or civil forfeiture by governments; properly secured self-custodied Bitcoin cannot be confiscated",wrong:["Both assets are equally vulnerable to government seizure since courts can subpoena Bitcoin private keys the same way they can seize titled property","Real estate is better protected from seizure than Bitcoin because constitutional property rights provide stronger legal safeguards against government confiscation","Bitcoin is more vulnerable to seizure than real estate since regulated exchanges are required to freeze accounts and comply with government asset orders"]},{q:"How does Bitcoin's divisibility compare to real estate for investors with limited capital?",a:"Bitcoin is divisible down to 1 satoshi (0.00000001 BTC), allowing fractional purchases at any size; you cannot sell 0.01% of a house to raise cash",wrong:["Real estate through REITs is more divisible than Bitcoin, which enforces a minimum practical transaction size of 0.001 BTC on most networks","Both assets are equally accessible to small investors since modern fractional ownership platforms let people buy proportional shares of any property","Real estate is more accessible to capital-constrained investors because government programs allow property acquisition with as little as 1% down payment"]},{q:"How does Bitcoin's geographic risk profile differ from that of real estate?",a:"Real estate values depend entirely on local economies and geography; Bitcoin is a global asset uncorrelated with any specific regional market or jurisdiction",wrong:["Bitcoin and real estate are highly correlated hard assets that respond identically to global CPI inflation data and Federal Reserve policy changes","Bitcoin carries more geographic concentration risk than real estate because the majority of mining activity occurs in just two or three countries","Major global-city real estate is uncorrelated with local economic conditions and behaves identically to fully global assets like commodity futures"]},{q:"How has Bitcoin performed relative to real estate over any 4-year or longer holding period?",a:"Bitcoin has outperformed real estate by an enormous margin over every 4-year or longer holding period across its entire existence as an asset class",wrong:["Real estate has consistently outperformed Bitcoin on a risk-adjusted basis over 4-year holding periods due to its substantially lower price volatility","Bitcoin and real estate have delivered nearly identical total returns over 4-year periods once leverage, tax benefits, and rental income are properly included","Bitcoin has outperformed real estate only in exceptional bull market cycles; most 4-year holding period comparisons show highly mixed and inconclusive results"]},{q:"What happened to real estate values during hyperinflation in countries like Venezuela, Zimbabwe, and Lebanon?",a:"Real estate also lost value in hard money terms during hyperinflation across Venezuela, Zimbabwe, and Lebanon; Bitcoin preserved purchasing power for those who held it",wrong:["Real estate proved the most reliable inflation hedge in both Venezuela and Zimbabwe, outperforming gold, foreign currency, and all other asset classes","Real estate retained its full value in all documented hyperinflationary environments since physical property cannot be devalued by money printing alone","Real estate outperformed Bitcoin in hyperinflationary countries because local governments shut down cryptocurrency exchanges and banned digital asset transactions"]}],gold_standard_history:[{q:"What characterized the Classical Gold Standard era from roughly 1870 to 1914?",a:"44 years of remarkable price stability, subdued long-run inflation, and a long-term investment culture that financed and enabled the Industrial Revolution",wrong:["44 years of recurring deflationary collapses and economic stagnation caused by the rigid link between currency and a slowly growing physical gold supply","Frequent currency crises triggered by large gold discoveries in California and South Africa that constantly disrupted global price stability and trade","A period of rising inflation and sovereign debt caused by British imperial expansion and surging demand for commodities in colonial territories"]},{q:"What monetary system did the Bretton Woods agreement establish in 1944?",a:"The USD was pegged to gold at $35 per ounce and all other major currencies were pegged to the dollar, making it the world reserve currency",wrong:["All G7 currencies were simultaneously pegged directly to gold at individually negotiated rates, with no single national currency designated as reserve","A post-war trade liberalization treaty that created the WTO and established a system of managed floating exchange rates among Allied nations","The British pound replaced gold as the global reserve standard at a fixed rate of £1 to $4.03, with the US and UK serving as dual anchors"]},{q:'What was the "Nixon Shock" of August 15, 1971?',a:"Nixon unilaterally suspended the dollar's gold convertibility, ending Bretton Woods entirely and launching the global era of pure unbacked fiat currency",wrong:["Nixon imposed sweeping wage and price controls to combat inflation while simultaneously proposing a formal gold revaluation to $100 per ounce","Nixon signed legislation allowing foreign central banks to convert dollars to gold at a newly negotiated rate of $70 per ounce going forward","Nixon coordinated a multilateral agreement with G10 finance ministers to collectively devalue all major currencies against gold by 10 percent simultaneously"]},{q:"What did Executive Order 6102 of 1933 do, and what penalty did it carry?",a:"FDR's order made it illegal for Americans to own gold bullion, with penalties of up to 10 years in prison and a $10,000 fine for violations",wrong:["FDR's order nationalized the Federal Reserve System and established direct Treasury Department control over all money supply decisions nationwide","A 1933 executive order creating the gold exchange standard to formally replace the classical gold standard with a centrally managed currency regime","A 1933 banking regulation requiring all gold held by private commercial banks to be audited quarterly and insured by the federal government"]},{q:'What was gold\'s "fatal flaw" as a monetary standard, according to "The Fiat Standard"?',a:"Spatial salability — gold was too heavy and risky to transport globally, driving centralization into bank vaults and enabling gradual government seizure and control",wrong:["Temporal salability — gold's slowly growing supply made it deflationary over time, consistently discouraging consumption and causing recurring economic stagnation","Divisibility — gold could not be split into units small enough for everyday retail transactions without significantly debasing its purity and market value","Verifiability — gold could not be authenticated quickly enough in ordinary commerce, creating widespread fraud through counterfeit coins and debased alloys"]},{q:"What caused the Weimar Republic's catastrophic hyperinflation between 1921 and 1923?",a:"The German government printed money to pay WWI reparations demanded by the Allies, causing prices to double every few days at the peak of the crisis",wrong:["A speculative bubble in German industrial equities collapsed, triggering simultaneous bank runs and uncontrolled monetary expansion by the Reichsbank","The Allied naval blockade of German ports cut off essential imports, creating artificial commodity shortages that drove a runaway wage-price spiral","A series of devastating agricultural droughts in 1921 and 1922 destroyed food harvests, causing scarcity-driven price spikes that spiraled into full hyperinflation"]},{q:"How did the gold standard enable the large-scale infrastructure of the Industrial Revolution?",a:"Sound money preserved the value of savings over decades, allowing investors to patiently fund long-term projects like railroads, power grids, and telephone networks",wrong:["Gold-backed currency enabled colonial resource extraction that directly funded industrial projects in Britain through forced labor and administrative taxation systems","The gold standard had minimal direct impact on industrial investment, which was primarily financed through short-term commercial bank credit and trade finance","Industrial Revolution infrastructure was financed mainly through royal patronage and long-term government bonds rather than private savings kept in hard money"]},{q:"How does gold's stock-to-flow ratio compare with Bitcoin's as halvings continue?",a:"Gold's stock-to-flow is roughly 60 years; Bitcoin's surpasses gold after each halving and approaches infinity as block rewards eventually diminish to zero",wrong:["Gold's stock-to-flow of 60 years permanently exceeds Bitcoin's because Bitcoin's supply grows faster than newly mined gold production in absolute terms","Both gold and Bitcoin effectively share equivalent stock-to-flow ratios of around 50–60 years, making them equally scarce as long-term monetary commodities","Gold's stock-to-flow is actually only 20 years due to advances in deep-sea and asteroid mining technology; this makes direct comparison with Bitcoin impossible"]},{q:"How does Bitcoin's hard supply cap compare to gold's theoretical total supply?",a:"Gold's supply is theoretically unlimited through asteroid mining and new geological discoveries; Bitcoin is mathematically capped forever at exactly 21 million coins",wrong:["Gold's accessible supply is now effectively fixed because known economically viable deposits are nearly exhausted and new mining is no longer profitable","Both gold and Bitcoin have effectively unlimited supplies since gold recycling and Bitcoin's layer-2 solutions eliminate any meaningful long-term scarcity constraint","Bitcoin's supply is also theoretically unlimited because permanently lost coins reduce effective circulation, creating protocol pressure to eventually reissue them"]},{q:"Why did the US dollar become the global reserve currency at Bretton Woods in 1944?",a:"The US held the world's largest gold reserves in 1944, making the dollar the most credible currency to serve as the global gold-backed reserve anchor",wrong:["The dollar was chosen because the US had the largest economy and most liquid bond markets regardless of the size of its gold reserve holdings","The British pound was the initial reserve currency at Bretton Woods; the dollar only replaced it after the UK defaulted on its post-war Lend-Lease debts","The IMF selected the dollar through a competitive evaluation of Allied nations' monetary policy track records and fiscal discipline over the preceding decade"]}],cypherpunks:[{q:'What did Eric Hughes declare in "A Cypherpunk\'s Manifesto" (1993)?',a:'"Privacy is necessary for an open society in the electronic age... We must defend our own privacy if we expect to have any."',wrong:['"Encryption is a weapon of the people... The state\'s monopoly on surveillance must be broken by making cryptography universally available and free."','"Anonymity is the foundation of all digital freedom... Any government that surveils its citizens without consent has permanently forfeited its legitimacy."','"Code is the new law... Those who control cryptographic infrastructure ultimately control the rights and freedoms of citizens in the digital age."']},{q:"Where did Satoshi Nakamoto first publish the Bitcoin whitepaper on October 31, 2008?",a:"The Cypherpunks mailing list, the center of digital privacy and cryptographic activism since its founding in 1992 by Eric Hughes and John Gilmore",wrong:["The Bitcoin.org website, which Satoshi registered in August 2008 specifically to host the whitepaper and distribute the initial open-source software release","The SourceForge code repository, where Satoshi posted the whitepaper alongside the initial C++ source code for broad public review and comment","The Cryptography mailing list hosted at metzdowd.com, a separate but closely overlapping community focused primarily on academic cryptographic research"]},{q:"What was Adam Back's technical contribution that directly shaped Bitcoin's design?",a:"He invented Hashcash in 1997 — a proof-of-work system directly cited in the Bitcoin whitepaper that became the foundation of Bitcoin's mining mechanism",wrong:["He created the Merkle tree data structure in 1994 that Bitcoin uses to efficiently organize and cryptographically verify transaction data inside each block","He developed the elliptic curve digital signature algorithm that Bitcoin uses to cryptographically authenticate ownership and authorize every transaction","He invented the SHA-256 hashing algorithm in 1995 that Bitcoin relies on to secure its proof-of-work calculations and generate transaction identifiers"]},{q:"Who was Hal Finney and what was his historic role in Bitcoin's earliest days?",a:"He received the first Bitcoin transaction from Satoshi (block 170), ran the second node, created RPOW in 2004, and died of ALS in 2014 with his brain cryonically preserved",wrong:["He authored the cryptographic foundations of the original Bitcoin whitepaper before Satoshi transformed them into a fully operational peer-to-peer payment system","He mined the genesis block alongside Satoshi and ran Bitcoin's first public exchange, converting BTC into USD for the earliest adopters of the network","He ran Bitcoin's first currency exchange and facilitated the landmark pizza transaction, the first documented real-world commercial use of Bitcoin"]},{q:"Why do many researchers suspect Nick Szabo is Satoshi Nakamoto?",a:'He coined the term "smart contracts" in 1994 and created bit gold in 1998 — a Bitcoin direct predecessor featuring similar proof-of-work and digital scarcity mechanics',wrong:["He registered bitcoin.org before the whitepaper's release and was the only known cypherpunk with sufficient C++ expertise to write the original client","His writing style matched the Bitcoin whitepaper with 99% confidence according to multiple independent linguistic forensic analysis studies published in 2013",'He confirmed in a 2019 podcast interview that he was "deeply involved in Bitcoin\'s conceptual design" without explicitly claiming sole authorship of the protocol']},{q:"What was Wei Dai's contribution to digital cash, and how is he honored in crypto today?",a:'He created b-money in 1998, the first proposal for anonymous distributed electronic cash directly cited by Satoshi; Ethereum\'s smallest unit, the "wei," is named after him',wrong:['He invented the zero-knowledge proof protocol in 1992 underlying Ethereum\'s privacy layer; the "gwei" denomination honors his foundational cryptographic contribution',"He designed the distributed hash table architecture in 1997 that directly inspired Bitcoin's peer-to-peer network topology and decentralized node discovery protocol",'He created e-gold in 1996, the first operational digital gold currency system, and MakerDAO\'s "dai" stablecoin was named in honor of his legacy']},{q:'What did Timothy May argue in his "Crypto-Anarchist Manifesto" written in 1988?',a:"Cryptography would make governments unable to tax or regulate digital communications, enabling untraceable anonymous transactions and entirely new free markets",wrong:["Encryption would enable investigative journalists to safely transmit whistleblower documents across borders, fundamentally reforming government accountability worldwide","Public-key cryptography would make government-issued identity documents and passports completely obsolete within two decades of widespread civilian adoption","Digital cash systems would eliminate banking fees for ordinary citizens and redistribute trillions in financial industry profits directly to technology developers"]},{q:"What is Len Sassaman's unusual and permanent connection to the Bitcoin blockchain?",a:"He was a cypherpunk cryptographer who died in July 2011 shortly after Satoshi went dark; his obituary was permanently encoded into the Bitcoin blockchain as tribute",wrong:["He merged Satoshi's final code commits before the creator went dark in 2011, making him the last developer to interact officially with the original Bitcoin client","He operated the longest-running Bitcoin full node during the first year of the network, and his node identifier was encoded in the metadata of block 21,000","He contributed the peer-to-peer networking module to the original Bitcoin client, and his PGP public key is permanently embedded inside the genesis block's coinbase script"]},{q:"What legal precedent did Phil Zimmermann establish through his battles over PGP encryption?",a:'His US prosecution for "exporting munitions" when PGP spread abroad established the critical constitutional precedent that software source code is protected free speech',wrong:["His case established that no court could compel production of cryptographic keys as self-incriminating testimony, extending Fifth Amendment protections to encryption","His legal battle with RSA Security over patent licensing established the foundational principle that mathematical algorithms cannot be privately owned as intellectual property","His prosecution established that open-source cryptographic software cannot under any circumstances be classified as a weapon under the Arms Export Control Act"]},{q:"What was Julian Assange's connection to the cypherpunk movement and to Bitcoin's early adoption?",a:"Assange was a cypherpunk mailing list subscriber when Satoshi published the whitepaper in 2008; WikiLeaks later became one of Bitcoin's first major organizational adopters",wrong:["Assange personally corresponded with Satoshi throughout 2009 to coordinate WikiLeaks's launch of a dedicated anonymous Bitcoin donation infrastructure for sources",'Assange co-authored the "Cypherpunks" book with Jacob Appelbaum in 2012, which became a widely cited foundational text within the early Bitcoin community',"Assange was a contributing Bitcoin developer before founding WikiLeaks, writing the anonymous transaction routing code that appeared in client version 0.2"]}],satoshi_nakamoto_deep:[{q:"How many posts did Satoshi Nakamoto make on the BitcoinTalk forum before going silent?",a:"Exactly 575 documented posts on the BitcoinTalk forum before Satoshi went dark in late 2010 and early 2011, handing off to Gavin Andresen",wrong:["Approximately 3,200 posts across BitcoinTalk and the Cypherpunks mailing list before formally transferring all authority and repository access to Gavin Andresen","Around 1,100 public posts on BitcoinTalk, plus hundreds of private direct messages to core developers that were later partially leaked online","Fewer than 100 public posts total, since Satoshi strongly preferred communicating through private encrypted email rather than open public forum discussions"]},{q:"What is considered significant about Satoshi's self-reported birthday of April 5, 1975?",a:"April 5 is the date of FDR's 1933 Executive Order 6102 confiscating gold, and 1975 is the year Americans regained the legal right to own gold again",wrong:["April 5 is the date Satoshi registered bitcoin.org in 2008, and 1975 is the year Whitfield Diffie and Martin Hellman published the public-key cryptography paper","April 5 is the date of the first confirmed Bitcoin transaction in 2009, and 1975 marks the founding of the first academic digital money research consortium","April 5 was chosen as a random privacy-preserving date, and 1975 simply reflects the year the cypherpunk movement's core philosophical foundations were established"]},{q:"What is notable about how Satoshi Nakamoto managed Bitcoin addresses for privacy?",a:"Satoshi maintained over 22,000 documented unique addresses and reportedly never reused a single one, demonstrating perfect on-chain privacy hygiene throughout",wrong:["Satoshi used a single master address for all early mining rewards to simplify personal accounting, then rotated to new addresses only after 2010","Satoshi reused addresses intentionally to signal authenticity to early users, maintaining fewer than 50 documented unique addresses across all activity","Satoshi's addresses followed a deterministic pattern researchers cracked in 2013, successfully mapping every early mining reward back to a single master wallet"]},{q:"What did Satoshi write in his final known email to Gavin Andresen in April 2011?",a:'"I have moved on to other things. It is in good hands with Gavin and everyone."',wrong:['"The system is working as intended. Never add features without thorough peer review, and always keep the codebase minimal and fully auditable."','"Please do not attempt to contact me again. Bitcoin must stand entirely on its own without any individual being perceived as its leader."','"Protect the 21 million supply cap above all else. Any proposal to alter total issuance must be permanently and unconditionally rejected."']},{q:"What surprising feature was hidden inside Satoshi's original Bitcoin source code?",a:"The unfinished beginnings of an online poker game were embedded within the original approximately 31,000 lines of C++ source code",wrong:["A built-in decentralized exchange for direct peer-to-peer currency swaps without intermediaries, which was deliberately stripped out before the 2009 launch","An early DNS-based identity system allowing users to cryptographically link human-readable usernames to their Bitcoin addresses across the network","A complete payment channel prototype closely resembling the Lightning Network that Satoshi implemented fully but deliberately disabled before the January 2009 launch"]},{q:"What does Satoshi's registration of netcoin.org reveal about the project's late development?",a:"Satoshi registered netcoin.org one day before bitcoin.org, strongly suggesting the project's final name was still undecided until very late in development",wrong:["Satoshi registered netcoin.org as a deliberate decoy domain to mislead corporate legal teams that were monitoring digital currency development for patent filings","Netcoin.org was registered by Hal Finney on Satoshi's behalf as a geographic mirror for distributing the whitepaper outside of US legal jurisdiction","The netcoin.org registration proves Satoshi initially envisioned a narrower online payment network before expanding the scope to a full decentralized monetary system"]},{q:"How did the pre-launch Bitcoin parameters differ from the version released in January 2009?",a:"Pre-launch Bitcoin used 15-minute block times and 30-day difficulty adjustments; these were changed to 10-minute blocks and a 2-week difficulty window before launch",wrong:["Pre-launch Bitcoin used 1-minute block times and 24-hour difficulty adjustments; these were deliberately slowed to improve stability and prevent network spam","The original technical parameters matched the final launch version exactly; no substantive changes were made between the whitepaper publication and the software release","Pre-launch Bitcoin had no automatic difficulty adjustment at all; the 2-week adjustment period was proposed by Hal Finney and added during the first year of operation"]},{q:"What is notable about the approximately 1 million Bitcoin Satoshi mined in the early days?",a:"Satoshi mined roughly 1 million BTC using a deliberately limited single-threaded miner to avoid dominating the network, and none of these coins have ever moved",wrong:["Satoshi mined approximately 1 million BTC but transferred the majority to a multi-signature escrow wallet controlled by the Bitcoin Foundation before going dark in 2011","Satoshi mined approximately 1 million BTC and quietly liquidated about half of them during the 2013 bull run to fund ongoing anonymous development work","Satoshi's early mining totaled only around 50,000 BTC; the widely cited 1 million figure is a persistent myth based on demonstrably flawed blockchain analysis methods"]},{q:"What happens to Bitcoin that fans send to the original Genesis Block address as tribute?",a:"Over 68 BTC have been sent as tribute to the Genesis Block address, but they are permanently unspendable since the output carries no valid scriptPubKey to spend from",wrong:["Bitcoin sent to the Genesis Block address is automatically destroyed by the protocol itself, permanently reducing the circulating supply below 21 million coins","Genesis Block donations remain locked and are accessible only to whoever controls Satoshi's original private keys, creating an enduring cryptographic mystery","All Bitcoin sent to the Genesis Block address accumulates in a special reserve fund governed collectively by the Bitcoin Core development team and maintainers"]},{q:"What does the fact that only 0.06% of Bitcoin Core code remains from Satoshi's original suggest?",a:'The global community has rebuilt nearly everything from scratch, embodying the spirit that "we are all Satoshi" through decades of collective open-source maintainership',wrong:["Satoshi's original code was so poorly structured and buggy that developers had to replace it entirely, raising serious questions about Satoshi's actual programming expertise","The 0.06% figure proves Satoshi contributed only the whitepaper concept while the actual software was primarily written by Hal Finney and other early collaborators","Bitcoin Core has diverged so completely from Satoshi's original design that it should be treated as an entirely different protocol incompatible with the founding vision"]}],books_deep:[{q:"Which book did Michael Saylor credit as most impactful in MicroStrategy's decision to adopt Bitcoin?",a:"The Bitcoin Standard by Saifedean Ammous",wrong:["The Fiat Standard by Saifedean Ammous","Gradually Then Suddenly by Parker Lewis","Broken Money by Lyn Alden"]},{q:'In "The Bitcoin Standard," what economic concept measures the ratio of above-ground supply to annual production?',a:"Stock-to-Flow ratio",wrong:["Purchasing power parity index","Time preference discount rate","Monetary velocity multiplier"]},{q:'What is the subtitle of Saifedean Ammous\'s second book, "The Fiat Standard"?',a:"The Debt Slavery Alternative to Human Civilization",wrong:["The Hidden Tax on Every Holder of Currency","How Central Banks Destroyed the Modern World","A Monetary History of the Post-Gold Era"]},{q:"In \"21 Lessons,\" DerGigi describes Bitcoin's origin as having no founder still in control, no premine, and no ICO — he calls this Bitcoin's what?",a:"Immaculate conception",wrong:["Genesis paradox","Sovereign neutrality principle","Trustless bootstrap event"]},{q:'In "Gradually, Then Suddenly," Parker Lewis argues Bitcoin cannot be copied because of what, not because the code is proprietary?',a:"Bitcoin's network effects make a copy worthless from day one",wrong:["Bitcoin's mining hardware creates a prohibitive barrier to entry for copycats","Bitcoin's regulatory approval cannot be duplicated by any fork or altcoin","Bitcoin's cryptographic proof-of-work algorithm is patented and legally protected"]},{q:"Jason Lowery's \"Softwar\" was submitted as an MIT thesis. What novel claim does it make about Bitcoin's proof-of-work?",a:"PoW is a form of non-lethal power projection allowing nations to compete via hashrate instead of violence",wrong:["PoW is an energy accounting system that proves Bitcoin's value in physical thermodynamic terms","PoW functions as a diplomatic signaling mechanism that deters state-level cyberattacks on infrastructure","PoW creates a decentralized arms-control treaty enforced by thermodynamics rather than international law"]},{q:"According to Vijay Boyapati's \"The Bullish Case for Bitcoin,\" what is the correct order of Bitcoin's monetization stages?",a:"Collectible → store of value → medium of exchange → unit of account",wrong:["Store of value → collectible → medium of exchange → unit of account","Medium of exchange → store of value → unit of account → collectible","Collectible → medium of exchange → store of value → unit of account"]},{q:'Nik Bhatia\'s "Layered Money" argues that monetary layers built atop Bitcoin — like Lightning — are a natural evolution. What historical precedent does he trace this pattern through?',a:"The monetary hierarchy from gold to central bank notes to commercial bank deposits through history",wrong:["The progression from barter to commodity money to bills of exchange in medieval Europe","The development of the Federal Reserve system from private clearinghouses after the Panic of 1907","The transition from the classical gold standard to the Bretton Woods dollar-gold exchange system"]},{q:"Jonathan Bier's \"The Blocksize War\" documents the 2015–2017 governance battle. What broader lesson does it demonstrate about who ultimately controls Bitcoin's protocol?",a:"Economic nodes and users — not miners — hold final power over which consensus rules Bitcoin enforces",wrong:["Core developers hold final power because miners must adopt whatever client they release to the network","Miners hold final power because they can always reorganize the chain and override node-level rules","Large exchanges hold final power because they determine which version of Bitcoin earns the ticker symbol"]},{q:'Lyn Alden\'s "Broken Money" is primarily a macro case for Bitcoin. What does she identify as the core structural flaw in the current monetary system?',a:"The dollar-based reserve system built after 1971 creates persistent debt growth and destroys savings over time",wrong:["The Federal Reserve's dual mandate forces it to create inflation to meet employment targets indefinitely","Commercial banks' fractional reserve lending multiplies currency beyond any anchor to productive activity","Government deficit spending requires continuous monetization that no neutral reserve asset can currently absorb"]}],human_rights_deep:[{q:'Alex Gladstein of the Human Rights Foundation wrote "Check Your Financial Privilege." What percentage of people does he say live in liberal democracies with stable reserve currencies?',a:"Only about 13% of the global population",wrong:["Only about 28% of the global population","Roughly half — about 49% of the global population","Approximately 34% of the global population"]},{q:"When Nigeria's central bank banned banks from servicing crypto exchanges in 2021, what happened to peer-to-peer Bitcoin trading volumes?",a:"They surged to the highest levels in Africa as Nigerians routed around the ban",wrong:["They collapsed by over 80% as citizens feared criminal prosecution for trading","They remained flat because most Nigerians were unaware of hardware wallet alternatives","They shifted entirely to stablecoins, with Bitcoin trading volumes dropping to near zero"]},{q:"In Venezuela's hyperinflation crisis, what was the typical fee range that families lost when sending remittances through traditional wire and cash services?",a:"20–40% of the total transfer in fees and unfavorable exchange rates",wrong:["5–10% of the total transfer in fees and unfavorable exchange rates","50–70% of the total transfer in fees and currency conversion losses","10–15% of the total transfer in fees and exchange rate spreads"]},{q:"During the 2019–2020 Lebanese banking crisis, how did the situation differ for Bitcoin holders versus bank depositors?",a:"Banks froze depositor accounts entirely, while Bitcoin holders retained full, unobstructed access to their funds",wrong:["Bitcoin holders saw their funds seized by Lebanese authorities, while bank depositors received partial access","Both groups faced equal restrictions, as Lebanese courts extended banking freezes to crypto wallets","Bank depositors could withdraw up to $400 per week, while Bitcoin holders faced blockchain-level withdrawal limits"]},{q:"In Taliban-controlled Afghanistan, what specific financial freedom does Bitcoin on a mobile phone enable for women?",a:"Women legally barred from holding bank accounts can control their own money without requiring male permission or a bank",wrong:["Women can receive international aid disbursements that Taliban officials cannot intercept or redirect to male relatives","Women can pay for goods anonymously, preventing Taliban tracking of purchases deemed un-Islamic by local authorities","Women can earn wages in Bitcoin from foreign employers, bypassing Taliban labor laws restricting female employment"]},{q:"During the 2022 Canadian trucker convoy protests, what happened to the GoFundMe campaign, and how did the Bitcoin alternative compare in size?",a:"GoFundMe froze $10 million in donations; Bitcoin campaigns raised approximately $21 million which could not be frozen",wrong:["GoFundMe froze $3 million in donations; Bitcoin campaigns raised approximately $7 million which could not be frozen","GoFundMe froze $25 million in donations; Bitcoin campaigns raised approximately $4 million which could not be frozen","GoFundMe froze $10 million in donations; Bitcoin campaigns raised approximately $4 million which was later seized"]},{q:"In 2010, WikiLeaks was financially blockaded — Visa, Mastercard, and PayPal all cut off donations under US government pressure. What did this event demonstrate about Bitcoin?",a:"Bitcoin was completely immune to the blockade, allowing WikiLeaks to continue receiving donations without any payment processor",wrong:["Bitcoin donations to WikiLeaks were blocked by exchanges cooperating with US Treasury demands at the network layer","Bitcoin provided a brief alternative but was later traced by the NSA, leading to arrests of major WikiLeaks donors","Bitcoin exposure forced WikiLeaks to pause fundraising temporarily due to volatility making donation values unpredictable"]},{q:"How many adults worldwide are estimated to lack a bank account, and what does Bitcoin's mobile-first design offer them?",a:"About 1.4 billion unbanked adults can access Bitcoin-based financial services using only a mobile phone",wrong:["About 500 million unbanked adults can access Bitcoin-based financial services using only a mobile phone","About 3 billion unbanked adults can access Bitcoin-based financial services using only a mobile phone","About 800 million unbanked adults can access Bitcoin-based financial services using only a mobile phone"]},{q:"In Cuba, what financial problem does Bitcoin solve for diaspora families sending money home?",a:"It eliminates the 10%+ fees charged by Western Union and other remittance services for transfers to Cuba",wrong:["It bypasses the US embargo by routing transfers through Bitcoin exchanges outside Western financial networks","It prevents Cuban authorities from seizing transfers that exceed government-set remittance caps per household","It allows Cuban recipients to hold value that cannot be confiscated during government mandated currency conversions"]},{q:"Alex Gladstein argues that the global financial privilege gap is poorly understood by people in wealthy nations. What is the key stat that reframes the debate?",a:"87% of humanity lives under authoritarian or semi-authoritarian governments with weaker, less stable currencies",wrong:["65% of global GDP is produced in countries whose citizens cannot freely buy or sell foreign currencies","92% of global inflation occurs in the developing world, yet monetary reform debates are dominated by G7 economists","74% of the world's population has experienced at least one episode of government-imposed capital controls since 1970"]}],cbdc:[{q:"What does CBDC stand for, and what is its most fundamental difference from Bitcoin?",a:"Central Bank Digital Currency — it is centrally controlled by government, unlike Bitcoin which has no central issuer",wrong:["Crypto-Backed Digital Contract — it requires collateral backing unlike Bitcoin which is backed only by decentralized consensus","Cross-Border Digital Currency — it is designed for international trade unlike Bitcoin which was designed for domestic payments","Central Bank Distributed Coin — it uses distributed ledger technology unlike Bitcoin which uses a single-node blockchain"]},{q:"What is one programmability feature of CBDCs that no physical cash or Bitcoin can ever impose on a user?",a:"Expiry dates that cause the money to disappear from your account if not spent within a set time period",wrong:["Verification requirements that confirm every transaction is spent on government-approved goods and services only","Mandatory conversion into physical cash if not used for digital transactions within a quarterly spending window","Automatic tax withholding on all transactions above a threshold set by the treasury at the time of payment"]},{q:"China's digital yuan (e-CNY) is one of the most advanced CBDC deployments. How has it been distributed and monitored?",a:"It has been used in government benefit payments and all transactions are monitored in real time by Chinese authorities",wrong:["It has been distributed exclusively through commercial banks and monitored only for transactions exceeding 50,000 yuan","It runs on a private blockchain shared with approved banks, with full transaction privacy from government surveyors","It has been issued only to state employees as salary, with transaction data retained only for anti-fraud purposes"]},{q:"How could a CBDC theoretically implement negative interest rates in a way that physical cash makes impossible?",a:"The government could directly reduce account balances over time to penalize saving and force consumer spending",wrong:["The government could block transactions with foreign merchants to concentrate spending within the domestic economy","The government could require merchants to charge surcharges on CBDC payments relative to digital yuan alternatives","The government could convert idle CBDC balances into government bonds automatically after 90 days without spending"]},{q:'Privacy advocates have called CBDCs "panopticon money." What does this metaphor mean in practice?',a:"Every purchase is tracked and visible to authorities — no transaction can be anonymous like cash transactions currently are",wrong:["All financial data is visible to a network of multinational banks and corporations rather than just the government issuer","CBDC balances are displayed publicly on a blockchain explorer, removing all financial privacy from citizens","The government can see transaction patterns across all users but cannot identify specific individuals behind purchases"]},{q:"When Nigeria launched one of the world's first CBDCs — the eNaira in 2021 — what happened to public adoption?",a:"Adoption was extremely low, with citizens preferring cash and Bitcoin over the government's digital currency",wrong:["Adoption was very high in urban areas but failed in rural regions where smartphone penetration is below 20%","Adoption was forced above 60% when the government imposed penalties on businesses refusing eNaira payments","Adoption was moderate but froze after the central bank suspended the eNaira following a technical hack in 2022"]},{q:"How does a CBDC differ from ordinary digital bank money in terms of government control over individual accounts?",a:"With a CBDC the government controls the ledger directly, enabling confiscation without going through a bank as intermediary",wrong:["With a CBDC users earn interest set by the central bank directly, bypassing commercial bank interest rate decisions entirely","With a CBDC government transfers are instant and fee-free, but commercial transactions still pass through bank clearing systems","With a CBDC citizens interact with a public ledger they can audit, unlike traditional bank accounts that are privately held"]},{q:"How many central banks globally were actively researching or developing CBDC programs as of the mid-2020s?",a:"Over 130 central banks were actively exploring or developing CBDC programs",wrong:["About 40 central banks were actively exploring or developing CBDC programs","Over 200 central banks were actively exploring or developing CBDC programs","Approximately 80 central banks were actively exploring or developing CBDC programs"]},{q:"What is the key distinction between Bitcoin's permissionless access model and a CBDC's access model?",a:"Bitcoin allows anyone to participate without approval, while CBDC authorities decide who is permitted to use the system",wrong:["Bitcoin requires miners to validate identities before transactions confirm, while CBDCs use zero-knowledge proofs for privacy","Bitcoin charges higher fees than CBDCs because it lacks a central issuer to subsidize transaction processing costs","Bitcoin transactions are reversible within 24 hours, while CBDC transactions are irreversible from the moment of broadcast"]},{q:"What concern do economists raise about spending limits and category restrictions that CBDCs could technically enforce?",a:"Governments could block purchases of disfavored goods — fuel, firearms, political donations — at the payment protocol level",wrong:["Governments could restrict CBDC use to domestic merchants, effectively creating a new form of capital controls overnight","Economists worry CBDCs will displace commercial banks entirely by eliminating the need for deposit-taking institutions","Economists warn that real-time CBDC settlement will allow high-frequency traders to front-run ordinary consumer purchases"]}],block_size_wars:[{q:"What was the central technical debate in the Blocksize War of 2015–2017?",a:"Whether to increase Bitcoin's block size limit to fit more transactions per block for on-chain scaling",wrong:["Whether to replace Bitcoin's SHA-256 proof-of-work algorithm with a memory-hard alternative to reduce miner centralization","Whether to implement a second script language alongside Bitcoin Script to support smart contract functionality on-chain","Whether to increase the total Bitcoin supply cap from 21 million to accommodate growing global payment demand"]},{q:'What was the "big blocker" argument for raising the block size limit?',a:"Larger blocks would allow more on-chain transactions, keeping fees low and enabling Bitcoin to scale as a global payment system",wrong:["Larger blocks would make mining more profitable, incentivizing more miners and increasing Bitcoin's overall network security","Larger blocks would reduce orphan block rates, making the chain more stable and resistant to selfish mining attacks","Larger blocks would decrease blockchain download times by batching more data per round-trip during initial sync"]},{q:'What was the core "small blocker" concern about raising the block size limit?',a:"Larger blocks would make running a full node too expensive, concentrating Bitcoin verification among large miners and data centers",wrong:["Larger blocks would slow transaction propagation globally, allowing well-connected miners to dominate block production","Larger blocks would require a hard fork that could be exploited by adversarial states to attack Bitcoin's consensus layer","Larger blocks would reduce the fee market needed to sustain miners after the block subsidy eventually reaches zero"]},{q:"What was BIP148 (UASF) and why was it historically significant?",a:"It was a User-Activated Soft Fork where node operators threatened to reject non-SegWit blocks — users directly forced miners to comply",wrong:["It was a miner-activated upgrade proposal that required 95% hash power signaling before SegWit could activate on mainnet","It was a protocol patch that fixed the transaction malleability bug independently of SegWit, resolving the scaling debate peacefully","It was a compromise proposal combining a 2 MB block size increase with the SegWit witness discount in a single hard fork"]},{q:"What did SegWit (BIP141) actually do to Bitcoin's effective block capacity?",a:"It increased effective capacity to approximately 2–4 MB by applying a discount to signature (witness) data without a hard fork",wrong:["It increased effective capacity to exactly 8 MB by separating transaction data from signatures in a full hard fork upgrade","It doubled raw on-chain TPS by compressing transaction data with a new serialization format in a backward-compatible upgrade","It increased effective capacity to approximately 1.5 MB by removing redundant script opcodes from the transaction format"]},{q:"What was the New York Agreement (SegWit2x) and what happened to it?",a:"A 2017 deal between miners and businesses to activate SegWit then hard fork to 2 MB blocks — it was ultimately rejected and abandoned",wrong:["A 2016 deal between Core developers and exchanges to freeze block size at 1 MB permanently in exchange for Lightning funding","A 2017 proposal to move Bitcoin to a proof-of-stake system signed by major mining pools; it collapsed after a Chinese mining ban","A 2015 agreement between Blockstream and major miners to develop SegWit in exchange for their opposition to competing clients"]},{q:"Bitcoin Cash (BCH) was created on August 1, 2017. Who were the two most prominent figures leading the big-block faction that forked off?",a:'Roger Ver ("Bitcoin Jesus") and Jihan Wu of Bitmain, the dominant mining hardware manufacturer',wrong:["Gavin Andresen and Mike Hearn, the original Bitcoin Core developers who departed over the governance dispute","Charlie Lee and Craig Wright, who disagreed on block size before Craig later launched Bitcoin SV as a separate fork","Vitalik Buterin and Brian Armstrong, who favored higher-throughput chains compatible with Ethereum's transaction model"]},{q:"What did the outcome of the Blocksize War prove about the power structure in Bitcoin's governance?",a:"Miners cannot override the economic nodes — exchanges, businesses, and users running full nodes hold final authority over consensus rules",wrong:["Core developers hold veto power over any upgrade because miners must route block templates through their reference code","Large institutional holders effectively control protocol direction by threatening to sell if unfavorable forks succeed on the market","Mining pools hold governance power because they can reorganize the blockchain to reverse any soft fork that harms profitability"]},{q:"Which book is considered the definitive account of the Blocksize War and who wrote it?",a:'"The Blocksize War" by Jonathan Bier, which documents the full 2015–2017 governance battle in detail',wrong:['"Digital Gold" by Nathaniel Popper, which documents the governance battle alongside early Bitcoin adoption stories','"The Bitcoin Standard" by Saifedean Ammous, which includes a full chapter on the governance crisis and its resolution','"Cryptoassets" by Chris Burniske and Jack Tatar, which covers the fork wars across Bitcoin, Ethereum, and other protocols']},{q:"What is the broader lesson Bitcoin historians draw from the Blocksize War about contentious protocol changes?",a:"Bitcoin's governance is uniquely robust because controversial changes are extremely difficult to force through without broad consensus",wrong:["Bitcoin's governance is dangerously slow because improvements like SegWit took two years longer than technically necessary to deploy","Bitcoin's governance proves that miners always win long-term disputes because they control the hash power securing the chain","Bitcoin's governance shows that off-chain political agreements like the New York Agreement are the most effective scaling path"]}],mtgox:[{q:'What does the name "Mt. Gox" actually stand for, and what was the platform before it became a Bitcoin exchange?',a:"Magic: The Gathering Online Exchange — it was originally a card trading site repurposed for Bitcoin in 2010",wrong:["Mountain Gold Exchange — it was originally a commodity futures platform repurposed by Mark Karpeles in 2010","Monetary Transfer Global Operations Exchange — it was founded as a forex broker then pivoted to Bitcoin in 2011","Multiple Trading and Order Xchange — it was originally a stock options platform converted to Bitcoin trading in 2009"]},{q:"At its peak in 2013, what share of all global Bitcoin transactions passed through Mt. Gox?",a:"Over 70% of all global Bitcoin transactions were processed through Mt. Gox at its peak",wrong:["Over 90% of all global Bitcoin transactions were processed through Mt. Gox at its peak","Approximately 40% of all global Bitcoin transactions were processed through Mt. Gox at its peak","Roughly 55% of all global Bitcoin transactions were processed through Mt. Gox at its peak"]},{q:"When Mt. Gox collapsed in February 2014, how many BTC did it announce had been lost, and how many were later found internally?",a:"Mt. Gox reported ~850,000 BTC lost; approximately 200,000 BTC were later discovered in old wallets and recovered",wrong:["Mt. Gox reported ~650,000 BTC lost; approximately 150,000 BTC were later discovered in cold storage and recovered","Mt. Gox reported ~1.2 million BTC lost; approximately 350,000 BTC were later discovered during bankruptcy proceedings","Mt. Gox reported ~850,000 BTC lost; none were ever recovered as all coins were immediately laundered by the attackers"]},{q:"What were the two root causes that allowed Mt. Gox to be drained of Bitcoin over a period of years?",a:"Transaction malleability exploits combined with severe internal financial mismanagement and lack of auditing",wrong:["A private key leak on the public GitHub repository combined with a social engineering attack on the core server team","Insider theft by a rogue employee combined with a zero-day exploit in the OpenSSL library used for wallet encryption","A 51% attack on the Bitcoin network combined with poor hot wallet security that left most funds in an online server"]},{q:"What crime was Mt. Gox CEO Mark Karpeles ultimately convicted of in Japan?",a:"Data manipulation — he was convicted of falsifying electronic records, though embezzlement charges were dropped",wrong:["Theft and embezzlement — he was convicted of directly moving customer Bitcoin to personal wallets for his own enrichment","Securities fraud — he was convicted of issuing false statements about exchange reserves to prevent a bank run","Money laundering — he was convicted of funneling customer funds through shell companies registered in France and Japan"]},{q:"What phrase, now a cornerstone of Bitcoin culture, emerged directly from the lessons of the Mt. Gox collapse?",a:'"Not your keys, not your coins" — the principle that only self-custody guarantees ownership of your Bitcoin',wrong:['"Proof of reserves or proof of fraud" — the principle that exchanges must publish verifiable on-chain reserve attestations','"Run your own node, trust no one" — the principle that verifying the chain yourself is the only true form of sovereignty','"Cold storage or capitulation" — the principle that any Bitcoin left on an exchange is a loan you may never get back']},{q:"How long did Mt. Gox creditors wait for repayment, and what was notable about the form the repayment took?",a:"Creditors waited approximately 10 years; distributions began in 2024 and were paid in BTC worth far more in dollar terms than original claims",wrong:["Creditors waited approximately 5 years; distributions began in 2019 and were paid in Japanese yen at 2014 Bitcoin valuations","Creditors waited approximately 7 years; distributions began in 2021 and were partially repaid in BCH following the 2017 fork","Creditors waited approximately 10 years; distributions began in 2024 but were paid only in fiat at 2014 prices per court order"]},{q:"How did Bitcoin's price respond to the Mt. Gox collapse in early 2014, and how long did recovery take?",a:"Bitcoin dropped from roughly $800 to roughly $350 and took nearly 3 years to reclaim its pre-Mt. Gox price",wrong:["Bitcoin dropped from roughly $1,200 to roughly $150 and took nearly 5 years to reclaim its pre-Mt. Gox price","Bitcoin dropped from roughly $800 to roughly $600 and recovered within 6 months as markets shrugged off the exchange failure","Bitcoin dropped from roughly $500 to roughly $50 and took over 4 years to reclaim its pre-collapse all-time high"]},{q:"What lasting contribution to Bitcoin's security culture did the Mt. Gox failure accelerate?",a:"It drove rapid development of hardware wallets and normalized self-custody as the standard practice for holding Bitcoin",wrong:["It accelerated the development of proof-of-reserve auditing standards that all major exchanges now publish quarterly","It prompted the creation of the Bitcoin Foundation to lobby for exchange insurance requirements in major jurisdictions","It caused Bitcoin developers to implement mandatory withdrawal delays on-protocol to prevent rapid theft from online wallets"]},{q:"Despite being the largest exchange failure in crypto history, what did the Mt. Gox debacle definitively prove about the Bitcoin protocol itself?",a:"The Bitcoin protocol was never compromised — it was Mt. Gox's internal systems that were hacked, not the Bitcoin network",wrong:["The Bitcoin protocol's transaction malleability bug was the root cause, proving base layer security vulnerabilities are existential","The Bitcoin protocol survived only because developers issued an emergency patch within 48 hours of the malleability exploit","The Bitcoin protocol was briefly compromised but miners voluntarily reorganized the chain to restore 200,000 stolen coins"]}],mining_hardware:[{q:"What was the correct order of Bitcoin mining hardware evolution?",a:"CPU → GPU → FPGA → ASIC",wrong:["GPU → CPU → ASIC → FPGA","CPU → FPGA → GPU → ASIC","FPGA → GPU → CPU → ASIC"]},{q:"In what year did CPU mining of Bitcoin begin?",a:"2009",wrong:["2010","2011","2008"]},{q:"Who co-founded Bitmain, the dominant ASIC manufacturer?",a:"Jihan Wu and Micree Zhan",wrong:["Roger Ver and Charlie Lee","Adam Back and Greg Maxwell","Hal Finney and Nick Szabo"]},{q:"What is the efficiency metric used to measure ASIC mining performance?",a:"Joules per terahash (J/TH)",wrong:["Kilowatts per gigahash (kW/GH)","Watts per megahash (W/MH)","Terahash per kilowatt-hour (TH/kWh)"]},{q:"Approximately what hash rate does the open-source Bitaxe home miner achieve?",a:"About 3 TH/s",wrong:["About 30 TH/s","About 300 GH/s","About 0.3 PH/s"]},{q:"Why can ASICs not be repurposed once Bitcoin mining becomes unprofitable?",a:"They are application-specific and can only run the SHA-256 algorithm",wrong:["They require proprietary firmware that prevents other software from running","Their cooling systems are designed exclusively for Bitcoin network voltage requirements","They use encrypted memory modules that are locked to Bitcoin pool credentials"]},{q:"Which early Bitcoin miner was also known as a prolific GPU miner around 2010–2011?",a:"Laszlo Hanyecz (the Bitcoin Pizza guy)",wrong:["Hal Finney, who mined the first transaction from Satoshi","Roger Ver, who mined the first blocks on Bitcoin testnet","Nick Szabo, who later sold his GPU rigs to fund Bit Gold research"]},{q:"What milestone did the Bitcoin network hashrate reach in 2025?",a:"1 ZH/s (1 zettahash per second)",wrong:["1 EH/s (1 exahash per second)","1 PH/s (1 petahash per second)","100 EH/s (100 exahashes per second)"]},{q:"What notable event happened with a Bitaxe miner in July 2024?",a:"A Bitaxe solo-mined a valid Bitcoin block, beating billion-to-one odds",wrong:["A Bitaxe achieved a world record hash rate of 10 TH/s for a home device","A Bitaxe was the first open-source device submitted to a major mining pool","A Bitaxe operator won a class-action lawsuit against an ASIC manufacturer"]},{q:"How are some miners repurposing the waste heat from ASIC rigs?",a:"Heating homes, greenhouses, and swimming pools",wrong:["Powering adjacent data centers through thermoelectric generators","Generating steam to drive small turbines for on-site electricity recovery","Pre-heating industrial boilers to reduce natural gas consumption at factories"]}],mining_economics:[{q:"What is the current Bitcoin block subsidy after the April 2024 halving?",a:"3.125 BTC per block",wrong:["6.25 BTC per block","1.5625 BTC per block","2.5 BTC per block"]},{q:'What is "hashprice" in Bitcoin mining economics?',a:"Revenue earned per unit of hashrate per day, usually expressed in $/TH/day",wrong:["The market price of a new ASIC miner measured in USD per terahash of rated capacity","The electricity cost required to produce one terahash of mining output per hour","The break-even Bitcoin price at which a miner's marginal cost equals block reward value"]},{q:"What electricity cost range do large-scale miners typically target to remain competitive?",a:"$0.02–$0.05 per kWh",wrong:["$0.08–$0.12 per kWh","$0.10–$0.15 per kWh","$0.01–$0.02 per kWh"]},{q:"What percentage of a Bitcoin miner's operating costs does energy typically represent?",a:"60–80% of total operating costs",wrong:["20–35% of total operating costs","40–55% of total operating costs","85–95% of total operating costs"]},{q:'What is the "security budget" debate in Bitcoin mining?',a:"Whether transaction fees will be sufficient to incentivize miners after block subsidies approach zero",wrong:["Whether mining pool operators should be required to hold a reserve of BTC as collateral","Whether governments can legally tax mining revenue without undermining network security","Whether energy costs will eventually make proof-of-work mining economically impossible"]},{q:"What is the typical mining pool fee that pools charge for shared mining rewards?",a:"Around 1–2% of earned rewards",wrong:["Around 5–10% of earned rewards","Around 0.1–0.25% of earned rewards","Around 3–5% of earned rewards"]},{q:"How does Bitcoin's difficulty adjustment maintain the ~10-minute block time?",a:"It recalibrates every 2,016 blocks to keep average block time near 10 minutes regardless of hashrate changes",wrong:["It automatically throttles miners' submission rate if blocks are found faster than every 9 minutes","It uses a rolling 144-block average to smoothly adjust the proof-of-work target every day","It resets the target difficulty at each block based on the hash of the previous block header"]},{q:"Approximately how much energy does Bitcoin consume annually?",a:"About 150 TWh per year",wrong:["About 50 TWh per year","About 500 TWh per year","About 1,000 TWh per year"]},{q:"What proportion of Bitcoin mining is estimated to use renewable energy sources?",a:"Over 50% is estimated to come from renewable sources",wrong:["About 10–15% is estimated to come from renewable sources","About 25–30% is estimated to come from renewable sources","About 75–80% is estimated to come from renewable sources"]},{q:"Why do transaction fees become proportionally more important after each halving?",a:"The block subsidy is cut in half, so fees make up a larger share of total miner revenue",wrong:["More transactions are broadcast after each halving due to increased Bitcoin adoption and price","Mining difficulty resets after each halving, temporarily increasing the fee market competitiveness","ASIC efficiency improvements slow after halvings, raising the cost basis miners must recover"]}],taproot_assets:[{q:"What company developed the Taproot Assets protocol?",a:"Lightning Labs",wrong:["Blockstream","Spiral (formerly Square Crypto)","Chaincode Labs"]},{q:"What was the original name of the Taproot Assets protocol before it was renamed?",a:"Taro",wrong:["Omni","Fabric","Sapio"]},{q:"Where does the actual asset data live in the Taproot Assets protocol?",a:"Off-chain, with cryptographic proofs committed on-chain via Taproot",wrong:["Fully on-chain inside OP_RETURN outputs attached to each UTXO","In a federated sidechain pegged to the Bitcoin mainchain via a two-way peg","Distributed across Lightning Network gossip messages anchored by node signatures"]},{q:"What Bitcoin upgrade was a technical prerequisite for the Taproot Assets protocol?",a:"Taproot (BIP341/342), which introduced MAST and tapscript commitment structures",wrong:["SegWit (BIP141), which introduced the witness discount and fixed transaction malleability","CheckSequenceVerify (BIP112), which introduced relative timelocks for channel safety","P2SH (BIP16), which introduced hash-locked scripts and multi-signature spending conditions"]},{q:"What key benefit does Taproot Assets offer to users in high-inflation countries?",a:"They can hold USD-pegged stablecoins and transact over Lightning while inheriting Bitcoin's security",wrong:["They can convert local currency to BTC automatically at the best available exchange rate","They can access zero-fee remittance corridors by routing through sovereign node operators","They can participate in DeFi yield protocols without leaving the Bitcoin network stack"]},{q:"When did Taproot Assets launch on Bitcoin mainnet?",a:"Late 2023",wrong:["Early 2021, shortly after the Taproot soft fork activated","Mid 2022, following a year-long testnet deployment by Lightning Labs","Early 2024, alongside the Bitcoin halving block at height 840,000"]},{q:"How does edge routing work in a Taproot Assets Lightning payment?",a:"Intermediate routing nodes handle only BTC; the final recipient receives the Taproot Asset",wrong:["Every routing node must hold the specific Taproot Asset being transferred along the path","Taproot Asset payments are split into BTC-equivalent shards that each routing node recombines","The sender converts the asset to BTC at the first hop and the receiver converts back at the last hop"]},{q:"How does Taproot Assets differ from Ethereum ERC-20 tokens?",a:"Taproot Assets inherit Bitcoin's security and require no separate smart contract execution environment",wrong:["Taproot Assets use a layer-2 virtual machine that runs alongside the Bitcoin script interpreter","Taproot Assets require validator nodes to stake BTC as a bond to attest to correct asset issuance","Taproot Assets rely on zero-knowledge rollups posted to Bitcoin rather than on-chain contract state"]},{q:"What data structure does Taproot Assets use to commit asset state to Bitcoin?",a:"Merkle trees committed inside Taproot's MAST structure",wrong:["Verkle trees embedded in the SegWit witness field of Bitcoin transactions","Sparse Merkle tries anchored via OP_RETURN outputs to each Bitcoin block","Patricia tries stored in Lightning channel state and settled during channel closure"]},{q:"What type of assets can be issued using the Taproot Assets protocol?",a:"Fixed-supply tokens, reissuable stablecoins, and other custom asset types",wrong:["Only non-fungible tokens representing unique Bitcoin UTXOs with inscribed metadata","Only fiat-pegged stablecoins backed by proof-of-reserve attestations from custodians","Only wrapped versions of existing ERC-20 tokens bridged from Ethereum via atomic swaps"]}],op_codes_bitcoin:[{q:"What is the foundational opcode that verifies a digital signature in Bitcoin Script?",a:"OP_CHECKSIG",wrong:["OP_VERIFY","OP_EQUALVERIFY","OP_HASH160"]},{q:"What Bitcoin scripting language property prevents infinite loops and ensures termination?",a:"Bitcoin Script is non-Turing-complete with no loops or recursion",wrong:["Bitcoin Script has a hard gas limit that terminates execution after a fixed number of opcodes","Bitcoin Script requires all scripts to be pre-registered in a whitelist of approved templates","Bitcoin Script uses a time-boxed interpreter that terminates any script exceeding 10 milliseconds"]},{q:"What does OP_RETURN do in Bitcoin Script?",a:"Marks an output as permanently unspendable and allows arbitrary data to be embedded",wrong:["Returns the top stack value to the calling script as an exit code for conditional branches","Refunds the transaction fee to the sender if the script fails to execute successfully","Terminates script execution early and marks the transaction as valid without further checks"]},{q:"What is OP_CHECKLOCKTIMEVERIFY (CLTV) commonly used for?",a:"Locking coins until a specified block height or Unix timestamp, used in Lightning HTLCs",wrong:["Verifying that a transaction was signed before a certain block height to prevent replay attacks","Checking whether a block timestamp is within a valid range to prevent time-warp exploits","Requiring that spending transactions include a minimum number of confirmations before being valid"]},{q:"What is OP_CHECKSEQUENCEVERIFY (CSV) and how does it differ from CLTV?",a:"A relative timelock locking a coin for N blocks after the UTXO was created, unlike CLTV's absolute lock",wrong:["An absolute timelock identical to CLTV but measured in seconds rather than block heights","A relative fee check ensuring a transaction pays at least N satoshis per byte before being relayed","A sequence number validator that confirms inputs are signed with the correct nSequence bitmask"]},{q:"Why was OP_CAT originally disabled in Bitcoin Script?",a:"Satoshi disabled it as a precaution against potential vulnerabilities and memory exhaustion attacks",wrong:["Miners voted to disable it in 2011 to prevent concatenation-based denial-of-service on full nodes","The BIP process rejected OP_CAT because it duplicated functionality already covered by OP_SUBSTR","Core developers disabled it during the 2013 database fork to reduce script complexity mid-crisis"]},{q:"What capability would re-enabling OP_CAT provide to Bitcoin Script?",a:"Covenants, ZK proof verification on-chain, vaults, and expanded smart contract functionality",wrong:["Turing-complete execution, allowing arbitrary programs to run inside Bitcoin transactions","Native cross-chain atomic swaps without requiring hash time-locked contracts or pre-images","Dynamic fee adjustment inside scripts, allowing self-amending transactions based on mempool state"]},{q:"What is BitVM and who proposed it?",a:"A system by Robin Linus enabling Turing-complete computation via optimistic execution and fraud proofs",wrong:["A formal verification framework by Andrew Poelstra for proving Bitcoin script correctness at compile time","A proposed opcode suite by Jeremy Rubin enabling covenants and recursive transaction templates natively","A sidechain design by Adam Back using Bitcoin opcodes for confidential transaction verification"]},{q:"What does OP_VAULT (BIP345) enable for Bitcoin holders?",a:"Coin vaults with enforced withdrawal delays and a recovery path to thwart theft",wrong:["Multi-party time-locked escrow contracts that release funds based on external oracle attestations","Automatic re-locking of coins to a cold storage address if a spending transaction is unconfirmed","Covenant-based inheritance schemes where heirs receive coins after a fixed block height delay"]},{q:"What is the Simplicity language and who developed it?",a:"A formally verifiable smart contract language for Bitcoin developed by Andrew Poelstra at Blockstream",wrong:["A high-level scripting language for Bitcoin compiled to opcodes, developed by Robin Linus at BitVM Labs","A zero-knowledge proof system for Bitcoin scripts created by Pieter Wuille at Chaincode Labs","A stack-based Turing-complete language for Bitcoin sidechains designed by Gregory Maxwell at Blockstream"]}],bip_standards:[{q:"What does BIP stand for in Bitcoin development?",a:"Bitcoin Improvement Proposal",wrong:["Bitcoin Integration Protocol","Bitcoin Implementation Parameter","Bitcoin Infrastructure Patch"]},{q:"What does BIP32 define?",a:"Hierarchical deterministic (HD) wallets that generate a full key tree from one master seed",wrong:["The mnemonic seed phrase standard using a 2048-word wordlist for human-readable backups","The derivation path format m/purpose'/coin'/account'/change/index for wallet compatibility","The Pay-to-Script-Hash address format allowing complex redemption scripts to use short addresses"]},{q:"How many words are in a standard BIP39 mnemonic seed phrase?",a:"12 or 24 words drawn from a 2048-word wordlist",wrong:["8 or 16 words drawn from a 4096-word phonetically distinct wordlist","10 or 20 words drawn from a 1024-word wordlist filtered for international readability","6 or 12 words drawn from a 512-word wordlist designed for maximum memorability"]},{q:"What unique property do BIP39 words share that aids disambiguation?",a:"The first 4 letters of each word are unique across the entire 2048-word wordlist",wrong:["Each word contains exactly one vowel cluster, making audio transcription unambiguous","No two words share more than two consecutive letters, preventing handwriting confusion","Every word has a unique last two letters, enabling checksummed manual entry validation"]},{q:"What critical bug did BIP141 (SegWit) fix in the Bitcoin protocol?",a:"Transaction malleability, which had prevented safe construction of the Lightning Network",wrong:["The block size limit bug that allowed miners to produce blocks larger than 1 MB without penalty","The time-warp attack that allowed difficulty manipulation by lying about block timestamps","The inflation bug that briefly allowed miners to create more coinbase outputs than permitted"]},{q:"What three major improvements did BIP341/342 (Taproot) introduce?",a:"Schnorr signatures, MAST (Merkelized Abstract Syntax Trees), and Tapscript",wrong:["Bulletproofs, covenant opcodes, and cross-input signature aggregation for privacy","Confidential transactions, threshold signatures, and probabilistic payment channels","Adaptor signatures, recursive covenants, and scriptless script channel factories"]},{q:"What does BIP119 (CTV / CheckTemplateVerify) propose?",a:"A covenant opcode constraining how a coin can be spent to a set of pre-defined transaction templates",wrong:["A threshold signature scheme allowing n-of-m signers to collaboratively authorize transactions","A payment channel factory design enabling thousands of channels from a single on-chain transaction","A fee estimation algorithm that pre-commits to a fee rate before mining to reduce fee sniping"]},{q:"What privacy mechanism does BIP47 (PayNym) provide?",a:"Payment codes letting senders derive unique per-payment addresses via ECDH without address reuse",wrong:["CoinJoin coordination codes that allow trustless mixing of outputs across multiple participants","Stealth addresses generated per-block so receivers never publish a static on-chain identifier","Blind signature tokens allowing receivers to request payments without revealing their public key"]},{q:"How does BIP78 (PayJoin) disrupt blockchain surveillance?",a:"Sender and receiver both contribute inputs, breaking common chain analysis ownership heuristics",wrong:["It replaces transaction IDs with unlinkable blinded identifiers stored in the witness field","It batches multiple payments into one transaction with indistinguishable output values","It routes payments through an intermediary node that reassembles split UTXOs before broadcast"]},{q:"What is the derivation path structure defined by BIP44?",a:"m/purpose'/coin'/account'/change/index",wrong:["m/account'/coin'/purpose'/index/change","m/index/change/account'/coin'/purpose'","m/coin'/purpose'/change/account'/index"]}]},QUEST_TRIGGERS=[5,15,25,40,60,80,100];let currentQuest=null,isRetry=!1,completedQuests=new Set,weeklyCompleted=[],visitedForQuest=[],questCount=0;function _getCurrentWeekKey(){var e=new Date,t=new Date(e.getFullYear(),0,1),o=Math.floor((e-t)/864e5)+1,n=Math.ceil((o+t.getDay())/7);return e.getFullYear()+"-W"+n}function _loadWeeklyCompleted(){var e=safeJSON("btc_quest_week",{}),t=_getCurrentWeekKey();e.week!==t&&(e={week:t,completed:[]},localStorage.setItem("btc_quest_week",JSON.stringify(e))),weeklyCompleted=e.completed||[]}function _saveWeeklyCompleted(e){var t=safeJSON("btc_quest_week",{}),o=_getCurrentWeekKey();t.week!==o&&(t={week:o,completed:[]}),t.completed||(t.completed=[]),-1===t.completed.indexOf(e)&&t.completed.push(e),localStorage.setItem("btc_quest_week",JSON.stringify(t)),weeklyCompleted=t.completed}function initQuests(){safeJSON("btc_visited_channels",[]).forEach(e=>{visitedForQuest.includes(e)||visitedForQuest.push(e)}),void 0!==auth&&auth.currentUser?(loadCompletedQuests(auth.currentUser.uid),_loadWeeklyCompleted()):setTimeout(initQuests,2e3)}function _getDailyActivities(){var e=(new Date).toISOString().split("T")[0],t=safeJSON("btc_daily_activities",{});return t.date!==e&&(t={date:e,quiz:!1,trivia:!1,poll:!1,sfAwarded:!1}),t}function _markDailyActivity(e){var t=_getDailyActivities();t[e]=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(t))}function _checkDailyAllThree(){var e=_getDailyActivities();if(e.quiz&&e.trivia&&e.poll&&!e.sfAwarded){e.sfAwarded=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(e));var t=(new Date).toISOString().split("T")[0];void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({dailyAllThreeDate:t,dailyQuizDone:!0,dailyTriviaDone:!0,dailyPollDone:!0}).catch(function(){}),"function"==typeof window.contributeSatoshiFavor&&window.contributeSatoshiFavor("daily_all_three")}}async function loadCompletedQuests(e){if(db)try{const t=await db.collection("users").doc(e).get();t.exists&&t.data().completedQuests&&(t.data().completedQuests.forEach(e=>completedQuests.add(e)),questCount=completedQuests.size)}catch(e){}}function onChannelVisitForQuest(e){visitedForQuest.includes(e)||visitedForQuest.push(e);const t=visitedForQuest.length;for(const e of QUEST_TRIGGERS)if(t===e&&!currentQuest){setTimeout(()=>{"function"==typeof showToast&&showToast("⚡ You have explored "+e+" channels! A Quest is ready!"),setTimeout(()=>generateAndShowQuest(),3e3)},2e3);break}}function generateAndShowQuest(e,t,o){var n=(new Date).toISOString().split("T")[0],i=safeJSON("btc_quest_daily",{});if(i.date!==n&&(i={date:n,count:0}),i.count>=1&&!o)return void(e&&"function"==typeof showToast&&showToast("⏰ You've completed your daily quiz! Go to Quiz Quests to retake it for a perfect score."));const a=safeJSON("btc_asked_questions",[]);let r=[];if(t&&QUESTION_BANK[t]&&QUESTION_BANK[t].forEach(e=>r.push({...e,source:t})),!t){for(const e of visitedForQuest){const t=QUESTION_BANK[e];t&&t.forEach(t=>r.push({...t,source:e}))}if(QUESTION_BANK._general&&QUESTION_BANK._general.forEach(e=>r.push({...e,source:"_general"})),r.length<5)for(const[e,t]of Object.entries(QUESTION_BANK))if(t.forEach(t=>{r.some(e=>e.q===t.q)||r.push({...t,source:e})}),r.length>=10)break}var s=t?Math.min(3,r.length):5;if(r.length!a.includes(e.q));function c(e){for(var t=e.q.toLowerCase(),o=[[/nostr/i,"nostr"],[/lightning/i,"lightning"],[/halving/i,"halving"],[/mining/i,"mining"],[/node/i,"node"],[/wallet/i,"wallet"],[/seed.?phrase/i,"seed"],[/private.?key/i,"privkey"],[/satoshi/i,"satoshi"],[/block.?chain/i,"blockchain"],[/proof.?of.?work/i,"pow"],[/fud\b/i,"fud"],[/self.?custody/i,"custody"],[/etf/i,"etf"],[/taproot/i,"taproot"],[/difficulty/i,"difficulty"],[/mempool/i,"mempool"],[/hash.?rate/i,"hashrate"],[/white.?paper/i,"whitepaper"],[/21.?million/i,"21m"],[/inflation/i,"inflation"],[/kyc/i,"kyc"],[/privacy/i,"privacy"],[/multisig/i,"multisig"],[/dca|dollar.cost/i,"dca"],[/el.?salvador/i,"elsalvador"]],n=0;nMath.random()-.5);var d=t?Math.min(l.length,5):5,u=[],p={};if(t)for(var m=0;me.q)];localStorage.setItem("btc_asked_questions",JSON.stringify(y));const b=u.map(e=>{const t=[e.a,...e.wrong].sort(()=>Math.random()-.5),o=t.indexOf(e.a);return{q:e.q,options:t,answer:o}});currentQuest={id:f,topicKey:t||null,title:getQuestTitle(questCount,t),questions:b},window._currentQuestServerId=null,"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("startQuest")({questions:b.map(function(e){return{answer:e.answer}}),topicKey:t||null}).then(function(e){window._currentQuestServerId=e.data.questId}).catch(function(e){console.warn("Quest registration failed:",e)}),showQuest(currentQuest,!1)}function getQuestTitle(e,t){if(t&&"_general"!==t){var o={mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",energy:"🔋",cryptography:"🔐",consensus:"🤝",regulation:"⚖️",maximalism:"🔥","difficulty-adjustment":"🎯",books:"📚",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊","smart-contracts":"📝","blockchain-timechain":"⛓️","pow-vs-pos":"⚔️","evidence-against-alts":"⚠️",organic:"🌳",peaceful:"☮️",supranational:"🔔"},n=t.replace(/_pt\d+$/,""),i=o[t]||o[n]||"⚡",a=t.replace(/_pt(\d+)$/,"").replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),r=t.match(/_pt(\d+)$/);return r&&(a+=" (Part "+r[1]+")"),i+" "+a+" Quest"}const s=["₿ Bitcoin Basics Quest","⚡ Lightning Learner Quest","🔒 Security Scholar Quest","💰 Economics Expert Quest","⛓ Technical Titan Quest","🟠 Culture Connoisseur Quest","🛡️ Sovereignty Sage Quest","👑 Satoshi Scholar Quest"];return s[e%s.length]}function playWarriorDrum(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const t=new(window.AudioContext||window.webkitAudioContext),o="undefined"!=typeof audioVolume?audioVolume:.5,n=t.currentTime;function e(e){const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.type="sine",i.frequency.setValueAtTime(150,n+e),i.frequency.exponentialRampToValueAtTime(60,n+e+.15),a.gain.setValueAtTime(.7*o,n+e),a.gain.exponentialRampToValueAtTime(.001,n+e+.4),i.start(n+e),i.stop(n+e+.4);const r=t.createOscillator(),s=t.createGain();r.connect(s),s.connect(t.destination),r.type="sine",r.frequency.setValueAtTime(80,n+e),r.frequency.exponentialRampToValueAtTime(50,n+e+.3),s.gain.setValueAtTime(.5*o,n+e),s.gain.exponentialRampToValueAtTime(.001,n+e+.5),r.start(n+e),r.stop(n+e+.5);const l=Math.floor(.08*t.sampleRate),c=t.createBuffer(1,l,t.sampleRate),d=c.getChannelData(0);for(let e=0;e",i+="

    "+(t?"Retry! Get 3+ correct for 25 XP!":"Answer 5 questions. 3+ correct = 50 XP. All 5 = 100 XP!")+"

    ",i+="",i+='
    ',e.questions.forEach((e,t)=>{i+='
    ',i+='
    Question '+(t+1)+" of 5
    ",i+='
    '+e.q+"
    ",i+='
    ',e.options.forEach((e,o)=>{i+='"}),i+="
    "}),i+="
    ",i+='',i+='',n.innerHTML=i,o.classList.add("open"),window._questAnswers=new Array(5).fill(-1),window._questCorrect=e.questions.map(e=>e.answer)}function selectAnswer(e,t,o){e.parentElement.querySelectorAll(".quest-opt").forEach(e=>e.classList.remove("selected")),e.classList.add("selected"),window._questAnswers[t]=o,window._questAnswers.every(e=>e>=0)&&(document.getElementById("questSubmitBtn").disabled=!1)}async function submitQuest(){if(window._questSubmitted)return;window._questSubmitted=!0;var e=document.getElementById("questSubmitBtn");e&&(e.disabled=!0,e.style.opacity="0.5",e.textContent="Grading...");const t=window._questAnswers,o=window._questCorrect;let n=0,i=0;if(window._currentQuestServerId&&"undefined"!=typeof firebase&&firebase.functions)try{var a=await firebase.functions().httpsCallable("gradeQuest")({questId:window._currentQuestServerId,answers:t,isRetry:!!isRetry});n=a.data.score,i=a.data.pts}catch(e){console.error("Server quest grading failed, falling back:",e),t.forEach((e,t)=>{e===o[t]&&n++})}else t.forEach((e,t)=>{e===o[t]&&n++});document.querySelectorAll(".quest-q").forEach((e,n)=>{e.querySelectorAll(".quest-opt").forEach((e,i)=>{e.disabled=!0,i===o[n]&&e.classList.add("correct"),i===t[n]&&i!==o[n]&&e.classList.add("wrong")})});let r="";var s=5===n,l=!!currentQuest.topicKey;if(isRetry)n>=3?(i||(i=25),r="🎉 "+n+"/5 correct on retry! +"+i+" XP!",!s&&l||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 - Better luck next time! Keep reading and try again.";else if(s){if(i||(i=100),r="🏆 PERFECT! 5/5! +"+i+" XP!",completedQuests.add(currentQuest.id),questCount++,"function"==typeof window.nachoGlobalAnnounce&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var c=void 0!==currentUser&¤tUser&¤tUser.username||auth.currentUser.displayName||"A mystery Bitcoiner",d=currentQuest.title||"a Quiz Quest";window.nachoGlobalAnnounce("🏆 @"+c+" just aced "+d+" with a PERFECT 5/5! Think you can do the same? ➡️ [Quest Hub](#quests)",auth.currentUser.uid)}}else n>=3?(i||(i=50),r="🎉 "+n+"/5 correct! +"+i+" XP!",l||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 - You can retry for 25 XP!";if(i>0){"function"==typeof notifySelfQuest&¬ifySelfQuest(currentQuest.title),"function"==typeof notifySelfPoints&¬ifySelfPoints(i,"🏆 Quest: "+(currentQuest.title||"Quest")),"function"==typeof window._raidOnQuizComplete&&window._raidOnQuizComplete(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(i);var u=(new Date).toISOString().split("T")[0],p=safeJSON("btc_quest_daily",{});p.date!==u&&(p={date:u,count:0}),p.count++,p.lastScore=n,p.lastTopic=currentQuest.topicKey||null,p.lastTitle=currentQuest.title||null,localStorage.setItem("btc_quest_daily",JSON.stringify(p)),_markDailyActivity("quiz"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({questsCompletedToday:p.count||0,lastQuestDate:u}).catch(function(e){console.error("Quest sync failed:",e)})}try{completedQuests.has(currentQuest.id)&&void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&(await db.collection("users").doc(auth.currentUser.uid).update({completedQuests:firebase.firestore.FieldValue.arrayUnion(currentQuest.id)}),db.collection("stats").doc("global").set({questsCompleted:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){}))}catch(e){console.error("Quest completion sync failed:",e)}const m=document.getElementById("questSubmitBtn");m&&(m.style.display="none");const h=document.querySelector(".quest-skip");h&&(h.style.display="none"),window._questScore=n,window._questMsg=r,window._questPts=i;const g=document.querySelector(".quest-header");g&&(g.innerHTML='
    ⚡ QUEST COMPLETE

    '+currentQuest.title+'

    '+(5===n?"🏆":n>=3?"🎉":"😅")+'
    '+n+' / 5 Correct
    Review your answers below - green is correct, red is wrong
    ');const f=document.getElementById("questInner");f&&f.scrollTo({top:0,behavior:"smooth"}),"function"==typeof showToast&&showToast(r)}function playHooraySound(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const e=new(window.AudioContext||window.webkitAudioContext),t="undefined"!=typeof audioVolume?audioVolume:.5,o=e.currentTime;[523,659,784,1047].forEach((n,i)=>{const a=e.createOscillator(),r=e.createGain();a.connect(r),r.connect(e.destination),a.type="sine",a.frequency.value=n,r.gain.setValueAtTime(.15*t,o+.1*i),r.gain.exponentialRampToValueAtTime(.001,o+.1*i+.4),a.start(o+.1*i),a.stop(o+.1*i+.4);const s=e.createOscillator(),l=e.createGain();s.connect(l),l.connect(e.destination),s.type="triangle",s.frequency.value=2*n,l.gain.setValueAtTime(.06*t,o+.1*i),l.gain.exponentialRampToValueAtTime(.001,o+.1*i+.3),s.start(o+.1*i),s.stop(o+.1*i+.3)}),[1047,1319,1568].forEach(n=>{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.type="sine",i.frequency.value=n,a.gain.setValueAtTime(.12*t,o+.45),a.gain.linearRampToValueAtTime(.1*t,o+.7),a.gain.exponentialRampToValueAtTime(.001,o+1.3),i.start(o+.45),i.stop(o+1.3)})}catch(e){}}function _resolveQuestChannel(e){if(!e||void 0===CHANNELS)return null;if(CHANNELS[e])return e;var t=e.replace(/_pt\d+$/,"");if(CHANNELS[t])return t;var o={cycles:"cyles",dlcs:"discrete_log_contracts__dlcs",first_principles:"1_first_principles",foss:"free_and_open_source_software__foss",ordinals_inscriptions:"ordinals",spv:"simplified_payment_verification__spv",halving:"scarce","el-salvador":"regulation"};if(o[e]&&CHANNELS[o[e]])return o[e];if(o[t]&&CHANNELS[o[t]])return o[t];for(var n=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper"],i=0;i=3&&playHooraySound();const n=document.querySelector(".quest-questions");n&&(n.style.display="none");var i=_resolveQuestChannel(currentQuest?currentQuest.topicKey:null);if(!i&&void 0!==CHANNELS){var a=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper","cryptography","philosophy","energy","nodes"].filter(function(e){return!!CHANNELS[e]}).sort(function(){return Math.random()-.5});a.length&&(i=a[0])}var r="";if(i&&void 0!==CHANNELS&&CHANNELS[i]){var s=CHANNELS[i].title;r='
    '+(currentQuest&¤tQuest.topicKey&&_resolveQuestChannel(currentQuest.topicKey)?5===e?"📚 Keep learning":"📖 Study up on":"🔍 Explore next")+'
    '+s+" →
    "}const l=document.querySelector(".quest-header");l&&(l.innerHTML='
    ⚡ QUEST COMPLETE

    '+currentQuest.title+'

    '+(5===e?"🏆":e>=3?"🎉":"😅")+'
    '+e+' / 5 Correct
    '+t+"
    "+(o>0?'
    +'+o+" XP earned!
    ":"")+r+(e<5?'":"")+'');const c=document.getElementById("questInner");c&&(c.scrollTop=0)}function retryQuest(){currentQuest.questions.forEach(e=>{const t=e.options[e.answer];e.options.sort(()=>Math.random()-.5),e.answer=e.options.indexOf(t)}),showQuest(currentQuest,!0)}function startQuestManual(e){if(!currentQuest)if(e){if(generateAndShowQuest(!0,e),"function"==typeof isMobile&&isMobile()){const e=document.getElementById("sidebar");e&&e.classList.remove("open")}}else _showQuestTopicPicker()}function _getDailyRecommendedQuiz(e){if(!e||0===e.length)return null;for(var t=e.map(function(e){return e.key}).sort(),o=t.length,n=new Date("2026-01-01T00:00:00Z").getTime(),i=(new Date).toISOString().split("T")[0],a=new Date(i+"T00:00:00Z").getTime(),r=Math.floor((a-n)/864e5),s=r%o,l=Math.floor(r/o),c=t.slice(),d=7919*l+31337,u=c.length-1;u>0;u--){var p=(d=(16807*d+0)%2147483647)%(u+1),m=c[u];c[u]=c[p],c[p]=m}var h=c[s];return e.find(function(e){return e.key===h})||null}function _showQuestTopicPicker(){var e=[],t={_general:"🌐",mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜","satoshi-nakamoto":"🧩",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",philosophy:"🤔",energy:"🔋",cryptography:"🔐",consensus:"🤝",taproot:"🌳",regulation:"⚖️",maximalism:"🔥",utxos:"📦","difficulty-adjustment":"🎯",transaction_fees:"💳",game_theory:"♟️",books:"📚","orange-pilling":"🍊",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊",geopolitics___macroeconomics:"🌎",human_rights__social_justice_and_freedo:"✊","smart-contracts":"📝",sidechains:"🔗",stablecoins:"🏦",fedimints:"🏛️","pow-vs-pos":"⚔️","blockchain-timechain":"⛓️",softwar:"🪖",time_preference:"⏳",governance:"🏛️","apps-tools":"🧰","misconceptions-fud":"🚫",elevator_pitches:"🗣️"};for(var o in QUESTION_BANK)if("_general"!==o){var n=QUESTION_BANK[o];if(n&&!(n.length<3)){var i=o.replace(/_pt(\d+)$/,"").replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),a=o.match(/_pt(\d+)$/);a&&(i+=" (Part "+a[1]+")");var r=o.replace(/_pt\d+$/,""),s=t[o]||t[r]||"📖",l=completedQuests.has("quest_"+o)||completedQuests.has(o)||-1!==weeklyCompleted.indexOf(o);e.push({key:o,label:i,emoji:s,count:n.length,done:l})}}e.sort(function(e,t){return e.done!==t.done?e.done?1:-1:e.label.localeCompare(t.label)});var c=e.filter(function(e){return e.done}).length,d=document.getElementById("questModal");if(d){var u=document.getElementById("questInner");if(u){var p='

    Choose a Quest Topic

    Pick a Bitcoin topic to test your knowledge

    '+c+"/"+e.length+' topics completed
    ',m=_getDailyRecommendedQuiz(e);m&&(p+=""),p+='',p+='',p+='
    ',e.forEach(function(e){var t=e.done?"rgba(34,197,94,0.06)":"rgba(255,255,255,0.02)",o=e.done?"rgba(34,197,94,0.2)":"var(--border)",n=e.done?'':''+e.count+"Q";p+=""}),p+="
    ",p+='',u.innerHTML=p,setTimeout(function(){var e=document.querySelectorAll("#questTopicList button");e.forEach(function(e){var t=(e.getAttribute("onclick")||"").match(/_startQuestTopic\('([^']+)'\)/);t&&(e.dataset.key=t[1]),e.dataset.label=e.textContent.trim()});var t=document.getElementById("questSearch");t&&t.addEventListener("input",function(){var t=this.value.toLowerCase();e.forEach(function(e){var o=e.dataset.label.toLowerCase();e.style.display=o.includes(t)?"":"none"})})},0),d.classList.add("open")}}}function skipQuest(){closeQuest()}function closeQuest(){document.getElementById("questModal").classList.remove("open"),currentQuest=null,isRetry=!1}function _renderFavorTab(e){if(e){var t="function"==typeof window._resolveFavorState?window._resolveFavorState():null,o=t&&t.favorActive,n=t&&t.points||0,i=Math.min(100,n/21*100),a='
    ✨⛏️
    Satoshi\'s Favor
    Community mining when the community earns 21 points.
    Chance to win 21,000 sats! ⚡
    ';if(o){var r=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();a+='
    🎉 SATOSHI\'S FAVOR IS ACTIVE!
    '+Math.floor(r/6e4)+"m "+Math.floor(r%6e4/1e3)+'s
    Mine below 1,000 to win 21,000 sats!
    ',a+=''}else a+='
    '+n+'/21 points
    '+(21-n)+" more points to activate
    ";if(a+='
    ⚔️ Faction SF Competition
    🐝
    Cyber Hornets
    0
    SF points
    VS
    🦡
    Honey Badgers
    0
    SF points
    👤Unaffiliated - Choose a Faction!
    0pts
    ',a+='
    How it works:
    This is a community challenge - everyone\'s points combine!

    • Complete the daily Quiz Quest, Trivia & Poll = 1 point
    • Earn a badge = 1 point
    • Level up to Pleb/Stacker ranks = 1 point each
    • Level up to Maxi ranks = 5 points each
    • Level up to Papa John or higher = 10 points
    • At 21 points, a mining competition opens for 60 minutes
    • Extra points beyond 21 add +3 min each (even while active!)
    • 10 hashes max per minute per user (60 second cooldown)
    • Generate a random hash. Below 1,000 = win 21,000 sats!',a+='
    🏆 All-Time Lowest Hashes
    Loading...
    ',a+='
    ⭐ Your Personal Best
    Loading...
    ',a+="
    ",e.innerHTML=a,_startFactionScoreboardListener(),_loadFavorLeaderboards(),o){var s=document.getElementById("favorTabTimer");if(s)var l=setInterval(function(){if(s){if(!t||!t.favorActive)return s.textContent="EXPIRED",void clearInterval(l);var e=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();if(e<=0)s.textContent="00:00";else{var o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);s.textContent=o+"m "+n+"s"}}else clearInterval(l)},1e3)}}}function _startFactionScoreboardListener(){if(window._factionScoreUnsub&&(window._factionScoreUnsub(),window._factionScoreUnsub=null),void 0!==db){var e=db.collection("satoshiFavor").doc("factionTotals");window._factionScoreUnsub=e.onSnapshot(function(e){var t=e.exists?e.data():{cyber_hornets:0,honey_badgers:0,unaffiliated:0},o=t.cyber_hornets||0,n=t.honey_badgers||0,i=o+n,a=document.getElementById("sfScoreHornets"),r=document.getElementById("sfScoreBadgers"),s=document.getElementById("sfScoreUnaffiliated"),l=document.getElementById("sfScoreLeader"),c=document.getElementById("sfScoreBar"),d=document.getElementById("sfScoreBarFill"),u=document.getElementById("sfNoFactionNote"),p=t.unaffiliated||0;if(a&&(a.textContent=o.toLocaleString()),r&&(r.textContent=n.toLocaleString()),s&&(s.textContent=p.toLocaleString()),l&&(l.textContent=o>n?"🐝 Leading":n>o?"🦡 Leading":i>0?"Tied!":""),c&&d&&i>0){c.style.display="block";var m=Math.round(o/i*100);d.style.background="linear-gradient(90deg, #f7931a "+m+"%, #a855f7 "+m+"%)"}var h=void 0!==currentUser&¤tUser&¤tUser.faction||"";u&&(u.style.display=h?"none":"block");var g=document.getElementById("sfAdminBackfill");if(g){var f=void 0!==currentUser&¤tUser&&"needcreations@gmail.com"===currentUser.email;g.style.display=f?"block":"none"}var y=void 0!==currentUser&¤tUser&¤tUser.faction||"",b=document.getElementById("factionScoreboardInner");if(b&&y){var v=b.querySelectorAll('div[style*="flex:1"]');v[0]&&(v[0].style.borderWidth="cyber_hornets"===y?"3px":"2px"),v[1]&&(v[1].style.borderWidth="honey_badgers"===y?"3px":"2px")}},function(e){console.warn("[FACTION-SCORE] Listener error:",e)})}}window._retakeLastQuiz=function(){var e=safeJSON("btc_quest_daily",{}).lastTopic||null,t=document.getElementById("questHubOverlay");t&&t.remove(),setTimeout(function(){generateAndShowQuest(!0,e,!0)},200)},window._startQuestTopic=function(e){var t=document.getElementById("questModal");if(t&&t.classList.remove("open"),currentQuest=null,!e){var o=[];for(var n in QUESTION_BANK)"_general"!==n&&(QUESTION_BANK[n].length<3||completedQuests.has("quest_"+n)||completedQuests.has(n)||-1!==weeklyCompleted.indexOf(n)||o.push(n));if(o.length>0)e=o[Math.floor(Math.random()*o.length)];else{var i=Object.keys(QUESTION_BANK).filter(function(e){return"_general"!==e&&QUESTION_BANK[e].length>=3});e=i[Math.floor(Math.random()*i.length)]}}setTimeout(function(){generateAndShowQuest(!0,e)},200)},setTimeout(initQuests,3e3),window.closeQuestHubForFavor=function(){var e=document.getElementById("questHubOverlay");e&&e.remove(),window._cleanupRaidBoss&&window._cleanupRaidBoss(),window._factionScoreUnsub&&(window._factionScoreUnsub(),window._factionScoreUnsub=null)},window._runFactionBackfill=function(){if("undefined"!=typeof firebase){var e=document.querySelector("#sfAdminBackfill button");e&&(e.textContent="⏳ Running backfill...",e.disabled=!0),firebase.functions().httpsCallable("backfillFactionTotals")({}).then(function(t){var o=t.data;"function"==typeof showToast&&showToast("✅ Backfill done! 🐝 "+(o.totals&&o.totals.cyber_hornets||0)+" vs 🦡 "+(o.totals&&o.totals.honey_badgers||0)),e&&(e.textContent="✅ Done!")}).catch(function(t){"function"==typeof showToast&&showToast("❌ Backfill error: "+t.message),e&&(e.textContent="⚡ Backfill historical data (admin)",e.disabled=!1),console.error("[BACKFILL]",t)})}};var _favorTopHashesUnsub=null,_favorPBUnsub=null;function _renderTopHashesHTML(e){for(var t=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null,o="",n=0;n
    '+s+''+(c?"🏆 ":"")+l+(a?" (you)":"")+'
    '+i.value.toLocaleString()+"
    "}return o}function _renderPBHTML(e){var t=e<1e3;return'
    '+(t?"🏆 ":"")+e.toLocaleString()+'
    Your all-time lowest hash
    '}function _loadFavorLeaderboards(){if(void 0!==db){_favorTopHashesUnsub&&(_favorTopHashesUnsub(),_favorTopHashesUnsub=null),_favorPBUnsub&&(_favorPBUnsub(),_favorPBUnsub=null),_favorTopHashesUnsub=db.collection("satoshiFavor").doc("topHashes").onSnapshot(function(e){var t=document.getElementById("favorTopHashes");t&&(e.exists&&e.data().entries&&0!==e.data().entries.length?t.innerHTML=_renderTopHashesHTML(e.data().entries):t.innerHTML='
    No hashes yet. Be the first to mine!
    ')},function(){var e=document.getElementById("favorTopHashes");e&&(e.innerHTML='
    Could not load leaderboard
    ')});var e=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null;if(e){var t=!1;_favorPBUnsub=db.collection("satoshiFavor").doc("personalBests").collection("users").doc(e).onSnapshot(function(o){var n=document.getElementById("favorPersonalBest");n&&(o.exists?n.innerHTML=_renderPBHTML(o.data().value):t?n.innerHTML='
    No hashes yet. Start mining!
    ':(t=!0,db.collection("satoshiFavor").doc("personalBests").get().then(function(t){if(n=document.getElementById("favorPersonalBest"))if(t.exists){var o=(t.data().users||{})[e];n.innerHTML=o?_renderPBHTML(o.value):'
    No hashes yet. Start mining!
    '}else n.innerHTML='
    No hashes yet. Start mining!
    '}).catch(function(){})))},function(){var e=document.getElementById("favorPersonalBest");e&&(e.innerHTML='
    Could not load personal best
    ')})}else{var o=document.getElementById("favorPersonalBest");o&&(o.innerHTML='
    Sign in to track your personal best
    ')}}}function _renderQuestHubTab(){var e=window._questHubTab||"quiz";["Quiz","Trivia","Poll","Raid","Favor","Charity"].forEach(function(t){var o=document.getElementById("qhTab"+t);if(o){var n=e===t.toLowerCase(),i="Raid"===t&&n,a="Charity"===t&&n;o.style.background=i?"linear-gradient(135deg,#8b5cf6,#7c3aed)":a?"linear-gradient(135deg,#ef4444,#dc2626)":n?"var(--accent)":"none",o.style.color=n?"#fff":"var(--text-muted)",o.style.borderColor=i?"#8b5cf6":a?"#ef4444":n?"var(--accent)":"var(--border)"}});var t=document.getElementById("questHubBody");t&&("raid"!==e&&window._cleanupRaidBoss(),"quiz"===e?_renderQuizTab(t):"trivia"===e?_renderTriviaTab(t):"poll"===e?_renderPollTab(t):"raid"===e?_renderRaidTab(t):"favor"===e?_renderFavorTab(t):"charity"===e&&_renderCharityTab(t))}void 0!==startQuestManual&&(window.startQuestManual=startQuestManual),void 0!==selectAnswer&&(window.selectAnswer=selectAnswer),void 0!==submitQuest&&(window.submitQuest=submitQuest),void 0!==skipQuest&&(window.skipQuest=skipQuest),void 0!==closeQuest&&(window.closeQuest=closeQuest),void 0!==showQuest&&(window.showQuest=showQuest),void 0!==generateAndShowQuest&&(window.generateAndShowQuest=generateAndShowQuest),void 0!==_showQuestTopicPicker&&(window._showQuestTopicPicker=_showQuestTopicPicker),void 0!==showQuestFinalResults&&(window.showQuestFinalResults=showQuestFinalResults),void 0!==retryQuest&&(window.retryQuest=retryQuest),void 0!==_renderQuestHubTab&&(window._renderQuestHubTab=_renderQuestHubTab),window._questHubTab="quiz",window.showQuestHub=function(){window._chatOverlayOpen&&"function"==typeof toggleChatOverlay&&toggleChatOverlay();var e=document.getElementById("questHubOverlay");e&&e.remove();var t=document.createElement("div");t.id="questHubOverlay",t.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.88);z-index:100000;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(5px);padding:20px;animation:nachoPop 0.25s ease;",t.onclick=function(e){e.target===t&&(window._cleanupRaidBoss(),t.remove())};var o=document.createElement("div");o.style.cssText="background:var(--bg-side,#141425);border:1px solid var(--border);width:100%;max-width:520px;max-height:85vh;border-radius:24px;overflow:hidden;display:flex;flex-direction:column;position:relative;";var n=document.createElement("style");n.textContent='@media(min-width:600px){#questHubOverlay [style*="font-size:0.6"]{font-size:0.82rem!important}#questHubOverlay [style*="font-size:0.7"]{font-size:0.88rem!important}#questHubOverlay [style*="font-size:0.75"]{font-size:0.9rem!important}#questHubOverlay [style*="font-size:0.78"]{font-size:0.92rem!important}#questHubOverlay [style*="font-size:0.8"]{font-size:0.95rem!important}#questHubOverlay [style*="font-size:0.82"]{font-size:0.97rem!important}#questHubOverlay [style*="font-size:0.85"]{font-size:1rem!important}#questHubOverlay [style*="font-size:0.9"]{font-size:1.05rem!important}#questHubOverlay [style*="font-size:0.95"]{font-size:1.08rem!important}#questHubOverlay p,[id="questHubBody"] div{font-size:inherit}#questHubBody{font-size:1rem}#questHubTabs button{font-size:0.88rem!important;padding:12px 0!important}}',o.appendChild(n);var i=document.createElement("div");i.style.cssText="padding:20px 24px 0;flex-shrink:0;",i.innerHTML='

    ⚔️ Quest Hub

    Earn XP by testing your Bitcoin knowledge
    ';var a=document.createElement("div");a.id="questHubBody",a.style.cssText="padding:0 24px 24px;overflow-y:auto;flex:1;",o.appendChild(i),o.appendChild(a),t.appendChild(o),document.body.appendChild(t),_renderQuestHubTab()};var _charityStats=null,_charityRecent=[],_charityStatsLoaded=!1;function _loadCharityStats(e){if("undefined"==typeof firebase||!firebase.firestore)return e&&e();var t=firebase.firestore();Promise.all([t.collection("charity_stats").doc("global").get({source:"server"}),t.collection("charity_donations").orderBy("ts","desc").limit(10).get({source:"server"})]).then(function(t){var o=t[0],n=t[1];_charityStats=o.exists?o.data():{totalDonated:0,factionTotals:{}},_charityRecent=[],n.forEach(function(e){_charityRecent.push(e.data())}),_charityStatsLoaded=!0,e&&e()}).catch(function(){e&&e()})}function _renderCharityTab(e){e.innerHTML='
    Loading charity data...
    ',_loadCharityStats(function(){_renderCharityTabInner(e)})}function _renderCharityTabInner(e){var t="function"==typeof escapeHtml?escapeHtml:function(e){return String(e||"").replace(//g,">")},o=void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous,n=void 0!==currentUser&¤tUser&¤tUser.faction||"",i=void 0!==currentUser&¤tUser&¤tUser.points||0,a=void 0!==currentUser&¤tUser&¤tUser.pointsClaimed||0,r=void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,s=Math.max(0,i-a-r),l=_charityStats||{totalDonated:0,factionTotals:{}},c=l.totalDonated||0,d=l.factionTotals&&l.factionTotals.cyber_hornets||0,u=l.factionTotals&&l.factionTotals.honey_badgers||0,p="";p+='
    ❤️
    Donate XP for Charity
    1,000 XP = 1,000 sats donated - 10× more impact than redeeming for yourself
    ',p+='
    🌍 Community Pledge
    '+c.toLocaleString()+' sats pledged
    ('+c.toLocaleString()+" XP donated by the community)
    ";var m=d+u,h=m>0?Math.round(d/m*100):50,g=100-h;p+='
    ⚔️ Faction Giving
    🐝 Cyber Hornets🦡 Honey Badgers
    '+d.toLocaleString()+" XP ("+h+"%)"+u.toLocaleString()+" XP ("+g+"%)
    ",o?n?(p+='
    🎡 Your Donation
    Available to donate: '+s.toLocaleString()+" XP"+(r>0?' ('+r.toLocaleString()+" already donated)":"")+"
    ",p+='
    ',[5,10,25,50,100].forEach(function(e){var t=Math.floor(s*e/100);p+='"}),p+="
    ",p+='
    ',p+='
    ',p+='',p+="
    "):p+="
    ⚔️
    Choose Your Faction First
    Your faction's donation total is tracked for the community leaderboard. Join a side before you donate!
    ":p+='
    🔐 Sign in to donate XP for charity
    ',_charityRecent.length>0&&(p+='
    📜 Recent Donations
    ',_charityRecent.forEach(function(e){var o,n=e.anonymous||!e.uid||"Anonymous"===(e.username||""),i="cyber_hornets"===e.faction?'🐝':"honey_badgers"===e.faction?'🦡':"";o=n?"color:var(--text-muted);":"cyber_hornets"===e.faction?"color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,1px 1px 0 #000,-1px 1px 0 #000;font-weight:700;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;":"honey_badgers"===e.faction?"color:#e5e7eb;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,1px 1px 0 #000,-1px 1px 0 #000;font-weight:700;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;":"color:var(--text);font-weight:600;cursor:pointer;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:2px;";var a=n?''+t(e.username||"Anonymous")+"":''+t(e.username||"Anonymous")+"";p+='
    '+i+" "+a+'+'+(e.amount||0).toLocaleString()+" XP
    "}),p+="
    "),p+='
    🗳️ Community Charity Vote
    Coming soon - the community will vote on which charities receive our pledged sats. Focused on Bitcoin education and adoption, but not limited to it.
    ',p+="

    Our community will vote on which charities our contributions go to. In Bitcoin, the charities will focus on Bitcoin education and adoption - but our donations are not limited to the Bitcoin ecosystem. We can find charities outside of Bitcoin that we want to support as a community.

    ⚠️ Donations are non-refundable. Donated XP cannot be reclaimed or reversed. Donations are a community pledge and are not tax-deductible. This is not a registered charitable organization and no tax receipts are issued.

    ",p+='
    🏅 Donation Badges
    ';var f="function"==typeof safeJSON?safeJSON("btc_hidden_badges",[]):[];[{id:"donor_100",emoji:"🫷",name:"Giving Pleb",thresh:"100 XP",reward:"50 XP"},{id:"donor_500",emoji:"💛",name:"Stack Sharer",thresh:"500 XP",reward:"150 XP"},{id:"donor_1000",emoji:"🧡",name:"Community Builder",thresh:"1,000 XP",reward:"300 XP"},{id:"donor_5000",emoji:"❤️",name:"Archive Patron",thresh:"5,000 XP",reward:"1,000 XP"},{id:"donor_10000",emoji:"🔥",name:"Sats Saint",thresh:"10,000 XP",reward:"2,000 XP"},{id:"donor_25000",emoji:"⚡",name:"Lightning Philanthropist",thresh:"25,000 XP",reward:"4,000 XP"},{id:"donor_50000",emoji:"🏆",name:"Satoshi's Steward",thresh:"50,000 XP",reward:"7,500 XP"},{id:"donor_100000",emoji:"👑",name:"Legend of the Archive",thresh:"100,000 XP",reward:"15,000 XP"}].forEach(function(e){var t=f.includes(e.id)||void 0!==currentUser&¤tUser&&Array.isArray(currentUser.donationBadges)&¤tUser.donationBadges.includes(e.id);p+='
    '+e.emoji+'
    '+e.name+'
    '+e.thresh+' donated
    +'+e.reward+" reward
    "}),p+="
    ",e.innerHTML=p,window._charitySetAmount=function(e){var t=document.getElementById("charityAmtInput");t&&(t.value=e>0?e:"")},window._submitCharityDonation=function(){if("undefined"!=typeof firebase&&firebase.functions){var e=document.getElementById("charityAmtInput"),t=parseInt(e?e.value:"")||0;if(!t||t<1)"function"==typeof showToast&&showToast("Enter a valid amount");else{var o=Math.max(0,void 0!==currentUser&¤tUser?(currentUser.points||0)-(currentUser.pointsClaimed||0)-(currentUser.pointsDonated||0):0);if(t>o)"function"==typeof showToast&&showToast("Not enough available XP. You have "+o.toLocaleString()+" pts available.");else{var n=!!document.getElementById("charityAnonToggle")&&document.getElementById("charityAnonToggle").checked,i=document.querySelector('[onclick="window._submitCharityDonation()"]');i&&(i.disabled=!0,i.textContent="Donating..."),firebase.functions().httpsCallable("donatePoints")({amount:t,anonymous:n}).then(function(e){void 0!==currentUser&¤tUser&&(currentUser.pointsDonated=(currentUser.pointsDonated||0)+t,e.data&&e.data.bonusPts&&(currentUser.points=(currentUser.points||0)+e.data.bonusPts));var o=e.data&&e.data.newBadges||[],n=o.length>0?" You earned "+o.length+" new badge"+(o.length>1?"s":"")+"!":"";if("function"==typeof showToast&&showToast("❤️ Thank you! "+t.toLocaleString()+" XP donated ("+t.toLocaleString()+" sats pledged to charity)."+n,5e3),window._charityThankYou(t,o,e.data&&e.data.bonusPts||0),o.length>0&&"function"==typeof window.contributeSatoshiFavor){var i={donor_100:{emoji:"🫷",name:"Giving Pleb"},donor_500:{emoji:"💛",name:"Stack Sharer"},donor_1000:{emoji:"🧡",name:"Community Builder"},donor_5000:{emoji:"❤️",name:"Archive Patron"},donor_10000:{emoji:"🔥",name:"Sats Saint"},donor_25000:{emoji:"⚡",name:"Lightning Philanthropist"},donor_50000:{emoji:"🏆",name:"Satoshi's Steward"},donor_100000:{emoji:"👑",name:"Legend of the Archive"}};o.forEach(function(e){var t=i[e];t&&window.contributeSatoshiFavor("badge_earned",t.emoji+" "+t.name).catch(function(){})})}_charityStatsLoaded=!1,_renderCharityTab(document.getElementById("questHubBody"))}).catch(function(e){i&&(i.disabled=!1,i.textContent="❤️ Donate XP for Charity"),"function"==typeof showToast&&showToast("❌ "+(e.message||"Donation failed. Try again."),4e3)})}}}else"function"==typeof showToast&&showToast("Firebase not ready")}}function _renderQuizTab(e){var t=(new Date).toISOString().split("T")[0],o=safeJSON("btc_quest_daily",{}),n=o.date===t?o.count:0,i=completedQuests?completedQuests.size:0,a=o.date===t&&n>=1&&o.lastScore&&o.lastScore<5,r="";if(a){o.lastTopic&&o.lastTopic.replace(/['\\]/g,"");var s=o.lastTitle||"your last quiz";r='
    🔄 You scored '+o.lastScore+"/5 on "+("function"==typeof escapeHtml?escapeHtml(s):s)+'
    Retake it to get a perfect score! +25 XP for improvement
    '}e.innerHTML='
    📝
    Quiz Quests
    1 daily quiz - retake until you ace it!
    '+n+'
    Today
    '+i+'
    All Time
    3+ correct = 50 XP
    Perfect = 100 XP
    '+r+"
    "}function _getTriviaToday(){if("undefined"==typeof TRIVIA_BANK||!TRIVIA_BANK||!TRIVIA_BANK.length)return null;var e=new Date,t=new Date(e.getFullYear(),0,0),o=(7*Math.floor((e-t)/864e5)+e.getFullYear())%TRIVIA_BANK.length;return{index:o,trivia:TRIVIA_BANK[o]}}function _getTriviaState(){try{return JSON.parse(localStorage.getItem("btc_trivia_state")||"{}")}catch(e){return{}}}function _setTriviaState(e){try{localStorage.setItem("btc_trivia_state",JSON.stringify(e))}catch(e){}}function _renderTriviaTab(e){var t=_getTriviaToday();if(t&&t.trivia){var o=_getTriviaState(),n=(new Date).toISOString().split("T")[0],i=o.date===n,a=t.trivia,r='
    🧠
    Trivia Quest
    1 new question every day
    +50 XP correct · +10 XP for trying
    ';r+='
    '+("function"==typeof escapeHtml?escapeHtml(a.q):a.q)+"
    ",r+='
    ';for(var s=0;s
    '+String.fromCharCode(65+s)+''+l+''+(p?''+p+"":"")+"
    "}else r+='"}r+="",i&&void 0!==db&&db.collection("trivia_stats").doc(n).get().then(function(e){var t=e.exists?e.data():{},o=t.total||0;if(!(o<1))for(var n=0;n
    💡 Explanation
    '+("function"==typeof escapeHtml?escapeHtml(a.explanation):a.explanation)+"
    ",r+='
    Come back tomorrow for a new trivia question! 🧠
    '),e.innerHTML=r}else e.innerHTML='
    Trivia questions loading...
    '}function _getPollToday(){if("undefined"==typeof POLL_BANK||!POLL_BANK||!POLL_BANK.length)return null;var e=new Date,t=new Date(e.getFullYear(),0,0),o=(13*Math.floor((e-t)/864e5)+e.getFullYear())%POLL_BANK.length;return{index:o,poll:POLL_BANK[o]}}function _getPollState(){try{return JSON.parse(localStorage.getItem("btc_poll_state")||"{}")}catch(e){return{}}}function _setPollState(e){try{localStorage.setItem("btc_poll_state",JSON.stringify(e))}catch(e){}}function _renderPollTab(e){var t=_getPollToday();if(t&&t.poll){var o=_getPollState(),n=(new Date).toISOString().split("T")[0],i=o.date===n&&"number"==typeof o.chosen,a=t.poll,r='
    📊
    Poll Quest
    Vote daily - see what the community thinks
    +50 XP for voting
    ';if(r+='
    '+("function"==typeof escapeHtml?escapeHtml(a.q):a.q)+"
    ",i)_renderPollResults(e,r,a,o,n);else{var s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null,l=a.id||"poll_day_"+n;s&&void 0!==db?db.collection("poll_votes").doc(l).get().then(function(i){if(i.exists&&i.data().voters&&-1!==i.data().voters.indexOf(s)){var l=o.chosen;_setPollState(o={date:n,index:t.index,chosen:"number"==typeof l?l:-1,pollId:a.id}),_renderPollResults(e,r,a,o,n)}else _showPollVoteButtons(e,r,a)}).catch(function(){_showPollVoteButtons(e,r,a)}):_showPollVoteButtons(e,r,a)}}else e.innerHTML='
    Polls loading...
    '}function _showPollVoteButtons(e,t,o){t+='
    ';for(var n=0;n'+String.fromCharCode(65+n)+""+i+""}t+="
    ",e.innerHTML=t}function _renderPollResults(e,t,o,n,i){var a=o.id||"poll_day_"+i;void 0!==db?db.collection("poll_votes").doc(a).get().then(function(i){var a=i.exists&&i.data().votes||[0,0,0,0],r=a.reduce(function(e,t){return e+t},0)||1;_drawPollResults(e,t,o,a,r,n.chosen)}).catch(function(){_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}):_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}function _drawPollResults(e,t,o,n,i,a){var r=t,s=["#f7931a","#3b82f6","#22c55e","#8b5cf6"];r+='
    ';for(var l=0;l
    '+(u?"✓":String.fromCharCode(65+l))+''+c+'
    '+d+"%
    "}r+="",r+='
    '+i+" total vote"+(1!==i?"s":"")+" · Come back tomorrow for a new poll!
    ",e.innerHTML=r}function _renderRaidTab(e){e.innerHTML='
    Loading Raid Boss...
    ',window._loadRaidBoss()}function _raidEmptyState(){return'
    ⚔️
    Raid Boss
    No active raid boss right now.
    Check back soon for community boss fights!
    '}function _raidVictoryBanner(e){var t="function"==typeof escapeHtml?escapeHtml(e.name||"Raid Boss"):e.name||"Raid Boss",o=_getRaidBossImage(e);return'
    '+(o?'
    '+t+'
    💀
    ':'
    💀
    ')+'
    BOSS DEFEATED! 🎉
    '+t+' has fallen!
    The community worked together and took it down! Great job everyone!
    🏆 Community reward unlocked!
    Extra orange ticket drawing for 21,000 sats - this Friday night!
    '}window._charityThankYou=function(e,t,o){var n=document.getElementById("charityThankYouOverlay");n&&n.remove();var i=document.createElement("div");i.id="charityThankYouOverlay",i.style.cssText="position:fixed;inset:0;z-index:300000;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;padding:20px;";var a=document.createElement("div");a.style.cssText="background:var(--card-bg);border:1px solid rgba(239,68,68,0.4);border-radius:20px;padding:28px 24px;max-width:360px;width:100%;text-align:center;position:relative;";var r='
    ❤️
    Thank You!
    You donated '+e.toLocaleString()+" XP - that's "+e.toLocaleString()+" sats pledged to charity.
    ";o>0&&(r+='
    +'+o.toLocaleString()+" bonus XP earned!
    "),t&&t.length>0&&(r+='
    🏼 New badge'+(t.length>1?"s":"")+" unlocked: "+t.join(", ")+"
    "),r+='
    The community will vote on which charities receive these sats.
    ',a.innerHTML=r,i.appendChild(a),i.addEventListener("click",function(e){e.target===i&&i.remove()}),document.body.appendChild(i)},window._renderCharityHome=function(){var e=document.getElementById("charityDonateHome");e&&"undefined"!=typeof firebase&&firebase.firestore&&firebase.firestore().collection("charity_stats").doc("global").get().then(function(t){var o=t.exists?t.data():{totalDonated:0,factionTotals:{}},n=o.totalDonated||0,i=o.factionTotals&&o.factionTotals.cyber_hornets||0,a=o.factionTotals&&o.factionTotals.honey_badgers||0;e.innerHTML='
    ❤️ Donate XP for Charity
    Tap to donate →
    '+n.toLocaleString()+' sats pledged
    🐝 '+i.toLocaleString()+' XP🦡 '+a.toLocaleString()+" XP
    "}).catch(function(){})},window.triviaAnswer=function(e){var t=_getTriviaToday();if(t&&t.trivia){var o=t.trivia,n=(new Date).toISOString().split("T")[0],i=_getTriviaState();if(i.date!==n){var a=e===o.answer,r=a?50:10;if(_setTriviaState(i={date:n,index:t.index,chosen:e,correct:a}),"function"==typeof awardPoints&&awardPoints(r,a?"🧠 Trivia Quest correct!":"🧠 Trivia Quest attempt"),a&&"function"==typeof window._raidOnTriviaCorrect&&window._raidOnTriviaCorrect(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(r),_markDailyActivity("trivia"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({lastTriviaDate:n,triviaAnswered:firebase.firestore.FieldValue.increment(1),triviaCorrect:firebase.firestore.FieldValue.increment(a?1:0)}).catch(function(){}),void 0!==db){var s={total:firebase.firestore.FieldValue.increment(1)};s["option_"+e]=firebase.firestore.FieldValue.increment(1),db.collection("trivia_stats").doc(n).set(s,{merge:!0}).catch(function(){})}var l=document.getElementById("questHubBody");l&&_renderTriviaTab(l),"function"==typeof showToast&&showToast(a?"✅ Correct! +50 XP 🧠":"❌ Wrong - +10 XP for trying!",3e3)}}},window.pollVote=function(e){var t=_getPollToday();if(t&&t.poll){var o=t.poll,n=(new Date).toISOString().split("T")[0],i=_getPollState();if(i.date!==n||"number"!=typeof i.chosen){var a=document.querySelectorAll("#pollOptions button");a.forEach(function(e){e.disabled=!0,e.style.opacity="0.5",e.style.cursor="default"});var r=o.id||"poll_day_"+n,s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null;if(void 0!==db&&s){var l=db.collection("poll_votes").doc(r);db.runTransaction(function(t){return t.get(l).then(function(n){var i=n.exists?n.data():{},a=i.voters||[];if(-1!==a.indexOf(s))return Promise.reject({code:"already-voted"});var c=i.votes||[0,0,0,0];c[e]=(c[e]||0)+1,a.push(s),t.set(l,{pollId:r,question:o.q,options:o.options,votes:c,voters:a,lastUpdated:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0})})}).then(function(){_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof awardPoints&&awardPoints(50,"📊 Poll Quest vote"),"function"==typeof window._raidOnPollVote&&window._raidOnPollVote(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(50),"function"==typeof showToast&&showToast("📊 Vote recorded! +50 XP",3e3),_markDailyActivity("poll"),_checkDailyAllThree(),auth.currentUser.isAnonymous||db.collection("users").doc(s).update({lastPollDate:n,pollsVoted:firebase.firestore.FieldValue.increment(1)}).catch(function(){});var a=document.getElementById("questHubBody");a&&_renderPollTab(a)}).catch(function(r){if(!r||"already-voted"!==r.code)return console.error("[POLL] Vote failed:",r),"function"==typeof showToast&&showToast("⚠️ Vote failed - try again",3e3),void a.forEach(function(e){e.disabled=!1,e.style.opacity="1",e.style.cursor="pointer"});_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("You already voted on this poll today!",3e3);var s=document.getElementById("questHubBody");s&&_renderPollTab(s)})}else{_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("📊 Vote recorded locally",3e3);var c=document.getElementById("questHubBody");c&&_renderPollTab(c)}}}},window._raidBossUnsub=null,window._raidParticipantsUnsub=null,window._raidTimerInterval=null,window._cleanupRaidBoss=function(){window._raidBossUnsub&&(window._raidBossUnsub(),window._raidBossUnsub=null),window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null),window._raidTimerInterval&&(clearInterval(window._raidTimerInterval),window._raidTimerInterval=null),window._raidDamageDealersOpen=!1},window._loadRaidBoss=function(){window._cleanupRaidBoss();var e=document.getElementById("raidBossContent");e&&(void 0!==db?window._raidBossUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.innerHTML=_raidEmptyState();else{var o=Date.now(),n=null,i=null,a=null;if(t.forEach(function(e){var t=e.data();t._id=e.id;var r=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,s=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime?i.startTime.toMillis?i.startTime.toMillis():i.startTime:0))&&(i=t):t.defeated&&(a||(a=t))}),a&&(i||n)&&!n){window._defeatedBossId=a._id;var r=_raidVictoryBanner(a);e.innerHTML=r;var s=document.createElement("div");return s.id="raidUpcomingSection",e.appendChild(s),window._currentRaidBoss=i||a,void _renderRaidBossCard(s,i)}var l=n||i||a;l?(window._currentRaidBoss=l,_renderRaidBossCard(e,l)):e.innerHTML=_raidEmptyState()}},function(t){console.error("[RAID] Boss listener error:",t),e.innerHTML='
    ⚠️ Failed to load raid boss
    '}):e.innerHTML='
    ⚠️ Database not available
    ')};var RAID_BOSS_IMAGES={"Channel-Crawler":"images/raid-bosses/channel-crawler.png","Quiz-Crusader":"images/raid-bosses/quiz-crusader.png","TV-Titan":"images/raid-bosses/tv-titan.png","Beats-Baron":"images/raid-bosses/beats-baron.png","Flash-Flash":"images/raid-bosses/flash-flash.png","XP-Hoarder":"images/raid-bosses/xp-hoarder.png","Poll-Patroller":"images/raid-bosses/poll-patroller.png","Chat-Charger":"images/raid-bosses/chat-charger.png","Badge-Builder":"images/raid-bosses/badge-builder.png","Streak-Sage":"images/raid-bosses/streak-sage.png","Topic-Explorer":"images/raid-bosses/topic-explorer.png","Lightning-Lancer":"images/raid-bosses/lightning-lancer.png","Forum-Forge":"images/raid-bosses/forum-forge.png","Trivia-Tactician":"images/raid-bosses/trivia-tactician.png","Content-Conqueror":"images/raid-bosses/content-conqueror.png"};function _getRaidBossImage(e){return e.image||RAID_BOSS_IMAGES[e.name]||""}function _renderRaidBossCard(e,t){Date.now();var o=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,n=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0,i=_getRaidBossImage(t);if(t.placeholder){var a=o?new Date(o):null,r=a?a.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"Soon",s=i?''+(t.name||':'
    ⚔️
    ';return e.innerHTML='
    '+s+'
    '+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
    '+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
    '+("function"==typeof escapeHtml?escapeHtml(r):r)+'
    Get ready to team up and take it down!
    🏆 Community Prize
    Defeat the boss = extra orange ticket giveaway for 21,000 sats!
    ',void _startRaidCountdown("raidCountdownPlaceholder",o)}if(t.defeated){var l=t.winners||[],c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null;if(c&&-1!==l.indexOf(c)&&localStorage.setItem("btc_raid_winner","true"),l.length>0)for(var d=0;d'+(t.name||
    💀
    ':'
    💀
    ';return e.innerHTML='
    '+u+'
    DEFEATED!
    '+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
    '+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
    🎉 Community reward unlocked!
    Extra orange ticket giveaway for 21,000 sats!
    ',void(window._defeatedBossId=t._id)}var p=void 0!==t.current?t.current:void 0!==t.currentHP?t.currentHP:0,m=t.target||t.targetHP||1,h=Math.min(100,Math.round(p/m*100)),g=Math.max(0,m-p),f=Math.max(0,100-h),y="function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss",b="function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"",v=i?''+y+'':'
    👹
    ';if(e.innerHTML='
    '+v+'
    '+y+'
    '+b+'
    ❤️ Boss Health'+g.toLocaleString()+" / "+m.toLocaleString()+' HP
    '+h+'% damage dealt
    ⏰ Time Remaining
    🏆 Community Prize
    Defeat the boss and the community earns an extra orange ticket giveaway for 21,000 sats!
    Loading...
    ',!document.getElementById("raidShimmerStyle")){var w=document.createElement("style");w.id="raidShimmerStyle",w.textContent="@keyframes raidShimmer{0%{transform:translateX(-100%)}100%{transform:translateX(100%)}}",document.head.appendChild(w)}_startRaidCountdown("raidTimer",n),window._raidActiveTab="current",window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),_listenRaidParticipants(t._id)}function _startRaidCountdown(e,t){function o(){var o=document.getElementById(e);if(!o)return clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var n=Math.max(0,t-Date.now());if(n<=0)return o.textContent="Time's up!",clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var i=Math.floor(n/864e5),a=Math.floor(n%864e5/36e5),r=Math.floor(n%36e5/6e4),s=Math.floor(n%6e4/1e3);o.textContent=(i>0?i+"d ":"")+(a>0?a+"h ":"")+(r<10?"0":"")+r+"m "+(s<10?"0":"")+s+"s"}window._raidTimerInterval&&clearInterval(window._raidTimerInterval),o(),window._raidTimerInterval=setInterval(o,1e3)}function _listenRaidParticipants(e){window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),void 0!==db&&(window._raidParticipantsUnsub=db.collection("raid_bosses").doc(e).collection("participants").orderBy("contributed","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t)if(e.empty)t.innerHTML='
    No raiders yet - be the first! ⚔️
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,l=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] Participants listener error:",e)}))}function _listenAllTimeRaiders(){window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),void 0!==db&&(window._raidAllTimeUnsub=db.collection("users").where("raidDamageAllTime",">",0).orderBy("raidDamageAllTime","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t&&"alltime"===window._raidActiveTab)if(e.empty)t.innerHTML='
    No all-time damage recorded yet.
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.raidDamageAllTime||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,l=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] All-time raiders listener error:",e);var t=document.getElementById("raidParticipants");t&&"alltime"===window._raidActiveTab&&(t.innerHTML='
    Could not load all-time data.
    ')}))}window._raidDamageDealersOpen=!1,window._raidDamageDealersUnsub=null,window._toggleRaidDamageDealers=function(){var e=document.getElementById("raidDamageDealers"),t=document.getElementById("raidDamageDealersBtn");if(e){if(window._raidDamageDealersOpen=!window._raidDamageDealersOpen,!window._raidDamageDealersOpen)return e.style.display="none",t&&(t.textContent="⚔️ Top Damage Dealers"),void(window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null));e.style.display="block",t&&(t.textContent="▲ Hide Damage Dealers"),e.innerHTML='
    Loading...
    ';var o=window._defeatedBossId||(window._currentRaidBoss&&window._currentRaidBoss._id?window._currentRaidBoss._id:null);o&&void 0!==db?window._raidDamageDealersUnsub=db.collection("raid_bosses").doc(o).collection("participants").orderBy("contributed","desc").limit(30).onSnapshot(function(e){var t=document.getElementById("raidDamageDealers");if(t)if(e.empty)t.innerHTML='
    No damage recorded for this boss.
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,l=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] Damage dealers listener error:",e);var t=document.getElementById("raidDamageDealers");t&&(t.innerHTML='
    Failed to load damage data.
    ')}):e.innerHTML='
    No damage data available.
    '}},window._raidActiveTab="current",window._raidAllTimeUnsub=null,window._switchRaidTab=function(e){if(e!==window._raidActiveTab){window._raidActiveTab=e;var t=document.getElementById("raidTabCurrent"),o=document.getElementById("raidTabAllTime");t&&(t.style.borderBottomColor="current"===e?"#8b5cf6":"transparent",t.style.color="current"===e?"#8b5cf6":"var(--text-faint)"),o&&(o.style.borderBottomColor="alltime"===e?"#8b5cf6":"transparent",o.style.color="alltime"===e?"#8b5cf6":"var(--text-faint)");var n=document.getElementById("raidParticipants");n&&(n.innerHTML='
    Loading...
    '),"current"===e?(window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._currentRaidBoss&&window._currentRaidBoss._id&&_listenRaidParticipants(window._currentRaidBoss._id)):(window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),_listenAllTimeRaiders())}};var RAID_GUIDANCE={uniqueUsers5Topics:{action:"Visit 5+ learning topics to deal damage!",nav:"home"},quizCompletions:{action:"Complete quiz quests to deal damage!",nav:"quests"},watchMinutes:{action:"Watch Timechain TV to deal damage!",nav:"tctv"},beatsMinutes:{action:"Listen to Bitcoin Beats to deal damage!",nav:"beats"},flashcardCompletions:{action:"Complete flashcard sets to deal damage!",nav:"quests"},totalXP:{action:"Earn XP from any activity to deal damage!",nav:"home"},pollVotes:{action:"Vote in Quest Hub polls to deal damage!",nav:"quests"},chatMessages:{action:"Send messages in Global Chat to deal damage!",nav:"chat"},badgesEarned:{action:"Earn badges to deal damage! Find them in the Leaderboard button 🏆",nav:"badges"},streakUsers:{action:"Maintain a 7-day daily visit streak to deal damage!",nav:"home"},uniqueTopicsVisited:{action:"Visit learning topics you haven't read yet!",nav:"home"},tipsSent:{action:"Send Lightning tips to deal damage!",nav:"home"},forumPosts:{action:"Create forum posts to deal damage!",nav:"forum"},triviaCorrect:{action:"Answer trivia correctly in Quest Hub to deal damage!",nav:"quests"},totalTopicReads:{action:"Read learning topics to deal damage!",nav:"home"}};window._contributeRaid=function(){var e=window._currentRaidBoss;if(e){var t=RAID_GUIDANCE[e.metric]||{action:"Complete activities on the site to deal damage!",nav:"home"};"function"==typeof showToast&&showToast("⚔️ "+t.action,3500);var o=document.getElementById("questHubOverlay");if(o&&o.remove(),"badges"===t.nav){if("function"==typeof toggleLeaderboard){var n=document.getElementById("leaderboard");if(n&&n.classList.contains("open")){n.classList.remove("open");var i=document.getElementById("lbFloatBtn");i&&(i.style.display="flex")}toggleLeaderboard(),setTimeout(function(){var e=document.getElementById("leaderboard");if(e)for(var t=e.querySelectorAll("h4"),o=0;o'+i.emoji+'
    '+i.title+'
    '+i.desc+"
    "}t+='',t+="";var a=document.createElement("div");a.id="forumRulesOverlay",a.innerHTML=t,document.body.appendChild(a)}window.acceptForumRules=function(){localStorage.setItem("btc_forum_rules_accepted","true");var e=document.getElementById("forumRulesOverlay");e&&e.remove()},window.showForumRulesBtn=function(){i()};var a=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","retard","nazi","hitler","kkk","porn","hentai","rape","pedo"];function r(e){for(var t=e.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/),o=0;o=4&&-1!==t[o].indexOf(a[n]))return!1}return!0}function s(e){return"function"==typeof escapeHtml?escapeHtml(e):String(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}window.forumBack=function(){history.back()};var l="recent",c=sessionStorage.getItem("btc_forum_category")||"all",d=null,u="discussions",p=["Bitcoin Basics","Lightning","Mining","Privacy","Self-Custody","Economics","Technical","Culture","Opinion","Tutorial","News Analysis"];function m(e,n){if(n)if(0!==e.length){var i="";e.forEach(function(e){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},a=o.find(function(t){return t.id===e.category}),r=a?a.emoji+" "+a.name:"",l=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),c=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid);i+='
    '+(e.upvotes||0)+'
    '+s(e.title)+"
    "+(e.body?'
    '+s(e.body).substring(0,120)+(e.body.length>120?"...":"")+"
    ":"")+"
    '+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'💬 '+(e.replyCount||0)+""+(r?''+r+"":"")+(l?"':"")+"
    "}),n.innerHTML=i}else n.innerHTML='
    🦌
    No posts yet. Be the first to start a discussion!
    '}async function h(e){var o=document.getElementById("forumReplies");if(o)try{var n=await db.collection("forum_replies").where("postId","==",e).orderBy("createdAt","asc").limit(100).get(),i=[];if(n.forEach(function(e){i.push({id:e.id,...e.data()})}),0===i.length)return void(o.innerHTML='
    No replies yet. Be the first!
    ');var a=[],r={};i.forEach(function(e){e.parentReplyId?(r[e.parentReplyId]||(r[e.parentReplyId]=[]),r[e.parentReplyId].push(e)):a.push(e)});var l='
    '+i.length+" "+(1===i.length?"reply":"replies")+"
    ";function c(e,o){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},i=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid),a=s(e.body).replace(/\n/g,"
    ");a=T(a=a.replace(/(https?:\/\/[^\s<]+)/g,'$1'));var r=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),l=auth&&auth.currentUser&&!auth.currentUser.isAnonymous;return'
    '+(e.parentAuthorName?'
    ↩ '+s(e.parentAuthorName)+"
    ":"")+'
    "+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'
    '+a+'
    "+(l?'':"")+(r?"':"")+"
    "}a.forEach(function(e){l+=c(e,!1),(r[e.id]||[]).forEach(function(e){l+=c(e,!0)})}),Object.keys(r).forEach(function(e){a.some(function(t){return t.id===e})||r[e].forEach(function(e){l+=c(e,!1)})}),o.innerHTML=l}catch(d){o.innerHTML='
    Error loading replies
    '}}window.renderForum=function(){var e=document.getElementById("forumContainer");if(e){e.innerHTML="";var t='
    ';if(t+='
    Home
    ',t+='

    🗣️ Pleb Talk

    Discuss Bitcoin with fellow learners
    ',t+='
    ',"stacker"===u){var n=window._snSearchQuery||"";t+='
    ',t+='',t+='',n&&(t+=''),t+="
    ";var a=window._snSub||"",r=[{id:"",label:"All"},{id:"bitcoin",label:"bitcoin"},{id:"lightning",label:"lightning"},{id:"nostr",label:"nostr"},{id:"privacy",label:"privacy"},{id:"tech",label:"tech"},{id:"meta",label:"meta"}];t+='
    ';for(var d=0;d'+S(p.label)+""}if(t+="
    ",n)t+='
    Search results for: '+S(n)+"
    ";else{var h=window._snSort||"top",g=window._snWhen||"day";t+='
    ';for(var f=[{id:"top",label:"🔥 Top"},{id:"recent",label:"🕐 Recent"},{id:"random",label:"🎲 Random"}],y=0;y'+b.label+""}if("top"===h){t+='"}t+='stacker.news ↗',t+="
    "}return t+='
    Loading Stacker News...
    ',t+="
    ",e.innerHTML=t,void(n?function(e){var t=document.getElementById("snFeed");if(t){var o="https://embed-proxy.needcreations.workers.dev/api/sn/search?q="+encodeURIComponent(e);fetch(o).then(function(e){return e.json()}).then(function(o){if(o&&o.data&&o.data.search&&o.data.search.items){var n=o.data.search.items;n.length?t.innerHTML=v(n):t.innerHTML='
    No results found for "'+S(e)+'"
    '}else t.innerHTML='
    No results found
    '}).catch(function(){t.innerHTML='
    Search failed.
    '})}}(n):loadStackerNewsFeed(window._snSort||"top",window._snWhen||"day",a))}"articles"!==u?(t+='
    ',["recent","top","discussed"].forEach(function(e){var o=l===e;t+=""}),t+='
    ",t+='
    Loading posts...
    ',t+="",e.innerHTML=t,document.getElementById("main").scrollTop=0,"true"!==localStorage.getItem("btc_forum_rules_accepted")&&i(),forumLoadPosts()):function(e,t){var o=e;o+='
    ',o+='
    ',["recent","top"].forEach(function(e){var t=l===e;o+=""}),o+="
    ",o+='
    Loading articles...
    ',o+="",t.innerHTML=o,document.getElementById("main").scrollTop=0,async function(){var e=document.getElementById("articlesList");if(e&&void 0!==db)try{var t="top"===l?"upvotes":"createdAt",o=await db.collection("articles").where("status","==","published").orderBy(t,"desc").limit(15).get(),n=[];if(o.forEach(function(e){n.push({id:e.id,...e.data()})}),0===n.length)return void(e.innerHTML='
    📝
    No articles yet
    Be the first to publish a Bitcoin article!
    ');var i="";n.forEach(function(e){var t="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},o=Math.max(1,Math.round((e.wordCount||500)/200)),n=e.createdAt&&e.createdAt.toDate?e.createdAt.toDate().toLocaleDateString():"",a=e.pinned?'📌 PINNED ':"";i+="
    ',e.coverUrl&&(i+='
    '),i+='
    ',i+=a+'

    '+s(e.title)+"

    ",e.subtitle&&(i+='
    '+s(e.subtitle)+"
    "),e.tags&&e.tags.length&&(i+='
    ',e.tags.forEach(function(e){i+=''+s(e)+""}),i+="
    "),i+='
    "+t.emoji+" "+s(e.authorName||"Anon")+"·"+o+" min read"+(n?"·"+n+"":"")+"
    ",i+='
    👍 '+(e.upvotes||0)+"💬 "+(e.replyCount||0)+""+(e.tipTotal?"⚡ "+e.tipTotal+" sats":"")+"
    ",i+="
    "}),e.innerHTML=i}catch(t){console.error("Articles load error:",t),e.innerHTML='
    Error loading articles
    '}}()}(t,e)}},window._forumUnsubscribe=null,window.forumLoadPosts=async function(){document.getElementById("forumPosts")&&void 0!==db&&(window._forumUnsubscribe&&(window._forumUnsubscribe(),window._forumUnsubscribe=null),async function(){var e=document.getElementById("forumPosts");if(e)try{var t="top"===l?"upvotes":"discussed"===l?"replyCount":"createdAt",o=c+"_"+l,n=Date.now();if(window._forumCache&&window._forumCache.key===o&&n-window._forumCache.time<12e4)return window._forumCache.posts,void m(window._forumCache.posts,e);var i="all"!==c?db.collection("forum_posts").where("category","==",c).orderBy(t,"desc").limit(50):db.collection("forum_posts").orderBy(t,"desc").limit(50),a=await i.get(),r=[];a.forEach(function(e){r.push({id:e.id,...e.data()})}),window._forumCache={key:o,time:Date.now(),posts:r},m(r,e)}catch(t){e.innerHTML='
    Error loading posts. Try refreshing.
    '}}())},window.forumSetSort=function(e){l=e,renderForum()},window.forumSetCategory=function(e){c=e,sessionStorage.setItem("btc_forum_category",e),renderForum()},window.forumViewPost=async function(e,o){var n=document.getElementById("forumContainer");if(n&&void 0!==db){o||history.pushState({channel:"forum",forumPost:e},"","#forum/post/"+e),n.innerHTML='
    ';try{var i=await db.collection("forum_posts").doc(e).get();if(!i.exists)return void renderForum();var a={id:i.id,...i.data()};d=a;var r="function"==typeof getLevel?getLevel(a.authorPoints||0):{emoji:"🟢"},l=a.voters&&auth&&auth.currentUser&&-1!==a.voters.indexOf(auth.currentUser.uid),c='
    ';if(c+='
    Home
    ',c+='',c+='

    '+s(a.title)+'

    "+r.emoji+" "+s(a.authorName||"Anon")+''+timeAgo(a.createdAt)+"
    ",a.body){var u=s(a.body).replace(/\n/g,"
    ").replace(/\*\*(.+?)\*\*/g,"$1");c+='
    '+(u=T(u=u.replace(/(https?:\/\/[^\s<]+)/g,'$1')))+"
    "}a.link&&(c+='🔗 '+s(a.link).substring(0,60)+(a.link.length>60?"...":"")+"
    ");var p=auth&&auth.currentUser&&a.authorId===auth.currentUser.uid||t();c+='
    💬 '+(a.replyCount||0)+" replies"+(p?"':"")+"
    ",c+="
    ",auth&&auth.currentUser&&!auth.currentUser.isAnonymous?c+='
    ':c+='
    🔒
    Want to join the conversation?
    ',c+='
    Loading replies...
    ',c+="
    ",n.innerHTML=c,document.getElementById("main").scrollTop=0,h(e)}catch(e){n.innerHTML='
    Error loading post
    '}}},window.forumNewPost=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){history.pushState({channel:"forum-new"},"","#forum");var e=document.getElementById("forumContainer");if(e){var t='
    ';t+='
    Home
    ',t+='',t+='

    📝 Create New Post

    ',t+='
    ';var n="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;";t+='",t+='',t+='',t+='',t+='
    ',t+='',t+='
    ',t+="
    ",window._forumFormOpenTime=Date.now(),e.innerHTML=t,document.getElementById("main").scrollTop=0}}else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
    🔒

    Registration Required

    Create a free account to post in the forum, join discussions, and earn XP! It only takes a few seconds.
    ')}};var g=0;function f(e){if(!e)return"";var t=s(e);return T(t='

    '+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,'$1')).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/(?$1')).replace(/^### (.+)$/gm,'

    $1

    ')).replace(/^## (.+)$/gm,'

    $1

    ')).replace(/^# (.+)$/gm,'

    $1

    ')).replace(/\*\*(.+?)\*\*/g,'$1')).replace(/\*(.+?)\*/g,"$1")).replace(/`(.+?)`/g,'$1')).replace(/^> (.+)$/gm,'
    $1
    ')).replace(/^- (.+)$/gm,'
  • $1
  • ')).replace(/^\d+\. (.+)$/gm,'
  • $1
  • ')).replace(/---/g,'
    ')).replace(/\n{2,}/g,'

    '))+"

    ")}window.forumSubmitPost=async function(){if(!window._forumSubmitting){var e=Date.now();if(e-g<3e4)"function"==typeof showToast&&showToast("⏳ Wait 30 seconds between posts");else{g=e,window._forumSubmitting=!0;var t=document.getElementById("forumPostStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o=document.getElementById("forumHoneypot");if(o&&o.value)t&&(t.innerHTML='Something went wrong. Please try again.');else if(window._forumFormOpenTime&&Date.now()-window._forumFormOpenTime<5e3)t&&(t.innerHTML='Please take a moment to write your post.');else{var n=(document.getElementById("forumNewTitle").value||"").trim(),i=(document.getElementById("forumNewBody").value||"").trim(),a=(document.getElementById("forumNewLink").value||"").trim(),l=document.getElementById("forumNewCat").value;if("function"==typeof sanitizeInput&&(n=sanitizeInput(n),i=sanitizeInput(i)),!n||n.length<5)t&&(t.innerHTML='Title must be at least 5 characters');else if(!r(n)||i&&!r(i))t&&(t.innerHTML='Post contains inappropriate language. Keep it clean!');else{a&&!/^https?:\/\//i.test(a)&&(a="https://"+a);var c=parseInt(localStorage.getItem("btc_forum_post_count")||"0"),d=localStorage.getItem("btc_forum_post_date")||"",u=(new Date).toISOString().split("T")[0];if(d!==u&&(c=0),c>=5)t&&(t.innerHTML='You\'ve reached the daily post limit (5). Try again tomorrow!');else{t&&(t.innerHTML='Posting...');try{var p=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",m=void 0!==currentUser&¤tUser&¤tUser.points||0,h=await db.collection("forum_posts").add({title:n,body:i.substring(0,2e3),link:a.substring(0,200)||null,category:l,authorId:auth.currentUser.uid,authorName:p,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:m,upvotes:0,voters:[],replyCount:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()});if(localStorage.setItem("btc_forum_post_count",(c+1).toString()),localStorage.setItem("btc_forum_post_date",u),"function"==typeof awardPoints&&awardPoints(10,"📝 Forum post"),"function"==typeof awardTickets&&awardTickets(5,"📝 Forum post"),forumNotifyMentions(i,"forum_post",h.id,n),db.collection("users").doc(auth.currentUser.uid).update({forumPosts:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumPosts=(currentUser.forumPosts||0)+1),"function"==typeof window._raidOnForumPost&&window._raidOnForumPost(),"function"==typeof window.nachoGlobalAnnounce){var f=s(n).substring(0,80),y=s(i).substring(0,120);window.nachoGlobalAnnounce("🗣️ New Forum Post: "+f+" by "+s(p)+": "+y+(i.length>120?"...":"")+" ➡️ [Open PlebTalk](#forum)")}forumBack()}catch(e){t&&(t.innerHTML='Error posting. Try again.')}}}}}else t&&(t.innerHTML='You must be signed in')}}},window._forumReplyingTo=null,window.forumReplyToReply=function(e,t){window._forumReplyingTo={replyId:e,authorName:t};var o=document.getElementById("forumReplyIndicator");o&&(o.style.display="flex",o.querySelector("span").textContent="↩ Replying to "+t);var n=document.getElementById("forumReplyInput");n&&(n.focus(),n.placeholder="Reply to "+t+"...")},window.forumCancelReplyTo=function(){window._forumReplyingTo=null;var e=document.getElementById("forumReplyIndicator");e&&(e.style.display="none");var t=document.getElementById("forumReplyInput");t&&(t.placeholder="Write a reply...")},window.forumSubmitReply=async function(e){if(!window._forumReplySubmitting){window._forumReplySubmitting=!0;var t=document.getElementById("forumReplyStatus"),o=document.getElementById("forumReplyInput");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&o){var n=o.value.trim();if(!n||n.length<2)return t&&(t.innerHTML='Reply is too short'),void(window._forumReplySubmitting=!1);if(!r(n))return t&&(t.innerHTML='Reply contains inappropriate language'),void(window._forumReplySubmitting=!1);t&&(t.innerHTML='Posting...');try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0,s={postId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:a,upvotes:0,voters:[],createdAt:firebase.firestore.FieldValue.serverTimestamp()},l=window._forumReplyingTo;l&&l.replyId&&(s.parentReplyId=l.replyId,s.parentAuthorName=l.authorName||""),await db.collection("forum_replies").add(s),await db.collection("forum_posts").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Forum reply");var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";if(l&&l.replyId){try{var u=await db.collection("forum_replies").doc(l.replyId).get();u.exists&&u.data().authorId&&"function"==typeof sendNotification&&sendNotification(u.data().authorId,"reply",c+' replied to your comment on "'+(d?(d.title||"").substring(0,40):"a post")+'"',"forum_post",e)}catch(e){}d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",c+' replied in your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e)}else d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",c+' replied to your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e);forumNotifyMentions(n,"forum_post",e,d?d.title:""),db.collection("users").doc(auth.currentUser.uid).update({forumReplies:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumReplies=(currentUser.forumReplies||0)+1),o.value="",window.forumCancelReplyTo(),t&&(t.innerHTML='✅ Reply posted!'),h(e)}catch(e){t&&(t.innerHTML='Error posting reply')}window._forumReplySubmitting=!1}else window._forumReplySubmitting=!1}},window.forumVotePost=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_posts").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your post "'+(a.title||"").substring(0,40)+'"',"forum_post",e)}}d&&d.id===e?forumViewPost(e):forumLoadPosts()}catch(e){}},window.forumVoteReply=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_replies").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;-1!==n.indexOf(i)?await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)}):await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)}),d&&h(d.id)}catch(e){}},window.forumDeletePost=async function(e){if(auth&&auth.currentUser){var o=t();if(confirm(o?"Admin: Delete this post and all its replies?":"Delete your post? This cannot be undone."))try{var n=await db.collection("forum_replies").where("postId","==",e).get(),i=db.batch();n.forEach(function(e){i.delete(e.ref)}),i.delete(db.collection("forum_posts").doc(e)),await i.commit(),"function"==typeof showToast&&showToast("🗑️ Post deleted"),forumBack()}catch(e){"function"==typeof showToast&&showToast("Error deleting post")}}},window.forumDeleteReply=async function(e,o){if(auth&&auth.currentUser){var n=t();if(confirm(n?"Admin: Delete this reply?":"Delete your reply? This cannot be undone."))try{await db.collection("forum_replies").doc(e).delete(),await db.collection("forum_posts").doc(o).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Reply deleted"),d&&h(o)}catch(e){"function"==typeof showToast&&showToast("Error deleting reply")}}},window.forumSwitchTab=function(e){u=e,renderForum()};var y=["Content must be Bitcoin-focused or Bitcoin-adjacent","Minimum 500 words, maximum 10,000 words","No promotion of altcoins, scams, or affiliate spam","Original content only — no plagiarism","No hate speech or personal attacks","Author grants the archive a non-exclusive license to display the content","Moderators may remove content that violates these guidelines"];async function b(e){var o=document.getElementById("articleReplies");if(o)try{var n=await db.collection("article_replies").where("articleId","==",e).orderBy("createdAt","asc").limit(50).get();if(n.empty)return void(o.innerHTML='
    No comments yet. Be the first!
    ');var i="";n.forEach(function(o){var n=o.data(),a="function"==typeof getLevel?getLevel(n.authorPoints||0):{emoji:"🟢"},r=n.createdAt&&n.createdAt.toDate?"function"==typeof timeAgo?timeAgo(n.createdAt.toDate()):n.createdAt.toDate().toLocaleDateString():"",l=auth&&auth.currentUser&&(auth.currentUser.uid===n.authorId||t());i+='
    "+a.emoji+" "+s(n.authorName||"Anon")+'· '+r+""+(l?"':"")+'
    '+T(s(n.body).replace(/\n/g,"
    ").replace(/(https?:\/\/[^\s<]+)/g,'$1'))+"
    "}),o.innerHTML=i}catch(e){o.innerHTML='
    Error loading comments
    '}}function v(e){for(var t="",o=0;o",t+='
    ',t+='
    ',t+='
    '+B(n.sats)+"
    ",t+='
    sats
    ',t+="
    ",t+='
    ',t+='
    '+S(n.title)+"
    ",t+='
    ',t+='@'+S(n.user.name)+"",t+="·",t+=""+i+"",n.ncomments>0&&(t+="·",t+="💬 "+n.ncomments+""),a&&(t+="·",t+=''+S(a)+""),r&&(t+=''+S(r)+""),t+="
    ",t+='',t+="
    "}return t}function w(e,t){for(var o="",n=0;n',o+='
    ',o+='@'+S(i.user.name)+"",o+="·",o+=""+k(i.createdAt)+"",i.sats>0&&(o+="·",o+='⚡ '+B(i.sats)+""),o+="
    ",i.text&&(o+='
    '+x(i.text)+"
    "),o+="",i.comments&&i.comments.comments&&i.comments.comments.length>0&&(o+=w(i.comments.comments,t+1))}return o}function x(e){if(!e)return"";var t=S(e);return'

    '+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/^#{3}\s+(.+)$/gm,'

    $1
    ')).replace(/^#{2}\s+(.+)$/gm,'
    $1
    ')).replace(/^#{1}\s+(.+)$/gm,'
    $1
    ')).replace(/\*\*\*(.+?)\*\*\*/g,"$1")).replace(/\*\*(.+?)\*\*/g,"$1")).replace(/\*(.+?)\*/g,"$1")).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/`([^`]+)`/g,'$1')).replace(/\n\n/g,'

    ')).replace(/\n/g,"
    "))+"

    "}function k(e){var t=Math.floor((Date.now()-new Date(e).getTime())/1e3);return t<60?"just now":t<3600?Math.floor(t/60)+"m ago":t<86400?Math.floor(t/3600)+"h ago":Math.floor(t/86400)+"d ago"}function B(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"k":String(e)}function S(e){return e?e.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""):""}function T(e){return e&&-1!==e.indexOf("@")?e.replace(/(<[^>]+>)|(@([a-zA-Z0-9_\-\.]{2,20}))/g,function(e,t,o,n){return t||'"+o+""}):e}window.articleNew=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void("function"==typeof showToast&&showToast("🔒 Sign in to write articles"));if((void 0!==currentUser&¤tUser&¤tUser.points||0)<100)"function"==typeof showToast&&showToast("📝 You need 100+ points to publish articles. Keep exploring!");else{var e=null;try{e=JSON.parse(localStorage.getItem("btc_article_draft"))}catch(e){}var t=document.getElementById("forumContainer");if(t){var o="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;",n='
    ';n+='',n+='

    ✍️ Write an Article

    ',n+='
    ',n+='',n+='',n+='
    ';var i=e&&e.tags?e.tags:[];p.forEach(function(e){var t=-1!==i.indexOf(e);n+=""}),n+="
    ",n+='
    ',n+='
    0 words · Min 500
    ',n+='',n+='
    📋 Content Guidelines
    ',y.forEach(function(e){n+='
    • '+e+"
    "}),n+='
    ',n+='
    ',n+='
    ',n+="
    ",t.innerHTML=n,document.getElementById("main").scrollTop=0;var a=document.getElementById("articleBody");a&&(a.addEventListener("input",function(){var e=this.value.trim().split(/\s+/).filter(function(e){return e.length>0}).length,t=document.getElementById("articleWordCount");t&&(t.textContent=e+" words · Min 500")}),window._articleAutoSave=setInterval(function(){articleSaveDraft(!0)},3e4))}}},window.toggleArticleTag=function(e,t){if(-1!==e.style.borderColor.indexOf("var(--accent)")||-1!==e.style.color.indexOf("var(--accent)"))e.style.border="1px solid var(--border)",e.style.background="none",e.style.color="var(--text-muted)";else{if(document.querySelectorAll('#articleTagsContainer button[style*="accent-bg"]').length>=3)return void("function"==typeof showToast&&showToast("Max 3 tags"));e.style.border="1px solid var(--accent)",e.style.background="var(--accent-bg)",e.style.color="var(--accent)"}},window.articleInsert=function(e,t,o){var n=document.getElementById("articleBody");if(n){n.focus();var i=n.selectionStart,a=n.selectionEnd,r=n.value.substring(i,a),s=r||o,l=e+s+t;n.setRangeText(l,i,a,"select"),r||(n.selectionStart=i+e.length,n.selectionEnd=i+e.length+s.length),n.dispatchEvent(new Event("input"))}},window.articleInsertLink=function(){var e=document.getElementById("articleBody");if(e){var t=e.value.substring(e.selectionStart,e.selectionEnd),o=document.getElementById("articleLinkDialog");o&&o.remove();var n=document.createElement("div");n.id="articleLinkDialog",n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",n.onclick=function(e){e.target===n&&n.remove()};var i="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";n.innerHTML='

    🔗 Insert Link

    ',document.body.appendChild(n),setTimeout(function(){document.getElementById("linkDialogUrl").focus()},100)}},window.articleDoInsertLink=function(){var e=(document.getElementById("linkDialogText").value||"").trim()||"link",t=(document.getElementById("linkDialogUrl").value||"").trim();if(t){t.match(/^https?:\/\//)||(t="https://"+t);var o=document.getElementById("articleBody");if(o){var n="["+e+"]("+t+")",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleLinkDialog").remove()}else"function"==typeof showToast&&showToast("Enter a URL")},window.articleInsertImage=function(){var e=document.getElementById("articleImageDialog");e&&e.remove();var t=document.createElement("div");t.id="articleImageDialog",t.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",t.onclick=function(e){e.target===t&&t.remove()};var o="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";t.innerHTML='

    🖼️ Insert Image

    Or upload from device:
    ',document.body.appendChild(t),setTimeout(function(){var e=document.getElementById("imageDialogFile");e&&e.addEventListener("change",function(){var e=this.files[0];if(e)if(e.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var t=document.getElementById("imageDialogPreview"),o=document.getElementById("imageDialogBtn");if(o&&(o.disabled=!0,o.textContent="Uploading..."),"undefined"!=typeof firebase&&firebase.storage&&void 0!==auth&&auth.currentUser)firebase.storage().ref("article-images/"+auth.currentUser.uid+"/"+Date.now()+"_"+e.name.replace(/[^a-zA-Z0-9._-]/g,"_")).put(e).then(function(e){return e.ref.getDownloadURL()}).then(function(e){document.getElementById("imageDialogUrl").value=e,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image"),"function"==typeof showToast&&showToast("✅ Image uploaded!")}).catch(function(e){"function"==typeof showToast&&showToast("Upload failed: "+(e.message||"Unknown error")),o&&(o.disabled=!1,o.textContent="Insert Image")});else{var n=new FileReader;n.onload=function(e){document.getElementById("imageDialogUrl").value=e.target.result,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image")},n.readAsDataURL(e)}}}),document.getElementById("imageDialogUrl").focus()},100)},window.articleDoInsertImage=function(){var e=(document.getElementById("imageDialogUrl").value||"").trim(),t=(document.getElementById("imageDialogAlt").value||"").trim()||"image";if(e){var o=document.getElementById("articleBody");if(o){var n="\n!["+t+"]("+e+")\n",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleImageDialog").remove()}else"function"==typeof showToast&&showToast("Enter an image URL or upload a file")},window.toggleArticlePreview=function(){var e=document.getElementById("articleBody"),t=document.getElementById("articlePreviewArea"),o=document.getElementById("articlePreviewBtn");e&&t&&("none"===t.style.display?(t.innerHTML=f(e.value),t.style.display="block",e.style.display="none",o.textContent="Edit"):(t.style.display="none",e.style.display="",o.textContent="Preview"))},window.articleSaveDraft=function(e){var t=(document.getElementById("articleTitle")||{}).value||"",o=(document.getElementById("articleSubtitle")||{}).value||"",n=(document.getElementById("articleBody")||{}).value||"",i=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&i.push(e.getAttribute("data-tag"))}),(t||n)&&(localStorage.setItem("btc_article_draft",JSON.stringify({title:t,subtitle:o,body:n,tags:i,savedAt:Date.now()})),e||"function"!=typeof showToast||showToast("💾 Draft saved!"))},window.articleSubmit=async function(){if(!window._articleSubmitting){var e=document.getElementById("articleStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var t=(document.getElementById("articleTitle").value||"").trim(),o=(document.getElementById("articleSubtitle").value||"").trim(),n=(document.getElementById("articleBody").value||"").trim(),i=document.getElementById("articleTerms");if(!t||t.length<10)e&&(e.innerHTML='Title must be at least 10 characters');else{var a=n.split(/\s+/).filter(function(e){return e.length>0}).length;if(a<500)e&&(e.innerHTML='Article must be at least 500 words (currently '+a+")");else if(a>1e4)e&&(e.innerHTML='Article must be under 10,000 words');else{var l=[];if(document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&l.push(e.getAttribute("data-tag"))}),l.length<1)e&&(e.innerHTML='Select at least 1 tag');else if(i&&i.checked)if(r(t)&&r(n)){window._articleSubmitting=!0,e&&(e.innerHTML='Publishing...');try{var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",d=void 0!==currentUser&¤tUser&¤tUser.points||0,p=void 0!==currentUser&¤tUser&¤tUser.profilePic?currentUser.profilePic:"",m="",h=document.getElementById("articleCover");if(h&&h.files&&h.files[0]){var g=h.files[0];if(g.size>3145728)return e&&(e.innerHTML='Cover image too large (max 3MB)'),void(window._articleSubmitting=!1);e&&(e.innerHTML='Uploading cover...');try{var f=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),y=await f.put(g);m=await y.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}e&&(e.innerHTML='Publishing article...');var b={title:t.substring(0,120),subtitle:o.substring(0,200),body:n.substring(0,5e4),tags:l.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),authorId:auth.currentUser.uid,authorName:c,authorPoints:d,authorPic:p,upvotes:0,voters:[],replyCount:0,tipTotal:0,status:"published",pinned:!1,agreedToTerms:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp(),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};m&&(b.coverUrl=m),await db.collection("articles").add(b),localStorage.removeItem("btc_article_draft"),window._articleAutoSave&&clearInterval(window._articleAutoSave),"function"==typeof awardPoints&&awardPoints(30,"📝 Article published"),"function"==typeof awardTickets&&awardTickets(20,"📝 Article published");var v=parseInt(localStorage.getItem("btc_articles_published")||"0");localStorage.setItem("btc_articles_published",String(v+1)),"function"==typeof showToast&&showToast("📝 Article published!"),u="articles",renderForum()}catch(t){console.error("Article submit error:",t),e&&(e.innerHTML='Error publishing: '+s(t.message)+"")}window._articleSubmitting=!1}else e&&(e.innerHTML='Content contains inappropriate language');else e&&(e.innerHTML='You must agree to the content guidelines')}}}else e&&(e.innerHTML='Sign in required')}},window.articleView=async function(e){var o=document.getElementById("forumContainer");if(o&&db){o.innerHTML='
    Loading article...
    ';try{var n=await db.collection("articles").doc(e).get();if(!n.exists)return void(o.innerHTML='
    Article not found
    ');var i=n.data();i.id=e;var a="function"==typeof getLevel?getLevel(i.authorPoints||0):{emoji:"🟢"},r=Math.max(1,Math.round((i.wordCount||500)/200)),l=i.createdAt&&i.createdAt.toDate?i.createdAt.toDate().toLocaleDateString():"",c=auth&&auth.currentUser&&auth.currentUser.uid===i.authorId,d=t(),u=auth&&auth.currentUser&&-1!==(i.voters||[]).indexOf(auth.currentUser.uid),p='
    ';if(p+='',i.coverUrl&&(p+='
    Cover
    '),p+='

    '+s(i.title)+"

    ",i.subtitle&&(p+='
    '+s(i.subtitle)+"
    "),p+='
    ',i.authorPic&&(p+=''),p+='
    "+a.emoji+" "+s(i.authorName||"Anon")+'
    '+l+" · "+r+" min read · "+(i.wordCount||0).toLocaleString()+" words
    ",c&&(p+="'),d&&(p+=""),p+="
    ",i.tags&&i.tags.length&&(p+='
    ',i.tags.forEach(function(e){p+=''+s(e)+""}),p+="
    "),p+='
    '+f(i.body)+"
    ",p+='
    ',p+="","function"==typeof tipButtonHtml&&(p+=tipButtonHtml({recipientName:i.authorName,recipientUid:i.authorId,context:"article",contextId:e,label:"⚡ Tip Author",size:"md"})),(c||d)&&(p+="'),p+="
    ",p+='

    💬 Comments

    ',p+='
    Loading comments...
    ',auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(p+='
    '),p+="
    ",o.innerHTML=p,document.getElementById("main").scrollTop=0,b(e),auth&&auth.currentUser){var m="btc_article_read_"+e;localStorage.getItem(m)||setTimeout(function(){document.getElementById("articleReplies")&&(localStorage.setItem(m,"1"),"function"==typeof awardPoints&&awardPoints(5,"📖 Read an article"),"function"==typeof showToast&&showToast("📖 +5 points for reading!"))},6e4)}}catch(e){console.error("Article view error:",e),o.innerHTML='
    Error loading article
    '}}},window.articleVote=async function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{var t=db.collection("articles").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your article "'+(a.title||"").substring(0,40)+'"',"article",e)}}articleView(e)}catch(e){}else"function"==typeof showToast&&showToast("🔒 Sign in to upvote")},window.articleSubmitReply=async function(e){var t=document.getElementById("articleReplyInput"),o=document.getElementById("articleReplyStatus");if(t&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var n=t.value.trim();if(!n||n.length<2)o&&(o.innerHTML='Comment too short');else if(r(n))try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0;await db.collection("article_replies").add({articleId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorPoints:a,createdAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("articles").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Article comment");try{var s=await db.collection("articles").doc(e).get();if(s.exists&&s.data().authorId&&"function"==typeof sendNotification){var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(s.data().authorId,"comment",l+' commented on your article "'+(s.data().title||"").substring(0,40)+'"',"article",e)}forumNotifyMentions(n,"article",e,s&&s.exists?s.data().title:"")}catch(e){}t.value="",o&&(o.innerHTML='✅ Comment posted!'),b(e)}catch(e){o&&(o.innerHTML='Error posting comment')}else o&&(o.innerHTML='Inappropriate language')}},window.articleDeleteReply=async function(e,t){if(confirm("Delete this comment?"))try{await db.collection("article_replies").doc(e).delete(),await db.collection("articles").doc(t).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Comment deleted"),b(t)}catch(e){}},window.articleEdit=async function(e){try{var o=await db.collection("articles").doc(e).get();if(!o.exists)return;var n=o.data();if(auth.currentUser.uid!==n.authorId&&!t())return;localStorage.setItem("btc_article_draft",JSON.stringify({title:n.title,subtitle:n.subtitle||"",body:n.body,tags:n.tags||[]})),window._articleEditId=e,articleNew(),setTimeout(function(){var e=document.querySelector('[onclick="articleSubmit()"]');e&&(e.textContent="✏️ Update Article",e.setAttribute("onclick","articleUpdate()"))},100)}catch(e){"function"==typeof showToast&&showToast("Error loading article for edit")}},window.articleUpdate=async function(){var e=window._articleEditId;if(e){var t=document.getElementById("articleStatus"),o=(document.getElementById("articleTitle").value||"").trim(),n=(document.getElementById("articleSubtitle").value||"").trim(),i=(document.getElementById("articleBody").value||"").trim(),a=i.split(/\s+/).filter(function(e){return e.length>0}).length;if(!o||o.length<10)t&&(t.innerHTML='Title must be at least 10 characters');else if(a<500)t&&(t.innerHTML='Min 500 words');else{var r=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&r.push(e.getAttribute("data-tag"))}),t&&(t.innerHTML='Updating...');try{var s=null,l=document.getElementById("articleCover");if(l&&l.files&&l.files[0]){var c=l.files[0];if(c.size>3145728)return void(t&&(t.innerHTML='Cover too large (max 3MB)'));t&&(t.innerHTML='Uploading cover...');try{var d=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),u=await d.put(c);s=await u.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}var p={title:o.substring(0,120),subtitle:n.substring(0,200),body:i.substring(0,5e4),tags:r.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};s&&(p.coverUrl=s),t&&(t.innerHTML='Saving...'),await db.collection("articles").doc(e).update(p),localStorage.removeItem("btc_article_draft"),window._articleEditId=null,"function"==typeof showToast&&showToast("✏️ Article updated!"),articleView(e)}catch(e){t&&(t.innerHTML='Error updating')}}}},window.articleTogglePin=async function(e,t){try{await db.collection("articles").doc(e).update({pinned:t}),"function"==typeof showToast&&showToast(t?"📌 Article pinned!":"📌 Article unpinned"),articleView(e)}catch(e){}},window.articleDelete=async function(e){if(confirm("Delete this article and all its comments? This cannot be undone."))try{var t=await db.collection("article_replies").where("articleId","==",e).get(),o=db.batch();t.forEach(function(e){o.delete(e.ref)}),o.delete(db.collection("articles").doc(e)),await o.commit(),"function"==typeof showToast&&showToast("🗑️ Article deleted"),u="articles",renderForum()}catch(e){"function"==typeof showToast&&showToast("Error deleting article")}},window.loadStackerNewsFeed=function(e,t,o){var n=document.getElementById("snFeed");if(n){var i="https://embed-proxy.needcreations.workers.dev/api/sn?sort="+encodeURIComponent(e)+"&when="+encodeURIComponent(t)+"&limit=21";o&&(i+="&sub="+encodeURIComponent(o)),fetch(i).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.items&&e.data.items.items){var t=e.data.items.items;t.length?n.innerHTML=v(t):n.innerHTML='
    No posts found
    '}else n.innerHTML='
    Could not load Stacker News feed
    '}).catch(function(){n.innerHTML='
    Failed to load feed.
    '})}},window.snDoSearch=function(){var e=document.getElementById("snSearchInput");if(e){var t=e.value.trim();t.length<2||(window._snSearchQuery=t,renderForum())}},window.snClearSearch=function(){window._snSearchQuery="",renderForum()},window.snOpenPost=function(e){var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading post...
    ',fetch("https://embed-proxy.needcreations.workers.dev/api/sn/item?id="+e).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.item){var o=e.data.item;!function(e,t){var o='
    ';if(o+='',o+='
    ',o+='

    '+S(t.title)+"

    ",o+='
    ',o+='⚡ '+B(t.sats)+" sats",o+="·",o+='@'+S(t.user.name)+"",o+="·",o+=""+k(t.createdAt)+"",t.ncomments>0&&(o+="·",o+="💬 "+t.ncomments+" comments"),o+="
    ",t.url){var n="";try{n=new URL(t.url).hostname.replace("www.","")}catch(e){}o+='🔗 '+S(n||t.url)+" ↗"}t.text&&(o+='
    '+x(t.text)+"
    "),o+='",o+="
    ",t.comments&&t.comments.comments&&t.comments.comments.length>0&&(o+='
    ',o+='
    💬 Comments ('+t.ncomments+")
    ",o+=w(t.comments.comments,0),o+="
    "),o+="
    ",e.innerHTML=o,e.scrollTop=0}(t,o)}else t.innerHTML='
    Post not found.
    '}).catch(function(){t.innerHTML='
    Failed to load post. ·
    '}))},window.forumMentionClick=function(e){e&&void 0!==db&&db.collection("users").where("username","==",e).limit(1).get().then(function(t){t.empty?db.collection("users").where("username_lower","==",e.toLowerCase()).limit(1).get().then(function(t){t.empty?"function"==typeof showToast&&showToast("User @"+e+" not found"):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){}):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){})},window.forumNotifyMentions=async function(e,t,o,n){if(e&&void 0!==db&&auth&&auth.currentUser){var i=e.match(/@([a-zA-Z0-9_\-\.]{2,20})/g);if(i){var a={},r=[];i.forEach(function(e){var t=e.substring(1).toLowerCase();a[t]||(a[t]=!0,r.push(e.substring(1)))});for(var s=auth.currentUser.uid,l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone",c=(n||"").substring(0,40),d=0;d=",e).where("username","<=",e+"").limit(5).get().then(function(e){e.forEach(function(e){var t=e.data();t.username&&!a[e.id]&&(a[e.id]=!0,i.push({uid:e.id,username:t.username,points:t.points||0}))})}).catch(function(){}).then(function(){++r>=t.length&&(i.sort(function(e,t){return(t.points||0)-(e.points||0)}),_.activeTextarea&&function(e,t){if(E(),t&&0!==t.length){_.results=t,_.selectedIdx=0;var o=document.createElement("div");o.id="mentionDropdown",o.style.cssText="position:absolute;z-index:9999;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,0.4);overflow:hidden;max-height:220px;overflow-y:auto;min-width:200px;",t.forEach(function(e,t){var n=document.createElement("div");n.className="mention-item",n.setAttribute("data-idx",t);var i="function"==typeof getLevel?getLevel(e.points||0):{emoji:"🟢"};n.innerHTML=''+i.emoji+' '+s(e.username)+""+(e.points?''+(e.points||0).toLocaleString()+" XP":""),n.style.cssText="padding:10px 14px;cursor:pointer;display:flex;align-items:center;gap:8px;font-size:0.85rem;color:var(--text);transition:background 0.15s;"+(0===t?"background:var(--accent-bg);":""),n.onmouseenter=function(){_.selectedIdx=t,C()},n.onmousedown=function(e){e.preventDefault(),A(t)},o.appendChild(n)});var n=e.getBoundingClientRect();window.pageYOffset||document.documentElement.scrollTop,o.style.position="fixed",o.style.left=n.left+"px",o.style.top=n.bottom+4+"px",o.style.width=Math.min(n.width,320)+"px",document.body.appendChild(o),_.dropdown=o}}(_.activeTextarea,i.slice(0,5)))})})}}(t.prefix)},300))}),e.addEventListener("keydown",function(e){_.dropdown&&("ArrowDown"===e.key?(e.preventDefault(),_.selectedIdx=Math.min(_.selectedIdx+1,_.results.length-1),C()):"ArrowUp"===e.key?(e.preventDefault(),_.selectedIdx=Math.max(_.selectedIdx-1,0),C()):"Enter"===e.key||"Tab"===e.key?_.results.length>0&&_.selectedIdx>=0&&(e.preventDefault(),A(_.selectedIdx)):"Escape"===e.key&&E())}),e.addEventListener("blur",function(){setTimeout(E,200)}))}function M(){var e=["forumNewBody","forumReplyInput","articleReplyInput"];if(e.forEach(function(e){var t=document.getElementById(e);t&&z(t)}),"undefined"!=typeof MutationObserver){var t=new MutationObserver(function(){e.forEach(function(e){var t=document.getElementById(e);t&&z(t)})}),o=document.getElementById("forumContainer");if(o)t.observe(o,{childList:!0,subtree:!0});else{var n=new MutationObserver(function(){var o=document.getElementById("forumContainer");o&&(n.disconnect(),t.observe(o,{childList:!0,subtree:!0}),e.forEach(function(e){var t=document.getElementById(e);t&&z(t)}))});n.observe(document.body,{childList:!0,subtree:!0})}}}var P=document.createElement("style");P.textContent=".forum-mention{color:var(--accent);cursor:pointer;font-weight:600;transition:opacity 0.15s;}.forum-mention:hover{opacity:0.8;text-decoration:underline;}",document.head.appendChild(P),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(M,1e3)}):setTimeout(M,1e3)}(),function(){"use strict";var e=[{emoji:"⚡",title:"Bitcoin Payments Only",desc:"All transactions use Bitcoin (Lightning or on-chain). No fiat payments. Buyers and sellers handle payment directly — LightningMart is not an escrow or payment processor."},{emoji:"🚫",title:"No Illegal or Illicit Items",desc:"Strictly prohibited: drugs, weapons, stolen goods, counterfeit items, hacking tools, malware, pirated content, illegal services of any kind. Violation results in immediate ban and may be reported to authorities."},{emoji:"🔞",title:"No Adult or Sexual Content",desc:"No selling or advertising of sexual services, adult content, escort services, or any sexually explicit material. This is an educational Bitcoin marketplace — keep it appropriate for all ages."},{emoji:"🎭",title:"No Fraud or Misrepresentation",desc:"List items honestly. No fake photos, misleading descriptions, bait-and-switch tactics, or counterfeit goods. If it's used, say so. If it has defects, disclose them."},{emoji:"🛡️",title:"Buyer & Seller Safety",desc:"Meet in public places for local trades. Never share your seed phrase, private keys, or send Bitcoin before receiving the item. Use Lightning for instant, irreversible payments."},{emoji:"💰",title:"No Money Laundering or Wash Trading",desc:"No using the marketplace to launder money, create fake transactions, artificially inflate sales, or manipulate pricing. All listings must represent genuine offers."},{emoji:"📋",title:"Accurate Listings",desc:"Titles must clearly describe the item. Include condition, shipping options, and price in sats. One listing per item — no duplicate spam listings."},{emoji:"🤝",title:"Be Professional & Respectful",desc:"Communicate clearly with buyers/sellers. Respond to messages promptly. No harassment, threats, discrimination, or abusive language in any marketplace interaction."},{emoji:"🚫",title:"No Financial Products or Securities",desc:'No selling of financial instruments, investment schemes, MLM/pyramid schemes, "guaranteed returns," or unregistered securities. This is a marketplace for goods and services, not investments.'},{emoji:"⚖️",title:"Disputes & Moderation",desc:"LightningMart does not mediate disputes. All sales are final between buyer and seller. Report fraudulent listings using the 🚩 button. Moderators may remove listings and ban users without notice."}];function t(t){for(var o='

    LightningMart Rules

    Read before buying or selling
    ',n=0;n'+i.emoji+'
    '+i.title+'
    '+i.desc+"
    "}o+='',o+="
    ";var a=document.createElement("div");a.id="marketRulesOverlay",a.innerHTML=o,document.body.appendChild(a)}function o(){if(!auth||!auth.currentUser)return!1;var e=auth.currentUser.email||"";return"needcreations@gmail.com"===e||"info.603btc@gmail.com"===e}window.acceptMarketRules=function(){localStorage.setItem("btc_market_rules_accepted","true");var e=document.getElementById("marketRulesOverlay");e&&e.remove()},window.showMarketRulesBtn=function(){t()};var n=[{id:"educational",name:"Educational Products",emoji:"🎓",desc:"Learn Bitcoin with the best tools"},{id:"general",name:"Other Products",emoji:"🛒",desc:"Buy & sell everything else"},{id:"merchants",name:"More Bitcoin Merchants",emoji:"🏪",desc:"Browse more Bitcoin merchants"},{id:"noderunners",name:"Even More Merchants",emoji:"🌐",desc:"Bitcoin shops via Node Runners"}],i=[{id:"books",name:"Books",emoji:"📚",section:"educational"},{id:"courses",name:"Courses & Workshops",emoji:"🎓",section:"educational"},{id:"hardware_edu",name:"Hardware Wallets",emoji:"🔐",section:"educational"},{id:"nodes",name:"Node Kits & Guides",emoji:"💻",section:"educational"},{id:"kids",name:"Kids & Family",emoji:"👨‍👩‍👧‍👦",section:"educational"},{id:"tools",name:"Learning Tools",emoji:"🧰",section:"educational"},{id:"edu_other",name:"Other Educational",emoji:"📦",section:"educational"},{id:"mining",name:"Mining Equipment",emoji:"⛏️",section:"general"},{id:"merch",name:"Apparel & Merch",emoji:"👕",section:"general"},{id:"art",name:"Art & Collectibles",emoji:"🎨",section:"general"},{id:"stickers",name:"Stickers & Prints",emoji:"🖼️",section:"general"},{id:"services",name:"Services",emoji:"🛠️",section:"general"},{id:"electronics",name:"Electronics & Tech",emoji:"📱",section:"general"},{id:"other",name:"Other",emoji:"📦",section:"general"}],a=[{id:"new",label:"New",color:"#22c55e"},{id:"like_new",label:"Like New",color:"#84cc16"},{id:"good",label:"Good",color:"#eab308"},{id:"fair",label:"Fair",color:"#f97316"},{id:"for_parts",label:"For Parts",color:"#ef4444"}],r=[{id:"newest",label:"Newest First"},{id:"price_low",label:"Price: Low → High"},{id:"price_high",label:"Price: High → Low"},{id:"popular",label:"Most Saved"}];function s(e,t){"listing"===e?history.pushState({channel:"marketplace",mktView:"listing",listingId:t},"","#marketplace/listing/"+t):"my"===e&&history.pushState({channel:"marketplace",mktView:"my"},"","#marketplace/my")}window.handleMarketplacePopState=function(e,t){if(e&&"listing"===e.mktView&&e.listingId)return renderMarketplace({listingId:e.listingId,_noHistory:!0}),!0;if(e&&"my"===e.mktView)return showMyListings(!0),!0;if(t&&0===t.indexOf("marketplace/listing/")){var o=t.replace("marketplace/listing/","");return renderMarketplace({listingId:o,_noHistory:!0}),!0}return"marketplace/my"===t?(showMyListings(!0),!0):(renderMarketplace({_noHistory:!0}),!0)};var l=!1,c=!1;function d(e,t){var o=document.getElementById(e),n=document.getElementById(t);if(o&&n){var i=n.getBoundingClientRect();o.style.cssText="position:fixed;left:"+i.left+"px;top:"+i.top+"px;width:"+i.width+"px;height:"+i.height+"px;z-index:100;border-radius:12px;overflow:hidden;border:1px solid var(--border);background:var(--card-bg);pointer-events:auto;",o._reposition=function(){var e=n.getBoundingClientRect();o.style.left=e.left+"px",o.style.top=e.top+"px",o.style.width=e.width+"px",o.style.height=e.height+"px"},window.addEventListener("scroll",o._reposition,!0),window.addEventListener("resize",o._reposition)}}function u(e){var t=document.getElementById(e);t&&(t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t._reposition&&(window.removeEventListener("scroll",t._reposition,!0),window.removeEventListener("resize",t._reposition),t._reposition=null))}function p(e){var t=document.getElementById("forumContainer");if(t){t.style.display="block",t.innerHTML="";var l=e.category||"all",c=e.search||"",p=e.sort||"newest",m=e.listingId||null;if(m)return e._noHistory||s("listing",m),void function(e,t){e.innerHTML='
    Loading...
    ',db.collection("marketplace").doc(t).get().then(function(n){if(n.exists){var r={id:n.id,...n.data()},s=a.find(function(e){return e.id===r.condition}),l=s?s.label:"",c=s?s.color:"var(--text-faint)",d=i.find(function(e){return e.id===r.category}),u=d?d.emoji+" "+d.name:"📦 Other",p=-1!==safeJSON("btc_market_saved",[]).indexOf(r.id),m=void 0!==auth&&auth.currentUser&&auth.currentUser.uid===r.sellerUid,g=o(),f=r.priceSats>=1e6?(r.priceSats/1e6).toFixed(2)+"M sats":r.priceSats>=1e3?Math.floor(r.priceSats/1e3)+"K sats":r.priceSats.toLocaleString()+" sats",y="";try{var b=parseFloat(localStorage.getItem("btc_last_price")||"0");b>0&&(y=' (~$'+(r.priceSats/1e8*b).toFixed(2)+")")}catch(e){}var v=h(r.createdAt?r.createdAt.toDate():new Date),w='
    ';w+='',r.imageUrl?w+="
    ]/g,""):"")+"') center/contain no-repeat;background-color:var(--bg-side);border-radius:14px;border:1px solid var(--border);margin-bottom:16px;\">
    ":w+='
    '+(d?d.emoji:"📦")+"
    ",w+='
    '+escapeHtml(r.title)+'
    ⚡ '+f+y+"
    ",w+='
    '+l+''+u+'🕐 '+v+""+(r.shipping?'📦 Ships':"")+(r.localPickup?'📍 Local pickup':"")+"
    ",w+='
    Description
    '+escapeHtml(r.description||"No description provided.")+"
    ",w+='
    Seller
    '+(r.sellerName?r.sellerName.charAt(0).toUpperCase():"?")+'
    '+escapeHtml(r.sellerName||"Anonymous")+"
    "+(r.sellerRank?'
    '+escapeHtml(r.sellerRank)+"
    ":"")+'
    👤
    ',m?w+='
    ':(w+='
    '+(g?"':"")+"
    ",w+='
    🛡️ Safety Tips: Use escrow when possible. Never send payment before receiving the item. Meet in public if trading locally. Report suspicious listings.
    ',r.lightningAddress&&(w+='
    ⚡ This seller accepts Lightning payments
    ')),w+="
    ",e.innerHTML=w,db.collection("marketplace").doc(t).update({views:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})}else e.innerHTML='
    😕
    Listing not found
    '}).catch(function(){e.innerHTML='
    Error loading listing.
    '})}(t,m);var g='
    ';g+='
    Home
    ',g+='
    Lightning Mart
    Buy & sell with Bitcoin ⚡
    ',g+='
    ';var f=e.section||"merchants";if("all"!==l&&"all"===f){var y=i.find(function(e){return e.id===l});y&&(f=y.section)}g+='
    ';for(var b=[{id:"all",name:"All",emoji:"🛒"}].concat(n),v=0;v'+w.emoji+" "+w.name+""}if(g+="
    ",u("gmIframeWrap"),u("nrIframeWrap"),"merchants"===f)return g+='
    ',g+="
    ",t.innerHTML=g,void d("gmIframeWrap","gmIframePlaceholder");if("noderunners"===f)return g+='
    ',g+="",t.innerHTML=g,void d("nrIframeWrap","nrIframePlaceholder");var k="all"===f?i:i.filter(function(e){return e.section===f});g+='
    ',g+="';for(var B=0;B'+S.emoji+" "+S.name+""}g+="
    ","educational"!==f&&"all"!==f||(g+='
    🛒
    603BTC Pleb Shop
    Bitcoin educational products, merch & gear
    '),g+='
    Loading...
    ",g+='
    ',g+="",t.innerHTML=g,function(e,t,o,n){var r=document.getElementById("marketListings"),s=document.getElementById("marketResultCount");if(r&&void 0!==db){for(var l='
    ',c=0;c<6;c++)l+='
    ';l+="
    ",r.innerHTML=l;var d=db.collection("marketplace").where("status","==","active");e&&"all"!==e&&(d=d.where("category","==",e)),(d="price_low"===o?d.orderBy("priceSats","asc"):"price_high"===o?d.orderBy("priceSats","desc"):"popular"===o?d.orderBy("saves","desc"):d.orderBy("createdAt","desc")).limit(50).get().then(function(e){var o=[];if(e.forEach(function(e){o.push({id:e.id,...e.data()})}),n&&"all"!==n){var l=i.filter(function(e){return e.section===n}).map(function(e){return e.id});o=o.filter(function(e){return-1!==l.indexOf(e.category)})}if(t){var c=t.toLowerCase();o=o.filter(function(e){return(e.title||"").toLowerCase().includes(c)||(e.description||"").toLowerCase().includes(c)})}if(s&&(s.textContent=o.length+" listing"+(1!==o.length?"s":"")),0!==o.length){var d=safeJSON("btc_market_saved",[]);r.innerHTML=o.map(function(e){var t,o=-1!==d.indexOf(e.id),n=a.find(function(t){return t.id===e.condition}),r=n?n.color:"var(--text-faint)",s=n?n.label:"",l=i.find(function(t){return t.id===e.category}),c=l?l.emoji:"📦";return t=e.priceSats>=1e6?(e.priceSats/1e6).toFixed(2)+"M sats":e.priceSats>=1e3?Math.floor(e.priceSats/1e3)+"K sats":e.priceSats.toLocaleString()+" sats","
    '+(e.imageUrl?"
    ]/g,""):"")+"') center/cover;border-bottom:1px solid var(--border);\">
    ":'
    '+c+"
    ")+'
    '+escapeHtml(e.title)+'
    ⚡ '+t+"
    "+(satsToUSD(e.priceSats)?'
    '+satsToUSD(e.priceSats)+"
    ":'
    ')+'
    '+s+"'+(o?"❤️":"🤍")+"
    "}).join("")}else r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){console.error("Marketplace load error:",e),r&&("failed-precondition"===e.code?(console.log("Trying fallback marketplace query..."),db.collection("marketplace").orderBy("createdAt","desc").limit(50).get().then(function(e){var t=[];e.forEach(function(e){var o=e.data();o.id=e.id,"active"===o.status&&t.push(o)}),t.length>0?(r.innerHTML=t.map(function(e){return"
    '+escapeHtml(e.title||"Untitled")+'
    ⚡ '+(e.priceSats||0).toLocaleString()+" sats
    "}).join(""),s&&(s.textContent=t.length+" listing"+(1!==t.length?"s":""))):r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){r.innerHTML='
    ⚙️ Marketplace needs a database index.
    This is a one-time setup.

    Click here to create the index manually if requested →
    '})):r.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+". Try refreshing.
    ")})}}(l,c,p,f)}}window._hideMarketIframes=function(){u("gmIframeWrap"),u("nrIframeWrap")},window.renderMarketplace=function(e){if(e=e||{},document.getElementById("forumContainer")){if(l||(l=!0,"true"!==localStorage.getItem("btc_market_rules_accepted")&&t()),function(){if(!c){if(c=!0,!document.getElementById("gmIframeWrap")){var e=document.createElement("div");e.id="gmIframeWrap",e.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",e.innerHTML='',document.body.appendChild(e)}if(!document.getElementById("nrIframeWrap")){var t=document.createElement("div");t.id="nrIframeWrap",t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t.innerHTML='',document.body.appendChild(t)}}}(),"function"==typeof showSkeletonLoader&&!e.listingId&&!e.search)return showSkeletonLoader("forumContainer"),void setTimeout(()=>p(e),300);p(e)}},window.showCreateListing=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to create a listing!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e='
    📝 Create Listing
    — or paste an image URL —
    ',t=document.createElement("div");t.innerHTML=e,document.body.appendChild(t.firstChild)};var m=0;function h(e){var t=Math.floor((new Date-e)/1e3);if(t<60)return"just now";var o=Math.floor(t/60);if(o<60)return o+"m ago";var n=Math.floor(o/60);if(n<24)return n+"h ago";var i=Math.floor(n/24);return i<30?i+"d ago":Math.floor(i/30)+"mo ago"}window.submitListing=function(){if(!window._mktSubmitting){var e=Date.now();if(e-m<6e4)"function"==typeof showToast&&showToast("⏳ Wait 60 seconds between listings");else{m=e;var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim();"function"==typeof sanitizeInput&&(t=sanitizeInput(t),a=sanitizeInput(a));var r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),l=document.getElementById("mktShipping").checked,c=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1||o>1e11)showToast("Price must be between 1 and 100B sats");else{var d=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anonymous",u="";if(void 0!==currentUser&¤tUser&&"function"==typeof getLevel){var p=getLevel(currentUser.points||0);u=p.emoji+" "+p.name}var h={title:t,description:a,priceSats:o,category:n,condition:i,imageUrl:r||null,lightningAddress:s||null,shipping:l,localPickup:c,sellerUid:auth.currentUser.uid,sellerName:d,sellerRank:u,status:"active",views:0,saves:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()};db.collection("marketplace").add(h).then(function(){window._mktUploadedImage=null;var e=document.getElementById("createListingOverlay");e&&e.remove(),"function"==typeof showToast&&showToast("🛒 Listing posted!"),"function"==typeof awardPoints&&awardPoints(15,"🛒 Marketplace listing!"),auth&&auth.currentUser&&(db.collection("users").doc(auth.currentUser.uid).update({marketListings:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketListings=(currentUser.marketListings||0)+1)),renderMarketplace()}).catch(function(e){console.error("Marketplace post error:",e),showToast("Error posting: "+(e.code||e.message||"Unknown error"))})}}}},window.toggleMarketSave=function(e){var t=safeJSON("btc_market_saved",[]),o=t.indexOf(e);-1!==o?(t.splice(o,1),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(-1)}).catch(function(e){console.error("[marketplace] Error:",e)})):(t.push(e),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})),localStorage.setItem("btc_market_saved",JSON.stringify(t)),void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({marketSaved:t}).catch(function(e){console.error("[marketplace] Error:",e)});var n=document.getElementById("forumContainer");n&&n.innerHTML.includes("marketListings")&&renderMarketplace()},window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return showToast("🔒 Sign in to contact sellers"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var o='
    💬 Message '+escapeHtml(t)+'
    ',n=document.createElement("div");n.innerHTML=o,document.body.appendChild(n.firstChild)},window.sendMarketMessage=function(e){var t=(document.getElementById("mktMessage").value||"").trim();if(t){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Buyer";db.collection("marketplace").doc(e).get().then(function(n){if(n.exists){var i=n.data().sellerUid||"";return db.collection("marketplace_messages").add({listingId:e,buyerUid:auth.currentUser.uid,sellerUid:i,buyerName:o,message:t,createdAt:firebase.firestore.FieldValue.serverTimestamp(),read:!1})}showToast("Listing not found")}).then(function(){var t=document.getElementById("contactSellerOverlay");t&&t.remove(),showToast("💬 Message sent to seller!"),"function"==typeof sendNotification&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists&&t.data().sellerUid){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(t.data().sellerUid,"dm","🛒 "+o+" is interested in your listing!","marketplace",e)}}).catch(function(){}),db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1)}).catch(function(){showToast("Error sending message. Try again.")})}else showToast("Please write a message")},window.showMyListings=function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){e||s("my");var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading your listings...
    ',db.collection("marketplace").where("sellerUid","==",auth.currentUser.uid).orderBy("createdAt","desc").get().then(function(e){var o,n='
    ';n+='',n+='
    📋 My Listings
    ',e.empty?n+='
    No listings yet. Create one!
    ':e.forEach(function(e){var t=e.data(),o="active"===t.status?"#22c55e":"sold"===t.status?"#ef4444":"var(--text-faint)";n+='
    '+escapeHtml(t.title)+'
    ⚡ '+(t.priceSats||0).toLocaleString()+' sats
    👁️ '+(t.views||0)+" views · ❤️ "+(t.saves||0)+' saves
    '+(t.status||"active")+""+("active"===t.status?"':"")+"
    "}),n+='
    💬 Messages
    ',n+='
    Loading messages...
    ',n+="
    ",t.innerHTML=n,(o=document.getElementById("myMarketMessages"))&&db.collection("marketplace_messages").orderBy("createdAt","desc").limit(20).get().then(function(e){var t=auth.currentUser.uid,n=[];e.forEach(function(e){var o=e.data();o.buyerUid===t&&n.push({id:e.id,...o,role:"buyer"})}),db.collection("marketplace").where("sellerUid","==",t).get().then(function(i){var a=[];i.forEach(function(e){a.push(e.id)}),e.forEach(function(e){var o=e.data();-1!==a.indexOf(o.listingId)&&o.buyerUid!==t&&n.push({id:e.id,...o,role:"seller"})}),0!==n.length?o.innerHTML=n.map(function(e){var t=e.createdAt?h(e.createdAt.toDate()):"";return'
    '+("seller"===e.role?"📩 From ":"📤 To seller · ")+escapeHtml(e.buyerName||"Buyer")+''+t+'
    '+escapeHtml(e.message)+"
    "}).join(""):o.innerHTML='
    No messages yet.
    '})})}).catch(function(e){console.error("My listings error:",e),"failed-precondition"===e.code?t.innerHTML='
    ⚙️ Setting up marketplace database (index)...
    Please refresh in 1 minute.
    ':t.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+"
    "}))}else showToast("🔒 Sign in to see your listings")},window.markSold=function(e){db.collection("marketplace").doc(e).update({status:"sold"}).then(function(){showToast("✅ Marked as sold!"),showMyListings()})},window.editListing=function(e){auth&&auth.currentUser&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists){var n=t.data();n.sellerUid===auth.currentUser.uid||o()?(showCreateListing(),setTimeout(function(){var t=document.getElementById("mktTitle"),o=document.getElementById("mktPrice"),i=document.getElementById("mktCategory"),a=document.getElementById("mktCondition"),r=document.getElementById("mktDesc"),s=document.getElementById("mktImage"),l=document.getElementById("mktLightning"),c=document.getElementById("mktShipping"),d=document.getElementById("mktLocal");t&&(t.value=n.title||""),o&&(o.value=n.priceSats||"",updateMktPriceUSD()),i&&(i.value=n.category||""),a&&(a.value=n.condition||""),r&&(r.value=n.description||""),s&&n.imageUrl&&!n.imageUrl.startsWith("data:")&&(s.value=n.imageUrl||""),l&&(l.value=n.lightningAddress||""),c&&(c.checked=!!n.shipping),d&&(d.checked=!!n.local);var u=document.getElementById("createListingOverlay");if(u){var p=u.querySelector('div[style*="font-size:1.2rem"]');p&&(p.textContent="✏️ Edit Listing")}var m=u?u.querySelector('button[onclick*="submitListing"]'):null;m&&(m.textContent="✏️ Update Listing",m.onclick=function(){updateExistingListing(e)})},100)):showToast("You can only edit your own listings")}else showToast("Listing not found")}).catch(function(e){showToast("Error loading listing: "+(e.message||"Unknown"))})},window.updateExistingListing=function(e){var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim(),r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),l=document.getElementById("mktShipping").checked,c=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1)showToast("Please enter a price in sats");else{var d={title:t.substring(0,80),priceSats:o,category:n,condition:i,description:a.substring(0,1e3),lightningAddress:s,shipping:l,local:c,updatedAt:firebase.firestore.FieldValue.serverTimestamp()};r&&(d.imageUrl=r),db.collection("marketplace").doc(e).update(d).then(function(){var t=document.getElementById("createListingOverlay");t&&t.remove(),showToast("✅ Listing updated!"),window._mktUploadedImage=null,renderMarketplace({listingId:e})}).catch(function(e){showToast("Error updating: "+(e.message||"Unknown"))})}},window.deleteListing=function(e){if(auth&&auth.currentUser){var t=o();confirm(t?"Admin: Delete this listing?":"Delete this listing?")&&db.collection("marketplace").doc(e).update({status:"deleted",deletedBy:t?"admin":"owner",deletedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){showToast("🗑️ Listing deleted"),renderMarketplace()})}},window.updateMktPriceUSD=function(){var e=parseInt(document.getElementById("mktPrice").value)||0,t=document.getElementById("mktPriceUSD");if(t)if(e<=0)t.textContent="";else{var o=parseFloat(localStorage.getItem("btc_last_price")||"0");if(o<=0)return fetch("https://mempool.space/api/v1/prices").then(function(e){return e.json()}).then(function(e){e&&e.USD&&(localStorage.setItem("btc_last_price",e.USD),updateMktPriceUSD())}).catch(function(e){console.error("[marketplace] Error:",e)}),void(t.textContent="Loading USD price...");var n=e/1e8*o;t.textContent="≈ $"+n.toFixed(2)+" USD"}},window.satsToUSD=function(e){var t=parseFloat(localStorage.getItem("btc_last_price")||"0");return t<=0||!e?"":"~$"+(e/1e8*t).toFixed(2)},window.handleMktImageUpload=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var o=new FileReader;o.onload=function(e){var t=new Image;t.onload=function(){var e=t.width,o=t.height;e>800&&(o=Math.round(800*o/e),e=800);var n=document.createElement("canvas");n.width=e,n.height=o,n.getContext("2d").drawImage(t,0,0,e,o);var i=n.toDataURL("image/jpeg",.8),a=document.getElementById("mktImagePreview"),r=document.getElementById("mktImagePreviewImg");a&&r&&(r.src=i,a.style.display="block"),window._mktUploadedImage=i;var s=document.getElementById("mktImage");s&&(s.value="")},t.src=e.target.result},o.readAsDataURL(t)}},window._plebShopOpen=!1,window._togglePlebShop=function(){var e=document.getElementById("plebShopEmbed"),t=document.getElementById("plebShopToggle");e&&(window._plebShopOpen=!window._plebShopOpen,window._plebShopOpen?(e.style.display="block",e.style.height="calc(100vh - 280px)",e.style.minHeight="500px",e.querySelector("iframe")||(e.innerHTML=''),t&&(t.textContent="Close Shop",t.style.background="var(--border)")):(e.style.height="0",e.style.minHeight="0",setTimeout(function(){e.style.display="none"},300),t&&(t.textContent="Open Shop",t.style.background="var(--accent)")))},window.clearMktImage=function(){window._mktUploadedImage=null;var e=document.getElementById("mktImagePreview");e&&(e.style.display="none");var t=document.getElementById("mktImageFile");t&&(t.value="")}}();var MSG_CONFIG={onlineThreshold:3e5,awayThreshold:9e5,presenceInterval:6e4,maxMsgLength:500,maxMsgsPerHour:30,maxConvoHistory:100,unreadPollInterval:3e4,maxNewConvosPerDay:5,newAccountCooldownMs:864e5,minPointsToDM:50,duplicateWindowMs:5e3},SUSPICIOUS_PATTERNS=[/send\s*(?:me|ur|your)\s*(?:btc|bitcoin|sats|seed|key|phrase)/i,/(?:double|triple|multiply)\s*(?:your|ur)\s*(?:btc|bitcoin|sats|crypto)/i,/(?:free|win|won|claim|airdrop)\s*(?:btc|bitcoin|sats|crypto|nft)/i,/(?:invest|deposit)\s*(?:now|today|here)\b/i,/(?:guaranteed|100%)\s*(?:return|profit|roi)/i,/send\s*\d+\s*(?:btc|sats)\s*(?:to|and)\s*(?:get|receive|earn)/i,/(?:seed|private)\s*(?:phrase|key)\s*(?:here|now|please|share)/i,/(?:validate|verify|sync)\s*(?:your|ur)\s*(?:wallet|account)/i,/(?:connect|link)\s*(?:your|ur)\s*(?:wallet|metamask|phantom)/i,/(?:nigerian|prince|inheritance|lottery)\s*(?:fund|money|payment)/i],SUSPICIOUS_URLS=[/bit\.ly|tinyurl|t\.co|goo\.gl|is\.gd|buff\.ly|ow\.ly|rebrand\.ly/i,/(?:discord\.gift|discordapp\.gift|nitro.*free)/i,/(?:steamcommunity|steampowered).*(?:gift|trade|login)/i,/(?:wallet|connect|validate|sync|claim|airdrop).*(?:\.com|\.io|\.xyz|\.site|\.app)/i,/(?:dapp|defi|swap|bridge|mint).*(?:\.com|\.io|\.xyz|\.site)/i],BLOCKED_CONTENT=[/(?:child|minor|underage).*(?:porn|nude|nsfw)/i,/(?:kill|murder|attack|bomb|shoot).*(?:yourself|someone|them|people|school)/i,/\b(?:doxx|doxing|swat)\b/i,/\b(?:nigger|nigga|faggot|kike|spic|wetback|chink|gook|towelhead|raghead|beaner|coon|darkie|zipperhead)\b/i,/\b(?:white\s*power|white\s*supremacy|sieg\s*heil|race\s*war|ethnic\s*cleansing|final\s*solution)\b/i,/\b(?:gas\s*the|death\s*to)\s+\w+/i,/\b(?:heil\s*hitler|genocide)\b/i,/\b(?:i\s*(?:will|wanna|gonna|want\s*to)\s*(?:kill|hurt|stab|shoot|beat|attack|find)\s*(?:you|u|him|her|them))\b/i,/\b(?:i\s*know\s*where\s*(?:you|u)\s*live)\b/i,/\b(?:watch\s*your\s*back|you(?:'re|\s*are)\s*dead)\b/i,/\b(?:track\s*(?:you|u)\s*down|come\s*find\s*(?:you|u))\b/i,/\b(?:kill\s*myself|cut(?:ting)?\s*myself|slit\s*my\s*wrist|hang\s*myself|end\s*my\s*life)\b/i,/\b(?:want(?:a)?\s*(?:to\s*)?die|kys|kill\s*yourself)\b/i,/\b(?:self[\s-]*harm|overdose\s*on|jump\s*off\s*a)\b/i,/\b(?:blowjob|handjob|gangbang|threesome|deepthroat|rimjob|creampie)\b/i,/\b(?:send\s*(?:me\s*)?nudes|dick\s*pic|show\s*(?:me\s*)?(?:your|ur)\s*(?:body|tits|boobs|ass|pussy|dick))\b/i,/\b(?:wanna|want\s*to|lets)\s*(?:fuck|bang|screw|bone|smash)\b/i,/\b(?:suck\s*my|sit\s*on\s*my|bend\s*over|get\s*on\s*your\s*knees)\b/i,/\b(?:masturbat|fingering|bondage|bdsm|fetish|dominatrix)\b/i,/\b(?:escort|prostitut|hooker|camgirl|sexting)\b/i],PII_PATTERNS=[/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:phone|number|address|email|ssn|social|zip|location|real name|full name|home|where.*live)/i,/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:id|passport|driver.?s?\s*license|bank|routing|account\s*number|credit\s*card|debit\s*card)/i,/(?:dm|message|text|call|contact)\s*(?:me\s+)?(?:on|at|@)\s*(?:whatsapp|telegram|signal|insta|instagram|snap|snapchat|facebook|messenger|wechat|line)\b/i,/(?:my|here(?:'s| is))\s*(?:phone|number|cell|whatsapp|telegram|signal)\s*(?:is|:|\s)\s*[\+\d\(\)\-\s]{7,}/i,/(?:my|here(?:'s| is))\s*(?:email|e-mail)\s*(?:is|:|\s)\s*\S+@\S+\.\S+/i,/(?:my|here(?:'s| is))\s*(?:address|location)\s*(?:is|:)/i];function containsSuspiciousLink(e){for(var t=e.match(/https?:\/\/[^\s<>"{}|\\^`\[\]]+/gi)||[],o=0;o]*>/g,"")).trim()).length>MSG_CONFIG.maxMsgLength&&(e=e.substring(0,MSG_CONFIG.maxMsgLength)),e):""}function containsPII(e){for(var t=0;t"']+)/gi,function(e){return''+e+""})}function _getDailyConvoLog(){try{var e=localStorage.getItem("btc_dm_daily_log");if(!e)return{date:"",recipients:[]};var t=JSON.parse(e),o=(new Date).toISOString().slice(0,10);return t.date!==o?{date:o,recipients:[]}:t}catch(e){return{date:(new Date).toISOString().slice(0,10),recipients:[]}}}function _logNewConvo(e){var t=_getDailyConvoLog();t.date=(new Date).toISOString().slice(0,10),-1===t.recipients.indexOf(e)&&t.recipients.push(e),localStorage.setItem("btc_dm_daily_log",JSON.stringify(t))}function _canStartNewConvo(e){var t=_getDailyConvoLog();return-1!==t.recipients.indexOf(e)||t.recipients.length
    🚨
    "Friends in Distress" Scam
    Scammers will impersonate people you know and trust — your friends, family, even coworkers. They can:
    • Clone their profile picture, name, and bio
    • Copy their writing style and messages
    • Use AI-generated voice clones that sound exactly like them
    • Create fake emergencies — "I\'m stuck," "I need help," "send me Bitcoin and I\'ll pay you back"
    The scammer will pressure you to act fast so you don\'t have time to think or verify. They prey on your emotions and trust.
    🛡️ How to protect yourself:
    NEVER send Bitcoin to anyone claiming to be in distress over a message
    Verify their identity through a separate channel — call them, video chat, or meet in person
    Real friends will understand if you take time to verify
    Bitcoin transactions are irreversible — once sent, it\'s gone forever
    • If it feels urgent and emotional, that\'s exactly what the scammer wants
    ',document.body.appendChild(e.firstChild)};var _lastSentMsg={text:"",time:0};function _isDuplicateMessage(e){var t=Date.now();return e===_lastSentMsg.text&&t-_lastSentMsg.time
    Why are you reporting this user?
    ',i=document.createElement("div");return i.innerHTML=n,void document.body.appendChild(i.firstChild)}},window.submitReport=function(e,t,o){var n=document.getElementById("reportModal");if(n&&n.remove(),db&&auth&&auth.currentUser){var i=void 0!==currentUser&¤tUser?currentUser.username:"Anonymous";db.collection("reports").add({reportedUid:e,reportedName:t,reporterUid:auth.currentUser.uid,reporterName:i,reason:o,createdAt:firebase.firestore.FieldValue.serverTimestamp(),status:"pending"}).then(function(){"function"==typeof showToast&&showToast("🚩 Report submitted. Thank you for keeping the community safe."),blockUser(e,t)}).catch(function(){"function"==typeof showToast&&showToast("Failed to submit report")})}};var _presenceTimer=null;function updatePresence(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e="false"!==localStorage.getItem("btc_online_status");try{e?db.collection("users").doc(auth.currentUser.uid).update({lastSeen:firebase.firestore.FieldValue.serverTimestamp(),isOnline:!0}).catch(function(){}):db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:null}).catch(function(){})}catch(e){}}}function startPresenceTracking(){updatePresence(),_presenceTimer&&clearInterval(_presenceTimer),_presenceTimer=setInterval(updatePresence,MSG_CONFIG.presenceInterval),window.addEventListener("beforeunload",function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db)try{db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){}}),document.addEventListener("visibilitychange",function(){"visible"===document.visibilityState&&updatePresence()})}function profileStat(e,t,o){return'
    '+e+'
    '+t+'
    '+o+"
    "}window.toggleOnlineStatus=function(){updatePresence()},window.getOnlineStatus=function(e){if(!e)return{status:"offline",color:"#6b7280",label:"Offline",dot:"⚫"};var t=e.toDate?e.toDate().getTime():"number"==typeof e?e:new Date(e).getTime(),o=Date.now()-t;return o'},window.showUserProfile=function(e){if(e&&db){var t=document.createElement("div");t.innerHTML='
    Loading profile...
    ',document.body.appendChild(t.firstChild),db.collection("users").doc(e).get().then(function(t){if(!t.exists)return(m=document.getElementById("userProfileModal"))&&m.remove(),void("function"==typeof showToast&&showToast("User not found"));var o=t.data(),n=getOnlineStatus(o.lastSeen),i="function"==typeof getLevel?getLevel(o.points||0):{name:"Newbie",emoji:"🌱"},a=o.createdAt&&o.createdAt.toDate?o.createdAt.toDate().toLocaleDateString():"Unknown",r="function"==typeof escapeHtml?escapeHtml(o.displayBadge||o.equippedBadge||""):(o.displayBadge||o.equippedBadge||"").replace(//g,">").replace(/"/g,"""),s=0;o.visibleBadges&&(s+=o.visibleBadges.length),o.hiddenBadges&&(s+=o.hiddenBadges.length);var l="";if(r){var c=r;if(void 0!==HIDDEN_BADGES&&r.length>5){var d=HIDDEN_BADGES.find(e=>e.id===r);d&&(c=d.emoji)}l='
    '+c+' '+i.emoji+"
    "}else l='
    '+i.emoji+"
    ";var u,p,m,h=auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&auth.currentUser.uid!==e,g=h?_canAccountDM():{ok:!1},f='
    '+l+'
    '+escapeHtml(o.username||"Bitcoiner")+'
    '+i.name+" · "+(o.points||0).toLocaleString()+' XP
    '+n.label+"
    "+(o.bio?'
    About
    '+escapeHtml(o.bio)+"
    ":"")+(o.twitter||o.nostr||o.website?'
    '+(o.twitter?'𝕏 '+escapeHtml(o.twitter)+"":"")+(o.nostr?'🟣 Nostr':"")+(o.website&&!/^(javascript|data|vbscript|blob):/i.test(o.website.trim())?'🌐 Website':"")+"
    ":"")+'
    '+profileStat("🏅",s,"Badges")+profileStat("📖",Array.isArray(o.visitedChannelsList)?o.visitedChannelsList.length:Array.isArray(o.readChannels)?o.readChannels.length:0,"Channels")+profileStat("🎟️",o.orangeTickets||0,"Tickets")+'
    '+profileStat("🗣️",o.forumPosts||0,"Posts")+profileStat("🔥",(o.streak||0)+"("+(o.bestStreak||o.streak||0)+")","Streak")+profileStat("📅",a,"Joined")+"
    "+(o.pvpWins||o.pvpLosses?'
    '+profileStat("⚔️",(o.pvpWins||0)+"W","PVP Wins")+profileStat("💀",(o.pvpLosses||0)+"L","PVP Losses")+profileStat("📊",((o.pvpWins||0)+(o.pvpLosses||0)>0?Math.round((o.pvpWins||0)/((o.pvpWins||0)+(o.pvpLosses||0))*100):0)+"%","Win Rate")+"
    ":"")+(o.predictions&&o.predictions.total?(p=(u=o.predictions).total>0?Math.round(u.correct/u.total*100):0,'
    '+profileStat("📈",u.total,"Predictions")+profileStat("🎯",p+"%","Accuracy")+profileStat("🔥",u.bestStreak||u.streak||0,"Best Streak")+"
    "):"")+(o.lightningAddress||o.lightning?(window._profileTipData={recipientName:o.username||"Bitcoiner",recipientUid:e,lightningAddress:o.lightningAddress||o.lightning||"",label:"Tip "+(o.username||"Bitcoiner"),context:"profile"},'
    '+escapeHtml(o.lightningAddress||o.lightning)+'
    "):"")+(h&&g.ok?"":h&&!g.ok?'
    '+escapeHtml(g.reason)+"
    ":auth&&auth.currentUser&&!auth.currentUser.isAnonymous?"":"")+(h?'
    '+(isUserBlocked(e)?"":"")+"
    ':"")+"
    ";(m=document.getElementById("userProfileModal"))&&m.remove();var y=document.createElement("div");y.innerHTML=f,document.body.appendChild(y.firstChild)}).catch(function(t){console.error("Profile load error:",t);var o=document.getElementById("userProfileModal");o&&o.remove(),"function"==typeof showToast&&showToast("Could not load profile ["+e+"]: "+(t.message||"permission error"))})}},window._tipFromProfile=function(){var e=window._profileTipData;if(e){var t=document.getElementById("userProfileModal");t&&t.remove(),"function"==typeof showTipOverlay?showTipOverlay(e):"function"==typeof showToast&&showToast("⚡ Lightning tips still loading, try again in a moment")}};var _msgSentTimestamps=[];function checkRateLimit(){var e=Date.now();return(_msgSentTimestamps=_msgSentTimestamps.filter(function(t){return e-t<36e5})).length
    💬 '+escapeHtml(o)+'
    ⚠️ Never share your seed phrase, private keys, or send Bitcoin to strangers or "friends in distress."
    ',s=document.createElement("div");s.innerHTML=r,document.body.appendChild(s.firstChild),setTimeout(function(){var e=document.getElementById("dmInput");e&&e.focus()},300),loadDMMessages(e,n,t,o),db.collection("dm_conversations").doc(e).get().then(function(e){if(e.exists&&e.data().isBuddyMatch){var t=document.getElementById("dmWindow");if(!t)return;var o=t.querySelector('div[style*="rgba(234,179,8,0.1)"]');o&&(o.style.background="rgba(34,197,94,0.08)",o.style.borderColor="rgba(34,197,94,0.2)",o.style.color="#22c55e",o.innerHTML="🦌 Nacho is in this chat! Ask any Bitcoin question and Nacho will jump in. Teachers can add context to help learners.")}}).catch(function(){}),db.collection("users").doc(t).get().then(function(e){if(e.exists){var t=getOnlineStatus(e.data().lastSeen),o=document.getElementById("dmStatusDot");o&&(o.innerHTML='')}}).catch(function(){})}function loadDMMessages(e,t,o,n){var i=document.getElementById("dmMessages");i&&(i.innerHTML='
    Loading messages...
    ',window._dmUnsubscribe=db.collection("dm_conversations").doc(e).collection("messages").orderBy("createdAt","asc").limit(MSG_CONFIG.maxConvoHistory).onSnapshot(function(o){if(i.innerHTML="",o.empty)i.innerHTML='
    💬
    Start a conversation with '+escapeHtml(n)+'!
    Messages are private between you two.
    ';else{var a="";o.forEach(function(e){var o=e.data(),n=o.senderUid===t;if(n||o.isNachoAuto||"function"!=typeof isUserBlocked||!isUserBlocked(o.senderUid)){var r=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):new Date,s=r.toLocaleDateString();s!==a&&(i.innerHTML+='
    '+s+"
    ",a=s);var l=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),c="nacho-bot"===o.senderUid||!0===o.isNachoAuto,d=n||c||!containsScamPattern(o.text)&&!containsSuspiciousLink(o.text)?"":'
    ⚠️ This message may contain a scam. Never send money to strangers.
    ',u=n||c||!containsPII(o.text)?"":'
    ⚠️ This person is asking for personal info. Only share details for Lightning Mart transactions.
    ',p=c?"rgba(34,197,94,0.08)":n?"var(--accent)":"var(--card-bg)",m=c?"1px solid rgba(34,197,94,0.25)":"none",h=c?"var(--text)":n?"#fff":"var(--text)",g=c?'
    🦌 Nacho
    ':"",f=linkifyText(escapeHtml(o.text)).replace(/\n/g,"
    "),y="";o.imageUrl&&(y=''),i.innerHTML+='
    '+g+(f||"")+y+d+u+'
    '+l+"
    "}}),i.scrollTop=i.scrollHeight,markDMRead(e,t)}},function(e){i.innerHTML='
    💬
    Start a conversation!
    Send your first message below.
    '}))}window.openDM=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to send messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var o=_canAccountDM();if(o.ok)if(isUserBlocked(e))"function"==typeof showToast&&showToast("🚫 This user is blocked. Unblock them to message.");else if(_canStartNewConvo(e)){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";showDMWindow(getConversationId(n,e),e,t,n,i)}else"function"==typeof showToast&&showToast("⏳ You can only message "+MSG_CONFIG.maxNewConvosPerDay+" new people per day. This helps keep the community safe.");else"function"==typeof showToast&&showToast(o.reason)},window.closeDM=function(){window._dmUnsubscribe&&(window._dmUnsubscribe(),window._dmUnsubscribe=null);var e=document.getElementById("dmWindow");e&&e.remove()},window.handleDMImage=function(e,t,o,n){if(e&&e.files&&e.files[0]){var i=e.files[0];if(e.value="",i.type.startsWith("image/"))if(i.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var a=null;try{a=firebase.storage()}catch(e){}if(a){"function"==typeof showToast&&showToast("📷 Uploading image…");var r=auth.currentUser.uid,s=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",l=i.type.indexOf("png")>-1?"png":i.type.indexOf("gif")>-1?"gif":i.type.indexOf("webp")>-1?"webp":"jpg",c=Date.now()+"_"+Math.random().toString(36).substr(2,6)+"."+l,d=a.ref("dm-images/"+r+"/"+c),u=document.getElementById("dmMessages");u&&(u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML=""),(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),u.innerHTML+='
    📷
    Uploading…
    ',u.scrollTop=u.scrollHeight),d.put(i,{contentType:i.type}).then(function(e){return e.ref.getDownloadURL()}).then(function(e){var i=u&&u.querySelector("[data-dm-img-uploading]");i&&i.remove();var a=db.collection("dm_conversations").doc(t),l={senderUid:r,senderName:s,text:"",imageUrl:e,createdAt:firebase.firestore.FieldValue.serverTimestamp()},c={lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r};return c["unread_"+o]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(o,"dm","📷 Image from @"+s,"dm",t),a.update(c).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[r,o],lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r,participantNames:{}};return t.participantNames[r]=s,t.participantNames[o]=n,t["unread_"+o]=firebase.firestore.FieldValue.increment(1),a.set(t)}throw e}).then(function(){return a.collection("messages").add(l)}).then(function(){"function"==typeof showToast&&showToast("📷 Image sent!"),u&&document.getElementById("dmMessages")&&loadDMMessages(t,r,o,n)})}).catch(function(e){console.error("[DM Image] Upload failed:",e),"function"==typeof showToast&&showToast("Failed to send image: "+(e.message||"upload error"));var t=u&&u.querySelector("[data-dm-img-uploading]");t&&t.remove()})}else"function"==typeof showToast&&showToast("Image upload unavailable")}else"function"==typeof showToast&&showToast("Sign in to send images");else"function"==typeof showToast&&showToast("Only images are allowed")}},window.showDMGifPicker=function(e,t,o){var n=document.getElementById("dmGifPicker");if(n)n.remove();else{var i=document.createElement("div");i.id="dmGifPicker",i.style.cssText="position:fixed;bottom:80px;left:50%;transform:translateX(-50%);z-index:600000;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:16px;padding:12px;width:90%;max-width:360px;max-height:350px;display:flex;flex-direction:column;box-shadow:0 8px 32px rgba(0,0,0,0.5);",window._dmGifConvo={convoId:e,recipientUid:t,recipientName:o},i.innerHTML='
    Type to search or tap a category
    ',document.body.appendChild(i),document.getElementById("dmGifSearchInput").focus()}};var _dmGifSearchTimer=null;function markDMRead(e,t){db.collection("dm_conversations").doc(e).update({["unread_"+t]:0}).catch(function(){})}window.searchDMGifs=function(e){_dmGifSearchTimer&&clearTimeout(_dmGifSearchTimer);var t=document.getElementById("dmGifResults");if(t)if(!e||e.length<2)t.innerHTML='
    Type to search
    ';else{var o=document.getElementById("dmGifSearchInput");o&&o.value!==e&&(o.value=e),t.innerHTML='
    Searching...
    ',_dmGifSearchTimer=setTimeout(function(){fetch("https://g.tenor.com/v1/search?q="+encodeURIComponent(e)+"&key=LIVDSRZULELA&limit=20&media_filter=minimal").then(function(e){return e.json()}).then(function(e){if(e.results&&0!==e.results.length){for(var o="",n=0;n')}t.innerHTML=o||'
    No GIFs found
    '}else t.innerHTML='
    No GIFs found
    '}).catch(function(){t.innerHTML='
    Search failed
    '})},400)}},window.sendDMGifUrl=function(){var e=document.getElementById("dmGifUrlInput");e&&e.value.trim()&&sendDMGif(e.value.trim())},window.sendDMGif=function(e){if(e){var t=window._dmGifConvo;if(t){var o=document.getElementById("dmGifPicker");if(o&&o.remove(),auth&&auth.currentUser){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",a=t.convoId,r=t.recipientUid,s=t.recipientName,l=document.getElementById("dmMessages");if(l){var c=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});l.innerHTML+='
    '+c+"
    ",l.scrollTop=l.scrollHeight}var d=db.collection("dm_conversations").doc(a),u={senderUid:n,senderName:i,text:"",imageUrl:e,isGif:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp()},p={lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n};p["unread_"+r]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(r,"dm","GIF from @"+i,"dm",a),d.update(p).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[n,r],lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n,participantNames:{}};return t.participantNames[n]=i,t.participantNames[r]=s,t["unread_"+r]=firebase.firestore.FieldValue.increment(1),d.set(t)}throw e}).then(function(){return d.collection("messages").add(u)}).then(function(){l&&document.getElementById("dmMessages")&&loadDMMessages(a,n,r,s)}).catch(function(e){console.error("[DM GIF] Send failed:",e),"function"==typeof showToast&&showToast("Failed to send GIF")})}else"function"==typeof showToast&&showToast("Sign in to send GIFs")}else"function"==typeof showToast&&showToast("Error: no conversation context")}},window.sendDM=function(e,t,o){var n=document.getElementById("dmInput");if(n){var i=sanitizeMessage(n.value);if(i)if(i.length>MSG_CONFIG.maxMsgLength)"function"==typeof showToast&&showToast("Message too long (max "+MSG_CONFIG.maxMsgLength+" chars)");else if(_isDuplicateMessage(i))"function"==typeof showToast&&showToast("⏳ Message already sent");else if(isUserBlocked(t))"function"==typeof showToast&&showToast("🚫 You have blocked this user");else if(containsBlockedContent(i))"function"==typeof showToast&&showToast("⛔ Message contains prohibited content");else{if(containsPII(i)&&!confirm("⚠️ This message appears to contain or request personal information (phone numbers, addresses, emails, etc.).\n\nSharing personal info with strangers is risky. Only share contact details for Lightning Mart transactions.\n\nSend anyway?"))return;if(!containsScamPattern(i)||confirm("⚠️ This message contains patterns commonly used in scams. Are you sure you want to send it?"))if(containsSuspiciousLink(i)&&"function"==typeof showToast&&showToast("⚠️ Warning: Suspicious link detected. Be cautious with URLs."),checkRateLimit()){var a=auth.currentUser.uid,r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";n.value="",_msgSentTimestamps.push(Date.now()),_logNewConvo(t);var s=db.collection("dm_conversations").doc(e),l={senderUid:a,senderName:r,text:i,createdAt:firebase.firestore.FieldValue.serverTimestamp()},c={lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a};c["unread_"+t]=firebase.firestore.FieldValue.increment(1);var d={participants:[a,t],lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a,participantNames:{}};d.participantNames[a]=r,d.participantNames[t]=o,d["unread_"+t]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(t,"dm","💬 New message from @"+r,"dm",e);var u=document.getElementById("dmMessages");if(u){u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML="");var p=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),m=(new Date).toLocaleDateString(),h=u.querySelector("div[data-dm-date]:last-of-type");m!==(h?h.getAttribute("data-dm-date"):"")&&(u.innerHTML+='
    '+m+"
    "),u.innerHTML+='
    '+linkifyText(escapeHtml(i))+'
    '+p+"
    ",u.scrollTop=u.scrollHeight}s.update(c).catch(function(e){if("not-found"===e.code||"permission-denied"===e.code||-1!==e.message.indexOf("NOT_FOUND")||-1!==e.message.indexOf("No document to update")||-1!==e.message.indexOf("PERMISSION_DENIED"))return s.set(d,{merge:!0});throw e}).then(function(){return s.collection("messages").add(l)}).then(function(){u&&document.getElementById("dmMessages")&&loadDMMessages(e,a,t,o);var n=parseInt(localStorage.getItem("btc_dms_sent")||"0");localStorage.setItem("btc_dms_sent",String(n+1)),"function"==typeof checkBadges&&setTimeout(checkBadges,500)}).catch(function(e){console.error("DM send error:",e),"function"==typeof showToast&&showToast("Failed to send: "+(e.code||e.message||"Unknown error"));var t=u&&u.querySelector("[data-optimistic]");t&&t.remove()})}else"function"==typeof showToast&&showToast("⏳ Slow down! Max "+MSG_CONFIG.maxMsgsPerHour+" messages per hour.")}}},window.showInbox=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to see messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e=auth.currentUser.uid,t=document.getElementById("dmInbox");t&&t.remove();var o=document.createElement("div");o.innerHTML='
    📬 Messages
    Loading...
    ',document.body.appendChild(o.firstChild),db.collection("dm_conversations").where("participants","array-contains",e).orderBy("lastMessageTime","desc").limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");o&&(console.log("Inbox snap size:",t.size),t.empty?o.innerHTML='
    📬
    No messages yet
    Tap a user on the leaderboard to start chatting!
    ':(o.innerHTML="",t.forEach(function(t){var n=t.data(),i=n.participants.find(function(t){return t!==e}),a=n.participantNames&&n.participantNames[i]||"User",r=n["unread_"+e]||0,s=n.lastMessage||"";s.length>50&&(s=s.substring(0,50)+"...");var l=n.lastMessageTime?timeAgo(n.lastMessageTime):"",c=n.lastSenderUid===e,d=!0===n.isBuddyMatch,u=d?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+';" onmouseover="this.style.background=\'var(--card-bg)\'" onmouseout="this.style.background=\''+(r>0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+'\'">
    '+(d?"🦌":a.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(a)+u+'
    '+l+'
    0?"600":"400")+';white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">'+(c?"You: ":"")+escapeHtml(s)+"
    "+(r>0?'
    '+r+"
    ":"")+"
    "})))}).catch(function(t){console.error("Inbox load error:",t);var o=document.getElementById("dmInboxList");o&&("failed-precondition"!==t.code?o.innerHTML='
    💬
    No messages yet
    Tap a user on the leaderboard or in PlebTalk to start chatting!
    ':db.collection("dm_conversations").where("participants","array-contains",e).limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");if(o)if(t.empty)o.innerHTML='
    📬
    No messages yet
    ';else{o.innerHTML="";var n=[];t.forEach(function(e){n.push({id:e.id,...e.data()})}),n.sort(function(e,t){return(t.lastMessageTime||0)-(e.lastMessageTime||0)}),n.forEach(function(t){var n=t.participants.find(function(t){return t!==e}),i=t.participantNames&&t.participantNames[n]||"User",a=t["unread_"+e]||0,r=t.lastMessage||"";r.length>50&&(r=r.substring(0,50)+"...");var s=t.lastSenderUid===e,l=!0===t.isBuddyMatch,c=l?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":l?"rgba(34,197,94,0.03)":"none")+';">
    '+(l?"🦌":i.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(i)+c+'
    '+(s?"You: ":"")+escapeHtml(r)+"
    "+(a>0?'
    '+a+"
    ":"")+"
    "})}}).catch(function(e){var t=document.getElementById("dmInboxList");t&&(t.innerHTML='
    💬
    No messages yet
    ')}))})};var _unreadCount=0,_unreadTimer=null;function checkUnreadCount(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e=auth.currentUser.uid;db.collection("dm_conversations").where("participants","array-contains",e).get().then(function(t){var o=0;t.forEach(function(t){var n=t.data();o+=n["unread_"+e]||0}),_unreadCount=o,updateUnreadBadge()}).catch(function(){})}}function updateUnreadBadge(){document.querySelectorAll(".dm-unread-badge").forEach(function(e){_unreadCount>0?(e.textContent=_unreadCount>99?"99+":_unreadCount,e.style.display="inline-flex"):e.style.display="none"});var e=document.getElementById("bnavMsgBadge");e&&(_unreadCount>0?(e.textContent=_unreadCount,e.style.display="block"):e.style.display="none")}function startUnreadPolling(){checkUnreadCount(),_unreadTimer&&clearInterval(_unreadTimer),_unreadTimer=setInterval(checkUnreadCount,MSG_CONFIG.unreadPollInterval)}window.initMessaging=function(){startPresenceTracking(),restoreBlockedList(),setTimeout(startUnreadPolling,5e3)},void 0!==auth&&auth&&auth.currentUser&&initMessaging();const HIDDEN_BADGES=[{id:"nacho_friend",name:"Nacho's Friend",emoji:"🦌",pts:25,desc:"Interact with Nacho",hint:"Click on Nacho!",hidden:!1,check:function(){return"true"===localStorage.getItem("btc_nacho_clicked")}},{id:"genesis",name:"Genesis Reader",emoji:"📜",pts:75,desc:"Read the whitepaper channel",hint:"Open the Whitepaper channel",hidden:!1,check:function(){return"undefined"!=typeof currentChannelId&&"whitepaper"===currentChannelId}},{id:"nacho_curious",name:"Curious Deer",emoji:"❓",pts:50,desc:"Ask Nacho your first question",hint:"Ask Nacho anything!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=1}},{id:"ticket_bronze",name:"Ticket Fish",emoji:"🐟",pts:200,desc:"Earn 25 Orange Tickets",hint:"Spin daily + referrals!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=25},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,25)+"/25":"0/25"}},{id:"ticket_silver",name:"Ticket Shark",emoji:"🦈",pts:500,desc:"Earn 50 Orange Tickets",hint:"Keep spinning & referring!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=50},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,50)+"/50":"0/50"}},{id:"ticket_gold",name:"Ticket Whale",emoji:"🐋",pts:1e3,desc:"Earn 100 Orange Tickets",hint:"The ultimate ticket badge!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=100},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,100)+"/100":"0/100"}},{id:"nacho_10q",name:"Inquisitive Buck",emoji:"🔍",pts:200,desc:"Ask Nacho 10 questions",hint:"Keep asking Nacho!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=10},progress:function(){return Math.min(parseInt(localStorage.getItem("btc_nacho_questions")||"0"),10)+"/10"}},{id:"collector",name:"Collector",emoji:"💎",pts:150,desc:"Save 10+ topics to favorites",hint:"Star your favorite topics",hidden:!1,check:function(){return safeJSON("btc_favs",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_favs",[]).length,10)+"/10"}},{id:"first_post",name:"Town Crier",emoji:"📣",pts:100,desc:"Make your first Pleb Talk post",hint:"Post in PlebTalk!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=1||void 0!==currentUser&¤tUser&¤tUser.forumPosts>=1}},{id:"first_reply",name:"Conversationalist",emoji:"💬",pts:75,desc:"Reply to a forum post",hint:"Join a discussion!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.forumReplies>=1}},{id:"market_seller",name:"Merchant",emoji:"🏪",pts:150,desc:"List an item on Lightning Mart",hint:"Sell something for sats on Lightning Mart!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketListings>=1}},{id:"market_buyer",name:"Shopper",emoji:"🛍️",pts:150,desc:"Contact a seller on the marketplace",hint:"Find something to buy!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketMessages>=1}},{id:"donor_100",name:"Giving Pleb",emoji:"🫷",pts:50,desc:"Donate 100 XP for charity",hint:"Donate 100 XP in the Charity tab!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=100},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,100)+"/100"}},{id:"donor_500",name:"Stack Sharer",emoji:"💛",pts:150,desc:"Donate 500 XP for charity",hint:"Keep donating!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=500},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,500)+"/500"}},{id:"donor_1000",name:"Community Builder",emoji:"🧡",pts:300,desc:"Donate 1,000 XP for charity",hint:"A true community builder!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e3)+"/1,000"}},{id:"donor_5000",name:"Archive Patron",emoji:"❤️",pts:1e3,desc:"Donate 5,000 XP for charity",hint:"An archive patron — legendary!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e3)+"/5,000"}},{id:"donor_10000",name:"Sats Saint",emoji:"🔥",pts:2e3,desc:"Donate 10,000 XP for charity",hint:"A sats saint among us!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e4)+"/10,000"}},{id:"donor_25000",name:"Lightning Philanthropist",emoji:"⚡",pts:4e3,desc:"Donate 25,000 XP for charity",hint:"A lightning philanthropist!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=25e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,25e3)+"/25,000"}},{id:"donor_50000",name:"Satoshi's Steward",emoji:"🏆",pts:7500,desc:"Donate 50,000 XP for charity",hint:"Satoshi's Steward — incredible!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e4)+"/50,000"}},{id:"donor_100000",name:"Legend of the Archive",emoji:"👑",pts:15e3,desc:"Donate 100,000 XP for charity",hint:"A true legend of the archive!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e5},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e5)+"/100,000"}},{id:"night_owl",name:"Night Owl",emoji:"🦉",pts:50,desc:"Visit the archive after midnight",hidden:!0,check:function(){return(new Date).getHours()>=0&&(new Date).getHours()<5}},{id:"speed_runner",name:"Speed Runner",emoji:"⚡",pts:100,desc:"Visit 15+ channels in one session",hidden:!0,check:function(){return void 0!==sessionChannels&&sessionChannels.size>=15}},{id:"scholar",name:"Bitcoin Scholar",emoji:"🎓",pts:300,desc:"Pass the Scholar Certification",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_scholar_passed")}},{id:"nacho_20q",name:"20 Questions",emoji:"🏅",pts:500,desc:"Ask Nacho 20 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=20}},{id:"explorer_10",name:"Curious Pleb",emoji:"🗺️",pts:100,desc:"Explore 10 topics",hint:"Keep exploring!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,10)+"/10"}},{id:"explorer_25",name:"Rabbit Holer",emoji:"🐇",pts:250,desc:"Explore 25 topics",hint:"Dive deeper!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=25},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,25)+"/25"}},{id:"explorer_50",name:"Half Stack",emoji:"📚",pts:500,desc:"Explore 50 topics",hint:"Halfway there!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=50},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,50)+"/50"}},{id:"explorer_100",name:"Century Club",emoji:"💯",pts:1e3,desc:"Explore 100 topics",hint:"Almost all of them!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=100},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,100)+"/100"}},{id:"explorer_all",name:"Archive Master",emoji:"👑",pts:2e3,desc:"Explore every single topic",hint:"Visit them all!",hidden:!0,check:function(){return void 0!==CHANNELS&&safeJSON("btc_visited_channels",[]).length>=Object.keys(CHANNELS).length}},{id:"marathon",name:"Marathon Reader",emoji:"🏃",pts:150,desc:"Spent 30+ minutes reading in one session",hidden:!0,check:function(){return Date.now()-(window._sessionStart||Date.now())>18e5}},{id:"early_adopter",name:"Early Adopter",emoji:"🌅",pts:200,desc:"Browsing between 5am and 7am",hidden:!0,check:function(){var e=(new Date).getHours();return e>=5&&e<7}},{id:"weekend_warrior",name:"Weekend Warrior",emoji:"🎉",pts:75,desc:"Learning Bitcoin on a weekend",hidden:!0,check:function(){var e=(new Date).getDay();return 0===e||6===e}},{id:"triple_threat",name:"Triple Threat",emoji:"🎯",pts:300,desc:"Completed a quest, sent a chat message, and read a channel in one session",hidden:!0,check:function(){return"true"===sessionStorage.getItem("btc_quest_done")&&"true"===sessionStorage.getItem("btc_chat_sent")&&void 0!==sessionChannels&&sessionChannels.size>=1}},{id:"nacho_50q",name:"Nacho Sage",emoji:"🧙",pts:500,desc:"Ask Nacho 50 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=50}},{id:"bookmark_collector",name:"Bookmark Hoarder",emoji:"📚",pts:100,desc:"Bookmarked 20+ messages",hidden:!0,check:function(){return safeJSON("btc_bookmarks",[]).length>=20}},{id:"pvp_streak",name:"Undefeated",emoji:"🔱",pts:250,desc:"Won 5 PVP battles in a row",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_pvp_win_streak")||"0")>=5}},{id:"sats_maxed",name:"Faucet King",emoji:"👑",pts:1e3,desc:"Claimed all 10,000 sats from the faucet",hidden:!0,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e4}},{id:"streak_freeze",name:"Ice Shield",emoji:"🧊",pts:50,desc:"Used a streak freeze to save your streak",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_freeze_used")}},{id:"nacho_closet_full",name:"Fashionista",emoji:"👗",pts:200,desc:"Unlocked all Nacho closet items from the spin wheel",hidden:!0,check:function(){return safeJSON("btc_spin_closet_items",[]).length>=10}}];function _syncPredictionToFirestore(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db)return;var t=auth.currentUser.uid;db.collection("users").doc(t).set({predictions:{lastPrediction:{direction:e.direction,price:e.price,time:e.time}}},{merge:!0}).catch(function(){}),db.collection("active_predictions").doc(t).set({uid:t,direction:e.direction,price:e.price,time:e.time,resolved:!1}).catch(function(){})}catch(e){}}function _updatePredictionStats(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db||"undefined"==typeof firebase)return;var t=auth.currentUser.uid,o=firebase.firestore.FieldValue.increment,n=parseInt(localStorage.getItem("btc_predict_streak")||"0"),i=parseInt(localStorage.getItem("btc_predict_best_streak")||"0"),a={"predictions.total":o(1),"predictions.lastResolved":Date.now()};if(e){a["predictions.correct"]=o(1);var r=n+1;a["predictions.streak"]=r,r>i&&(a["predictions.bestStreak"]=r,localStorage.setItem("btc_predict_best_streak",r.toString()))}else a["predictions.streak"]=0;db.collection("users").doc(t).set(a,{merge:!0}).catch(function(){});var s={total:o(1)};e&&(s.correct=o(1)),db.collection("stats").doc("predictions").set(s,{merge:!0}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.predictions||(currentUser.predictions={total:0,correct:0,streak:0,bestStreak:0}),currentUser.predictions.total=(currentUser.predictions.total||0)+1,e?(currentUser.predictions.correct=(currentUser.predictions.correct||0)+1,currentUser.predictions.streak=(currentUser.predictions.streak||0)+1,currentUser.predictions.streak>(currentUser.predictions.bestStreak||0)&&(currentUser.predictions.bestStreak=currentUser.predictions.streak)):currentUser.predictions.streak=0)}catch(e){}}!function(){const e=["🎓 Someone just passed the Bitcoin Basics Certification! Can you?","⚡ A pleb just completed a Lightning Network quest — 50 XP earned!","🗺️ Someone just finished all 10 steps of the Bitcoin Journey!","🎮 A Bitcoiner just aced a quiz in Nacho Mode — 10/10!","📚 A new user just explored their first 3 topics — features unlocking!","🧠 Someone just asked Nacho 100 questions — Bitcoin Scholar status!","🎯 A pleb just scored 5/5 on a Conversation Quest!","📖 Someone just read through the entire Timechain channel!","🔥 A Bitcoiner just hit a 30-day streak! Legendary dedication!","🔥 Someone just started a 7-day streak — can you beat them?","🏆 A pleb just crossed 5,000 XP! Climbing the leaderboard!","⭐ Someone just earned 200 XP in a single session!","🔥 A user just protected their streak with a Freeze Ticket! Smart move.","📈 Someone just jumped 10 spots on the Leaderboard!","🧡 A Bitcoiner just leveled up to Bitcoin Believer!","🏔 Someone just reached Maxi status — top of the mountain!","👑 A pleb just entered the Top 25 on the Leaderboard!","🌱 A brand new user just earned their first 50 XP! Welcome!","🎡 Someone just spun the daily wheel and won 5 Orange Tickets!","🎟️ A pleb just earned bonus tickets from a referral!","🧊 Someone won a Streak Freeze on the daily spin — lucky!","🎡 A Bitcoiner just won a closet item from the spin wheel!","💬 New discussion in PlebTalk: 'Best cold storage for beginners?'","💬 Someone just posted in PlebTalk — join the conversation!","🛒 New listing on LightningMart — check it out!","🤝 A meetup was just created in IRL Sync — find one near you!","💬 A PlebTalk post just got 5 upvotes!","⚡ Someone just tipped a forum post with Lightning!","🦌 Someone just entered Nacho Mode for a 30-minute deep dive!","🎽 A pleb just equipped Diamond Hooves in Nacho's Closet! 💎","🕶️ Someone just unlocked Cool Shades from the spin wheel!","👑 A Bitcoiner just equipped the Royal Crown — looking regal!","🦌 Nacho just helped someone understand seed phrases!","🗺️ Someone just explored their 50th channel — almost full coverage!","🦉 A Night Owl badge was just earned at 2 AM!","🎲 Someone just used Random Channel and discovered 'cypherpunks'!","🎨 A user just browsed the Art Gallery — 200+ Bitcoin artworks!","📡 A Bitcoiner just opted in to The Signal newsletter!","🎉 Over 100 users are learning Bitcoin here right now!","📊 The archive has been visited over 10,000 times this month!","🧡 146 channels of pure Bitcoin education — and growing!","⚡ Over 500 Nacho conversations happened this week!","🏆 The Leaderboard top 10 just shuffled — who's climbing?"];async function t(){const t=safeJSON("btc_visited_channels",[]).length,o=firebase.auth().currentUser&&!firebase.auth().currentUser.isAnonymous;if(t<3&&!o)return;const n=document.getElementById("activity-ticker"),i=document.getElementById("ticker-content");if(n&&i){var a=e.slice();try{var r=firebase.firestore();(await r.collection("forum_posts").orderBy("createdAt","desc").limit(3).get()).forEach(function(e){var t=e.data(),o=t.authorName||"A pleb";a.push("💬 "+o+' just posted in PlebTalk: "'+(t.title||"").substring(0,40)+'..."')});try{(await r.collection("marketplace").where("status","==","active").orderBy("createdAt","desc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🛒 New on LightningMart: "'+(t.title||"Item").substring(0,35)+'" for '+(t.priceSats||t.price||"???")+" sats!")})}catch(e){}try{var s=await r.collection("users").orderBy("points","desc").limit(10).get(),l=[];if(s.forEach(function(e){var t=e.data();t.username&&l.push(t.username)}),l.length>=3){a.push("👑 "+l[0]+" is holding #1 on the Leaderboard! Can you catch them?");var c=l[Math.floor(Math.random()*Math.min(5,l.length))];a.push("📈 "+c+" just climbed the Leaderboard — competition is heating up!")}}catch(e){}try{(await r.collection("irl_events").where("date",">=",(new Date).toISOString()).orderBy("date","asc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🤝 Upcoming meetup: "'+(t.title||"Bitcoin Meetup").substring(0,35)+'" — RSVP in IRL Sync!')})}catch(e){}}catch(e){console.log("Ticker live data skipped:",e)}for(var d=a.length-1;d>0;d--){var u=Math.floor(Math.random()*(d+1)),p=a[d];a[d]=a[u],a[u]=p}n.style.display="flex";var m=0;h(),setInterval(h,12e3)}function h(){i.style.animation="none",i.offsetHeight,i.textContent=a[m],i.style.animation="tickerScroll 12s linear infinite",m=(m+1)%a.length}}const o=document.createElement("style");o.textContent="\n #ticker-content { \n white-space: nowrap !important;\n overflow: visible !important;\n text-overflow: clip !important;\n display: inline-block !important;\n width: auto !important;\n padding-right: 50px;\n }\n @keyframes tickerScroll {\n 0% { transform: translateX(100%); }\n 100% { transform: translateX(-100%); }\n }\n ",document.head.appendChild(o),window.rateChannel=async function(e,t){const o=document.getElementById("sentiment-"+e);if(o){o.innerHTML='
    Thank you! 🦌
    Nacho will use this to organize better content.
    ';try{const o=firebase.firestore();await o.collection("channel_feedback").add({channelId:e,rating:t,uid:firebase.auth().currentUser?firebase.auth().currentUser.uid:"anon",createdAt:firebase.firestore.FieldValue.serverTimestamp()}),"function"==typeof awardPoints&&awardPoints(5,"Feedback bonus")}catch(e){console.log("Feedback save skipped:",e)}}},window.checkNewsletterPrompt=function(){localStorage.getItem("btc_newsletter_prompt_shown")||safeJSON("btc_visited_channels",[]).length>=10&&(function(){const e=document.createElement("div");e.id="newsletterModal",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);z-index:10000;display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(5px);",e.innerHTML='
    📡

    Stay Orange-Pilled

    You\'ve explored 10+ channels! Stay connected with Bitcoin updates and community news.

    📱 Join Telegram Updates📧 Subscribe on Substack
    ',document.body.appendChild(e)}(),localStorage.setItem("btc_newsletter_prompt_shown","true"))},window.optInNewsletter=async function(){const e=document.getElementById("newsletterModal"),t=firebase.auth().currentUser;if(!t||t.isAnonymous)return showToast("Please sign in with email to join the newsletter!"),"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void(e&&e.remove());try{const e=firebase.firestore();await e.collection("users").doc(t.uid).update({newsletterOptIn:!0,newsletterOptInDate:firebase.firestore.FieldValue.serverTimestamp()}),showToast("🎉 Welcome to the Orange Pill newsletter!")}catch(e){console.log("Newsletter opt-in failed:",e)}e&&e.remove()},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){t(),checkNewsletterPrompt()}):(t(),checkNewsletterPrompt())}(),window.showNachoStory=function(e){var t=[{title:"Chapter 1: The Genesis Block",text:"In the beginning, there was nothing but fiat. Nacho was just a young buck growing up in the White Mountains of New Hampshire — the Live Free or Die state. He spent his fawn days splashing in the Pemigewasset River, racing chipmunks through birch groves, and nibbling on leaves of debt from the forest of traditional finance. His mama always said the acorns were getting smaller every year, but nobody could explain why. One cold January day in 2009, a mysterious message appeared carved into a sugar maple: 'Chancellor on brink of second bailout for banks.' Nacho didn't understand it yet, but something had changed forever. A new kind of money had been born — one that no government could print, no bank could freeze, and no deer could counterfeit. It was called Bitcoin."},{title:"Chapter 2: The Pizza That Changed Everything",text:"Nacho heard a rumor from a blue jay passing through Franconia Notch: someone had traded 10,000 bitcoins for two pizzas. 'That's crazy!' he thought, nearly choking on a wild blueberry. But was it? Those pizzas proved Bitcoin had real value — people would actually exchange goods for it. Nacho realized this wasn't just internet magic beans. It was the beginning of price discovery. He thought about all the acorns he'd traded with the squirrels over the years — weren't those his first 'transactions' too? Every great journey starts with a single trade, and Bitcoin's started with pepperoni and cheese."},{title:"Chapter 3: Down the Rabbit Hole",text:"Nacho found a weathered copy of the whitepaper pinned to a bulletin board at a general store in Lincoln, New Hampshire. Only 9 pages, but each one hit different. Peer-to-peer. No trusted third party. Proof of work. 21 million cap. He read it by the light of a campfire near the Kancamagus Highway, the stars of the Granite State blazing overhead. The deeper he went, the more he understood: Bitcoin wasn't just new money. It was a paradigm shift. Sound money that couldn't be debased. A monetary network with no CEO, no headquarters, no off switch. Nacho's antlers tingled — literally. His first set was coming in. He was growing up, and he was becoming a Bitcoiner."},{title:"Chapter 4: HODL Through the Storm",text:"A nor'easter hit New Hampshire that winter, and the price of Bitcoin crashed right along with the temperature. Then crashed again. Nacho watched his sats lose 80% of their dollar value from a snow-covered ridge overlooking the Presidential Range. His forest friends laughed. 'Told you it was a scam!' chirped a skeptical chickadee. But Nacho had done his homework. He understood the halving cycles. He knew that every 210,000 blocks, the new supply gets cut in half. Scarcity + time = value. So Nacho did what legends do: he stood firm in the blizzard and held. Not because he was reckless, but because he understood what he held. The storms always pass. The mountains remain."},{title:"Chapter 5: Not Your Keys, Not Your Cheese",text:"One crisp autumn morning, as the New Hampshire maples blazed orange and gold, Nacho woke up to terrible news. An exchange had been hacked. Billions gone. Friends who kept their bitcoin on the exchange lost everything. A young doe from Vermont had her entire savings wiped out. Nacho felt sick — but also relieved. He'd moved his sats to a hardware wallet weeks ago, buried it in a waterproof case near his favorite granite boulder in the White Mountains. Cold storage. Air-gapped. His keys, his bitcoin. From that day forward, Nacho's motto was clear: 'Not your keys, not your cheese.' 🧀🔑 He even carved it into a birch tree so no deer would forget."},{title:"Chapter 6: The Halving",text:"Every four years, something magical happens — and Nacho had the perfect view from Mount Washington's summit. The block reward — the number of new bitcoins created with each block — gets cut in half. He watched the countdown with a group of bitcoiners who'd hiked up for the occasion, huddled together at 6,288 feet with thermoses of coffee and Lightning-powered phones. From 6.25 BTC to 3.125 BTC per block. Less new supply entering the market. Same or growing demand. The wind howled, but nobody cared. It's not magic; it's math. And it's the most predictable monetary policy in the history of money. Nacho shed a single tear — which immediately froze to his fur."},{title:"Chapter 7: Nacho's Mission",text:"Nacho looked out from his favorite overlook in the White Mountains — the same spot where he'd first read the whitepaper by campfire light. He'd grown from a gangly fawn into a strong buck with a magnificent rack of antlers (seven points, if you're counting). But so many deer — so many people — still didn't understand Bitcoin. They heard 'crypto' and thought of scams, memecoins, and celebrity tokens. But Bitcoin is different. It's the signal in the noise. So Nacho decided to dedicate his life to education, right here from the Live Free or Die state. Not shilling. Not pumping. Teaching. Because the best way to orange-pill someone isn't to tell them to buy — it's to help them understand WHY. And that's why you're here. Welcome to the Archive. 🦌🟠"}],o=(new Date).toISOString().split("T")[0],n=safeJSON("btc_nacho_story_days",[]);(0===n.length||-1===n.indexOf(o))&&(n.push(o),localStorage.setItem("btc_nacho_story_days",JSON.stringify(n)));var i,a=Math.min(n.length,t.length);if(void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryProgress:a,nachoStoryDate:o,nachoStoryDays:n}).catch(function(){})}catch(e){}localStorage.setItem("btc_nacho_story_highest",a.toString()),localStorage.setItem("btc_nacho_story_date",o),"number"==typeof e?(i=Math.min(e,a-1))<0&&(i=0):(i=a-1)<0&&(i=0);var r=t[i],s=document.createElement("div");s.id="nachoStoryOverlay",s.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",s.onclick=function(e){e.target===s&&s.remove()};for(var l='
    ',c=0;c'+(c+1)+"":''}l+="
    ";var u,p=i>0?"':"";u=i+1Next →':i>=t.length-1?'✅ Story Complete!':'🔒 Come back tomorrow!';var m=document.createElement("div");m.style.cssText="background:#1a1a2e;border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:500px;width:100%;margin:40px auto;color:#e2e8f0;font-family:inherit;",m.innerHTML='
    🦌📖
    '+l+'

    '+r.title+'

    '+r.text+'

    📖 Chapter '+(i+1)+" of "+t.length+" · "+a+" unlocked ("+(t.length-a)+' remaining)
    '+p+u+'
    ',s.appendChild(m),document.body.appendChild(s);var h=safeJSON("btc_nacho_story_awarded",[]);if("function"==typeof awardPoints&&-1===h.indexOf(i)){h.push(i),localStorage.setItem("btc_nacho_story_awarded",JSON.stringify(h));var g=i===t.length-1?50:15;awardPoints(g,"📖 Completed Chapter "+(i+1)),"function"==typeof showToast&&showToast("📖 +"+g+" XP — Chapter "+(i+1)+" complete!"),h.length===t.length&&setTimeout(function(){if(awardPoints(100,"📖🎉 Completed Nacho's Story!"),"function"==typeof awardOrangeTickets)awardOrangeTickets(25,"📖 Nacho's Story Complete!");else{var e=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(e+25).toString())}"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound();var t=document.createElement("div");if(t.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",t.onclick=function(){t.style.opacity="0",t.style.transition="opacity 0.4s",setTimeout(function(){t.remove()},400)},t.innerHTML='
    🦌📖🎉
    STORY COMPLETE!
    You\'ve followed Nacho\'s entire Bitcoin journey from the Genesis Block to his mission of education. You\'re officially a Story Master! 🏆
    +100
    BONUS PTS
    +25
    🎟️ TICKETS
    ',document.body.appendChild(t),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryComplete:!0,nachoStoryCompletedAt:(new Date).toISOString()}).catch(function(){})}catch(e){}},800)}},window.showPricePrediction=function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0;if(!e&&"undefined"!=typeof _lastWsPrice&&_lastWsPrice&&(e=_lastWsPrice,localStorage.setItem("btc_last_price",e.toString())),!e&&"undefined"!=typeof _dashData&&_dashData&&_dashData.price&&(e=_dashData.price,localStorage.setItem("btc_last_price",e.toString())),!e)return"function"==typeof showToast&&showToast("⏳ Fetching price..."),void fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd?(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),showPricePrediction()):"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")}).catch(function(){"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")});var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&t.remove()};var o=safeJSON("btc_price_prediction",null),n=document.createElement("div");if(n.style.cssText="background:var(--card-bg,#1a1a2e);border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:420px;width:100%;color:var(--text,#e2e8f0);font-family:inherit;text-align:center;",o&&Date.now()-o.time<864e5){var i=Date.now()-o.time;if(!(i>=864e5)){var a=Math.ceil((864e5-i)/36e5);return n.innerHTML='

    Prediction Locked In!

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+'

    ⏳ Results in ~'+a+" hour"+(1!==a?"s":"")+'
    Come back after 24 hours to see if you were right!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},500),t.appendChild(n),void document.body.appendChild(t)}var r=e-o.price,s=(r/o.price*100).toFixed(2),l="up"===o.direction&&r>0||"down"===o.direction&&r<0;o._notified||("function"==typeof notifyPredictionResult&¬ifyPredictionResult(l,o.direction),o._notified=!0,localStorage.setItem("btc_price_prediction",JSON.stringify(o)));var c=parseInt(localStorage.getItem("btc_predict_streak")||"0");n.innerHTML=''+(l?"🎉":"😅")+'

    Your Prediction

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+" ("+(r>=0?"+":"")+s+'%)

    '+(l?"✅ You were RIGHT! +25 XP":"❌ Not this time!")+"

    "+(l&&c>=2?'

    🔥 '+c+" correct in a row!

    ":"")+'
    Come back tomorrow for a new prediction!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},100)}else n.innerHTML='📈📉

    Predict Bitcoin\'s Price

    Current BTC Price:

    $'+Math.round(e).toLocaleString()+'

    Will Bitcoin go UP or DOWN in the next 24 hours?

    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStats");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 Be the first to predict!"})},100);t.appendChild(n),document.body.appendChild(t)},window._savePrediction=function(e){var t={direction:e,price:parseFloat(localStorage.getItem("btc_last_price"))||0,time:Date.now(),resolved:!1};localStorage.setItem("btc_price_prediction",JSON.stringify(t)),"function"==typeof showToast&&showToast("🎯 Prediction saved! Check back tomorrow to see if you were right."),"function"==typeof awardPoints&&awardPoints(5,"📈 Price prediction made"),_syncPredictionToFirestore(t)},window.checkPredictionResult=function(){var e=safeJSON("btc_price_prediction",null);if(e&&!e.resolved&&!(Date.now()-e.time<864e5)){var t=parseFloat(localStorage.getItem("btc_last_price"))||0;if(t&&e.price){var o=t-e.price,n=(o/e.price*100).toFixed(2),i="up"===e.direction&&o>0||"down"===e.direction&&o<0;e.resolved=!0,e.result=i?"correct":"wrong",e.finalPrice=t,localStorage.setItem("btc_price_prediction",JSON.stringify(e)),_updatePredictionStats(i);try{void 0!==auth&&auth.currentUser&&void 0!==db&&db.collection("active_predictions").doc(auth.currentUser.uid).delete().catch(function(){})}catch(e){}if(i){"function"==typeof awardPoints&&awardPoints(25,"🎯 Correct price prediction!");var a=parseInt(localStorage.getItem("btc_predict_streak")||"0")+1;localStorage.setItem("btc_predict_streak",a.toString()),setTimeout(function(){"function"==typeof showToast&&showToast("🎉 Your prediction was RIGHT! Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"% — +25 XP!"+(a>=3?" 🔥 "+a+" correct in a row!":""))},2e3)}else localStorage.setItem("btc_predict_streak","0"),setTimeout(function(){"function"==typeof showToast&&showToast("📉 Your prediction was wrong — Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"%. Try again tomorrow!")},2e3)}}};var _globalPredCache=null,_globalPredCacheTs=0;window.getGlobalPredictionStats=function(e){if(_globalPredCache&&Date.now()-_globalPredCacheTs<12e4)e(_globalPredCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{db.collection("stats").doc("predictions").get().then(function(t){t.exists?(_globalPredCache=t.data(),_globalPredCacheTs=Date.now(),e(_globalPredCache)):e(null)}).catch(function(){e(null)})}catch(t){e(null)}else e(null)},window.getPredictionStats=function(e){var t=e&&e.predictions?e.predictions:null;if(!t||!t.total)return null;var o=t.total>0?Math.round(t.correct/t.total*100):0;return{total:t.total||0,correct:t.correct||0,percentage:o,streak:t.streak||0,bestStreak:t.bestStreak||0}};var _communityStatsCache=null,_communityStatsCacheTs=0,_communityStatsUnsub=null;function _renderCommunityStats(e,t,o){var n=[];o.channelVisits&&n.push("📖 "+_fmtNum(o.channelVisits)+" channel reads"),o.questsCompleted&&n.push("⚡ "+_fmtNum(o.questsCompleted)+" quests completed"),o.chatMessages&&n.push("💬 "+_fmtNum(o.chatMessages)+" chat messages"),o.spins&&n.push("🎡 "+_fmtNum(o.spins)+" daily spins"),o.pvpMatches&&n.push("⚔️ "+_fmtNum(o.pvpMatches)+" PVP battles");var i=document.getElementById("visitCount");if(i&&"—"!==i.textContent&&n.push("👥 "+i.textContent+" total visits"),o.userCount&&n.push("🧑‍🤝‍🧑 "+_fmtNum(o.userCount)+" registered users"),o.watchTimeMinutes){var a=Math.floor(o.watchTimeMinutes/60);n.push("📺 "+(a>0?_fmtNum(a)+" hours":o.watchTimeMinutes+" min")+" Timechain TV watched")}if(0!==n.length){e.innerHTML=n.join("  ·  ");var r=function(e,t){var o=document.getElementById(e);o&&t&&(o.textContent=t.toLocaleString())};if(r("csChannelReads",o.channelVisits),r("csQuests",o.questsCompleted),r("csChatMsgs",o.chatMessages),r("csSpins",o.spins),r("csPvp",o.pvpMatches),r("csUsers",o.userCount),o.watchTimeMinutes){var s=Math.floor(o.watchTimeMinutes/60);r("csWatchTime",s>0?s:o.watchTimeMinutes)}}else e.innerHTML="No stats yet"}function _fmtNum(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function renderExplorationMap(){var e=document.getElementById("explorationMap");if(e&&void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]);void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>t.length&&(t=currentUser.readChannels);var o=Object.keys(CHANNELS),n=o.length,i=t.length,a=Math.round(i/n*100),r="";o.forEach(function(e){var o=-1!==t.indexOf(e),n=CHANNELS[e].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}|\u{2700}-\u{27BF}|\u{FE00}-\u{FEFF}|\u{1F900}-\u{1F9FF}|\u{1FA00}-\u{1FA6F}|\u{1FA70}-\u{1FAFF}|\u{200D}|\u{FE0F}]+)/u),i=n?n[1]:"📄";r+="
    '+(o?i:"?")+"
    "});var s="true"===localStorage.getItem("btc_explore_map_open");e.innerHTML="
    "+(s?"▾":"▸")+'🗺️ Exploration Map
    '+i+"/"+n+" ("+a+'%)
    '+r+"
    "}}window.loadCommunityStats=function(){var e=document.getElementById("communityStatsInner");if(e){var t=e.parentElement;if(_communityStatsUnsub&&_communityStatsCache)_renderCommunityStats(e,t,_communityStatsCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{_communityStatsUnsub=db.collection("stats").doc("global").onSnapshot(function(e){var t=e.exists?e.data():{};_communityStatsCache=t,_communityStatsCacheTs=Date.now();var o=document.getElementById("communityStatsInner");o&&_renderCommunityStats(o,o.parentElement,t)})}catch(e){}}},setTimeout(function(){"function"==typeof loadCommunityStats&&loadCommunityStats()},5e3),window.updatePredictionLabel=function(){var e=document.getElementById("predAccuracyLabel");return!!e&&void 0!==db&&"undefined"!=typeof firebase&&"function"==typeof getGlobalPredictionStats&&(getGlobalPredictionStats(function(t){var o=[];if(t&&t.total){var n=Math.round(t.correct/t.total*100);o.push("🌍 "+n+"% community accuracy")}if(void 0!==currentUser&¤tUser&¤tUser.predictions&¤tUser.predictions.total){var i=Math.round(currentUser.predictions.correct/currentUser.predictions.total*100);o.push("👤 "+i+"% you")}e.innerHTML=o.join("
    ")}),!0)},function(){var e=0,t=setInterval(function(){e++,(window.updatePredictionLabel&&window.updatePredictionLabel()||e>60)&&clearInterval(t)},1e3)}(),function e(){if("function"==typeof window.goHome){if(!window.goHome.__predHooked){var t=window.goHome;window.goHome=function(){var e=t.apply(this,arguments);return setTimeout(function(){window.updatePredictionLabel&&window.updatePredictionLabel()},400),e},window.goHome.__predHooked=!0}}else var o=setInterval(function(){"function"==typeof window.goHome&&(clearInterval(o),e())},500)}(),window.renderExplorationMap=renderExplorationMap;var BITCOIN_QUOTES=[{text:"If you don't believe it or don't get it, I don't have the time to try to convince you, sorry.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"The root problem with conventional currency is all the trust that's required to make it work.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"It might make sense just to get some in case it catches on.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"Running bitcoin.",author:"Hal Finney",channel:"history"},{text:"Bitcoin is a remarkable cryptographic achievement and the ability to create something that is not duplicable in the digital world has enormous value.",author:"Eric Schmidt",channel:"dominant"},{text:"Bitcoin is a technological tour de force.",author:"Bill Gates",channel:"one-stop-shop"},{text:"I think the internet is going to be one of the major forces for reducing the role of government. The one thing that's missing, but that will soon be developed, is a reliable e-cash.",author:"Milton Friedman (1999)",channel:"videos"},{text:"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.",author:"Bitcoin Genesis Block",channel:"history"},{text:"Not your keys, not your coins.",author:"Bitcoin Proverb",channel:"self-custody"},{text:"Stay humble, stack sats.",author:"Bitcoin Community",channel:"investment-strategy"},{text:"In the long run, hard money is superior to soft money.",author:"Gigi, 21 Lessons",channel:"articles-threads"},{text:"Bitcoin is the first truly digital solution to the problem of money.",author:"Saifedean Ammous",channel:"books"},{text:"Fix the money, fix the world.",author:"Bitcoin Mantra",channel:"problems-of-money"},{text:"The supply of Bitcoin is limited. Period. No central bank is going to come along and print more.",author:"Andreas Antonopoulos",channel:"scarce"},{text:"Everyone is a scammer until proven otherwise. Don't trust, verify.",author:"Bitcoin Culture",channel:"secure"},{text:"Bitcoin makes money great again. It lets you transact freely, save freely, and live freely.",author:"Michael Saylor",channel:"giga-chad"},{text:"There is no second best.",author:"Michael Saylor",channel:"maximalism"},{text:"I don't think there's anything more important in my lifetime to work on.",author:"Jack Dorsey",channel:"giga-chad"},{text:"Bitcoin is the most important invention in the history of the world since the internet.",author:"Roger Ver (before he fell off)",channel:"history"},{text:"The computer can be used as a tool to liberate and protect people, rather than to control them.",author:"Hal Finney",channel:"cryptography"},{text:"One of the greatest things that Satoshi did was disappear.",author:"Gigi, 21 Lessons",channel:"satoshi-nakamoto"},{text:"Bitcoin has no CEO, no marketing department, no headquarters. It has math.",author:"Bitcoin Education Archive",channel:"decentralized"},{text:"We are all Satoshi.",author:"Bitcoin Community",channel:"satoshi-nakamoto"},{text:"Cypherpunks write code.",author:"Eric Hughes",channel:"cryptography"},{text:"Privacy is necessary for an open society in the electronic age.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Money is a tool for trading human time.",author:"Robert Breedlove",channel:"articles-threads"},{text:"Bitcoin is Time.",author:"Gigi",channel:"time"},{text:"The root cause of the housing crisis, student debt crisis, and healthcare crisis is the money crisis.",author:"Saifedean Ammous",channel:"problems-of-money"},{text:"Tick tock, next block.",author:"Bitcoin Community",channel:"blockchain-timechain"},{text:"The difficulty adjustment is the most elegant feature of Bitcoin.",author:"Bitcoin Educators",channel:"difficulty-adjustment"},{text:"Every informed person needs to know about Bitcoin because it might be one of the world's most important developments.",author:"Leon Luow",channel:"one-stop-shop"},{text:"Bitcoin is the only commodity in the world that the more demand there is, the more supply does NOT increase.",author:"Parker Lewis",channel:"scarce"},{text:"Gradually, then suddenly.",author:"Parker Lewis / Ernest Hemingway",channel:"articles-threads"},{text:"You can't stop an idea whose time has come.",author:"Victor Hugo (on Bitcoin)",channel:"organic"},{text:"Bitcoin is a hedge against the entire system.",author:"Lyn Alden",channel:"investment-strategy"},{text:"The question isn't what Bitcoin's price will be. The question is what the dollar's price will be.",author:"Bitcoiners",channel:"problems-of-money"},{text:"I was once told that nobody ever lost money saving in Bitcoin for 4+ years. I checked. It's true.",author:"Anonymous Bitcoiner",channel:"investment-strategy"},{text:"Bitcoin is the exit.",author:"Bitcoin Maximalists",channel:"maximalism"},{text:"Don't trust, verify.",author:"Bitcoin Ethos",channel:"nodes"},{text:"Number go up technology.",author:"Bitcoin Twitter",channel:"fun-facts"},{text:"Energy is the universal currency. Bitcoin makes that literal.",author:"Bitcoin Mining Community",channel:"energy"},{text:"Bitcoin is not an investment — it is a savings technology.",author:"Bitcoin Educators",channel:"money"},{text:"Fiat currency always returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Give me control of a nation's money supply, and I care not who makes its laws.",author:"Mayer Amschel Rothschild",channel:"problems-of-money"},{text:"Inflation is taxation without legislation.",author:"Milton Friedman",channel:"problems-of-money"},{text:"Bitcoin is for enemies. That's the whole point.",author:"Bitcoin Community",channel:"game_theory"},{text:"When you understand Bitcoin, you understand everything else differently.",author:"Many Bitcoiners",channel:"philosophy"},{text:"Bitcoin doesn't care about your feelings.",author:"Bitcoin Proverb",channel:"fun-facts"},{text:"Stack sats and stay humble.",author:"Matt Odell",channel:"investment-strategy"},{text:"Number go up because money printer go brr.",author:"Bitcoin Memes",channel:"memes-funny"},{text:"Those who would give up essential liberty, to purchase a little temporary safety, deserve neither liberty nor safety.",author:"Benjamin Franklin",channel:"human_rights__social_justice_and_freedo"},{text:"Freedom is never more than one generation away from extinction.",author:"Ronald Reagan",channel:"human_rights__social_justice_and_freedo"},{text:"The only way to deal with an unfree world is to become so absolutely free that your very existence is an act of rebellion.",author:"Albert Camus",channel:"philosophy"},{text:"If the American people ever allow private banks to control the issue of their currency, first by inflation, then by deflation, the banks and corporations that will grow up around them will deprive the people of all property.",author:"Thomas Jefferson",channel:"problems-of-money"},{text:"It is well enough that people of the nation do not understand our banking and monetary system, for if they did, I believe there would be a revolution before tomorrow morning.",author:"Henry Ford",channel:"problems-of-money"},{text:"The most dangerous man to any government is the man who is able to think things out for himself.",author:"H.L. Mencken",channel:"philosophy"},{text:"In a time of deceit, telling the truth is a revolutionary act.",author:"George Orwell",channel:"philosophy"},{text:"The urge to save humanity is almost always a false front for the urge to rule it.",author:"H.L. Mencken",channel:"philosophy"},{text:"A society that puts equality before freedom will get neither. A society that puts freedom before equality will get a high degree of both.",author:"Milton Friedman",channel:"philosophy"},{text:"The state is that great fiction by which everyone tries to live at the expense of everyone else.",author:"Frédéric Bastiat",channel:"austrian_school_of_economics"},{text:"There is no means of avoiding the final collapse of a boom brought about by credit expansion.",author:"Ludwig von Mises",channel:"austrian_school_of_economics"},{text:"The first panacea for a mismanaged nation is inflation of the currency; the second is war. Both bring a temporary prosperity; both bring a permanent ruin.",author:"Ernest Hemingway",channel:"problems-of-money"},{text:"Gold is money. Everything else is credit.",author:"J.P. Morgan",channel:"money"},{text:"We don't have a trillion-dollar debt because we haven't taxed enough; we have a trillion-dollar debt because we spend too much.",author:"Ronald Reagan",channel:"problems-of-money"},{text:"Government is the only institution that can take a valuable commodity like paper, and make it worthless by applying ink.",author:"Ludwig von Mises",channel:"problems-of-money"},{text:"Whenever destroyers appear among men, they start by destroying money.",author:"Ayn Rand",channel:"problems-of-money"},{text:"The way to crush the bourgeoisie is to grind them between the millstones of taxation and inflation.",author:"Vladimir Lenin",channel:"problems-of-money"},{text:"Savings represent goods produced but not yet consumed. That's what real wealth is — not digits in a bank database.",author:"Saifedean Ammous",channel:"money"},{text:"Civilization is in a race between education and catastrophe. Let us learn the truth and spread it as far and wide as our circumstances allow.",author:"H.G. Wells",channel:"one-stop-shop"},{text:"Paper money eventually returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Bitcoin is the separation of money and state.",author:"Bitcoin Community",channel:"maximalism"},{text:"Bitcoin is the first money in the history of the world where the supply is entirely unaffected by an increase in demand.",author:"Jeff Booth",channel:"scarce"},{text:"In a world where everything is printed, scarcity is the ultimate feature.",author:"Bitcoin Educators",channel:"scarce"},{text:"Bitcoin is hope for humanity.",author:"Jack Mallers",channel:"one-stop-shop"},{text:"The cost of Bitcoin is measured in electricity. The cost of fiat is measured in human freedom.",author:"Bitcoin Community",channel:"energy"},{text:"Your savings should not be someone else's liability.",author:"Bitcoin Educators",channel:"self-custody"},{text:"Bitcoin is the peaceful protest that cannot be silenced.",author:"Alex Gladstein",channel:"human_rights__social_justice_and_freedo"},{text:"Bitcoin gives us the ability to opt out of a system that was designed to extract value from us.",author:"Many Bitcoiners",channel:"problems-of-money"},{text:"Proof of work means proof of energy. Energy is the one thing that cannot be faked.",author:"Bitcoin Mining Community",channel:"mining"},{text:"The Bitcoin network processes more value per year than Visa. Without a CEO.",author:"Bitcoin Stats",channel:"decentralized"},{text:"If Bitcoin is a bubble, it's the only bubble that reflated itself five times in a row.",author:"Bitcoin Community",channel:"fun-facts"},{text:"Bitcoin has died 474 times according to the media. It's still here.",author:"Bitcoin Obituaries",channel:"misconceptions-fud"},{text:"Your grandchildren will ask you why you didn't buy Bitcoin when it was under six figures.",author:"Bitcoin Twitter",channel:"predictions"},{text:"The next 4 years are going to be very exciting for Bitcoin.",author:"Every Bitcoiner, Every Year",channel:"fun-facts"},{text:"Bitcoin isn't getting more expensive. Your dollars are getting cheaper.",author:"Bitcoin Community",channel:"problems-of-money"},{text:"If you can't hold it, you don't own it. If you didn't earn it, you'll lose it.",author:"Bitcoin Wisdom",channel:"self-custody"},{text:"Think in sats, not dollars.",author:"Bitcoin Community",channel:"sats__or__bits"},{text:"The best time to buy Bitcoin was 10 years ago. The second best time is now.",author:"Bitcoin Proverb",channel:"investment-strategy"},{text:"Work is the transfer of energy over time. Money should measure exactly that.",author:"Jason Lowery",channel:"energy"},{text:"Bitcoin is not anti-government. Bitcoin is anti-fraud.",author:"Bitcoin Educators",channel:"regulation"},{text:"We must defend our own privacy if we expect to have any.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Cryptography is the ultimate form of non-violent direct action.",author:"Julian Assange",channel:"cryptography"},{text:"Strong cryptography can resist an unlimited application of violence.",author:"Jacob Appelbaum",channel:"cryptography"},{text:"The Net interprets censorship as damage and routes around it.",author:"John Gilmore",channel:"privacy-nonkyc"},{text:"Bitcoin is a weapon of peace.",author:"Jason Lowery, Softwar",channel:"geopolitics___macroeconomics"},{text:"Running a node means nobody can change the rules on you.",author:"Bitcoin Node Runners",channel:"nodes"},{text:"Hashrate is the heartbeat of Bitcoin. As long as miners mine, Bitcoin lives.",author:"Bitcoin Mining Community",channel:"mining"},{text:"Lightning is what makes Bitcoin usable for 8 billion people.",author:"Lightning Network Community",channel:"layer-2-lightning"},{text:"2,099,999,997,690,000 satoshis. That's all there will ever be.",author:"The Bitcoin Protocol",channel:"scarce"},{text:"Code is speech. Math is law. Cryptography is defense.",author:"Cypherpunks",channel:"cryptography"},{text:"I predict the Internet will go spectacularly supernova and in 1996 catastrophically collapse.",author:"Robert Metcalfe (1995) — They said this about Bitcoin too",channel:"misconceptions-fud"},{text:"Every generation needs a new revolution.",author:"Thomas Jefferson",channel:"philosophy"},{text:"First they ignore you, then they laugh at you, then they fight you, then you win.",author:"Often attributed to Gandhi",channel:"organic"},{text:"I do not think there is any other quality so essential to success of any kind as the quality of perseverance.",author:"John D. Rockefeller",channel:"philosophy"},{text:"The world is a dangerous place, not because of those who do evil, but because of those who look on and do nothing.",author:"Albert Einstein",channel:"philosophy"},{text:"Hard times create strong men. Strong men create good times. Good times create weak men. Weak men create hard times.",author:"G. Michael Hopf",channel:"time_preference"},{text:"An investment in knowledge pays the best interest.",author:"Benjamin Franklin",channel:"one-stop-shop"}];window.renderDailyQuote=function(){var e=document.getElementById("quoteOfDay");if(e){var t=new Date,o=Math.floor((t-new Date(t.getFullYear(),0,0))/864e5),n=BITCOIN_QUOTES[o%BITCOIN_QUOTES.length];n&&(e.innerHTML="
    💬 Quote of the Day
    "'+n.text+'"
    — '+n.author+"
    ")}},window.renderReadNext=function(e){if(void 0===CHANNELS)return"";var t=CHANNELS[e];if(!t)return"";var o=Object.entries(CHANNELS).filter(function(o){return o[1].cat===t.cat&&o[0]!==e});if(0===o.length)return"";var n=o.sort(function(){return Math.random()-.5}).slice(0,3),i='
    📖 Read Next
    ';return n.forEach(function(e){var t=e[1].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}]+)/u),o=t?t[1]:"📄";i+=""}),i+="
    "},window.getNachoStoryProgress=function(){return parseInt(localStorage.getItem("btc_nacho_story_highest")||"0")},window.checkHiddenBadges=function(){if(void 0!==HIDDEN_BADGES&&window._hiddenBadgesReady){var e=safeJSON("btc_hidden_badges",[]),t=!1;HIDDEN_BADGES.forEach(function(o){if(-1===e.indexOf(o.id))try{if(o.check&&o.check()&&(e.push(o.id),t=!0,"function"==typeof showToast&&showToast(o.emoji+" Secret Badge: "+(o.revealName||o.name)+"! +"+o.pts+" XP"),"function"==typeof awardPoints&&awardPoints(o.pts,"Hidden Badge: "+(o.revealName||o.name)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:e})}catch(e){}}catch(e){}}),t&&localStorage.setItem("btc_hidden_badges",JSON.stringify(e))}},setInterval(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},3e4),setTimeout(function(){window._hiddenBadgesReady||(window._hiddenBadgesReady=!0)},2e4),window.awardHiddenBadge=function(e,t){var o=safeJSON("btc_hidden_badges",[]);if(-1===o.indexOf(e)&&(o.push(e),localStorage.setItem("btc_hidden_badges",JSON.stringify(o)),t&&"function"==typeof showToast&&showToast("🏅 "+t),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:o})}catch(e){}},window.awardOrangeTickets=function(e,t){void 0!==currentUser&¤tUser&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,currentUser._isLocal||"function"!=typeof awardPoints||awardPoints(0,"🎟️ "+(t||"Orange Tickets"),null,e));var o=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(o+e).toString()),"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Ticket"+(e>1?"s":"")+(t?" — "+t:""))},window.setFloatingElementsVisible=function(e){["floatingRandomBtn","lbFloatBtn","mobileSearchBtn","backToTop","scrollToBottom","chatOverlayBtn","aiToolsBtn","dashboardFloatBtn"].forEach(function(t){var o=document.getElementById(t);o&&(o.style.display=e?"":"none")})},window.showCelebration=function(e){var t=e.emoji||"🎉",o=e.title||"Achievement Unlocked!",n=e.message||"",i=e.rewards||[],a=e.btnText||"Amazing! 🎉",r=document.createElement("div");r.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",r.onclick=function(e){e.target===r&&(r.style.opacity="0",r.style.transition="opacity 0.4s",setTimeout(function(){r.remove()},400))};var s="";i.length>0&&(s='
    ',i.forEach(function(e){s+='
    +'+e.label+'
    '+e.sub+"
    "}),s+="
    "),r.innerHTML='
    '+t+'
    '+o+'
    '+n+"
    "+s+'
    ",document.body.appendChild(r),"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound(),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200)},setInterval(function(){["prop","tech"].forEach(function(e){var t="btc_scholar_"+e+"_passed",o="btc_scholar_"+e+"_celebrated";if("true"===localStorage.getItem(t)&&"true"!==localStorage.getItem(o)){localStorage.setItem(o,"true");var n="tech"===e;setTimeout(function(){showCelebration({emoji:n?"🛠️🎓🏆":"📖🎓🎉",title:n?"PROTOCOL EXPERT!":"BITCOIN SCHOLAR!",message:n?"You passed the Technical Protocol Expert Certification! You understand Bitcoin at the deepest level. True cypherpunk material! 🔐":"You passed the Bitcoin Scholar Certification! You have a thorough understanding of Bitcoin's properties and economics! 🧡",rewards:[{label:"2,100",sub:"PTS",color:"#22c55e"},{label:n?"🛠️":"🎓",sub:"BADGE",color:"#f7931a"}],btnText:n?"Protocol Expert! 🛠️":"Scholar! 🎓"})},500)}})},3e3),function(){var e=[{pct:25,key:"explore_25",emoji:"🗺️🌱",title:"25% EXPLORED!",msg:"A quarter of the archive explored! You're building a solid Bitcoin foundation.",pts:50,tickets:10},{pct:50,key:"explore_50",emoji:"🗺️🔥",title:"50% EXPLORED!",msg:"Halfway through the entire archive! You know more about Bitcoin than most people on Earth.",pts:100,tickets:25},{pct:75,key:"explore_75",emoji:"🗺️⚡",title:"75% EXPLORED!",msg:"Three quarters done! You're in the top tier of Bitcoin knowledge seekers.",pts:200,tickets:50},{pct:100,key:"explore_100",emoji:"🗺️👑🏆",title:"ARCHIVE COMPLETE!",msg:"You've explored EVERY SINGLE channel in the archive. You are a true Bitcoin scholar. Satoshi would be proud! 🧡",pts:500,tickets:100}];window._checkExplorationMilestones=function(){if(void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]),o=Object.keys(CHANNELS).length,n=Math.round(t.length/o*100);e.forEach(function(e){if(n>=e.pct&&"true"!==localStorage.getItem("btc_"+e.key+"_celebrated")){if(localStorage.setItem("btc_"+e.key+"_celebrated","true"),"function"==typeof awardPoints&&awardPoints(e.pts,"🗺️ "+e.pct+"% Explored"),"function"==typeof awardOrangeTickets)awardOrangeTickets(e.tickets,"🗺️ "+e.pct+"% Explored");else{var t=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(t+e.tickets).toString())}if(setTimeout(function(){showCelebration({emoji:e.emoji,title:e.title,message:e.msg,rewards:[{label:e.pts.toString(),sub:"PTS",color:"#22c55e"},{label:e.tickets.toString(),sub:"🎟️ TICKETS",color:"#f7931a"}]})},800),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o={};o["explorationMilestone_"+e.pct]=!0;try{db.collection("users").doc(auth.currentUser.uid).update(o).catch(function(){})}catch(e){}}}})}};var t=window.renderExplorationMap;window.renderExplorationMap=function(){t(),window._checkExplorationMilestones()}}(),function(){var e=window.showQuestFinalResults;e&&(window.showQuestFinalResults=function(){e.apply(this,arguments);var t=window._questScore||0;5===t?("function"==typeof showToast&&showToast("🏆 PERFECT SCORE! You nailed every question!"),"function"==typeof launchConfetti&&setTimeout(launchConfetti,300)):t>=3&&"function"==typeof showToast&&showToast("⚡ Quest passed! +"+(window._questPts||0)+" XP earned!")});var t=window.nachoQuizAnswer;t&&(window.nachoQuizAnswer=function(e,o){t.apply(this,arguments),o&&"function"==typeof haptic&&haptic("success")});var o=window.convoQuizAnswer;o&&(window.convoQuizAnswer=function(e,t){o.apply(this,arguments),t&&"function"==typeof haptic&&haptic("light")})}(),function(){window._scrollPositions={};var e=window.go;e&&(window.go=async function(t,o,n){var i=document.getElementById("main"),a=location.hash.slice(1);a&&i&&(window._scrollPositions[a]=i.scrollTop),await e(t,o,n),window._scrollPositions[t]&&i&&setTimeout(function(){i.scrollTop=window._scrollPositions[t]},100)}),window.haptic=function(e){if("visible"===document.visibilityState&&"false"!==localStorage.getItem("btc_haptic")&&navigator.vibrate)switch(e){case"light":navigator.vibrate(10);break;case"medium":navigator.vibrate(25);break;case"heavy":navigator.vibrate([30,50,30]);break;case"success":navigator.vibrate([15,30,15,30,15]);break;case"error":navigator.vibrate([50,30,50]);break;default:navigator.vibrate(15)}};var t=window.awardPoints;t&&(window.awardPoints=function(){return haptic("success"),t.apply(this,arguments)});var o=window.showLevelUpCelebration;o&&(window.showLevelUpCelebration=function(){return haptic("heavy"),o.apply(this,arguments)}),function(){var e=document.createElement("style");e.textContent="@keyframes slideInRight{from{transform:translateX(30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInLeft{from{transform:translateX(-30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInUp{from{transform:translateY(20px);opacity:0}to{transform:translateY(0);opacity:1}}.page-transition-right{animation:slideInRight 0.25s ease-out;}.page-transition-left{animation:slideInLeft 0.25s ease-out;}.page-transition-up{animation:slideInUp 0.2s ease-out;}",document.head.appendChild(e);var t=document.getElementById("main");t&&new MutationObserver(function(){var e=document.getElementById("hero");e&&e.innerHTML&&(e.classList.remove("page-transition-right"),e.offsetWidth,e.classList.add("page-transition-right"))}).observe(document.getElementById("hero")||t,{childList:!0})}();var n=0;document.addEventListener("touchend",function(e){var t=Date.now();if(t-n<300){var o=e.target.closest&&e.target.closest('[onclick*="forumViewPost"]');if(o){var i=o.querySelector('[onclick*="forumVotePost"]');i&&(i.click(),haptic("medium")),e.preventDefault()}}n=t},{passive:!1});var i=(new Date).toISOString().split("T")[0];function a(e){return localStorage.getItem(e+"_"+i)||null}function r(e,t){localStorage.setItem(e+"_"+i,t)}function s(e){return parseInt(a(e)||"0",10)}function l(e){var t=s(e)+1;return r(e,String(t)),t}var c,d=[{id:"read",text:"📖 Read a new channel",check:function(){return"true"===a("btc_new_channel_read")}},{id:"nacho",text:"🦌 Ask Nacho a question",check:function(){return s("btc_nacho_asked")>0}},{id:"quiz",text:"🎮 Complete a quiz question",check:function(){return"true"===a("btc_quiz_done")}},{id:"explore",text:"🗺️ Visit 3 different channels",check:function(){return s("btc_channels_today")>=3}},{id:"forum",text:"🗣️ Visit the PlebTalk",check:function(){return"true"===a("btc_forum_visited")}},{id:"streak",text:"🔥 Log in to keep your streak",check:function(){return!0}},{id:"favorite",text:"⭐ Save a channel to favorites",check:function(){return"true"===a("btc_fav_added")}},{id:"tctv_10m",text:"📺 Watch 10 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=10}},{id:"tctv_visit",text:"📺 Tune in to Timechain TV",check:function(){return"true"===a("btc_tctv_visited")}},{id:"tctv_3ch",text:"📺 Watch 3 different TCTV stations",check:function(){try{var e=a("btc_tctv_stations_visited");return!!e&&JSON.parse(e).length>=3}catch(e){return!1}}},{id:"tctv_30m",text:"📺 Watch 30 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=30}},{id:"tip_send",text:"⚡ Send a Lightning tip to someone",check:function(){return"true"===a("btc_tip_sent")}},{id:"tip_3",text:"⚡ Send 3 Lightning tips today",check:function(){return s("btc_tips_sent_count")>=3}},{id:"ln_setup",text:"⚡ Set up your Lightning wallet",check:function(){return!!(localStorage.getItem("btc_nwc_url")||localStorage.getItem("btc_ln_address")||void 0!==currentUser&¤tUser&¤tUser.lightningAddress)}},{id:"chat_msg",text:"🌍 Send a message in Global Chat",check:function(){return"true"===a("btc_chat_sent")}},{id:"pvp_battle",text:"⚔️ Complete a PVP trivia battle",check:function(){return"true"===a("btc_pvp_done")}},{id:"beats_listen",text:"🎸 Listen to a track on Bitcoin Beats",check:function(){return"true"===a("btc_beats_played")}},{id:"explore_5",text:"🗺️ Explore 5 different channels today",check:function(){return s("btc_channels_today")>=5}},{id:"nacho_3",text:"🦌 Ask Nacho 3 questions",check:function(){return s("btc_nacho_asked")>=3}}];function u(){var e=(new Date).toISOString().split("T")[0],t=Math.floor(new Date(e).getTime()/864e5);return d[t%d.length]}function p(){var e=u(),t=(new Date).toISOString().split("T")[0],o=localStorage.getItem("btc_challenge_done")===t,n=document.getElementById("dailyChallengeCard");n&&(o?(n.style.borderColor="#22c55e",n.style.background="rgba(34,197,94,0.05)",n.innerHTML='
    Today\'s Challenge ✔️
    '+e.text+" — Done! +100 XP 🎉
    "):(n.style.borderColor="var(--border)",n.style.background="var(--card-bg)",n.innerHTML='
    🎯
    Today\'s Challenge
    '+e.text+"
    "))}if(window.checkDailyChallenge=function(){var e=(new Date).toISOString().split("T")[0];if(localStorage.getItem("btc_challenge_done")!==e&&u().check()){localStorage.setItem("btc_challenge_done",e),"function"==typeof awardPoints&&awardPoints(100,"🎯 Daily challenge!"),"function"==typeof awardOrangeTickets&&awardOrangeTickets(5,"🎯 Daily challenge!"),"function"==typeof showToast&&showToast("🎯 Daily challenge complete! +100 XP + 🎟️ 5 tickets!"),haptic("success"),p();var t=document.getElementById("dailyChallengeCard");t&&(t.style.transition="transform 0.3s, box-shadow 0.3s",t.style.transform="scale(1.03)",t.style.boxShadow="0 0 20px rgba(34,197,94,0.4)",setTimeout(function(){t.style.transform="",t.style.boxShadow=""},1500))}},setInterval(window.checkDailyChallenge,3e3),window._raidHomeUnsub=null,window._raidHomeTimer=null,window.renderRaidBossHome=function(){var e=document.getElementById("raidBossHomeCard");e&&("undefined"!=typeof firebase&&void 0!==db?(window._raidHomeUnsub&&(window._raidHomeUnsub(),window._raidHomeUnsub=null),window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),window._raidHomeUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.style.display="none";else{var o=Date.now(),n=null,i=null,a=null;t.forEach(function(e){var t=e.data();t.id=e.id;var r=t.startTime&&t.startTime.toDate?t.startTime.toDate().getTime():0,s=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime&&i.startTime.toDate?i.startTime.toDate().getTime():0))&&(i=t):t.defeated&&(a||(a=t))}),function(e,t,o,n){if(window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),t||o||n){e.style.display="";var i="if(typeof showQuestHub==='function'){showQuestHub();setTimeout(function(){if(typeof window._questHubTab!=='undefined'){window._questHubTab='raid';if(typeof _renderQuestHubTab==='function')_renderQuestHubTab();}},300)}",a="";if(t){var r=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0,s=t.target>0?Math.min(100,Math.round((t.current||0)/t.target*100)):0,l=Math.max(0,(t.target||0)-(t.current||0)),c=Math.max(0,100-s),d=c<=25?"#ef4444":c<=50?"#f59e0b":"#22c55e",u=t.image||"";if(!u){var p={"Channel-Crawler":"channel-crawler","Quiz-Crusader":"quiz-crusader","TV-Titan":"tv-titan","Beats-Baron":"beats-baron","Flash-Flash":"flash-flash","XP-Hoarder":"xp-hoarder","Poll-Patroller":"poll-patroller","Chat-Charger":"chat-charger","Badge-Builder":"badge-builder","Streak-Sage":"streak-sage","Topic-Explorer":"topic-explorer","Lightning-Lancer":"lightning-lancer","Forum-Forge":"forum-forge","Trivia-Tactician":"trivia-tactician","Content-Conqueror":"content-conqueror"};p[t.name]&&(u="images/raid-bosses/"+p[t.name]+".png")}a+='
    '+(u?'':'⚔️')+'
    ⚔️ CURRENT RAID BOSS
    '+(t.name||"Raid Boss")+'
    ❤️ '+l+"/"+t.target+' HP⏱ '+g(r)+'
    ',window._raidActiveEndMs=r}if(o){var m=o.startTime&&o.startTime.toDate?o.startTime.toDate().getTime():0,h=new Date(m).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"});a+='
    ⚔️
    NEXT BOSS
    '+(o.name||"TBD")+" — "+h+'
    Starts in '+g(m)+'
    ',window._raidUpcomingStartMs=m}n&&!t&&(a='
    💀
    🎉 BOSS DEFEATED!
    '+("function"==typeof escapeHtml?escapeHtml(n.name||"Raid Boss"):n.name||"Raid Boss")+' has fallen!
    🏆 Orange ticket drawing this Friday!
    '+a),e.innerHTML=a,window._raidHomeTimer=setInterval(function(){var e=document.getElementById("raidHomeCountdown");e&&window._raidActiveEndMs&&(e.textContent="⏱ "+g(window._raidActiveEndMs));var t=document.getElementById("raidHomeUpcomingCountdown");t&&window._raidUpcomingStartMs&&(t.textContent="Starts in "+g(window._raidUpcomingStartMs)),e||t||(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null)},1e3)}else e.style.display="none";function g(e){var t=Math.max(0,e-Date.now());if(t<=0)return"⏳ Any moment now...";var o=Math.floor(t/864e5),n=Math.floor(t%864e5/36e5),i=Math.floor(t%36e5/6e4),a=Math.floor(t%6e4/1e3);return o>0?o+"d "+n+"h "+i+"m":n>0?n+"h "+i+"m "+a+"s":i+"m "+a+"s"}}(e,n,i,a)}},function(){e.style.display="none"})):e.style.display="none")},c="",window._trackChallengeNav=function(e){e&&e!==c&&(c=e,"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e||r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},500))},window.go){var m=window.go;window.go=async function(e){var t=!1;e&&"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e&&(t=-1===safeJSON("btc_visited_channels",[]).indexOf(e));var o=await m.apply(this,arguments);return"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e),e&&"forum"!==e&&(l("btc_channels_today"),t&&r("btc_new_channel_read","true")),"forum"===e&&r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},300),o}}var h=window.nachoUnifiedAnswer;h&&(window.nachoUnifiedAnswer=function(e,t){return l("btc_nacho_asked"),h.apply(this,arguments)}),window.addEventListener("hashchange",function(){var e=location.hash.slice(1);e&&"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e)}),window.renderProgressRings=function(){var e=document.getElementById("progressRings");if(e){var t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=0;void 0!==currentUser&¤tUser&&(currentUser.readChannels&¤tUser.readChannels.length?o=currentUser.readChannels.length:currentUser.channelsVisited&&(o=currentUser.channelsVisited)),0===o&&(o=safeJSON("btc_visited_channels",[]).length);var n=void 0!==currentUser&¤tUser&¤tUser.streak||0,i=void 0!==currentUser&¤tUser&¤tUser.points||0,a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.innerHTML='
    '+r(Math.min(100,o/t*100),"#f7931a","Channels",o+"/"+t)+r(Math.min(100,5*n),"#22c55e","Streak","🔥"+n)+r(Math.min(100,i/21e3*100),"#8B5CF6","XP",i>999?Math.floor(i/1e3)+"k":i)+r(Math.min(100,2*a),"#3B82F6","Nacho",a)+"
    "}function r(e,t,o,n){var i=2*Math.PI*32;return'
    '+n+'
    '+o+"
    "}};var g=null;function f(){console.log("[MobileUX] Initializing..."),function(){var e=document.createElement("div");e.id="bottomNav",e.className="mobile-nav",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:200000;background:rgba(10,10,10,0.95);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border-top:1px solid rgba(255,255,255,0.1);padding:10px 0 env(safe-area-inset-bottom,10px) 0;padding-bottom:max(env(safe-area-inset-bottom,10px),10px);display:none;transition:transform 0.25s ease;-webkit-transform:translateZ(0);transform:translateZ(0);",e.innerHTML='
    ';var t=document.createElement("style");t.textContent=".bnav-btn{background:none;border:none;color:var(--text-dim,#666);font-size:0.6rem;cursor:pointer;font-family:inherit;padding:6px 0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;touch-action:manipulation;-webkit-tap-highlight-color:transparent;transition:0.2s;flex:1;min-width:0;}.bnav-icon{font-size:1.3rem;line-height:1;display:block;transition:transform 0.2s;}.bnav-label{font-size:0.55rem;line-height:1;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;}.bnav-btn:active .bnav-icon{transform:scale(1.2);}.bnav-btn.active{color:var(--accent);}@media(min-width:901px){#bottomNav{display:none!important;}}@media(max-width:900px){#bottomNav{display:block!important;visibility:visible!important;opacity:1!important;}.messages{padding-bottom:140px!important;}.home-page{padding-bottom:100px!important;}}",document.head.appendChild(t),document.body.appendChild(e)}(),function(){var e=document.getElementById("main");if(e){var t=0,o=document.getElementById("bottomNav");o&&e.addEventListener("scroll",function(){if(!(window.innerWidth>900)){var n=e.scrollTop,i=n-t;i>10&&n>200?o.classList.add("nav-hidden"):(i<-5||n<=10)&&o.classList.remove("nav-hidden"),t=n}},{passive:!0})}}(),setTimeout(function(){!function(){var e=0;if(void 0!==currentUser&¤tUser&&(e=currentUser.streak||0),!(e<2||document.getElementById("streakBanner"))){var t=document.createElement("div");t.id="streakBanner",t.style.cssText="position:fixed;top:32px;left:0;right:0;z-index:300;background:linear-gradient(135deg,#f7931a,#ea580c);color:#fff;padding:10px 16px;text-align:center;font-size:0.85rem;font-weight:700;cursor:pointer;animation:slideInUp 0.3s;",t.innerHTML="🔥 Day "+e+' streak! Keep it alive! tap to dismiss',t.onclick=function(){t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.remove()},300)},document.body.appendChild(t),setTimeout(function(){t.parentNode&&(t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.parentNode&&t.remove()},300))},5e3)}}(),function(){if("function"==typeof forceShowBubble&&!sessionStorage.getItem("btc_welcomed_back")){sessionStorage.setItem("btc_welcomed_back","true");var e="";void 0!==currentUser&¤tUser&¤tUser.username&&(e=currentUser.username);var t,o=void 0!==currentUser&¤tUser&¤tUser.streak||0,n=(new Date).getHours(),i=n<12?"Morning":n<17?"Afternoon":"Evening",a=u();t=e&&o>=2?"Good "+i.toLowerCase()+", "+e+"! ☀️ Day "+o+" streak — you're on fire! 🔥 Today's challenge: "+a.text:e?"Hey "+e+"! 🦌 Welcome back! Today's challenge: "+a.text:"Welcome back! 🦌 Today's challenge: "+a.text,setTimeout(function(){forceShowBubble(t)},3e3)}}(),p(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof renderProgressRings&&renderProgressRings()},2500)}window.addEventListener("beforeinstallprompt",function(e){if(e.preventDefault(),g=e,!window.matchMedia("(display-mode: standalone)").matches){var t=localStorage.getItem("btc_pwa_dismissed");if(t&&Date.now()-parseInt(t)<6048e5)return;window._pwaLoadTime=Date.now(),window._pwaCheckInterval=setInterval(function(){if(!(Date.now()-(window._pwaLoadTime||Date.now())<9e4)){var e=[];try{e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}e.length>=3&&(clearInterval(window._pwaCheckInterval),function(){if(!document.getElementById("pwaInstallBanner")){var e=document.createElement("div");if(e.id="pwaInstallBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Install Bitcoin Education
    Add to home screen for the best experience — works offline!
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}}())}},1e4)}}),window.installPWA=function(){g&&(g.prompt(),g.userChoice.then(function(e){"accepted"===e.outcome&&"function"==typeof showToast&&showToast("🦌 Welcome aboard! App installed!"),g=null})),dismissPWABanner()},window.dismissPWABanner=function(){var e=document.getElementById("pwaInstallBanner");e&&e.remove(),localStorage.setItem("btc_pwa_dismissed",Date.now().toString())},function(){var e=/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,t=/Safari/.test(navigator.userAgent)&&!/CriOS|FxiOS|Chrome/.test(navigator.userAgent),o=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(e&&t&&!o){var n=localStorage.getItem("btc_ios_a2hs_dismissed");n&&Date.now()-parseInt(n)<2592e6||setTimeout(function(){if(!document.getElementById("iosA2HSBanner")){var e=document.createElement("div");if(e.id="iosA2HSBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Add to Home Screen
    For the best experience, add this app to your home screen:
    1. Tap the Share button ⬆️ at the bottom
    2. Scroll down and tap Add to Home Screen
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}},12e4)}}(),window.dismissIOSA2HS=function(){var e=document.getElementById("iosA2HSBanner");e&&e.remove(),localStorage.setItem("btc_ios_a2hs_dismissed",Date.now().toString())},window.toggleMobileLearnMenu=function(){var e=document.getElementById("mobileLearnMenu");if(e)e.remove();else{var t=document.getElementById("appsMenu");t&&t.remove();var o=document.createElement("div");o.id="mobileLearnMenu",o.style.cssText="position:fixed;bottom:70px;left:8px;right:8px;z-index:250;max-width:400px;margin:0 auto;background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:18px;box-shadow:0 -8px 40px rgba(0,0,0,0.6);animation:fadeSlideIn 0.25s ease-out;",o.innerHTML='

    🎓 Learn

    ',document.body.appendChild(o),setTimeout(function(){document.addEventListener("click",function e(t){var o=document.getElementById("mobileLearnMenu");!o||o.contains(t.target)||t.target.closest("#bnavLearn")||(o.remove(),document.removeEventListener("click",e))})},100)}},window.toggleMobileFlashcards=function(){var e=document.getElementById("mLearnFlashGrid"),t=document.getElementById("mLearnFlashBtn");e&&("none"===e.style.display?(e.style.display="flex",t&&(t.textContent="📚 Flashcards ▼")):(e.style.display="none",t&&(t.textContent="📚 Flashcards ▶")))},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",f):f()}(),function(){"use strict";var e=null,t=null,o=null,n=null;function i(){if(!(e&&e.readyState<=1))try{(e=new WebSocket("wss://ws.coincap.io/prices?assets=bitcoin")).onopen=function(){console.log("[Dashboard] Price WebSocket connected (CoinCap)"),window._wsDataTimer=setTimeout(function(){t||(console.warn("[Dashboard] WS connected but no data — falling back"),r())},1e4)},e.onmessage=function(e){try{window._wsDataTimer&&(clearTimeout(window._wsDataTimer),window._wsDataTimer=null);var i=JSON.parse(e.data);if(!i.bitcoin)return;var a=parseFloat(i.bitcoin);!n&&t&&(n=t),t=a,n&&(o=(t-n)/n*100),n=parseFloat(i.o);var r=document.getElementById("dashLivePrice");r&&(r.textContent="$"+p(t,2));var s=document.getElementById("dashLiveChange");if(s){var l=o>=0?"#22c55e":"#ef4444",c=o>=0?"▲":"▼";s.innerHTML=''+c+" "+Math.abs(o).toFixed(2)+"% (24h)"}var d=document.getElementById("dashBtnPrice");if(d){var u=o>=0?"#22c55e":"#ef4444",m=o>=0?"▲":"▼";d.innerHTML="$"+p(t,0)+' '+m+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}catch(e){}},e.onclose=function(){console.log("[Dashboard] WS closed, reconnecting..."),e=null,setTimeout(i,5e3)},e.onerror=function(t){console.warn("[Dashboard] WS error, falling back to polling");try{e.close()}catch(e){}e=null,r()}}catch(e){r()}}var a=null;function r(){function e(){fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true").then(function(e){return e.json()}).then(function(e){if(e&&e.bitcoin){t=e.bitcoin.usd,o=e.bitcoin.usd_24h_change||0;var n=document.getElementById("dashLivePrice");n&&(n.textContent="$"+p(t,2));var i=document.getElementById("dashLiveChange");if(i){var a=o>=0?"#22c55e":"#ef4444",r=o>=0?"▲":"▼";i.innerHTML=''+r+" "+Math.abs(o).toFixed(2)+"% (24h)"}var s=document.getElementById("dashBtnPrice");if(s){var l=o>=0?"#22c55e":"#ef4444",c=o>=0?"▲":"▼";s.innerHTML="$"+p(t,0)+' '+c+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}}).catch(function(){})}a||(console.log("[Dashboard] Starting price polling fallback (CoinGecko)"),e(),a=setInterval(e,3e4))}var s="btc_dashboard_cache",l=12e4,c=null,d=!1,u=null;function p(e,t){return null==e?"—":"number"==typeof t?Number(e).toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t}):Number(e).toLocaleString()}function m(e){return null==e?"—":e>=1e12?"$"+(e/1e12).toFixed(1)+"T":e>=1e9?"$"+(e/1e9).toFixed(1)+"B":e>=1e6?"$"+(e/1e6).toFixed(1)+"M":e>=1e3?"$"+(e/1e3).toFixed(0)+"K":"$"+Math.round(e)}function h(e){return null==e?"—":e>=1e12?(e/1e12).toFixed(2)+" T":e>=1e9?(e/1e9).toFixed(2)+" B":p(e)}async function g(){if(d)return await new Promise(function(e){var t=setInterval(function(){d||(clearInterval(t),e())},200);setTimeout(function(){clearInterval(t),d=!1,e()},1e4)}),c||{};d=!0;var e=null;try{var i=JSON.parse(localStorage.getItem(s));if(i&&i.data&&(e=i.data,Date.now()-i.tse.text()).then(e=>{a.blockHeight=parseInt(e);try{localStorage.setItem("btc_last_height",a.blockHeight.toString())}catch(e){}var t=document.getElementById("btcDashCard");t&&!a.price&&a.blockHeight&&(t.innerHTML=f(a))}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/fees/recommended").then(e=>e.json()).then(e=>{a.feeFast=e.fastestFee,a.feeHalf=e.halfHourFee,a.feeHour=e.hourFee,a.feeEcon=e.economyFee,a.feeMin=e.minimumFee}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/mining/hashrate/1m").then(e=>e.json()).then(e=>{if(e.currentHashrate&&(a.hashrate=e.currentHashrate),e.currentDifficulty&&(a.difficulty=e.currentDifficulty),e.hashrates&&e.hashrates.length>=6){var t=e.hashrates.length,o=(e.hashrates[t-1].avgHashrate+e.hashrates[t-2].avgHashrate+e.hashrates[t-3].avgHashrate)/3,n=(e.hashrates[t-4].avgHashrate+e.hashrates[t-5].avgHashrate+e.hashrates[t-6].avgHashrate)/3;n>0&&(a.hashrateChange24h=(o-n)/n*100)}}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/difficulty-adjustment").then(e=>e.json()).then(e=>{a.diffChange=e.difficultyChange,a.diffEstDate=e.estimatedRetargetDate,a.diffRemaining=e.remainingBlocks,a.diffProgress=e.progressPercent}).catch(()=>{})),r.push(fetch("https://mempool.space/api/mempool").then(e=>e.json()).then(e=>{a.mempoolTxs=e.count,a.mempoolSize=e.vsize}).catch(()=>{})),r.push(fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true&include_24hr_vol=true&include_market_cap=true").then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{if(e.bitcoin){a.price=e.bitcoin.usd;try{localStorage.setItem("btc_last_price",e.bitcoin.usd.toString())}catch(e){}a.change24h=e.bitcoin.usd_24h_change,a.volume24h=e.bitcoin.usd_24h_vol,a.marketCap=e.bitcoin.usd_market_cap,!n&&a.price&&a.change24h&&(n=a.price/(1+a.change24h/100),o=a.change24h)}var t=document.getElementById("btcDashCard");return t&&a.price&&(t.innerHTML=f(a)),new Promise(function(e){setTimeout(e,1500)})}).then(function(){return fetch("https://api.coingecko.com/api/v3/coins/bitcoin?localization=false&tickers=false&community_data=false&developer_data=false")}).then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{e.market_data&&(a.supply=e.market_data.circulating_supply,a.ath=e.market_data.ath?e.market_data.ath.usd:null,a.athDate=e.market_data.ath_date?e.market_data.ath_date.usd:null,a.athChange=e.market_data.ath_change_percentage?e.market_data.ath_change_percentage.usd:null,a.high24h=e.market_data.high_24h?e.market_data.high_24h.usd:null,a.low24h=e.market_data.low_24h?e.market_data.low_24h.usd:null,a.mktCapChange24h=e.market_data.market_cap_change_percentage_24h||null)}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/lightning/statistics/latest").then(e=>e.json()).then(e=>{e&&(a.lnCapacity=e.latest?e.latest.total_capacity:e.total_capacity,a.lnNodes=e.latest?e.latest.node_count:e.node_count,a.lnChannels=e.latest?e.latest.channel_count:e.channel_count)}).catch(()=>{})),r.push(fetch("https://api.alternative.me/fng/?limit=1").then(e=>e.json()).then(e=>{e.data&&e.data[0]&&(a.fearGreed=parseInt(e.data[0].value),a.fearGreedLabel=e.data[0].value_classification)}).catch(()=>{})),await Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,12e3))]),!a.price&&t&&(a.price=t);for(var u=[s,"btc_dash_backup"],p=0;p'+(r<=2?"Live metrics · Updates every 2 min":"📦 Data from "+(r<60?r+"m":Math.round(r/60)+"h")+" ago · Refreshing...")+"",a+='',a+="";var s=t||n.price,l=null!==o?o:n.change24h||0,c=l>=0?"#22c55e":"#ef4444",d=l>=0?"▲":"▼";if(a+='
    ',a+='
    $'+p(s,2)+"
    ",a+='
    '+d+" "+Math.abs(l).toFixed(2)+"%
    ",a+='
    🔴 Live — updates automatically · All % changes are 24h
    ',a+='
    ',a+='24h High: $'+p(n.high24h,0)+"",a+='24h Low: $'+p(n.low24h,0)+"",a+="
    ",a+="
    ",void 0!==n.halvingDays){var u=n.halving?((21e4-n.halving)/21e4*100).toFixed(1):0,m=n.halvingEta?n.halvingEta.toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"}):"—";a+='
    ',a+='
    ⏳ Next Halving — Block #'+p(n.halvingBlock)+'
    ',window._halvingTargetMs=Date.now()+10*n.halving*60*1e3,a+='
    ',a+='
    '+(n.halvingDays||0)+'
    Days
    ',a+='
    :
    ',a+='
    '+(n.halvingHours||0)+'
    Hours
    ',a+='
    :
    ',a+='
    '+(n.halvingMins||0)+'
    Mins
    ',a+='
    :
    ',a+='
    00
    Secs
    ',a+="
    ",a+='
    Est. '+m+" · "+p(n.halving)+" blocks remaining
    ",a+='
    ',a+='
    ',a+="
    ",a+='
    '+u+"% through epoch · Subsidy drops "+n.subsidy+" → "+(n.nextSubsidy||"?")+" BTC
    ",a+="
    "}a+='
    ',a+=y("⚡","Sats per Dollar",p(n.satsPerDollar),"Moscow Time","How many satoshis (sats) you get for $1 USD. A satoshi is the smallest unit of Bitcoin (0.00000001 BTC). Also called Moscow Time — the number on the clock is how many sats per dollar."),a+=y("⛓️","Block Height",p(n.blockHeight),"","The total number of blocks mined since Bitcoin's Genesis Block on Jan 3, 2009. A new block is added roughly every 10 minutes. This number only goes up — never down."),a+=y("🪙","Block Subsidy",n.subsidy+" BTC",p(n.halving)+" blocks to halving","The reward miners receive for finding each new block. Started at 50 BTC in 2009 and halves every 210,000 blocks (~4 years). Currently 3.125 BTC per block.");var g,f="";if(null!=n.hashrateChange24h){var b=n.hashrateChange24h;f=''+(b>=0?"▲":"▼")+" "+Math.abs(b).toFixed(1)+"%"}a+=y("⛏️","Hashrate",null==(g=n.hashrate)?"—":g>=1e18?(g/1e18).toFixed(2)+" EH/s":g>=1e15?(g/1e15).toFixed(2)+" PH/s":g>=1e12?(g/1e12).toFixed(2)+" TH/s":g>=1e9?(g/1e9).toFixed(2)+" GH/s":g>=1e6?(g/1e6).toFixed(2)+" M":g>=1e3?(g/1e3).toFixed(1)+"K":p(g),f,"The total computing power securing the Bitcoin network, measured in hashes per second. Higher hashrate = more secure network. EH/s = quintillion hashes per second."),a+=y("🎯","Difficulty",h(n.difficulty),"","How hard it is to mine a new block. Adjusts every 2,016 blocks (~2 weeks) to keep block times at ~10 minutes. If miners join, difficulty goes up. If miners leave, it goes down."),a+=y("🔄","Next Adjustment",(n.diffChange>=0?"+":"")+(n.diffChange||0).toFixed(2)+"%",i+" · "+p(n.diffRemaining)+" blocks","The estimated change in mining difficulty at the next adjustment. Positive means blocks are being found faster than 10 min (more miners joined). Negative means slower (miners left)."),a+=y("💸","Fast Fee",(n.feeFast||"—")+" sat/vB","Half-hour: "+(n.feeHalf||"—")+" · Economy: "+(n.feeEcon||"—"),"The recommended transaction fee in satoshis per virtual byte (sat/vB). Fast = next block (~10 min). Half-hour = 1-3 blocks. Economy = lowest priority. Higher fees = faster confirmation."),a+=y("📋","Mempool",p(n.mempoolTxs)+" txs",n.mempoolSize?(n.mempoolSize/1e6).toFixed(1)+" MvB":"","The waiting room for unconfirmed Bitcoin transactions. Shows how many transactions are waiting to be included in a block and their total size. A full mempool means higher fees."),a+=y("💰","Circulating Supply",function(e){return e?(e/1e6).toFixed(2)+"M / 21M":"—"}(n.supply),function(e){return e?(e/21e6*100).toFixed(2)+"%":"—"}(n.supply)+" mined","How many of the 21 million total Bitcoin have been mined so far. No more than 21 million will ever exist — this is enforced by code and consensus. The last Bitcoin will be mined around the year 2140.");var v="";if(null!=n.mktCapChange24h){var w=n.mktCapChange24h;v=''+(w>=0?"▲":"▼")+" "+Math.abs(w).toFixed(1)+"%"}a+=y("📊","Market Cap","$"+h(n.marketCap),v,"Total value of all Bitcoin in circulation (price × circulating supply). Puts Bitcoin's size in perspective compared to gold (~$16T), the S&P 500, or global real estate.");var x="";n.volume24h&&n.marketCap&&(x="Vol/MCap: "+(n.volume24h/n.marketCap*100).toFixed(2)+"%"),a+=y("📈","24h Volume","$"+h(n.volume24h),x,"Total USD value of Bitcoin traded across all exchanges in the last 24 hours. High volume often signals strong market interest or significant price moves.");var k=n.lnCapacity?(n.lnCapacity/1e8).toFixed(0):"—",T=n.lnCapacity&&n.price?"$"+h(n.lnCapacity/1e8*n.price):"",E=(n.lnNodes?p(n.lnNodes)+" nodes · ":"")+(n.lnChannels?p(n.lnChannels)+" channels":"")+(T?"
    "+T:"");a+=y("⚡","Lightning Capacity",p(k)+" BTC",E,"Total Bitcoin locked in Lightning Network payment channels. Lightning enables instant, near-free Bitcoin payments. More capacity = more liquidity for fast payments. Nodes route payments; channels connect them."),n.ath&&(a+='
    ',a+='🏔️',a+='
    All-Time High
    ',a+='
    $'+p(n.ath,0)+"
    ",a+='
    '+(n.athChange||0).toFixed(1)+"%
    ",n.athDate&&(a+='
    '+new Date(n.athDate).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})+"
    "),a+="
    "),a+="
    ";var A=n.marketCap?n.marketCap/1e12:0;return a+='
    ',a+='
    ⚖️ Bitcoin vs Gold
    ',a+='
    ',a+='
    ₿ Bitcoin$'+A.toFixed(2)+"T
    ",a+='
    ',a+='
    🥇 GoldLoading...
    ',a+='
    Fetching live gold price...
    ',a+="
    ",setTimeout(function(){!function(e,t){if(!B)try{var o=JSON.parse(localStorage.getItem("btc_gold_cache"));o&&o.p&&(B=o.p,S=o.t||0)}catch(e){}B&&Date.now()-S<18e5?_(B,e,t):(B&&_(B,e,t),fetch("https://api.coingecko.com/api/v3/simple/price?ids=tether-gold&vs_currencies=usd").then(function(e){return e.json()}).then(function(o){var n=o["tether-gold"]?o["tether-gold"].usd:null;if(n){B=n,S=Date.now();try{localStorage.setItem("btc_gold_cache",JSON.stringify({p:n,t:Date.now()}))}catch(e){}_(n,e,t)}}).catch(function(){B||_(3200,e,t)}))}(A,n.supply||0)},150),a+='
    ',a+='
    🏛️ Bitcoin Treasuries ⓘ tap for top holders
    ',a+='
    Loading live treasury data...
    ',a+="
    ",setTimeout(function(){!function(e){var t=document.getElementById("treasuryData");if(t){if(!I)try{var o=JSON.parse(localStorage.getItem("btc_treasury_cache"));o&&o.d&&(I=o.d,C=o.t||0)}catch(e){}I&&Date.now()-C<18e5?z(t,I,e):(I&&z(t,I,e),fetch("https://api.coingecko.com/api/v3/companies/public_treasury/bitcoin").then(function(e){return e.json()}).then(function(o){I=o,C=Date.now();try{localStorage.setItem("btc_treasury_cache",JSON.stringify({d:o,t:Date.now()}))}catch(e){}z(t,o,e)}).catch(function(){I||(t.innerHTML='
    Could not load treasury data
    ')}))}}(n.price||0)},200),a+='
    ',a+='
    🏦 Bitcoin ETFs top 5 by BTC in custody
    ',a+='
    Loading ETF holdings...
    ',a+="
    ",setTimeout(function(){!function(e,t){var o=document.getElementById("etfHoldingsData");if(o){var n=e||parseFloat(localStorage.getItem("btc_last_price"))||83e3,i=t||1984e4,a=null;try{a=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"))}catch(e){}a&&a.holdings&&L(o,a.holdings,a.totalBtc,n,i,a.updated),fetch("data/etf-holdings.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.holdings&&e.holdings.length){try{localStorage.setItem("btc_etf_holdings_cache",JSON.stringify(e))}catch(e){}L(o,e.holdings,e.totalBtc,n,i,e.updated)}}).catch(function(){a||L(o,M,P,n,i,null)})}}(n.price||0,n.supply||0)},250),a+='
    ',a+='',a+='
    ",a+='
    ',a+="Data Sources: ",a+='mempool.space (blocks, fees, hashrate, difficulty, mempool) · ',a+='CoinGecko (price, market cap, supply, volume) · ',a+='Alternative.me (Fear & Greed Index) · ',a+='BitcoinTreasuries.net (company & government holdings)',a+='
    Last updated: '+new Date(n.ts||Date.now()).toLocaleTimeString()+"
    ",a+="
    ",setTimeout(function(){window._halvingTargetMs&&document.getElementById("halvSecs")&&"function"==typeof window._startHalvingTicker&&window._startHalvingTicker(),"function"==typeof window._attachTipListeners&&window._attachTipListeners()},100),a}function y(e,t,o,n,i){return"
    '+e+" "+t+(i?' ':"")+'
    '+(o||"—")+"
    "+(n?'
    '+n+"
    ":"")+""}setInterval(function(){d&&(console.warn("[Dashboard] Force-clearing stuck loading flag"),d=!1)},15e3);var b="ontouchstart"in window||navigator.maxTouchPoints>0;function v(){injectDashboardButton(),injectHomeDashboardButton(),i()}window.showDashTip=function(e,t){var o=document.getElementById("dashTipPopup");o&&o.remove();var n=document.createElement("div");n.id="dashTipPopup",n.style.cssText="position:absolute;left:50%;transform:translateX(-50%);bottom:calc(100% + 8px);z-index:10;background:var(--bg-side,#1a1a2e);border:1px solid var(--accent);border-radius:10px;padding:10px 14px;max-width:320px;width:max-content;box-shadow:0 8px 24px rgba(0,0,0,0.5);animation:fadeSlideIn 0.2s ease-out;pointer-events:auto;",n.innerHTML='
    '+t.replace(/\\n/g,"
    ").replace(/\n/g,"
    ")+'
    ',e.style.position="relative",e.appendChild(n),setTimeout(function(){document.addEventListener("click",function e(t){n.parentNode&&n.remove(),document.removeEventListener("click",e)},{once:!0})},50)},window.hideDashTip=function(e){var t=e?e.querySelector("#dashTipPopup"):document.getElementById("dashTipPopup");t&&t.remove()},window._attachTipListeners=function(){document.querySelectorAll("[data-dash-tip]:not([data-tip-bound])").forEach(function(e){e.setAttribute("data-tip-bound","1");var t=e.getAttribute("data-dash-tip");t&&(b?e.addEventListener("click",function(o){o.stopPropagation();var n=e.querySelector("#dashTipPopup");n?n.remove():showDashTip(e,t)}):(e.addEventListener("mouseenter",function(){showDashTip(e,t)}),e.addEventListener("mouseleave",function(){hideDashTip(e)})))})},window.injectDashboardButton=function(){},window.injectHomeDashboardButton=function(){},window.toggleDashboard=async function(){var e=document.getElementById("btcDashOverlay");if(e)return e.remove(),clearInterval(u),void(u=null);var t=document.createElement("div");t.id="btcDashOverlay",t.style.cssText="position:fixed;inset:0;z-index:10002;background:rgba(0,0,0,0.88);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&closeDashboard()};var o=document.createElement("div");o.id="btcDashCard",o.style.cssText="background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:24px;max-width:500px;width:100%;margin:40px auto;box-shadow:0 20px 60px rgba(0,0,0,0.5);animation:fadeSlideIn 0.3s ease-out;",t.appendChild(o),document.body.appendChild(t),i();var n=!1;try{var a=JSON.parse(localStorage.getItem(s));a&&a.data&&(a.data.price||a.data.blockHeight)&&(o.innerHTML=f(a.data),n=!0)}catch(e){}if(!n){var r={};if("undefined"!=typeof nachoLiveData&&(nachoLiveData.price&&(r.price=nachoLiveData.price),nachoLiveData.blockHeight&&(r.blockHeight=nachoLiveData.blockHeight)),!r.price)try{r.price=parseFloat(localStorage.getItem("btc_last_price"))||0}catch(e){}if(!r.blockHeight)try{r.blockHeight=parseInt(localStorage.getItem("btc_last_height"))||0}catch(e){}r.price||r.blockHeight?(o.innerHTML=f(r),n=!0):o.innerHTML='
    Loading Bitcoin metrics...
    '}g().then(function(e){var t=document.getElementById("btcDashCard");if(t){var o=document.getElementById("topIndicatorsPanel"),i=o&&"none"!==o.style.display;if(e&&(e.price||e.blockHeight)?t.innerHTML=f(e):n||(t.innerHTML='
    📊
    Unable to load fresh metrics.
    Showing last known data. Try again later.
    '),i){var a=document.getElementById("topIndicatorsPanel"),r=document.getElementById("topIndArrow");a&&(a.style.display="block",w=!1,k()),r&&(r.textContent="▲")}}}),u=setInterval(async function(){if(document.getElementById("btcDashOverlay")){var e=document.getElementById("topIndicatorsPanel"),t=e&&"none"!==e.style.display;localStorage.removeItem(s);var o=await g(),n=document.getElementById("btcDashCard");if(n&&(n.innerHTML=f(o),t)){var i=document.getElementById("topIndicatorsPanel"),a=document.getElementById("topIndArrow");i&&(i.style.display="block",w=!1,k()),a&&(a.textContent="▲")}}else clearInterval(u)},l)},window.closeDashboard=function(){var e=document.getElementById("btcDashOverlay");e&&e.remove(),u&&(clearInterval(u),u=null)},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(v,2e3)}):setTimeout(v,2e3),window.toggleTopIndicators=function(){var e=document.getElementById("topIndicatorsPanel"),t=document.getElementById("topIndArrow");e&&("none"===e.style.display?(e.style.display="block",t.textContent="▲",k()):(e.style.display="none",t.textContent="▼"))};var w=!1,x="btc_top_indicators_cache";function k(){if(!w){w=!0;var e=document.getElementById("topIndContent");if(e){try{var t=JSON.parse(localStorage.getItem(x));if(t&&t.html){var o=Math.round((Date.now()-t.ts)/6e4),n=o>5?'
    📦 Cached '+(o<60?o+"m":Math.round(o/60)+"h")+" ago · refreshing...
    ":"";e.innerHTML=n+t.html}}catch(e){}var i=c||{},a=i.price||0,r=i.blockHeight||0,s=i.supply||0,l=i.fearGreed||0,d=i.fearGreedLabel||"—",u=[];if(r){var m=Math.floor(r/21e4),h=50/Math.pow(2,m)*6*24*365,g=h>0?(s||198e5)/h:0,f=Math.pow(10,3.31954*Math.log10(g)-1.32093),y=a>0?(a/f).toFixed(2):"—";u.push({emoji:"📈",name:"Stock-to-Flow",value:g.toFixed(1),sub:"Model: $"+p(Math.round(f))+" · Ratio: "+y+"x",tip:"Stock-to-Flow measures scarcity. Higher S2F = scarcer asset. Bitcoin's S2F increases with each halving. Gold is ~62, Silver ~22. A ratio below 1x suggests undervalued vs the model."})}if(l){var b=l<=25?"#ef4444":l<=45?"#f97316":l<=55?"#eab308":l<=75?"#84cc16":"#22c55e";u.push({emoji:"😱",name:"Fear & Greed",value:l,color:b,sub:d,tip:"Crypto Fear & Greed Index. 0 = Extreme Fear (potential buy), 100 = Extreme Greed (potential sell). Aggregates volatility, momentum, social media, and surveys."})}if(u.push({emoji:"📐",name:"Mayer Multiple",value:"...",sub:"Loading...",tip:"Price divided by 200-day moving average. Below 1.0 = historically cheap. Above 2.4 = overheated. Named after Trace Mayer.",id:"mayerMultiple"}),r){var v=r%21e4,k=(v/21e4*100).toFixed(1),B=Math.round(10*v/1440),S=B>=365&&B<=730;u.push({emoji:"🔄",name:"Halving Cycle",value:k+"%",sub:"Day "+B+"/~1460"+(S?" · 🔥 Peak Window":""),color:S?"#f97316":null,tip:"Position in the current 4-year halving cycle (210,000 blocks). Historically, price peaks occur 12-24 months after a halving (Day 365-730). We are at day "+B+"."})}if(i.ath&&i.athDate){var T=new Date(i.athDate),_=Math.floor((Date.now()-T.getTime())/864e5),I=i.athChange?Math.abs(i.athChange).toFixed(1):"—";u.push({emoji:"🏔️",name:"ATH Drawdown",value:"-"+I+"%",sub:_+" days since ATH ($"+p(Math.round(i.ath))+")",tip:"Current drawdown from the all-time high. In previous cycles, bear markets saw -70% to -85% drawdowns. Recovery to new ATH has always followed."})}if(a&&s&&r){m=Math.floor(r/21e4);for(var C=0,E=r,A=0;A<=m&&E>0;A++){var z=Math.min(E,21e4);C+=z*(50/Math.pow(2,A)),E-=z}var M=3e4*C,L=M>0?(a*s/M).toFixed(1):"—";u.push({emoji:"🌡️",name:"Thermo Multiple",value:L+"x",sub:"Market Cap / Thermocap",tip:'Thermocap Multiple compares market cap to total miner revenue (a proxy for "energy spent"). Values >5x historically signal overheating (cycle tops hit 4-8x). <10x = accumulation zone.'})}if(a&&s&&i.volume24h){var U=a*s,q=i.volume24h>0?(U/i.volume24h).toFixed(1):"—",N=q<30?"#22c55e":q>150?"#ef4444":"var(--heading)";u.push({emoji:"📡",name:"NVT Ratio",value:q,color:N,sub:q<30?"Undervalued zone":q>150?"Overvalued zone":"Normal range",tip:"Network Value to Transactions ratio. Compares market cap to annualized transaction volume. Below 30 = undervalued relative to usage. Above 150 = potentially overvalued. Think of it like P/E ratio for Bitcoin."})}if(i.marketCap){var H=i.marketCap/.62;(i.marketCap/H*100).toFixed(1),u.push({emoji:"👑",name:"BTC Dominance",value:"~62%",sub:"Market cap share vs all crypto",tip:"Bitcoin's share of the total cryptocurrency market cap. Higher dominance = Bitcoin is outperforming alts. During alt seasons, dominance drops below 40%. During Bitcoin seasons (now), it rises above 55-65%. Historically, increasing dominance signals strength.",id:"btcDominance"})}if(u.push({emoji:"💎",name:"MVRV Z-Score",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Market Value to Realized Value ratio. Compares market cap to realized cap (sum of each coin valued at its last move price). Above 3.0 historically marks cycle tops. Below 1.0 marks bottoms. Data from CBBI open-source API. Top threshold: normalized ≥ 0.7 (≈ MVRV 3+).",id:"mvrvScore"}),a){var D=new Date("2009-01-03T00:00:00Z"),O=Math.floor((Date.now()-D.getTime())/864e5),W=5.82*Math.log10(O)-17.01,R=Math.pow(10,W),j=((a-R)/R*100).toFixed(0),F=parseFloat(j),G=F>200?"#ef4444":F>100?"#f97316":F<-30?"#22c55e":"var(--heading)",V=F>200,Q=F>200?"Far above — extreme ⚠️":F>100?"Above trend — elevated":F>0?"Above fair value":F>-30?"Near fair value":"Below trend — deep value 🟢";u.push({emoji:"📏",name:"Power Law",value:(F>=0?"+":"")+j+"%",color:G,sub:"Fair value: ~$"+p(Math.round(R))+" · "+Q,tip:"Bitcoin Power Law model tracks the long-term price trend using a log-log regression since genesis (Jan 3, 2009). Parameters: P = 10^(5.82 × log₁₀(days) - 17.01). Above +200% = historically extreme (cycle top zone). Below -30% = deep value accumulation. Current: "+O+" days since genesis.",flashing:V})}if(u.push({emoji:"🔵",name:"Pi Cycle Top",value:"...",sub:"Loading...",tip:"When the 111-day MA crosses above the 350-day MA × 2, it has historically signaled the exact top of every Bitcoin cycle. Flashes when the gap narrows to <5%.",id:"piCycleTop",flashing:!1}),r&&a){var J=(144*(i.subsidy?parseFloat(i.subsidy):3.125)*a/27e6).toFixed(2),Y=parseFloat(J);u.push({emoji:"⛏️",name:"Puell Multiple",value:J,color:Y>2.2?"#ef4444":Y<.5?"#22c55e":"var(--heading)",sub:Y>2.2?"Miners overleveraged ⚠️":Y<.5?"Miner capitulation zone 🟢":"Normal range",tip:"Ratio of daily miner revenue to its 365-day moving average. Above 2.2 = miners are earning far more than usual (historically a sell signal). Below 0.5 = miner capitulation (buy signal). Top threshold: ≥ 2.2.",flashing:Y>=2.2})}if(a){for(var X=new Date("2010-07-18"),K=Math.floor((Date.now()-X.getTime())/864e5),$=Math.log(K+1400),Z=[2.775,2.788,2.801,2.815,2.8295,2.8445,2.859,2.872,2.886,2.9],ee=10,te=0;te=9})}if(a){for(var ae=new Date("2009-01-03T00:00:00Z"),re=Math.floor((Date.now()-ae.getTime())/864e5),se=0,le=0;le<1460;le++){var ce=re-le;ce>365&&(se+=Math.pow(10,5.82*Math.log10(ce)-17.01))}var de=se/1460,ue=de>0?(a/de).toFixed(2):"—",pe=parseFloat(ue);u.push({emoji:"📊",name:"4-Year MA Multiple",value:ue+"x",color:pe>=3.5?"#ef4444":pe<1?"#22c55e":"var(--heading)",sub:"Est. 4Y MA: ~$"+p(Math.round(de))+(pe>=3.5?" · Top zone ⚠️":""),tip:"Price divided by the 4-year (1460-day) moving average. Historically, when price exceeds 3.5× the 4-year MA, it signals a cycle top. Below 1× = accumulation zone. Top threshold: ≥ 3.5.",flashing:pe>=3.5})}if(u.push({emoji:"💰",name:"NUPL",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Net Unrealized Profit/Loss. Shows aggregate profit/loss of all Bitcoin holders. Above 75% = euphoria (top zone). Below 0% = capitulation (bottom zone). Data from CBBI open-source API. Top threshold: normalized ≥ 0.75.",id:"nuplScore"}),a&&r){var me=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),he=Math.pow(10,5.82*Math.log10(me)-17.01),ge=he>0?(a/he).toFixed(2):"—",fe=parseFloat(ge);u.push({emoji:"🔢",name:"AHR999",value:ge,color:fe>1.2?"#ef4444":fe<.45?"#22c55e":"var(--heading)",sub:fe>1.2?"Overvalued — stop DCA ⚠️":fe<.45?"Deep value — DCA zone 🟢":fe<1?"Below model — DCA":"Near model",tip:"AHR999 compares current price to its long-term model value. Below 0.45 = extreme buy (accumulate aggressively). Above 1.2 = stop DCA, consider selling. Used by cost-averaging investors to time entries. Top threshold: ≥ 1.2.",flashing:fe>=1.2})}if(a){for(var ye=new Date("2009-01-03T00:00:00Z"),be=Math.floor((Date.now()-ye.getTime())/864e5),ve=0,we=0;we<730;we++){var xe=be-we;xe>365&&(ve+=Math.pow(10,5.82*Math.log10(xe)-17.01))}var ke=ve/730,Be=5*ke,Se=a>Be;u.push({emoji:"📉",name:"2-Year MA ×5",value:(a/ke).toFixed(2)+"x",color:Se?"#ef4444":a365&&(Ie+=Math.pow(10,5.82*Math.log10(Ee)-17.01))}var Ae=Ie/350,ze=Ae>0?(a/Ae).toFixed(2):"—",Me=parseFloat(ze),Pe=Me>=8?"Above ×8 — max top ⚠️":Me>=5?"Above ×5 — overheated":Me>=3?"Above ×3 — elevated":Me>=1.6?"Above ×1.6 — bullish":"Below ×1.6";u.push({emoji:"🔱",name:"Golden Ratio",value:ze+"x",color:Me>=5?"#ef4444":Me>=3?"#f97316":"var(--heading)",sub:"350d MA: $"+p(Math.round(Ae))+" · "+Pe,tip:"Price relative to the 350-day MA using Fibonacci golden ratio multiples (1.6, 2, 3, 5, 8, 13, 21). Each cycle top has touched a lower multiple. Top threshold: ≥ 5×.",flashing:Me>=5})}if(r&&s&&a){for(var Le=0,Ue=r,qe=0;qe<=Math.floor(r/21e4)&&Ue>0;qe++){var Ne=Math.min(Ue,21e4);Le+=Ne*(50/Math.pow(2,qe)),Ue-=Ne}var He=21*(s>0?3e4*Le/s:0),De=He>0?(a/He*100).toFixed(0):"—";u.push({emoji:"🎯",name:"Terminal Price",value:"$"+p(Math.round(He)),color:a>=He?"#ef4444":"var(--heading)",sub:"Current: "+De+"% of terminal · "+(a>=He?"ABOVE — extreme ⚠️":"Below terminal"),tip:"Terminal Price = Transferred Price × 21. Represents a theoretical maximum based on cumulative miner revenue and coin movement. Every cycle top has approached or exceeded this level. Top threshold: price ≥ Terminal Price.",flashing:a>=He})}if(a){var Oe=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),We=Math.pow(10,5.82*Math.log10(Oe)-17.01),Re=(We>0?(Math.log10(a)-Math.log10(We))/.3:0).toFixed(1),je=parseFloat(Re);u.push({emoji:"🫧",name:"Bubble Index",value:Re+"σ",color:je>=2?"#ef4444":je>=1?"#f97316":je<-1?"#22c55e":"var(--heading)",sub:je>=2?"Extreme bubble ⚠️":je>=1?"Elevated":je<-1?"Deep discount 🟢":"Normal",tip:"How many standard deviations Bitcoin's price is above its long-term log trend. Above +2σ = extreme bubble territory (historical tops). Below -1σ = deep value. Top threshold: ≥ 2σ.",flashing:je>=2})}if(a){var Fe=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),Ge=Math.pow(10,5.82*Math.log10(Fe-90)-17.01),Ve=(Ge>0?100*(Math.pow(a/Ge,4)-1):0).toFixed(0),Qe=parseFloat(Ve);u.push({emoji:"🚀",name:"3M Annualized",value:(Qe>=0?"+":"")+Ve+"%",color:Qe>200?"#ef4444":Qe>100?"#f97316":"var(--heading)",sub:Qe>200?"Unsustainable — top risk ⚠️":Qe>100?"Very high":"Normal",tip:"3-month return annualized. When Bitcoin is gaining over 200% annualized, it historically signals the late stages of a bull run. Top threshold: > 200%.",flashing:Qe>200,id:"ann3m"})}if(a){var Je=75694,Ye=762099,Xe=((a-Je)/Je*100).toFixed(1);u.push({emoji:"🏢",name:"MSTR Avg Cost",value:"$"+p(Je),sub:p(Ye)+" BTC · P&L: "+(Xe>=0?"+":"")+Xe+"%",tip:"MicroStrategy (MSTR) average Bitcoin acquisition cost. When price is far above MSTR's cost basis, it indicates broader market euphoria. MSTR holds "+p(Ye)+" BTC. Informational — no top threshold.",flashing:!1,noFlashLogic:!0})}if(u.push({emoji:"🎯",name:"CBBI Index",value:"...",color:"var(--heading)",sub:"Loading CBBI data...",tip:"Colin Talks Crypto Bitcoin Bull Run Index. Combines 9 on-chain metrics into a single 0-100 confidence score. Above 80 = approaching cycle top. Below 20 = approaching bottom. Open source. Top threshold: ≥ 80.",id:"cbbiScore"}),u.push({emoji:"💎",name:"RHODL Ratio",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Realized HODL Ratio. Compares 1-week realized value to 1-2 year realized value, adjusted by market age. High values = speculative activity dominating (top signal). Low values = long-term holders dominating. Top threshold: normalized ≥ 0.85.",id:"rhodlRatio"}),u.push({emoji:"📊",name:"Macro Oscillator",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Bitcoin Macro Oscillator (Woobull). Composite z-score of MVRV, VWAP, CVDD, and Sharpe ratios. Above 0.7 = euphoria zone. Below 0.2 = accumulation zone. Top threshold: normalized ≥ 0.7.",id:"macroOsc"}),a){var Ke=23e4,$e=(a/Ke*100).toFixed(1);u.push({emoji:"🔮",name:"Smithson's Forecast",value:$e+"%",color:parseFloat($e)>=90?"#ef4444":"var(--heading)",sub:"Target: $"+p(175e3)+"-$"+p(Ke)+" · Current: $"+p(Math.round(a)),tip:"Sminston With quantile regression model (99th percentile). Forecasts cycle top at $175K-$230K. Progress shows how close current price is to the upper target. Top threshold: ≥ 90% of target.",flashing:parseFloat($e)>=90})}u.push({emoji:"⏳",name:"LTH/STH Ratio",value:"...",color:"var(--heading)",sub:"Estimated from CBBI data...",tip:"Long-Term Holder to Short-Term Holder supply ratio (estimated). When LTH supply drops sharply (distributing to STH), it signals late-cycle selling. When LTH supply grows, holders are accumulating. Derived from CBBI on-chain metrics. Top threshold: CBBI MVRV + Puell both > 0.7.",id:"lthSthRatio"}),u.push({emoji:"📉",name:"RSI-22 Day",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Relative Strength Index over 22 days. Above 80 = overbought (potential top signal). Below 30 = oversold (potential bottom). 22-day RSI smooths out short-term noise. Top threshold: ≥ 80.",id:"rsi22d"}),u.push({emoji:"🚨",name:"AHR999x",value:"...",color:"var(--heading)",sub:"Loading 200d MA...",tip:"AHR999x Escape Top indicator. Calculated as (price / 200-day MA)². When above 8, signals extreme overvaluation. Above 3.5 = elevated. A complement to the AHR999 DCA indicator. Top threshold: ≥ 8.",id:"ahr999x"}),u.push({emoji:"🏦",name:"ETF/BTC Ratio",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Bitcoin spot ETF total AUM divided by BTC market cap. Shows how much of Bitcoin's value is held in ETFs. High ratios (>8%) could indicate institutional overexposure. Low ratios = room to grow. Top threshold: ≥ 8%.",id:"etfBtcRatio"}),u.push({emoji:"📊",name:"ETF Net Flow",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Daily Bitcoin spot ETF net inflows/outflows. Sustained outflows (7+ days) can signal institutional selling. Sustained inflows signal demand. Data from Bitbo/BitcoinTreasuries. Top threshold: 7+ consecutive outflow days.",flashing:!1,id:"etfNetFlow"}),u.push({emoji:"📈",name:"ETF 5-Day Flow",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Sum of last 5 trading days of ETF flows. Large negative = sustained selling pressure. Large positive = accumulation. Top threshold: 5-day sum below -$500M.",flashing:!1,id:"etf5dFlow"}),u.forEach(function(e){if(!e.noFlashLogic&&void 0===e.flashing){var t=e.name;e.flashing="Stock-to-Flow"===t?a>0&&f>0&&a>1.5*f:"Fear & Greed"===t?l>=75:"Mayer Multiple"!==t&&("Halving Cycle"===t?e.sub&&-1!==e.sub.indexOf("Peak Window"):"ATH Drawdown"===t?parseFloat(e.value)>-5:"Thermo Multiple"===t?parseFloat(e.value)>5:"NVT Ratio"===t&&parseFloat(e.value)>150)}});var Ze=u.filter(function(e){return e.flashing}).length,et=u.filter(function(e){return!e.noFlashLogic}).length,tt="",ot=et>0?Math.round(Ze/et*100):0,nt=0===Ze?"#22c55e":ot<15?"#eab308":ot<40?"#f97316":"#ef4444";tt+='
    ',tt+='
    '+Ze+" / "+et+"
    ",tt+='
    '+(0===Ze?"No top signals — Accumulate 🟢":ot<15?"Few signals — Monitor 🟡":ot<40?"Multiple signals — Caution 🟠":"Many signals — Extreme caution 🔴")+"
    ",tt+='
    Top indicators flashing 🔴 = potential cycle top signal
    ',tt+="
    ",u.forEach(function(e){var t=e.flashing?"rgba(239,68,68,0.5)":"var(--border)",o=e.flashing?"background:rgba(239,68,68,0.04);":"";tt+="",e.noFlashLogic||(e.flashing?tt+='
    🔴 TOP
    ':tt+='
    🟢 OK
    '),tt+='
    '+e.emoji+" "+e.name+(e.tip?' ':"")+"
    ",tt+='
    '+(e.value||"—")+"
    ",e.sub&&(tt+='
    '+e.sub+"
    "),tt+=""}),tt+='',e.innerHTML=tt,setTimeout(function(){"function"==typeof window._attachTipListeners&&window._attachTipListeners()},50);try{localStorage.setItem(x,JSON.stringify({html:tt,ts:Date.now()}))}catch(e){}fetch("https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=365&interval=daily").then(function(e){return e.json()}).then(function(e){if(e&&e.prices&&e.prices.length>=200){for(var t=e.prices,o=t.length,n=0,i=Math.max(0,o-200);i2.4?"#ef4444":"var(--heading)";l.style.color=c,l.textContent=s+"x";var d=l.nextElementSibling;d&&(d.textContent="200d MA: $"+p(Math.round(a))+(s<1?" · Below MA ✅":s>2.4?" · Overheated ⚠️":""));var u=l.closest('div[style*="border-radius:12px"]');if(u&&s>2.4){u.style.borderColor="rgba(239,68,68,0.5)",u.style.background="rgba(239,68,68,0.04)";var m=u.querySelector('div[style*="OK"]');m&&(m.innerHTML="🔴 TOP",m.style.color="#ef4444",m.style.background="rgba(239,68,68,0.15)",m.style.borderColor="rgba(239,68,68,0.4)")}}if(o>=111){for(var h=0,g=o-111;g0?((f-w)/w*100).toFixed(1):0,k=parseFloat(x),B=document.getElementById("piCycleTop");if(B){var S=k>=0;B.textContent=(k>=0?"+":"")+x+"%",B.style.color=S?"#ef4444":k>-5?"#f97316":"var(--heading)";var T=B.nextElementSibling;T&&(T.textContent="111d: $"+p(Math.round(f))+" vs 350d×2: $"+p(Math.round(w))+(S?" · CROSSED ⚠️":k>-5?" · Narrowing!":""));var _=B.closest('div[style*="border-radius:12px"]');if(_&&S){_.style.borderColor="rgba(239,68,68,0.5)",_.style.background="rgba(239,68,68,0.04)";var I=_.querySelector('div[style*="OK"]');I&&(I.innerHTML="🔴 TOP",I.style.color="#ef4444",I.style.background="rgba(239,68,68,0.15)",I.style.borderColor="rgba(239,68,68,0.4)")}}}if(o>=23){for(var C=0,E=0,A=o-22;A0?C+=z:E-=z}var M=E/22,P=0===M?100:100-100/(1+C/22/M),L=P.toFixed(1),U=document.getElementById("rsi22d");if(U){var q=P>=80;U.textContent=L,U.style.color=P>=80?"#ef4444":P<=30?"#22c55e":"var(--heading)";var N=U.nextElementSibling;if(N&&(N.textContent=P>=80?"Overbought ⚠️":P<=30?"Oversold ✅":P>=60?"Bullish":P<=40?"Bearish":"Neutral"),q){var H=U.closest('div[style*="border-radius:12px"]');if(H){H.style.borderColor="rgba(239,68,68,0.5)",H.style.background="rgba(239,68,68,0.04)";var D=H.querySelector('div[style*="OK"]');D&&(D.innerHTML="🔴 TOP",D.style.color="#ef4444",D.style.background="rgba(239,68,68,0.15)",D.style.borderColor="rgba(239,68,68,0.4)")}}}}var O=Math.pow(r/a,2).toFixed(2),W=document.getElementById("ahr999x");if(W){var R=parseFloat(O),j=R>=8;W.textContent=O,W.style.color=R>=8?"#ef4444":R>=3.5?"#f97316":"var(--heading)";var F=W.nextElementSibling;if(F&&(F.textContent="200d MA: $"+p(Math.round(a))+(R>=8?" · Extreme top ⚠️":R>=3.5?" · Elevated":R<1?" · Below MA":" · Normal")),j){var G=W.closest('div[style*="border-radius:12px"]');if(G){G.style.borderColor="rgba(239,68,68,0.5)",G.style.background="rgba(239,68,68,0.04)";var V=G.querySelector('div[style*="OK"]');V&&(V.innerHTML="🔴 TOP",V.style.color="#ef4444",V.style.background="rgba(239,68,68,0.15)",V.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("mayerMultiple");e&&(e.textContent="N/A")}),fetch("https://api.coingecko.com/api/v3/global").then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.market_cap_percentage&&e.data.market_cap_percentage.btc){var t=e.data.market_cap_percentage.btc.toFixed(1),o=document.getElementById("btcDominance");if(o){o.textContent=t+"%";var n=t>55?"#22c55e":t<40?"#ef4444":"var(--heading)";o.style.color=n;var i=o.nextElementSibling;i&&(i.textContent=t>55?"Bitcoin season 👑":t<40?"Alt season ⚠️":"Neutral")}}}).catch(function(){}),fetch("https://colintalkscrypto.com/cbbi/data/latest.json").then(function(e){return e.json()}).then(function(e){if(e&&e.Confidence){var t=Object.keys(e.Confidence).sort(),o=t[t.length-1],n=(100*e.Confidence[o]).toFixed(0),i=parseInt(n),a=document.getElementById("cbbiScore");if(a){a.textContent=n+"%",a.style.color=i>=80?"#ef4444":i<=20?"#22c55e":"var(--heading)";var r=a.nextElementSibling;if(r&&(r.textContent=i>=80?"Approaching top ⚠️":i<=20?"Approaching bottom 🟢":i>=50?"Mid-cycle bullish":"Early cycle"),i>=80){var s=a.closest('div[style*="border-radius:12px"]');if(s){s.style.borderColor="rgba(239,68,68,0.5)",s.style.background="rgba(239,68,68,0.04)";var l=s.querySelector('div[style*="OK"]');l&&(l.innerHTML="🔴 TOP",l.style.color="#ef4444",l.style.background="rgba(239,68,68,0.15)",l.style.borderColor="rgba(239,68,68,0.4)")}}}var c=Object.keys(e.RHODL).sort(),d=e.RHODL[c[c.length-1]],u=document.getElementById("rhodlRatio");if(u){u.textContent=(100*d).toFixed(0)+"%",u.style.color=d>=.85?"#ef4444":d<=.2?"#22c55e":"var(--heading)";var p=u.nextElementSibling;if(p&&(p.textContent=d>=.85?"Speculative frenzy ⚠️":d<=.2?"Accumulation zone 🟢":"Normalized: "+(100*d).toFixed(0)+"%"),d>=.85){var m=u.closest('div[style*="border-radius:12px"]');if(m){m.style.borderColor="rgba(239,68,68,0.5)",m.style.background="rgba(239,68,68,0.04)";var h=m.querySelector('div[style*="OK"]');h&&(h.innerHTML="🔴 TOP",h.style.color="#ef4444",h.style.background="rgba(239,68,68,0.15)",h.style.borderColor="rgba(239,68,68,0.4)")}}}var g=Object.keys(e.Woobull).sort(),f=e.Woobull[g[g.length-1]],y=document.getElementById("macroOsc");if(y){y.textContent=(100*f).toFixed(0)+"%",y.style.color=f>=.7?"#ef4444":f<=.2?"#22c55e":"var(--heading)";var b=y.nextElementSibling;if(b&&(b.textContent=f>=.7?"Euphoria zone ⚠️":f<=.2?"Accumulation 🟢":"Normalized: "+(100*f).toFixed(0)+"%"),f>=.7){var v=y.closest('div[style*="border-radius:12px"]');if(v){v.style.borderColor="rgba(239,68,68,0.5)",v.style.background="rgba(239,68,68,0.04)";var w=v.querySelector('div[style*="OK"]');w&&(w.innerHTML="🔴 TOP",w.style.color="#ef4444",w.style.background="rgba(239,68,68,0.15)",w.style.borderColor="rgba(239,68,68,0.4)")}}}var x=Object.keys(e.MVRV).sort(),k=Object.keys(e.Puell).sort(),B=e.MVRV[x[x.length-1]],S=e.Puell[k[k.length-1]],T=document.getElementById("lthSthRatio");if(T){var _=((B+S)/2*100).toFixed(0),I=parseInt(_);T.textContent=I+"%",T.style.color=I>=70?"#ef4444":I<=25?"#22c55e":"var(--heading)";var C=T.nextElementSibling;if(C&&(C.textContent=I>=70?"LTH distributing ⚠️":I<=25?"LTH accumulating 🟢":"Distribution score: "+I+"%"),I>=70){var E=T.closest('div[style*="border-radius:12px"]');if(E){E.style.borderColor="rgba(239,68,68,0.5)",E.style.background="rgba(239,68,68,0.04)";var A=E.querySelector('div[style*="OK"]');A&&(A.innerHTML="🔴 TOP",A.style.color="#ef4444",A.style.background="rgba(239,68,68,0.15)",A.style.borderColor="rgba(239,68,68,0.4)")}}}var z=document.getElementById("mvrvScore");if(z){var M=(100*B).toFixed(0);z.textContent=M+"%",z.style.color=B>=.7?"#ef4444":B<=.2?"#22c55e":"var(--heading)";var P=z.nextElementSibling;if(P&&(P.textContent=B>=.7?"Overvalued — top zone ⚠️":B<=.2?"Undervalued — accumulate 🟢":"Normalized: "+M+"%"),B>=.7){var L=z.closest('div[style*="border-radius:12px"]');if(L){L.style.borderColor="rgba(239,68,68,0.5)",L.style.background="rgba(239,68,68,0.04)";var U=L.querySelector('div[style*="OK"]');U&&(U.innerHTML="🔴 TOP",U.style.color="#ef4444",U.style.background="rgba(239,68,68,0.15)",U.style.borderColor="rgba(239,68,68,0.4)")}}}var q=Object.keys(e.RUPL).sort(),N=e.RUPL[q[q.length-1]],H=document.getElementById("nuplScore");if(H){var D=(100*N).toFixed(0);H.textContent=D+"%",H.style.color=N>=.75?"#ef4444":N<=.2?"#22c55e":"var(--heading)";var O=H.nextElementSibling;if(O&&(O.textContent=N>=.75?"Euphoria ⚠️":N<=.2?"Capitulation zone 🟢":"Normalized: "+D+"%"),N>=.75){var W=H.closest('div[style*="border-radius:12px"]');if(W){W.style.borderColor="rgba(239,68,68,0.5)",W.style.background="rgba(239,68,68,0.04)";var R=W.querySelector('div[style*="OK"]');R&&(R.innerHTML="🔴 TOP",R.style.color="#ef4444",R.style.background="rgba(239,68,68,0.15)",R.style.borderColor="rgba(239,68,68,0.4)")}}}var j=Object.keys(e.ReserveRisk).sort();e.ReserveRisk[j[j.length-1]];try{localStorage.setItem("cbbi_cache",JSON.stringify({ts:Date.now(),confidence:n,rhodl:d,woobull:f,mvrv:B,puell:S}))}catch(e){}}}).catch(function(){try{var e=JSON.parse(localStorage.getItem("cbbi_cache"));if(e&&Date.now()-e.ts<864e5){var t=document.getElementById("cbbiScore");t&&(t.textContent=e.confidence+"%")}}catch(e){}}),fetch("data/etf-flows.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.latestFlow){var t=document.getElementById("etfNetFlow");if(t){var o=e.latestFlow,n=(o>=0?"+":"")+o.toFixed(1)+"M";t.textContent=n,t.style.color=o>0?"#22c55e":o<-100?"#ef4444":o<0?"#f97316":"var(--heading)";var i=t.nextElementSibling;if(i&&(i.textContent=e.latestDate+" · "+e.outflowDays+"/"+e.totalDays+" outflow days"+(e.outflowDays>=7?" ⚠️":"")),e.outflowDays>=7){var a=t.closest('div[style*="border-radius:12px"]');if(a){a.style.borderColor="rgba(239,68,68,0.5)",a.style.background="rgba(239,68,68,0.04)";var r=a.querySelector('div[style*="OK"]');r&&(r.innerHTML="🔴 TOP",r.style.color="#ef4444",r.style.background="rgba(239,68,68,0.15)",r.style.borderColor="rgba(239,68,68,0.4)")}}}var s=document.getElementById("etf5dFlow");if(s){var l=e.sum5d;s.textContent=(l>=0?"+":"")+l.toFixed(1)+"M",s.style.color=l>100?"#22c55e":l<-500?"#ef4444":l<0?"#f97316":"var(--heading)";var c=s.nextElementSibling;if(c&&(c.textContent="5-day total"+(l<-500?" · Heavy selling ⚠️":l>500?" · Strong inflows 🟢":"")),l<-500){var d=s.closest('div[style*="border-radius:12px"]');if(d){d.style.borderColor="rgba(239,68,68,0.5)",d.style.background="rgba(239,68,68,0.04)";var u=d.querySelector('div[style*="OK"]');u&&(u.innerHTML="🔴 TOP",u.style.color="#ef4444",u.style.background="rgba(239,68,68,0.15)",u.style.borderColor="rgba(239,68,68,0.4)")}}}var p=P;try{var m=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"));m&&m.totalBtc&&(p=m.totalBtc)}catch(e){}var h=parseFloat(localStorage.getItem("btc_last_price"))||83e3,g=p*h,f=1984e4*h,y=f>0?(g/f*100).toFixed(1):"—",b=document.getElementById("etfBtcRatio");if(b){var v=parseFloat(y);b.textContent=y+"%",b.style.color=v>=8?"#ef4444":"var(--heading)";var w=b.nextElementSibling;if(w&&(w.textContent="ETF AUM: ~$"+(g/1e9).toFixed(0)+"B / Mkt Cap: ~$"+(f/1e12).toFixed(2)+"T"+(v>=8?" · High exposure ⚠️":"")),v>=8){var x=b.closest('div[style*="border-radius:12px"]');if(x){x.style.borderColor="rgba(239,68,68,0.5)",x.style.background="rgba(239,68,68,0.04)";var k=x.querySelector('div[style*="OK"]');k&&(k.innerHTML="🔴 TOP",k.style.color="#ef4444",k.style.background="rgba(239,68,68,0.15)",k.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("etfNetFlow");e&&(e.textContent="N/A")})}}}var B=null,S=0,T=212582*32150.7;function _(e,t,o){var n=e*T/1e12,i=t>0?(t/n*100).toFixed(1):"—",a=o>0?Math.round(1e12*n/o):"—",r=document.getElementById("goldMktCapLabel");r&&(r.textContent="$"+n.toFixed(1)+"T");var s=document.getElementById("goldBar");s&&(s.style.width=Math.min(parseFloat(i)||0,100)+"%");var l=document.getElementById("goldPctArea");l&&(l.innerHTML='
    '+i+'% of Gold Market Cap
    BTC needs ~$'+("number"==typeof a?p(a):a)+'/coin to match Gold
    Gold: $'+p(Math.round(e))+"/oz · Live via CoinGecko
    ");var c=document.getElementById("goldCompareCard");if(c){var d="Gold has been humanitys store of value for 5,000+ years. Bitcoin is digital gold — scarce, durable, portable, divisible, and verifiable. Gold price: $"+p(Math.round(e))+"/oz. Total above-ground gold: ~212,582 tonnes (~6.83B troy oz). Gold market cap: ~$"+n.toFixed(1)+"T. The flippening = Bitcoin absorbs golds entire monetary premium.";c.setAttribute("data-dash-tip",d),"function"==typeof window._attachTipListeners&&window._attachTipListeners()}}var I=null,C=0,E=[{name:"🇺🇸 United States",btc:325293},{name:"🇨🇳 China",btc:19e4},{name:"🇬🇧 United Kingdom",btc:61245},{name:"🇧🇹 Bhutan",btc:10635},{name:"🇸🇻 El Salvador",btc:6135}],A=649864;function z(e,t,o){var n=(t.companies||[]).slice(0,5),i=Math.round(t.total_holdings||0),a=t.total_value_usd||0,r=o||(i>0?a/i:0),s=n.map(function(e){return'
    '+(e.name||"?")+''+p(e.total_holdings)+" BTC
    "}).join(""),l=E.map(function(e){return'
    '+e.name+''+p(e.btc)+" BTC
    "}).join(""),c=i+A;e.innerHTML='
    🏢 Public Companies
    '+p(i)+'
    BTC · ~'+m(a||i*r)+'
    🏛️ Governments
    '+p(A)+'
    BTC · ~'+m(A*r)+'
    Total: '+p(c)+" BTC ("+(c/21e6*100).toFixed(1)+'% of supply)
    TOP 5 COMPANIES
    '+s+'
    TOP 5 GOVERNMENTS
    '+l+'
    Companies: live via CoinGecko · Governments: bitcointreasuries.net
    ';var d=document.getElementById("treasuryCard");d&&d.removeAttribute("onclick")}var M=[{ticker:"IBIT",name:"BlackRock",btc:787044,color:"#6366f1"},{ticker:"FBTC",name:"Fidelity",btc:213399,color:"#22c55e"},{ticker:"GBTC",name:"Grayscale",btc:180584,color:"#eab308"},{ticker:"ARKB",name:"ARK 21Shares",btc:63920,color:"#f97316"},{ticker:"BITB",name:"Bitwise",btc:53930,color:"#06b6d4"}],P=1367239;function L(e,t,o,n,i,a){var r=o*n,s=(o/i*100).toFixed(1),l=t[0].btc,c=t.map(function(e){var t=Math.max(4,e.btc/l*100).toFixed(0),o=m(e.btc*n);return'
    '+e.ticker+' '+e.name+''+p(e.btc)+' BTC
    '+o+"
    "}).join(""),d="";if(a){var u=Math.round((Date.now()-new Date(a).getTime())/36e5);d=u<1?"Updated just now":u<24?"Updated "+u+"h ago":"Updated "+Math.round(u/24)+"d ago"}e.innerHTML='
    '+p(o)+' BTC
    ~'+m(r)+" AUM · "+s+'% of supply held in ETFs
    '+c+'
    Data: SEC filings + CoinGlass'+(d?" · "+d:"")+"
    "}var U=null;window._startHalvingTicker=function(){U&&clearInterval(U),U=setInterval(function(){if(window._halvingTargetMs){var e=document.getElementById("halvSecs");if(!e)return clearInterval(U),void(U=null);var t=Math.max(0,window._halvingTargetMs-Date.now()),o=Math.floor(t/1e3),n=Math.floor(o/86400),i=Math.floor(o%86400/3600),a=Math.floor(o%3600/60),r=o%60,s=document.getElementById("halvDays"),l=document.getElementById("halvHours"),c=document.getElementById("halvMins");s&&(s.textContent=n),l&&(l.textContent=i),c&&(c.textContent=a),e.textContent=r<10?"0"+r:r}},1e3)}}(),function(){if(window._sessionStart=window._sessionStart||Date.now(),window._cleanUrl=function(e){if(!e)return"/";var t=window.location.pathname;return t==="/"+e||t==="/app/"+e?t:"#"+e},window._parseCleanUrl=function(){var e,t=window.location.pathname;return(e=t.match(/^\/channels\/(.+)$/))||(e=t.match(/^\/app\/(.+)$/))?e[1]:"/timechain-tv"===t||"/tv"===t?"timechain-tv":"/meetup-builder"===t?"meetup-builder":"/irl-sync"===t||"/meet"===t?"irl-sync":"/forum"===t?"forum":"/marketplace"===t?"marketplace":"/bitcoin-beats"===t||"/beats"===t?"bitcoin-beats":"/chat"===t?"chat":"/pvp"===t?"pvp":window.location.hash.replace("#","")||null},!document.getElementById("lb")){var e=document.createElement("div");e.id="lb",e.onclick=function(){document.getElementById("lb").classList.remove("open")},e.innerHTML='',document.body.appendChild(e)}function t(e){document.getElementById("lb-img").src=e,document.getElementById("lb").classList.add("open")}function o(){return window.innerWidth<=900}function n(){const e="light"!==document.body.getAttribute("data-theme");document.body.setAttribute("data-theme",e?"light":"dark"),localStorage.setItem("theme",e?"light":"dark");const t=document.getElementById("themeBtn");t&&(t.textContent=e?"☀️":"🌙");const o=document.getElementById("mobileThemeBtn");o&&(o.textContent=e?"☀️":"🌙")}function i(){var e=document.getElementById("sidebar");e&&(e.classList.toggle("open"),"function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!e.classList.contains("open")))}function a(){var e=document.getElementById("sidebar");if(e){var t=e.classList.toggle("sidebar-collapsed");try{localStorage.setItem("sidebar-collapsed",t?"1":"0")}catch(e){}}}function r(e){var t=e.nextElementSibling;if(t){var o=e.querySelector(".cat-arrow");"true"===e.getAttribute("data-expanded")?(t.style.display="none",e.setAttribute("data-expanded","false"),o&&(o.textContent="▶")):(t.style.display="",e.setAttribute("data-expanded","true"),o&&(o.textContent="▼"))}}function s(e){if(e){var t=e.closest(".cat-group");if(t&&"none"===t.style.display){var o=t.previousElementSibling;if(o&&o.classList.contains("cat-toggle")){t.style.display="",o.setAttribute("data-expanded","true");var n=o.querySelector(".cat-arrow");n&&(n.textContent="▼")}}}}function l(){return safeJSON("btc_favs",[])}function c(){var e=document.getElementById("favsList"),t=document.getElementById("favsSection");if(e){var o=l(),n=safeJSON("btc_bookmarks",[]);if(!(o.length>0||n.length>0))return e.innerHTML="",(i=document.getElementById("bookmarksList"))&&(i.innerHTML=""),void(t&&(t.style.display="none"));t&&(t.style.display="block");var i,a="";if(o.forEach(function(e){var t=void 0!==CHANNELS?CHANNELS[e]:null,o=t?(t.emoji||"")+" "+(t.name||e):e;a+="
    "+o+"
    "}),e.innerHTML=a,i=document.getElementById("bookmarksList"))if(0===n.length)i.innerHTML="";else{var r='
    🔖 Bookmarked Messages
    ';n.slice(0,15).forEach(function(e){var t=void 0!==CHANNELS&&CHANNELS[e.channel]?CHANNELS[e.channel]:null,o=t?(t.emoji||"")+" "+(t.name||e.channel):e.channel;r+="
    🔖 "+o+"
    "}),i.innerHTML=r}}}function d(e,t){let o=l();if(o.includes(e))o=o.filter(t=>t!==e),t&&(t.innerHTML="☆ Save");else{o.push(e),t&&(t.innerHTML="⭐ Saved");try{var n=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_fav_added_"+n,"true")}catch(e){}}var i;i=o,localStorage.setItem("btc_favs",JSON.stringify(i)),c(),"function"==typeof syncFavsToFirebase&&syncFavsToFirebase()}!function(){try{if(window.innerWidth>900&&"1"===localStorage.getItem("sidebar-collapsed")){var e=document.getElementById("sidebar");e&&e.classList.add("sidebar-collapsed")}}catch(e){}}();let u=!1,p=null,m=null;function h(e){u=!u;const t=document.getElementById("galleryBtn");t&&(t.classList.toggle("active",u),t.textContent=u?"📄 List View":"🖼️ Gallery View"),g(e)}function g(e){const t=p;if(!t)return;const n=document.getElementById("msgs");if(u){let e=[];t.msgs.forEach(t=>{t.imgs&&t.imgs.forEach(t=>e.push(t))});let i='",e.length>a&&(window._galleryImgs=e,window._galleryOffset=a,i+='"),n.innerHTML=i}else{const i=o()?20:50,a=t.msgs;let r=function(){const t=a.slice(0,0+i);let n="";{const t=void 0!==CHANNELS?CHANNELS[e]:null;t&&t.desc&&(n+='
    🦌
    Nacho\'s Summary
    '+t.desc+"
    ")}return t.forEach((t,i)=>{if(n+='
    ',t.text){let e=t.text,i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"});let a=[];e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){const t=e.startsWith("http")?e:"https://"+e;return a.push(t),"%%TW"+(a.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){const n=a[parseInt(t)],i="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),l=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+l+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),n+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?n+='':n+=''});var a=0+i,r=safeJSON("btc_bookmarks",[]).some(function(t){return t.channel===e&&t.idx===a});n+="',n+="
    "}),n}();a.length>i&&(r+='"),n.innerHTML=r,window._currentMsgs=a,window._currentOffset=i}window._sidebarOrder||(window._sidebarOrder=[...document.querySelectorAll(".ch-btn")].map(e=>{const t=e.getAttribute("onclick").match(/go\('([^']+)'/);return t?t[1]:null}).filter(Boolean));const i=window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),a=i.indexOf(e),r=a0?i[a-1]:i[i.length-1]);CHANNELS[s]&&CHANNELS[s].title;let l='
    ';l+="',l+='',l+='',l+='',l+='',l+="',l+="
    ",l+='
    ',l+='',l+="
    ","function"==typeof renderReadNext&&(l+=renderReadNext(e)),l+='
    Disclaimer
    This Bitcoin education is presented authentically and from a first-principles standpoint that maximizes truth. However, this is not financial, investment, legal, or tax advice and anyone reading this material should still verify its validity by doing their own research. Bitcoin is volatile and you can lose money. Bitcoin Education Archive, its operators, and contributors make no warranty regarding the accuracy, completeness, or timeliness of any educational content and accept no liability for decisions made based on it. Always consult a licensed professional before making financial decisions. Terms · Privacy
    ',n.innerHTML+=l,n.classList.add("fade-in")}let f=!1;function y(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML='
    Loading tweet...
    ',f)b(e,t);else{const o=document.createElement("script");o.src="https://platform.twitter.com/widgets.js",o.async=!0,o.onload=function(){f=!0,b(e,t)},document.head.appendChild(o)}}function b(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML="",window.twttr&&window.twttr.widgets){const e=t.match(/status\/(\d+)/);if(e){const n=document.createElement("div");o.appendChild(n),twttr.widgets.createTweet(e[1],n,{theme:"light"===document.body.getAttribute("data-theme")?"light":"dark",align:"center",conversation:"none",width:500}).then(function(e){e||(o.innerHTML='')})}}else o.innerHTML=''}async function v(){window._keepFloatingBtn=!0;const e=Object.keys(CHANNELS);window._randomChannelHistory||(window._randomChannelHistory=[]);var t=e.filter(function(e){return-1===window._randomChannelHistory.indexOf(e)});0===t.length&&(window._randomChannelHistory.length=0,t=e);const o=t[Math.floor(Math.random()*t.length)];window._randomChannelHistory.push(o),window._randomChannelHistory.length>Math.floor(.3*e.length)&&window._randomChannelHistory.shift(),await go(o),window._keepFloatingBtn=!1,S("__random__","🎲","Next Random Channel")}async function w(e,t,o){window._keepFloatingBtn=!0;const n=CHANNELS[e];if(!n)return void(window._keepFloatingBtn=!1);let i;if(V[e])i=V[e];else try{const t=await fetch(n.file);i=await t.json(),V[e]=i}catch(e){return}const a=i.msgs.length>1?i.msgs.slice(1):i.msgs,r=[];if(a.forEach((e,t)=>{e.imgs&&e.imgs.length>0&&r.push(t)}),0!==r.length){window._randomHistory||(window._randomHistory={}),window._randomHistory[e]||(window._randomHistory[e]=[]);var s=window._randomHistory[e],l=Math.min(Math.floor(.2*r.length),50),c=r.filter(function(e){return-1===s.indexOf(e)});0===c.length&&(s.length=0,c=r);var d=c[Math.floor(Math.random()*c.length)];s.push(d),s.length>l&&s.shift();var u=a[d];if(u&&u.imgs&&u.imgs.forEach(function(e){(new Image).src=e}),await go(e),d>=50){const e=document.getElementById("loadMoreBtn");for(var p=0;window._currentOffset<=d&&e&&document.contains(e)&&p<50;)window.loadMoreMsgs(),p++}setTimeout(function(){const n=document.getElementById("msg-"+d);n&&(n.querySelectorAll('img[loading="lazy"]').forEach(function(e){e.loading="eager"}),n.scrollIntoView({behavior:"smooth",block:"center"}),n.style.transition="box-shadow 0.3s, border-color 0.3s",n.style.boxShadow="0 0 20px rgba(247,147,26,0.4)",n.style.borderColor="#f7931a",setTimeout(function(){n.style.boxShadow="",n.style.borderColor=""},2e3),window._keepFloatingBtn=!1,S(e,t,o))},300)}}function x(){return w("memes-funny","😂","Next Random Meme")}function k(){return w("art-inspiration","🎨","Next Random Art")}function B(){return w("graphics","📊","Next Random Graphic")}function S(e,t,o){var n=document.getElementById("floatingRandomBtn");n||((n=document.createElement("button")).id="floatingRandomBtn",n.style.cssText="position:fixed;bottom:140px;right:180px;z-index:150;padding:12px 20px;background:var(--accent);color:#fff;border:none;border-radius:12px;font-size:0.9rem;font-weight:700;cursor:pointer;font-family:inherit;box-shadow:0 4px 20px rgba(0,0,0,0.3);transition:0.2s;display:flex;align-items:center;gap:6px;",document.body.appendChild(n)),n.innerHTML=t+" "+o,n.onclick="__random__"===e?function(){v()}:function(){w(e,t,o)},n.style.display="flex",window.addEventListener("popstate",function e(){n.style.display="none",window.removeEventListener("popstate",e)},{once:!0})}function T(e,t){const o=e+"\n\n"+t;navigator.clipboard.writeText(o).then(()=>{showToast("📋 Note copied! Paste it in Primal to post.")}).catch(()=>{}),window.open("https://primal.net/home","_blank")}window.goRandomMeme=x,window.goRandomArt=k,window.goRandomGraphic=B,window.toggleBookmark=function(e,t,o){var n=safeJSON("btc_bookmarks",[]),i=n.findIndex(function(o){return o.channel===e&&o.idx===t});-1!==i?(n.splice(i,1),o&&(o.style.opacity="0.3",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Bookmark removed")):(n.push({channel:e,idx:t,ts:Date.now()}),o&&(o.style.opacity="1",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Saved to sidebar")),localStorage.setItem("btc_bookmarks",JSON.stringify(n)),c(),"function"==typeof syncBookmarksToFirebase&&syncBookmarksToFirebase()},window.loadMoreGallery=function(){const e=window._galleryImgs,o=window._galleryOffset,n=document.querySelector(".gallery-grid"),i=document.getElementById("loadMoreGallery");e.slice(o,o+100).forEach(e=>{const o=document.createElement("img");o.src=e,o.loading="lazy",o.onclick=function(){t(this.src)},n.appendChild(o)}),window._galleryOffset=o+100,window._galleryOffset>=e.length?i.remove():i.textContent="Load more ("+(e.length-window._galleryOffset)+" remaining)"},window.showSpinWheel=function(){var e=localStorage.getItem("btc_last_spin_date"),t=(new Date).toDateString();if(e!==t){var o=document.getElementById("spinModal");o&&o.remove();var n=document.createElement("div");n.id="spinModal",n.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.85);-webkit-overflow-scrolling:touch;overflow-y:auto;padding:20px;";var i=[{label:"🎟️ 1 Ticket",value:"ticket_1",weight:25,color:"#f7931a"},{label:"🎟️ 2 Tickets",value:"ticket_2",weight:22,color:"#ea580c"},{label:"⭐ 25 XP",value:"points_25",weight:18,color:"#22c55e"},{label:"🎟️ 3 Tickets",value:"ticket_3",weight:12,color:"#fbbf24"},{label:"⭐ 50 XP",value:"points_50",weight:8,color:"#3b82f6"},{label:"👔 Closet!",value:"closet_item",weight:5,color:"#ec4899"},{label:"🧊 Freeze!",value:"freeze",weight:4,color:"#06b6d4"},{label:"⭐ 100 XP",value:"points_100",weight:3,color:"#8b5cf6"},{label:"🎟️ 5 Tickets",value:"ticket_5",weight:1.5,color:"#a855f7"},{label:"💎 RARE!",value:"rare_drop",weight:1.5,color:"#ef4444"}],a=[{label:"🎟️ 10 Tickets",value:"ticket_10",weight:1e3},{label:"🎟️ 25 Tickets",value:"ticket_25",weight:500},{label:"🎟️ 50 Tickets",value:"ticket_50",weight:100},{label:"🎟️ 100 Tickets!",value:"ticket_100",weight:50},{label:"🎟️ 500 Tickets!!",value:"ticket_500",weight:10},{label:"🎟️💎 1,000 Tickets!!!",value:"ticket_1000",weight:3},{label:"🎟️👑 10,000 TICKETS!!!!",value:"ticket_10000",weight:1}];n.innerHTML='
    🎡
    Daily Spin

    Spin for Orange Tickets, XP, Nacho Closet items, and rare Freeze Tickets!

    ',document.body.appendChild(n);var r=document.getElementById("spinCanvas").getContext("2d"),s=125,l=125,c=2*Math.PI/i.length;i.forEach(function(e,t){r.beginPath(),r.moveTo(s,l),r.arc(s,l,120,t*c,(t+1)*c),r.fillStyle=e.color,r.fill(),r.strokeStyle="#fff",r.lineWidth=2,r.stroke(),r.save(),r.translate(s,l),r.rotate(t*c+c/2),r.textAlign="right",r.fillStyle="#fff",r.font="bold 12px sans-serif",r.fillText(e.label,105,4),r.restore()});var d=!1,u=document.getElementById("spinBtn"),p=document.getElementById("spinResult");u.addEventListener("click",function(){if(!d){d=!0,u.disabled=!0,u.style.opacity="0.5";for(var e=i.reduce(function(e,t){return e+t.weight},0),o=Math.random()*e,n=0,m=0,h=0;hMath.floor(30*(d-.01))&&"function"==typeof playSpinTick&&playSpinTick(),requestAnimationFrame(e);else{"function"==typeof playSpinWin&&playSpinWin();var h="",f=g.value.split("_")[0],y=parseInt(g.value.split("_")[1])||1;if("rare_drop"===g.value){for(var b=a.reduce(function(e,t){return e+t.weight},0),w=Math.random()*b,x=a[0],B=0,S=0;S.01&&(T=100,x={label:"🎟️ 100 Tickets!",value:"ticket_100"}),h="💎 RARE DROP! "+x.label,"function"==typeof awardOrangeTickets)awardOrangeTickets(T,"Rare Spin Drop");else{var _=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",_+T)}T>=100&&("function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound())}else if("closet"===f){var I=safeJSON("btc_spin_closet_items",[]),C=["orange_scarf","sunglasses","bowtie","mining_helmet","lightning_chain","party_hat","hodl_hoodie","crown","steak","diamond_hooves"].filter(function(e){return-1===I.indexOf(e)});if(C.length>0){var E=C[Math.floor(Math.random()*C.length)];if(I.push(E),localStorage.setItem("btc_spin_closet_items",JSON.stringify(I)),void 0!==currentUser&¤tUser&&!currentUser._isLocal)try{db.collection("users").doc(auth.currentUser.uid).update({spinClosetItems:firebase.firestore.FieldValue.arrayUnion(E)}).catch(function(){})}catch(e){}h="👔 CLOSET ITEM! You unlocked: "+({orange_scarf:"Bitcoin Scarf 🧣",sunglasses:"Cool Shades 🕶️",bowtie:"Fancy Bowtie 🎀",mining_helmet:"Mining Helmet ⛑️",lightning_chain:"Lightning Chain ⚡",party_hat:"Party Hat 🎉",hodl_hoodie:"HODL Hoodie 🧥",crown:"Royal Crown 👑",steak:"Proof of Steak 🥩",diamond_hooves:"Diamond Hooves 💎"}[E]||E)+"! Equip it in Nacho's Closet!"}else h="👔 You already own all spin closet items! +25 bonus XP instead!","function"==typeof awardPoints&&awardPoints(25,"Closet bonus")}else if("freeze"===f){h="🧊 STREAK FREEZE TICKET! Your streak is protected for 1 missed day!";var A=parseInt(localStorage.getItem("btc_streak_freezes")||"0");localStorage.setItem("btc_streak_freezes",A+1),"function"==typeof awardPoints&&awardPoints(0,"🧊 Streak Freeze",null,0,1),void 0!==currentUser&¤tUser&&(currentUser.streakFreezes=(currentUser.streakFreezes||0)+1)}else if("ticket"===f)if(h="🎟️ You won "+y+" Orange Ticket"+(y>1?"s":"")+"!","function"==typeof awardOrangeTickets)awardOrangeTickets(y,"Daily Spin");else{var z=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",z+y)}else if("points"===f)if(h="⭐ You won "+y+" XP!","function"==typeof awardPoints)awardPoints(y,"Daily Spin");else{var M=parseInt(localStorage.getItem("btc_points")||"0");localStorage.setItem("btc_points",M+y)}p.innerHTML='
    '+g.label.split(" ")[0]+'
    '+h+'
    ',"function"==typeof notifySelfSpin&¬ifySelfSpin(h);var P=parseInt(localStorage.getItem("btc_spin_count")||"0");localStorage.setItem("btc_spin_count",String(P+1));var L=localStorage.getItem("btc_spin_last_day")||"";if(L===new Date(Date.now()-864e5).toISOString().slice(0,10)){var U=parseInt(localStorage.getItem("btc_spin_streak")||"0");localStorage.setItem("btc_spin_streak",String(U+1))}else L!==t&&localStorage.setItem("btc_spin_streak","1");localStorage.setItem("btc_spin_last_day",t),"rare_drop"===g.value&&localStorage.setItem("btc_spin_hit_rare","true"),localStorage.setItem("btc_last_spin_date",t),"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("dailySpin")({}).catch(function(e){console.log("[SPIN] Server validation:",e.message||"ok")}),void 0!==currentUser&¤tUser&¤tUser._isLocal}})}}),n.addEventListener("click",function(e){e.target===n&&n.remove()})}else showToast("🎡 You already spun today! Come back tomorrow!")};var _=null;function I(e,t,o,n,i){var a="dc_"+Math.random().toString(36).substr(2,6),r=n?'Open ↗':"";return'
    '+e+"
    "+(i?'
    '+e+' QR
    ':"")+(t?'
    "+o+'
    "+r+"
    ":"")+"
    "}function C(e,t){navigator.clipboard.writeText(e).then(()=>{t.classList.add("copied"),t.textContent="✅ Copied!",setTimeout(()=>{t.classList.remove("copied"),t.innerHTML="🔗 Copy Link"},2e3)})}setTimeout(function(){var e=new Image;e.crossOrigin="anonymous",e.src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:spontaneousleopard54@zeuspay.com",e.onload=function(){try{var t=document.createElement("canvas");t.width=e.width,t.height=e.height,t.getContext("2d").drawImage(e,0,0),_=t.toDataURL("image/png")}catch(t){_=e.src}}},3e3),window.showDonateModal=function(){var e=document.getElementById("donateModal");e&&e.remove();var t=document.createElement("div");t.id="donateModal",t.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:flex-start;justify-content:center;background:rgba(2,6,23,0.9);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;";var o="spontaneousleopard54@zeuspay.com",n=_||"https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:"+o;t.innerHTML='
    🧡
    Support the Archive

    Your sats help keep this archive free and open for the next billion Bitcoiners! 🦌⚡

    Lightning QR Code
    '+o+"

    ⚠️ Donations are non-refundable

    "+I("💵 Cash App","$NEEDcreations","$NEEDcreations","https://cash.app/$NEEDcreations","images/donate/cashapp-qr.jpg")+I("💜 Venmo","@Phil2140","@Phil2140","https://venmo.com/code?user_id=1358236213051392692&created=1773155307","images/donate/venmo-qr.jpg")+I("💙 PayPal","paypal.me/PhilipFazioli","paypal.me/PhilipFazioli","https://paypal.me/PhilipFazioli","images/donate/paypal-qr.jpg")+I("💚 Zelle",null,null,null,"images/donate/zelle-qr.jpg")+I("₿ On-Chain Bitcoin","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf",null,"images/donate/onchain-qr.jpg")+I("🔒 BIP47 Payment Code","PM8TJWpq8HqPeBEuz3dAoB3uyZADVxQjWekQJCJYddpWPce9nDaeK6XjYnifBUnjjKcWF8Y98EkfPZYaftC7uDJkiFqBTBYrd8TJhRg5qQwXtfnTTg89","PM8TJWpq8Hq...Tg89",null,"images/donate/bip47-qr.jpg")+"
    ",document.body.appendChild(t);var i=document.getElementById("donateCopyBtn");i&&i.addEventListener("click",function(e){e.stopPropagation();var t=this;if(navigator.clipboard)navigator.clipboard.writeText(o).then(function(){t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)});else{var n=document.createElement("textarea");n.value=o,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)}}),t.addEventListener("click",function(e){e.target===t&&t.remove()})};let E=!1;function A(){const e=document.getElementById("supportBtn");E?(navigator.clipboard.writeText("info.603btc@gmail.com").then(function(){e.innerHTML="✅ Copied!",e.style.color="#22c55e",setTimeout(function(){e.innerHTML='info.603btc@gmail.com tap to copy',e.style.color="var(--text)"},1500)}).catch(function(){}),window.location.href="mailto:info.603btc@gmail.com?subject=Support%20-%20Bitcoin%20Education%20Archive"):(E=!0,e.style.transition="0.3s",e.style.background="var(--accent)",e.style.color="#fff",e.style.borderColor="var(--accent)",e.innerHTML='info.603btc@gmail.com tap to copy',setTimeout(function(){e.style.background="var(--card-bg)",e.style.color="var(--text)",e.style.borderColor="var(--border)"},400))}function z(e){if(!e)return"";var t=new Date(e),o=t.getHours(),n=t.getMinutes(),i=o>=12?"PM":"AM";return 0==(o%=12)&&(o=12),o+":"+(n<10?"0":"")+n+" "+i}window._nachoMode=!1,window._nachoModeEarnings={points:0,badges:[],interactions:0},window.enterNachoMode=function(e){if(window._nachoMode=!0,window._nachoBusy=!0,window._nachoModeEarnings={points:0,badges:[],interactions:0},window._nachoModeStartTime=Date.now(),window._nachoModeTopics=[],window._nachoConvoQuizOffered=!1,!window._nachoPointsHooked){window._nachoPointsHooked=!0;var t=window.awardPoints;t&&(window.awardPoints=function(e,o){return window._nachoMode&&window._nachoModeEarnings&&(window._nachoModeEarnings.points+=e),t.apply(this,arguments)});var o=window.showToast;o&&(window.showToast=function(e){return window._nachoMode&&window._nachoModeEarnings&&"string"==typeof e&&(-1!==e.indexOf("badge")||-1!==e.indexOf("Badge")||-1!==e.indexOf("🏅"))&&window._nachoModeEarnings.badges.push(e),o.apply(this,arguments)})}e||history.pushState({nachoMode:!0},"","/app/nacho"),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="none")});var n=document.querySelector(".mobile-bar");n&&(n.style.display="none");var i=document.getElementById("main");i.scrollTop=0,"undefined"!=typeof NACHO_SVG&&NACHO_SVG,void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var a=!(!window.SpeechRecognition&&!window.webkitSpeechRecognition),r=a?'':"";window._nachoChatHistory=safeJSON("btc_nacho_chat",[]),window._nachoSentHistory=safeJSON("btc_nacho_sent",[]),window._nachoSentIdx=-1;var s=document.createElement("div");s.id="nachoModeScreen",s.style.cssText="display:flex;flex-direction:column;height:calc(100vh - 32px);margin-top:32px;animation:fadeSlideIn 0.4s ease-out;position:relative;z-index:9999;",s.innerHTML='
    Nacho
    '+("function"==typeof nachoNickname?nachoNickname():"Nacho").toUpperCase()+' MODE
    Home
    '+r+'
    ',i.appendChild(s),q(),setTimeout(function(){var e=document.getElementById("nachoModeChat");e&&(e.scrollTop=e.scrollHeight)},100),W();var l=document.getElementById("nachoEli5Btn");l&&(l.style.opacity=window._nachoEli5?"1":"0.5"),function(){var e=document.getElementById("nachoModeOverlay");if(e&&(e.innerHTML="","function"==typeof getEquippedItem)){var t=getEquippedItem();if(t){var o=t.hidden?t.revealEmoji:t.emoji,n=document.createElement("span");n.textContent=t.overlay&&t.overlay.custom?t.overlay.custom:o,n.style.cssText="position:absolute;font-size:2.5rem;pointer-events:none;",t.overlay&&(t.overlay.top&&(n.style.top=t.overlay.top),t.overlay.left&&(n.style.left=t.overlay.left),t.overlay.right&&(n.style.right=t.overlay.right),t.overlay.bottom&&(n.style.bottom=t.overlay.bottom),t.overlay.transform&&(n.style.transform=t.overlay.transform)),e.appendChild(n)}}}(),setTimeout(function(){var e=document.getElementById("nachoModeInput");e&&e.focus()},300)},window.nachoModeKeydown=function(e){if("Enter"!==e.key){var t=document.getElementById("nachoModeInput");if(t){var o=window._nachoSentHistory||[];if("ArrowUp"===e.key){if(0===o.length)return;-1===window._nachoSentIdx&&(window._nachoSentDraft=t.value),window._nachoSentIdx=Math.min(window._nachoSentIdx+1,o.length-1),t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault(),setTimeout(function(){t.setSelectionRange(t.value.length,t.value.length)},0)}else if("ArrowDown"===e.key){if(window._nachoSentIdx<=0)return window._nachoSentIdx=-1,void(t.value=window._nachoSentDraft||"");window._nachoSentIdx--,t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault()}}}else nachoModeSend()};var M=["There will only ever be 21 million Bitcoin. No government, company, or person can change this. 🔒","The Bitcoin network has been running non-stop since January 3, 2009 — over 99.98% uptime. No bank can say that! 🏦","The first Bitcoin transaction was 10,000 BTC for two pizzas. Today that's worth hundreds of millions! 🍕","Bitcoin processes over $10 billion in transactions daily — more than most countries' payment systems. 💸","Bitcoin mining now uses more renewable energy than almost any other industry — over 50%! ⚡","Satoshi Nakamoto's true identity remains unknown. They hold about 1 million BTC and have never spent any. 🕵️","A 'satoshi' (sat) is the smallest unit of Bitcoin: 0.00000001 BTC. You don't need to buy a whole coin! 🪙","The Bitcoin Lightning Network can process millions of transactions per second — faster than Visa! ⚡","El Salvador became the first country to adopt Bitcoin as legal tender in September 2021. 🇸🇻","Bitcoin's code is completely open source — anyone can read, verify, and contribute to it. 📖","Every 4 years, Bitcoin's new supply gets cut in half. This is called the 'halving.' The next one is in 2028! 📉","There are more Bitcoin wallets than bank accounts in most countries. Over 100 million and growing! 📈","Bitcoin can be sent anywhere in the world in minutes, 24/7, with no middleman. Try that on a Sunday with a bank! 🌍","The Genesis Block contains a hidden message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰","About 20% of all Bitcoin is estimated to be permanently lost — mostly from early users who lost their keys. 🔑","Bitcoin's difficulty adjustment is like a thermostat — it automatically adapts every 2 weeks to keep blocks at ~10 minutes. ⚙️","Running a Bitcoin node means YOU verify every transaction yourself. No trust required. Don't trust, verify! ✅","The Lightning Network lets you send payments as small as 1 sat (~$0.0003). Try doing that with a credit card! 💳","Bitcoin has survived 400+ declared 'deaths' by media. It keeps coming back stronger every time. 💪","Over 50 publicly traded companies now hold Bitcoin on their balance sheets, led by MicroStrategy. 🏢","Bitcoin transactions are pseudonymous, not anonymous. Every transaction is recorded on the public blockchain forever. 🔍","The Bitcoin network is protected by more computing power than all the world's supercomputers combined. 🖥️","You can run a full Bitcoin node on a Raspberry Pi — a $50 computer can verify the entire monetary system. 🥧","Bitcoin's inflation rate is currently lower than gold's. After the 2028 halving, it'll be even lower. 🥇","Multisig wallets require multiple keys to spend Bitcoin — like a safety deposit box that needs 2 of 3 keys. 🗝️","Bitcoin doesn't care about borders, politics, or holidays. It works the same everywhere, always. 🌐","The last Bitcoin won't be mined until approximately the year 2140. We're still very early! ⏰","Jack Dorsey, Elon Musk, and many tech leaders have publicly supported Bitcoin's vision. 🚀","A Bitcoin block is mined roughly every 10 minutes. That's about 144 blocks per day, every day, forever. ⛏️","Nostr is a decentralized social protocol that many Bitcoiners are building on — social media you can't be censored from. 📡"];window.nachoModeChip=function(e){var t=document.getElementById("nachoModeInput");t&&(t.value=e,nachoModeSend())},window._nachoEli5="true"===localStorage.getItem("btc_nacho_eli5"),window.toggleNachoEli5=function(){window._nachoEli5=!window._nachoEli5,localStorage.setItem("btc_nacho_eli5",window._nachoEli5?"true":"false");var e=document.getElementById("nachoEli5Btn");e&&(e.style.opacity=window._nachoEli5?"1":"0.5",e.title=window._nachoEli5?"ELI5 Mode ON — Simple language":"Explain Like I'm 5"),"function"==typeof showToast&&showToast(window._nachoEli5?"🧒 ELI5 Mode ON — Nacho will use simple language!":"🧒 ELI5 Mode OFF — Back to normal")},window.showEli5Prompt=function(){var e=window._nachoEli5,t='
    🧒
    ELI5 Mode
    Explain Like I\'m 5

    When turned on, Nacho will answer your questions using super simple language — like explaining Bitcoin to a 5-year-old! 🦌

    Perfect for beginners or anyone who wants the basics without the jargon.
    Currently: '+(e?"ON ✅":"OFF")+'
    ',o=document.createElement("div");o.innerHTML=t,document.body.appendChild(o.firstChild)},window.nachoShareAnswer=function(e){var t="🦌 I learned this from Nacho at bitcoineducation.quest:\n\n"+e.replace(/<[^>]+>/g,"").replace(/🦌\s*/g,"").substring(0,280);if(navigator.share)navigator.share({title:"Bitcoin Fact from Nacho 🦌",text:t,url:"https://bitcoineducation.quest"}).catch(function(){});else{var o=document.createElement("textarea");o.value=t,document.body.appendChild(o),o.select();try{document.execCommand("copy")}catch(e){}document.body.removeChild(o),"function"==typeof showToast&&showToast("📋 Copied to clipboard!")}};var P=!1,L=[{step:1,emoji:"📘",title:"What is Bitcoin?",q:"What is Bitcoin and how does it work?"},{step:2,emoji:"💡",title:"Why Bitcoin Matters",q:"Why is Bitcoin important? Why should I care?"},{step:3,emoji:"📈",title:"Bitcoin vs Money",q:"How is Bitcoin different from regular money and gold?"},{step:4,emoji:"🛒",title:"Buying Your First Bitcoin",q:"How do I buy my first Bitcoin? Where do I start?"},{step:5,emoji:"💼",title:"Wallets & Storage",q:"What Bitcoin wallet should I use? What are the types?"},{step:6,emoji:"🔑",title:"Seed Phrases & Security",q:"What is a seed phrase and how do I keep my Bitcoin safe?"},{step:7,emoji:"⚡",title:"Lightning Network",q:"What is the Lightning Network and why does it matter?"},{step:8,emoji:"⛏️",title:"Mining & Proof of Work",q:"How does Bitcoin mining work? What is proof of work?"},{step:9,emoji:"🏃",title:"Running a Node",q:"What is a Bitcoin node and should I run one?"},{step:10,emoji:"🔒",title:"Privacy & KYC",q:"How private is Bitcoin? What is KYC and why does it matter?"}];window.nachoLearningPath=function(){var e=parseInt(localStorage.getItem("btc_nacho_path_step")||"0");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth&&auth?auth.currentUser:null;if(document.getElementById("nachoModeChat")){var o='
    🗺️ Your Bitcoin Journey
    '+Math.round(e/L.length*100)+"% concepts mastered
    ";o+='
    ✅ All Features Unlocked

    Every app and feature is available to you. Explore freely! 🦌

    🗣️ Pleb Talk
    🤝 IRL Sync
    ⚡ Lightning Mart
    🔹 Sign Up: 🏁 Profile & Persistence
    ',o+='
    ';for(var n=0;n'+(a?"✅":i.emoji)+'
    Level '+i.step+": "+i.title+"
    "+(r?'NEXT →':"")+""}e>=L.length&&(o+='
    🎓🦌🎉
    Journey Complete!
    You\'ve covered all the Bitcoin basics. You\'re officially not a normie anymore!
    '),H("nacho","",o)}},window.nachoPathStep=function(e){var t=L[e];t&&(e>=parseInt(localStorage.getItem("btc_nacho_path_step")||"0")&&localStorage.setItem("btc_nacho_path_step",(e+1).toString()),nachoModeChip(t.q))};const U=[{q:"What is the primary benefit of running a Bitcoin full node?",a:"You can independently verify the consensus rules and your own transactions.",w:["It earns you a small percentage of every transaction fee on the network.","It automatically mines new Bitcoins using your computer's idle CPU.","It hides your IP address from everyone else using the network.","It increases the speed of your internet connection by 21%."]},{q:"What does 'Satoshi' represent in the context of Bitcoin?",a:"The smallest unit of Bitcoin, equal to 0.00000001 BTC.",w:["A type of advanced encryption used for private messages.","The official name for a Bitcoin wallet's public address.","A digital certificate of ownership for a single Bitcoin.","The name of the first computer used to mine block zero."]},{q:"Why is Bitcoin's difficulty adjustment important?",a:"It ensures blocks are produced roughly every 10 minutes regardless of total hash rate.",w:["It prevents the price of Bitcoin from dropping below its mining cost.","It automatically updates the Bitcoin Core software for all users.","It calculates the total number of users active on the network daily.","It decides which transactions are most important for the miners."]},{q:"What happens if you lose your 12 or 24-word seed phrase?",a:"You lose access to your funds forever, as there is no central 'reset' authority.",w:["You can call Bitcoin's customer support to verify your identity and reset it.","The government can recover your coins using your social security number.","Your hardware wallet will automatically generate a new phrase after 24 hours.","Your Bitcoin is donated to a pool for new developers to use for testing."]},{q:"What is the primary function of the Lightning Network?",a:"To enable instant, near-free Bitcoin payments by moving them off-chain.",w:["To increase the total number of Bitcoins that will ever exist to 42 million.","To allow Bitcoin to be mined using only mobile phones and tablets.","To encrypt the entire blockchain so it cannot be read by anyone.","To create a secondary blockchain that is faster but less secure than Bitcoin."]}];function q(){var e=document.getElementById("nachoModeChat");if(e){var t=window._nachoChatHistory||[];if(0!==t.length){for(var o,n="",i="",a=0;a'+s+"",i=s),"user"===r.role?n+='
    '+escapeHtml(r.text)+'
    '+z(r.ts)+"
    ":n+='
    🦌 '+escapeHtml("function"==typeof nachoNickname?nachoNickname():"Nacho")+": "+r.html+'
    '+z(r.ts)+"
    "}e.innerHTML=n,e.scrollTop=e.scrollHeight}else{var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"";e.innerHTML='
    Nacho
    🦌 NACHO MODE
    '+(l?"Hey "+escapeHtml(l)+"! Let's talk Bitcoin.":"Hey! Let's talk Bitcoin.")+'
    💡 DID YOU KNOW?
    '+(o=Math.floor((Date.now()-new Date((new Date).getFullYear(),0,0))/864e5),M[o%M.length]+'
    Tap a topic or ask me anything:
    ')+function(){for(var e=[{emoji:"📘",label:"What is Bitcoin?",q:"What is Bitcoin and what problem does it solve?"},{emoji:"💰",label:"Why Bitcoin?",q:"Why is Bitcoin better than regular money and why should I care?"},{emoji:"🔒",label:"21 Million",q:"Why is the 21 million cap important and why can't it be changed?"},{emoji:"🛒",label:"How to Buy",q:"How do I buy my first Bitcoin and start stacking sats?"},{emoji:"🔑",label:"Self-Custody",q:"What is self-custody and why is it the most important thing in Bitcoin?"},{emoji:"⚡",label:"Lightning",q:"What is the Lightning Network and how does it make Bitcoin faster?"},{emoji:"🪙",label:"Why Not Altcoins?",q:"Why do Bitcoiners only focus on Bitcoin and not other cryptocurrencies?"},{emoji:"🌍",label:"Fix the World",q:"How is Bitcoin actually changing the world for the better?"}],t='
    ',o=0;o"+e[o].emoji+" "+e[o].label+"";return t+"
    "}()+'
    '}}}function N(e,t,o){var n={role:e,text:t||"",html:o||escapeHtml(t||""),ts:Date.now()};return window._nachoChatHistory.push(n),nachoChatSave(),n}function H(e,t,o){var n=document.getElementById("nachoModeChat");if(n){window._nachoChatHistory.length<=1&&n.querySelector("#nachoModeAvatar")&&(n.innerHTML="");var i=z(Date.now()),a=document.createElement("div");if(a.className="nm-msg "+("user"===e?"nm-user":"nm-nacho"),"user"===e)a.innerHTML=""+escapeHtml(t)+'
    '+i+"
    ";else{var r="function"==typeof nachoNickname?nachoNickname():"Nacho";a.innerHTML='🦌 '+escapeHtml(r)+": "+o+'
    '+i+"
    "}n.appendChild(a),"user"===e?n.scrollTop=n.scrollHeight:a.scrollIntoView({behavior:"smooth",block:"start"})}}function D(){if(window._nachoMode){var e=document.getElementById("nachoModeInput");if(e&&e===document.activeElement)setTimeout(D,3e4);else if(document.querySelector(".nm-nacho .thinking, .nm-thinking"))setTimeout(D,1e4);else{var t=window._nachoModeTopics||[];if(!(t.length<3)){var o=[],n=[],i=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;if(i&&"object"==typeof i&&Object.keys(i).forEach(function(e){var t=i[e];Array.isArray(t)&&t.forEach(function(t){n.push({question:t.q,options:[t.a].concat(t.wrong||[]),answer:t.a,category:e})})}),n.length>0){for(var a=0;a3&&-1!==c.indexOf(r[d])){o.push(l);break}}for(;o.length<3&&n.length>0;){var u=n[Math.floor(Math.random()*n.length)];-1===o.indexOf(u)&&o.push(u)}}0!==o.length&&(H("nacho","",'
    🎯
    Conversation Quest!
    You\'ve been learning a lot! Let\'s see how much you remember from our chat.
    '),window._convoQuizQuestions=o)}}}}function O(){var e,t,o,n,i=window._convoQuizQuestions||[],a=window._convoQuizIdx||0;if(a>=window._convoQuizTotal||a>=i.length)e=window._convoQuizScore||0,t=window._convoQuizTotal||3,H("nacho","",'
    '+(o>=80?"🏆":o>=60?"⭐":o>=40?"💪":"📚")+'
    Conversation Quest Complete!
    '+e+"/"+t+' correct
    '+(o>=80?"Outstanding! You really paid attention!":o>=60?"Great job! You learned a lot from our chat!":o>=40?"Not bad! Keep learning and you'll get there!":"Keep going! Every question is a learning opportunity!")+"
    "+((n=5*e)>0?'
    +'+n+" XP earned! 🎉
    ":"")+"
    "),n>0&&("function"==typeof awardPoints&&awardPoints(n,"🎯 Conversation Quest!"),"function"==typeof showToast&&showToast("🎯 +"+n+" XP — Conversation Quest!"));else{for(var r=i[a],s='
    Question '+(a+1)+" of "+window._convoQuizTotal+'
    '+escapeHtml(r.question)+"
    ",l=r.options||[],c=0;c'+escapeHtml(l[c])+""}H("nacho","",s+="
    ")}}function W(){var e=document.getElementById("nachoModeFriendship");if(e){var t="function"==typeof getNachoFriendship?getNachoFriendship():{emoji:"🦌",name:"Unknown",level:0},o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.textContent=t.emoji+" Friendship: "+t.name+" · "+o+" interactions"}}function R(){const e=document.getElementById("continueReading");if(!e)return;const t=localStorage.getItem("btc_last_channel");if(t&&CHANNELS[t]){const o=CHANNELS[t];e.style.display="block",e.innerHTML='
    📖 Continue Reading
    "+o.title+'
    '+o.cat+"
    "}else e.style.display="none"}window.nachoQuizMe=function(e){if(!window._nachoMode)return void("function"==typeof enterNachoMode&&(enterNachoMode(),setTimeout(function(){nachoQuizMe(e)},500)));let t=[];var o=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;o&&"object"==typeof o&&Object.keys(o).length>0&&Object.keys(o).forEach(e=>{var n=o[e];Array.isArray(n)&&n.forEach(o=>{t.push({question:o.q,options:fisherYates([o.a,...o.wrong||o.w||[]]),answer:o.a,category:e})})}),U.forEach(e=>{t.push({question:e.q,options:fisherYates([e.a,...e.w]),answer:e.a,category:"generic"})});var n=e?t.filter(function(t){return t.category&&-1!==t.category.toLowerCase().indexOf(e.toLowerCase())}):t;0===n.length&&(n=t);for(var i=n[Math.floor(Math.random()*n.length)],a='
    🎮 Quiz Time!
    '+(e?"Topic: "+e:"Nacho Challenge")+'
    '+escapeHtml(i.question)+"
    ",r=i.options||[],s=0;s'+escapeHtml(r[s])+""}a+="
    ",e||(a+='
    🦌 Pro Tip: Chat with me first! Future quizzes will be based on the questions you ask me.
    '),H("nacho","",a+="')},window.nachoQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n,i=e.parentElement.querySelectorAll("button");i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.7"}),t?(e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1","function"==typeof awardPoints&&awardPoints(10,"🎮 Quiz correct!"),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(34,197,94,0.1);border:1px solid #22c55e;border-radius:8px;color:#22c55e;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="✅ Correct! +10 XP",e.parentElement.appendChild(n)):(e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.borderColor="#22c55e",t.style.color="#22c55e",t.style.opacity="1")}),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(239,68,68,0.1);border:1px solid #ef4444;border-radius:8px;color:#ef4444;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="❌ Incorrect. Try another!",e.parentElement.appendChild(n))},window.nachoChatSave=function(){var e=window._nachoChatHistory||[];e.length>100&&(e=e.slice(e.length-100)),window._nachoChatHistory=e;try{localStorage.setItem("btc_nacho_chat",JSON.stringify(e))}catch(e){}},window.startConversationQuiz=function(){var e=window._convoQuizQuestions||[];0!==e.length&&(window._convoQuizIdx=0,window._convoQuizScore=0,window._convoQuizTotal=Math.min(e.length,5),O())},window.convoQuizAnswer=function(e,t){var o=e.parentElement,n=o.querySelectorAll("button");if(n.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1",window._convoQuizScore=(window._convoQuizScore||0)+1;var i=document.createElement("div");i.style.cssText="margin-top:6px;color:#22c55e;font-size:0.8rem;font-weight:700;",i.textContent="✅ Correct!",o.appendChild(i)}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",n.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var a=document.createElement("div");a.style.cssText="margin-top:6px;color:#ef4444;font-size:0.8rem;font-weight:700;",a.textContent="❌ Not quite!",o.appendChild(a)}window._convoQuizIdx=(window._convoQuizIdx||0)+1,setTimeout(O,1500)},window.nachoChatExport=function(){var e=window._nachoChatHistory||[];if(0!==e.length){for(var t=["=== Nacho Mode Chat Export ===","Exported: "+(new Date).toLocaleString(),""],o=0;o]+>/g,"");t.push("["+i+"] "+a+": "+r)}t.push("","--- bitcoineducation.quest ---");var s=new Blob([t.join("\n")],{type:"text/plain"}),l=document.createElement("a");l.href=URL.createObjectURL(s),l.download="nacho-chat-"+(new Date).toISOString().slice(0,10)+".txt",l.click(),URL.revokeObjectURL(l.href),"function"==typeof showToast&&showToast("💾 Chat saved!")}else"function"==typeof showToast&&showToast("No chat to save!")},window.nachoChatClear=function(){confirm("Clear all chat history with Nacho?")&&(window._nachoChatHistory=[],localStorage.removeItem("btc_nacho_chat"),q(),"function"==typeof showToast&&showToast("🗑️ Chat cleared"))},window.nachoModeSend=function(){var e=document.getElementById("nachoModeInput");if(e){var t=e.value.trim();if(t){e.value="",window._nachoSentIdx=-1,window._nachoSentDraft="",window._nachoAskedQuestions||(window._nachoAskedQuestions=[]),window._nachoAskedQuestions.push(t.toLowerCase()),window._nachoAskedQuestions.length>30&&(window._nachoAskedQuestions=window._nachoAskedQuestions.slice(-20)),window._nachoSentHistory.push(t),window._nachoSentHistory.length>50&&window._nachoSentHistory.shift();try{localStorage.setItem("btc_nacho_sent",JSON.stringify(window._nachoSentHistory))}catch(e){}var o;(o=document.getElementById("nachoHeroAvatar"))&&o.classList.add("talking"),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,window._nachoModeTopics&&t.length>10&&window._nachoModeTopics.push(t),!window._nachoConvoQuizOffered&&window._nachoModeStartTime&&window._nachoModeTopics&&(Date.now()-window._nachoModeStartTime)/6e4>=15&&window._nachoModeTopics.length>=5&&(window._nachoConvoQuizOffered=!0,setTimeout(function(){D()},8e3)),N("user",t),H("user",t),function(){var e=document.getElementById("nachoModeChat");if(e){e.querySelector("#nachoModeAvatar")&&(e.innerHTML="");var t=document.createElement("div");t.id="nmThinking",t.className="nm-msg nm-nacho",t.innerHTML='🦌 Thinking',e.appendChild(t),e.scrollTop=e.scrollHeight;var o=t.querySelector(".nacho-dots"),n=0;window._nmDotsTimer=setInterval(function(){n=(n+1)%4,o&&(o.textContent=".".repeat(n))},400)}}();var n="nm_"+Date.now()+"_"+Math.random().toString(36).substr(2,4),i=!1,a=setTimeout(function(){i||(i=!0,console.warn("[Nacho] Master timer fired — pipeline took >15s for:",t),s("That's a great question! I'm having a little trouble with my brain right now 🦌 Try asking me again in a moment, or explore the channels on the left to learn about Bitcoin!","fallback"))},15e3);if("function"!=typeof nachoUnifiedAnswer){if(!document.querySelector("script[data-nacho-retry]")){var r=document.createElement("script");r.src="nacho-qa.js?v="+Date.now(),r.setAttribute("data-nacho-retry","1"),document.head.appendChild(r)}setTimeout(function(){if("function"==typeof nachoUnifiedAnswer)try{nachoUnifiedAnswer(t,l)}catch(e){console.warn("Nacho pipeline retry error:",e),l({type:"fallback",answer:"I'm still loading up my Bitcoin knowledge! Try again in a moment 🦌"})}else!function(e,t){if("function"==typeof checkOffTopic){var o=checkOffTopic(e);if(o)return void t("function"==typeof personalize?personalize(o):o,"offtopic")}var n=e.toLowerCase().trim();if(/^(hey|hi|hello|yo|sup|howdy|hola|what'?s up|how are you|how'?s it going|good morning|good evening|good afternoon|gm|greetings)$/i.test(n)||/^(hey|hi|hello|yo) (nacho|there|buddy|friend|deer)/i.test(n)){var i=["Hey there! 🦌 Doing great — just hanging out waiting for someone to ask me about Bitcoin! What's on your mind?","Hey hey! 🧡 Welcome! I'm Nacho, your Bitcoin buddy. What would you like to learn about today?","Well hello! 🦌 Nice to see you. Ask me anything about Bitcoin — I've got 146 channels of knowledge in these antlers!","Hey! 👋 I'm good, thanks for asking! Ready to talk Bitcoin whenever you are. What's on your mind?"];t(i[Math.floor(Math.random()*i.length)],"offtopic")}else"function"==typeof nachoTrackMiss&&nachoTrackMiss(e),t("Give me just a moment — I'm loading up my Bitcoin knowledge! Try again in a few seconds. 🦌","fallback")}(t,s)},2e3)}else try{console.log("[Nacho] Calling nachoUnifiedAnswer for:",t),nachoUnifiedAnswer(t,function(e){console.log("[Nacho] Pipeline returned:",e?e.type:"null"),l(e)})}catch(e){console.error("[Nacho] Pipeline CRASH:",e),l({type:"fallback",answer:"Oops, my brain hit a bump! 🦌 Try asking again — I know a LOT about Bitcoin!"})}}}function s(e,o){!function(){window._nmDotsTimer&&(clearInterval(window._nmDotsTimer),window._nmDotsTimer=null);var e=document.getElementById("nmThinking");e&&e.remove()}(),function(){var e=document.getElementById("nachoHeroAvatar");e&&e.classList.remove("talking")}();var i="";if(o&&"safety"!==o){window._nachoAnswerData||(window._nachoAnswerData={}),window._nachoAnswerData[n]=e;var a="background:none;border:1px solid var(--border);border-radius:16px;cursor:pointer;font-size:0.75rem;padding:4px 10px;transition:0.2s;color:var(--text-muted);display:inline-flex;align-items:center;gap:3px;touch-action:manipulation;",r='
    ';"function"==typeof nachoRatingHtml&&(r+='",r+='"),r+="',i+=r+="
    ",i+=function(e){if(!e||0===e.length)return"";for(var t='
    ',o=0;o💬 "+e[o]+"";return t+"
    "}("function"==typeof nachoFollowUps?nachoFollowUps((t||"")+" "+(e||"")):[])}N("nacho","",e+i),H("nacho","",e+i),W(),"function"==typeof nachoTrackTopic&&nachoTrackTopic(t,o||"unknown");var s=function(){if(P)return null;for(var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[10,25,50,100,200,500],o=safeJSON("btc_nacho_q_milestones",[]),n=null,i=0;i=a&&-1===o.indexOf(r)&&-1===o.indexOf(a)&&(o.push(r),n=a)}return null===n?null:(localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(o)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({nachoMilestones:o}).catch(function(){}),P=!0,{10:"🎉 10 questions! You're officially a Bitcoin Beginner! Keep going — there's so much to learn! 🦌",25:"🎉 25 questions! You've leveled up to Bitcoin Explorer! You're asking the right questions! 💪",50:"🎉 50 questions! Bitcoin Apprentice unlocked! You know more than most people already! 🧠",100:"🏆 100 questions! You're a Bitcoin Scholar now! Satoshi would be proud! 🎓",200:"🔥 200 questions! Bitcoin Expert status! You could probably teach ME a thing or two! 🦌💡",500:"👑 500 QUESTIONS! You are a Bitcoin LEGEND! There's nothing Nacho can't discuss with you now! 🦌🏆🔥"}[n]||null)}();s&&setTimeout(function(){N("nacho","",s),H("nacho","",s)},1500)}function l(e){if(!i){i=!0,clearTimeout(a);var t="";e&&e.siteAction?t='

    ":e&&e.channel&&(t='

    📖 Read more: '+(e.channelName||e.channel)+" →"),s((e&&e.answer?e.answer:"Hmm, let me think about that... Try asking another way! 🦌")+t,e&&e.type||"fallback")}}},window.nachoModeAvatarTap=function(){var e=document.getElementById("nachoModeAvatar");e&&(e.style.transform="scale(1.1) rotate("+(Math.random()>.5?"5":"-5")+"deg)",setTimeout(function(){e.style.transform=""},300),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,W())},window._nachoModeRecognition=null,window._nachoModeListening=!1,window.nachoModeVoice=function(){var e=window.SpeechRecognition||window.webkitSpeechRecognition;if(e){var t=document.getElementById("nachoModeInput"),o=document.getElementById("nachoModeMic");if(t&&o)if(window._nachoModeListening&&window._nachoModeRecognition)window._nachoModeRecognition.stop();else{var n=new e;window._nachoModeRecognition=n,n.lang="en-US",n.interimResults=!0,n.maxAlternatives=1,n.continuous=!0,o.style.opacity="1",o.innerHTML="🛑",t.placeholder="Nacho is listening... (Tap 🛑 to finish)",t.style.borderColor="#f7931a",window._nachoModeListening=!0;var i="";n.onresult=function(e){for(var o="",n=e.resultIndex;n0&&nachoModeSend()},n.onerror=function(){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6",t.style.borderColor="var(--border,#333)",t.placeholder="Voice error — try typing"};try{n.start()}catch(e){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6"}}}},window.exitNachoMode=function(e){window._nachoMode=!1,window._nachoBusy=!1,window._btcPriceTimer&&(clearInterval(window._btcPriceTimer),window._btcPriceTimer=null);var t=document.getElementById("nachoModeScreen");t&&t.remove(),document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="")});var o=document.querySelector(".mobile-bar");if(o&&window.innerWidth<=900&&(o.style.display="flex"),!e){var n=window._nachoModeEarnings,i=window._nachoModeStartTime||Date.now(),a=Math.round((Date.now()-i)/6e4);if("function"==typeof showToast){var r=[];a>0&&r.push("⏱️ "+a+" min"),n&&n.interactions>0&&r.push("🦌 "+n.interactions+" interactions"),n&&n.points>0&&r.push("+"+n.points+" XP");var s=n?Array.isArray(n.badges)?n.badges.length:n.badges||0:0;s>0&&r.push("🏅 "+s+" badge"+(s>1?"s":"")),r.length>0?showToast(r.join(" · ")):showToast("🦌 Thanks for hanging out with "+("function"==typeof nachoNickname?nachoNickname():"Nacho")+"!")}goHome()}},window.goHome=function(e){if(document.activeElement&&document.activeElement.blur&&document.activeElement.blur(),"function"==typeof hideUsernamePrompt){var t=document.getElementById("usernameModal");t&&t.classList.contains("open")&&hideUsernamePrompt()}"function"==typeof _tctvStopTracker&&_tctvStopTracker();var n=document.getElementById("bottomNav");n&&n.classList.remove("nav-hidden"),"function"==typeof _updateSEO&&_updateSEO("home","Learn Bitcoin","A curated Bitcoin education archive with 146 topics, 8800+ messages, and community tools.");var i=document.getElementById("floatingRandomBtn");i&&(i.style.display="none");var a=document.getElementById("lbFloatBtn");a&&a.classList.remove("chat-shifted"),(c=document.getElementById("forumContainer"))&&(c.style.display="none"),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes();var r=document.getElementById("msgs");r&&(r.style.display="none");var s=document.getElementById("hero");s&&(s.style.display="none");var l=void 0!==auth&&auth?auth.currentUser:null;l&&l.email,void 0!==currentUser&¤tUser&¤tUser.totalVisits;try{safeJSON("btc_visited_channels",[]).length}catch(e){}var c,d=document.querySelector('[onclick*="showSpinWheel"]'),u=(document.querySelector('[onclick*="showPricePrediction"]'),document.querySelector('[onclick*="showNachoStory"]'),document.getElementById("dailyChallengeCard")),p=document.querySelector("[onclick*=\"go('bitcoin-beats'\"]"),m=document.querySelector("[onclick*=\"go('forum'\"]"),h=document.querySelector("[onclick*=\"go('marketplace'\"]"),g=document.querySelector('[onclick*="enterNachoMode"]');d&&(d.parentElement.style.display="grid"),u&&(u.style.display=""),m&&(m.style.display=""),p&&(p.style.display=""),h&&(h.style.display=""),g&&(g.style.display=""),(c=document.getElementById("forumContainer"))&&(c.style.display="none",c.innerHTML="");var f=document.getElementById("hero");f&&(f.style.display="none",f.innerHTML="");var y=document.getElementById("msgs");if(y&&(y.style.display="none",y.innerHTML=""),document.getElementById("home").classList.remove("hidden"),document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),document.getElementById("main").scrollTop=0,e||history.pushState({channel:null},"","/"),"function"==typeof window._renderSatoshiFavorHome&&window._renderSatoshiFavorHome(),o()){document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0);var b=document.querySelector(".mobile-bar");b&&(b.style.display="flex"),"function"==typeof updateRankUI&&updateRankUI()}R(),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof loadCommunityStats&&loadCommunityStats(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof window._renderCharityHome&&window._renderCharityHome(),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn()},document.addEventListener("keydown",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.isContentEditable){var t=e.key.toLowerCase();if(!e.ctrlKey&&!e.metaKey)if("h"!==t)if("/"!==t)if("c"!==t)if("r"!==t)if("m"!==t)if("a"!==t)if("t"!==t)if("s"!==t)if("l"!==t)if("q"!==t)if("f"!==t)if("n"!==t)if("d"!==t)if("v"!==t)if("g"!==t)if("p"!==t)if("x"!==t)if("j"!==t)if("k"!==t){if(" "===t)return e.preventDefault(),void document.getElementById("main").scrollBy({top:.8*window.innerHeight,behavior:"smooth"});if("?"===t||e.shiftKey&&"/"===t)!function(){var e=document.getElementById("kbHelpModal");if(e)e.remove();else{var t=document.createElement("div");t.id="kbHelpModal",t.style.cssText="position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.7);",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

    ⌨️ Keyboard Shortcuts

    Press ? to toggle this menu
    Navigation
    '+G("H","Go home")+G("/","Search")+G("C","Random topic")+G("M","Random Meme")+G("R","Random Art")+G("G","Random Graphic")+G("B","Back to last channel")+G("T","PlebTalk (Forum)")+G("S","Lightning Mart")+'
    Actions
    '+G("F","Favorite channel")+G("A","Ask Nacho")+G("N","Nacho Mode")+G("D","Dark / Light mode")+G("L","Leaderboard")+G("Q","Start quest")+G("V","Gallery view")+G("X","PVP Battle")+G("P","Donate")+G("I","Settings")+'
    Scrolling
    '+G("J","Scroll down")+G("K","Scroll up")+G("Space","Page down")+G("Esc","Close modals")+'
    Mobile Gestures
    '+G("2-finger","Nacho Mode")+G("3-finger","Settings")+G("Long-press","Explore Apps (on logo)")+"
    ",document.body.appendChild(t)}}();else if("i"!==t)if("b"!==t)if("2"!==t)if("3"!==t)if("1"!==t){if("0"===t)return F("Don't trust. Verify."),void("function"==typeof earnSticker&&earnSticker("cool"));if("9"===t)return F("Number go up!"),void("function"==typeof nachoFly&&nachoFly());if("2"!==window._eggBuffer||"1"!==t)if("w"!==t){if(window._eggBuffer=(window._eggBuffer||"")+t,window._eggBuffer.length>10&&(window._eggBuffer=window._eggBuffer.slice(-10)),-1!==window._eggBuffer.indexOf("btc")&&(window._eggBuffer="",localStorage.setItem("btc_bitcoin_eyes_unlocked","true"),"function"==typeof showToast&&showToast("₿₿ Secret unlocked: Bitcoin Eyes! Check Nacho's Closet!"),"function"==typeof haptic&&haptic("success")),"escape"===t){e.preventDefault();var i=document.getElementById("lb");if(i&&i.classList.contains("open"))return void i.classList.remove("open");var a=document.getElementById("usernameModal");if(a&&a.classList.contains("open"))return void("function"==typeof hideUsernamePrompt&&hideUsernamePrompt());var r=document.getElementById("questModal");if(r&&r.classList.contains("open"))return void r.classList.remove("open");var s=document.getElementById("searchOverlay");if(s&&"none"!==s.style.display)return void(s.style.display="none");var l=document.getElementById("nachoStoryOverlay");if(l)return void l.remove();var c=document.getElementById("spinModal");if(c)return void c.remove();var d=document.getElementById("donateModal");if(d)return void d.remove();var u=document.getElementById("kbHelpModal");if(u)return void u.remove();if(document.getElementById("pvpOverlay"))return void("function"==typeof exitPVPMode&&exitPVPMode());var p=document.getElementById("appsMenu");if(p&&"block"===p.style.display)return void(p.style.display="none");if(o()){var m=document.getElementById("sidebar");if(m&&m.classList.contains("open"))return m.classList.remove("open"),void("function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!0))}if(window._nachoMode&&"function"==typeof exitNachoMode)return void exitNachoMode()}}else F("Stay humble. Stack sats.");else F("Twenty-one million. Final and absolute.")}else F("One more block.");else F("Three point one two five. The current block reward.");else F("There is no second best.");else{var h=localStorage.getItem("btc_last_channel");h&&go(h)}else"function"==typeof showSettingsPage&&showSettingsPage("account")}else document.getElementById("main").scrollBy({top:-300,behavior:"smooth"});else document.getElementById("main").scrollBy({top:300,behavior:"smooth"});else"function"==typeof _launchPVP&&_launchPVP();else showDonateModal();else B();else{var g=document.getElementById("galleryBtn");g&&g.click()}else n();else"function"==typeof enterNachoMode&&enterNachoMode();else{var f=document.getElementById("favBtn");f&&f.click()}else{var y=document.getElementById("questBtn");y&&y.click()}else"function"==typeof toggleLeaderboard&&toggleLeaderboard();else go("marketplace");else go("forum");else"function"==typeof showNachoInput&&showNachoInput();else x();else k();else v();else{e.preventDefault();var b=document.getElementById("searchInput");b&&(b.focus(),o()&&document.getElementById("sidebar").classList.add("open"))}else goHome()}});var j=0;function F(e){var t=Date.now();if(!(t-j<3e3)){j=t,"function"==typeof showToast&&showToast("🟠 "+e);try{var o=new SpeechSynthesisUtterance(e);o.rate=.9,o.pitch=.85,o.volume=.8;var n=speechSynthesis.getVoices().find(function(e){return-1!==e.name.indexOf("Daniel")||-1!==e.name.indexOf("Google UK English Male")||-1!==e.name.indexOf("Male")});n&&(o.voice=n),speechSynthesis.cancel(),speechSynthesis.speak(o)}catch(e){}}}function G(e,t){return'
    '+e+'
    '+t+"
    "}"undefined"!=typeof speechSynthesis&&speechSynthesis.getVoices(),function(){if("ontouchstart"in window){var e=0,t=0;window.addEventListener("devicemotion",function(o){var n=o.acceleration&&null!==o.acceleration.x?o.acceleration:null;if(n&&Math.abs(n.x)+Math.abs(n.y)+Math.abs(n.z)>25){if(e++,clearTimeout(window._shakeResetTimer),window._shakeResetTimer=setTimeout(function(){e=0},1e3),e<3)return;e=0;var i=Date.now();if(i-t<1e4)return;t=i;var a=["There is no second best.","One more block.","Don't trust. Verify.","Number go up!","Stay humble. Stack sats.","Not your keys, not your coins.","Bitcoin fixes this.","Tick tock, next block."];F(a[Math.floor(Math.random()*a.length)]),Math.random()<.3&&"function"==typeof nachoFly&&nachoFly()}});var o=0,n=0,i=0,a=document.getElementById("main");a.addEventListener("touchstart",function(e){"INPUT"===e.target.tagName||"TEXTAREA"===e.target.tagName||e.target.closest(".no-swipe")||(o=e.touches[0].clientX,n=e.touches[0].clientY,i=Date.now())},{passive:!0}),a.addEventListener("touchend",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.closest(".no-swipe")){var t=e.changedTouches[0].clientX-o,a=e.changedTouches[0].clientY-n,r=Date.now()-i,s=Math.abs(t),l=Math.abs(a);r>600||s>150&&s>2.5*l&&(t>0?(goPrev(),"function"==typeof haptic&&haptic("light")):(goNext(),"function"==typeof haptic&&haptic("light")))}},{passive:!0});var r=0,s=0;document.getElementById("main").addEventListener("touchstart",function(e){2===e.touches.length&&(s=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(s&&0===e.touches.length&&e.changedTouches.length>=1){var t=Date.now()-s;if(s=0,t>400)return;var o=Date.now();if(o-r<3e3)return;r=o,"function"==typeof enterNachoMode&&enterNachoMode()}},{passive:!0}),document.querySelectorAll(".home-logos img, .channel-logos .channel-logo-img").forEach(d),new MutationObserver(function(){document.querySelectorAll(".channel-logos .channel-logo-img").forEach(d)}).observe(document.getElementById("main"),{childList:!0,subtree:!0});var l=0,c=0;document.getElementById("main").addEventListener("touchstart",function(e){3===e.touches.length&&(c=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(c&&0===e.touches.length){var t=Date.now()-c;if(c=0,t>400)return;var o=Date.now();if(o-l<3e3)return;l=o,"function"==typeof showSettings&&showSettings()}},{passive:!0})}function d(e){var t;e._logoLongPress||(e._logoLongPress=!0,e.addEventListener("touchstart",function(e){t=setTimeout(function(){"function"==typeof toggleAppsMenu&&toggleAppsMenu(),"function"==typeof haptic&&haptic("medium")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t)}),e.addEventListener("touchmove",function(){clearTimeout(t)}))}}();const V={};function Q(){const e=safeJSON("btc_visited_channels",[]).length;void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth?auth:null,o=t&&t.currentUser;o&&o.email;var n="function"==typeof getOnboardingProfile?getOnboardingProfile():null;n&&("advanced"===n.level||n.level);const i=document.querySelectorAll(".cat-label.cat-toggle"),a=document.querySelectorAll(".quest-start-btn, .home-cta, #beatsBtnHome, [onclick*=\"go('forum'\"], [onclick*=\"go('marketplace'\"]");function r(e){return function(){var t=e.match(/^go\(['"]([^'"]+)['"]/);if(t)go(t[1]);else{var o=e.match(/^(?:if\(typeof\s+(\w+)==='function'\))?\s*(\w+)\(\)/);if(o){var n=o[2]||o[1];if("function"==typeof window[n])return void window[n]()}var i=e.match(/renderChatHub\(['"](\w+)['"]\)/);if(i&&"function"==typeof window.renderChatHub)window.renderChatHub(i[1]);else{var a=e.match(/showSettingsPage\(['"](\w+)['"]\)/);a&&"function"==typeof window.showSettingsPage?window.showSettingsPage(a[1]):console.warn("[SECURITY] Unrecognized action pattern:",e)}}}}i.forEach(function(e){var t=e.nextElementSibling;t&&t.classList.contains("cat-group")&&(e.style.display="",t.style.display="true"===e.getAttribute("data-expanded")?"":"none")}),a.forEach(e=>{if(e.closest("#appsMenu")||e.closest("#guideOverlay")||e.closest("#questHubOverlay"))return;const t=e.getAttribute("data-name")||e.textContent.replace("🔒 ","").trim();e.getAttribute("data-name")||e.setAttribute("data-name",t);const o=e.getAttribute("data-onclick")||e.getAttribute("onclick");e.getAttribute("data-onclick")||e.setAttribute("data-onclick",o),e.innerHTML=t,e.style.opacity="1",e.style.filter="none",e.style.cursor="pointer",e.title="";var n=e.getAttribute("data-onclick");n&&(e.onclick=r(n))}),document.querySelectorAll("[data-tier]").forEach(t=>{const o=t.getAttribute("data-tier"),n=t.getAttribute("data-unlock-name")||t.textContent.trim(),i=t.getAttribute("data-onclick")||t.getAttribute("onclick");!t.getAttribute("data-onclick")&&i&&t.setAttribute("data-onclick","string"==typeof i?i:i.toString()),!t.getAttribute("data-orig-tooltip")&&t.getAttribute("data-tooltip")&&t.setAttribute("data-orig-tooltip",t.getAttribute("data-tooltip"));let a=!1,s="";if("explorer"===o?(a=true,s="🔒 Visit "+Math.max(0,3-e)+" more channel"+(3-e==1?"":"s")+" to unlock "+n+"!"):"community"===o?(a=true,s="🔒 Explore "+Math.max(0,5-e)+" more channel"+(5-e==1?"":"s")+" to unlock "+n+"!"):"full"===o&&(a=true,s="🔒 Explore "+Math.max(0,10-e)+" more channel"+(10-e==1?"":"s")+" or sign in to unlock "+n+"!"),a){t.innerHTML=n,t.style.opacity="1",t.style.filter="none";var l=t.getAttribute("data-orig-tooltip")||t.getAttribute("data-tooltip");l?(t.title=l,t.setAttribute("data-tooltip",l)):t.title=n,t.style.cursor="pointer",t.title="";var c=t.getAttribute("data-onclick");c&&(t.onclick=r(c))}else t.innerHTML="🔒 "+n,t.style.opacity="0.45",t.style.filter="grayscale(0.8)",t.style.cursor="help",t.title=s,t.setAttribute("data-tooltip",s),t.onclick=function(e){e.preventDefault(),e.stopPropagation(),"function"==typeof showToast&&showToast(s)}});var s=localStorage.getItem("btc_unlocked_tier")||"none",l=["none","explorer","community","full"],c="full",d=l.indexOf(s);if(l.indexOf(c)>d){localStorage.setItem("btc_unlocked_tier",c);var u=document.getElementById("appsMenu");u&&u.remove(),"function"==typeof showToast&&showToast("🚀 ⚡ Lightning Mart unlocked! You have full access!")}var p=document.getElementById("sidebarMilestone");p&&p.remove()}function J(){window.audioEnabled=!window.audioEnabled,localStorage.setItem("btc_audio",window.audioEnabled.toString()),X(),"function"==typeof showToast&&showToast(window.audioEnabled?"🔊 Sound on":"🔇 Sound off")}function Y(e){window.audioVolume=parseFloat(e),localStorage.setItem("btc_volume",window.audioVolume.toString()),window.audioVolume<=0?(window.audioEnabled=!1,localStorage.setItem("btc_audio","false")):window.audioEnabled||(window.audioEnabled=!0,localStorage.setItem("btc_audio","true")),window._beatsAudio&&(window._beatsAudio.volume=window.audioVolume),window._djAudio&&(window._djAudio.volume=window.audioVolume);var t=document.getElementById("beatsVolume");t&&(t.value=Math.round(100*window.audioVolume));var o=document.getElementById("djVolume");o&&(o.value=Math.round(100*window.audioVolume)),X()}function X(){const e=document.getElementById("audioBtn");e&&(e.textContent=window.audioEnabled&&window.audioVolume>0?window.audioVolume>.5?"🔊":"🔉":"🔇");const t=document.getElementById("volumeSlider");t&&(t.value=window.audioEnabled?window.audioVolume:0),document.querySelectorAll('button[onclick*="toggleAudio"]').forEach(function(e){"ON"!==e.textContent&&"OFF"!==e.textContent||(e.textContent=window.audioEnabled?"ON":"OFF",e.style.background=window.audioEnabled?"#22c55e":"var(--bg-side)",e.style.color=window.audioEnabled?"#fff":"var(--text-muted)")})}Q(),window._sidebarTierInterval=setInterval(Q,5e3),window.audioEnabled="false"!==localStorage.getItem("btc_audio"),window.audioVolume=parseFloat(localStorage.getItem("btc_volume")||"0.5"),window.canPlaySound=function(){return window.audioEnabled&&window.audioVolume>0&&"visible"===document.visibilityState},window.goNext=function(){if(void 0===CHANNELS)return;const e=window._sidebarOrder&&window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(m);if(-1===t)return void go(e[0]);const o=t0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(m);if(-1===t)return void go(e[e.length-1]);const o=t>0?e[t-1]:e[e.length-1];go(o)},window.go=async function(e,t,n){"function"==typeof _tctvStopTracker&&_tctvStopTracker();var i=document.getElementById("bottomNav");i&&i.classList.remove("nav-hidden"),window._nachoMode&&!n&&("function"==typeof nachoChatSave&&nachoChatSave(),window._nachoReturnPending=!0);var a=document.getElementById("msgs"),r=document.getElementById("hero");const c=CHANNELS[e];let d="";c&&(d='"),a.innerHTML=d+'
    \x3c!-- Nacho Summary skeleton --\x3e
    \x3c!-- Message skeletons --\x3e
    \x3c!-- Image skeleton --\x3e
    ',a.style.display="",document.getElementById("home").classList.add("hidden"),r.style.display="none",o()&&document.getElementById("sidebar").classList.remove("open");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var h,f=void 0!==auth&&auth?auth.currentUser:null;if(f&&f.email,"forum"===e||"marketplace"===e||"bitcoin-beats"===e||"irl-sync"===e||"dms"===e||"lightning"===e||"chat"===e||"first-purchase"===e||"timechain-tv"===e||"trails"===e)return window._nachoMode&&exitNachoMode(!0),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.getElementById("msgs").style.display="none",document.getElementById("hero").style.display="none",(h=document.getElementById("forumContainer"))&&(h.style.display="block"),n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&document.getElementById("sidebar").classList.remove("open"),function e(t,o){if(o=o||0,"first-purchase"===t&&"function"==typeof renderFirstPurchase)renderFirstPurchase(),document.getElementById("main").scrollTop=0;else if("timechain-tv"===t&&"function"==typeof renderTimechainTV)renderTimechainTV(),document.getElementById("main").scrollTop=0,"function"==typeof _tctvStartTracker&&_tctvStartTracker();else if("marketplace"===t&&"function"==typeof renderMarketplace)renderMarketplace();else if("bitcoin-beats"===t&&"function"==typeof renderBitcoinBeats)renderBitcoinBeats();else if("irl-sync"===t&&"function"==typeof renderIRLSync)renderIRLSync();else if("dms"===t&&"function"==typeof showInbox)showInbox();else if("lightning"===t&&"function"==typeof renderLightning)renderLightning();else if("chat"===t&&"function"==typeof renderChatHub)renderChatHub("global");else if("trails"===t&&"function"==typeof renderModules)renderModules();else if("forum"===t&&"function"==typeof renderForum)renderForum();else if(o<20){if(setTimeout(function(){e(t,o+1)},250),0===o){var n=document.getElementById("forumContainer");n&&(n.innerHTML='
    Loading...
    ')}}else if("forum"===t&&"function"==typeof renderForum)renderForum();else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
    ⚠️
    Still loading...
    This feature is taking longer than expected.
    ')}}(e),document.getElementById("main").scrollTop=0,h&&(h.scrollTop=0),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0,setTimeout(function(){document.getElementById("main").scrollTop=0,document.getElementById("forumContainer")&&(document.getElementById("forumContainer").scrollTop=0),window.scrollTo(0,0)},50),setFloatingElementsVisible(!0),void("function"==typeof nachoOnPage&&nachoOnPage(e));if(!c)return;if(window._nachoMode&&exitNachoMode(!0),(h=document.getElementById("forumContainer"))&&(h.style.display="none",h.innerHTML=""),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes(),document.getElementById("hero").style.display="",document.getElementById("msgs").style.display="",!window._keepFloatingBtn){var y=document.getElementById("floatingRandomBtn");y&&"none"!==y.style.display&&"memes-funny"!==e&&"art-inspiration"!==e&&"graphics"!==e&&(y.style.display="none")}localStorage.setItem("btc_last_channel",e),function(){if(window.canPlaySound())try{const e=new(window.AudioContext||window.webkitAudioContext),t=window.audioVolume,o=e.createOscillator(),n=e.createGain();o.connect(n),n.connect(e.destination),o.frequency.value=880,o.type="sine",n.gain.setValueAtTime(.08*t,e.currentTime),n.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15),o.start(e.currentTime),o.stop(e.currentTime+.15);const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=1318.5,i.type="sine",a.gain.setValueAtTime(.05*t,e.currentTime+.05),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.25),i.start(e.currentTime+.05),i.stop(e.currentTime+.25)}catch(e){}}(),document.getElementById("home").classList.add("hidden"),(a=document.getElementById("msgs")).innerHTML=d+'
    ',document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),t?(t.classList.add("active"),s(t)):document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("'"+e+"'")&&(t.classList.add("active"),s(t))});const b=["graphics","memes-funny","art-inspiration","charts","swag-merch","fun-facts"].includes(e),v="https://bitcoineducation.quest/#"+e,w=c.title+" — Bitcoin Education Archive";let x;if(document.getElementById("hero").innerHTML='
    Home
    '+c.cat+"

    "+c.title+'

    "+(b?'":""),document.getElementById("hero").classList.remove("fade-in"),document.getElementById("msgs").innerHTML='
    Loading channel...
    ',document.getElementById("main").scrollTop=0,n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&(document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0)),V[e])x=V[e];else try{const t=await fetch(c.file);x=await t.json(),V[e]=x}catch(e){return void(document.getElementById("msgs").innerHTML='
    Error loading channel data
    ')}if(p=x,m=e,window.currentChannelId=e,u=!1,"function"==typeof window._raidOnChannelVisit&&window._raidOnChannelVisit(e),"function"==typeof _updateSEO&&void 0!==CHANNELS&&CHANNELS[e]){var k=CHANNELS[e];_updateSEO(e,k.title||k.name,k.desc||"")}if(g(e),window._searchScrollTarget&&window._searchScrollTarget.channel===e){var B=0;setTimeout(function e(){B++,window._searchScrollTarget&&(document.getElementById("msg-"+window._searchScrollTarget.msgIdx)||B>=3?"function"==typeof window._tryScrollToSearchResult&&window._tryScrollToSearchResult():setTimeout(e,400*B))},200)}document.getElementById("hero").classList.add("fade-in"),document.getElementById("msgs").classList.add("fade-in"),window._currentMsgs=x.msgs,window._currentOffset=o()?20:50,window._currentLoadChannel=e,window.loadMoreMsgs=function(){if(window._currentLoadChannel!==m)return;const e=window._currentOffset,t=window._currentMsgs,n=document.getElementById("loadMoreBtn");if(!n)return;const i=t.slice(e,e+50);let a="";i.forEach((t,n)=>{if(a+='
    ',t.text){let e=t.text,n=[],i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){var t=e.startsWith("http")?e:"https://"+e;return i.push(t),"%%TW"+(i.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){var n=i[parseInt(t)],a="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),l=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+l+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),a+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?a+='':a+=''}),a+="
    "}),n.insertAdjacentHTML("beforebegin",a),window._currentOffset=e+50,window._currentOffset>=t.length?(n.remove(),window._scrollObserver&&window._scrollObserver.disconnect()):n.textContent="Load more ("+(t.length-window._currentOffset)+" remaining)"},function(){if(window._scrollObserver&&(window._scrollObserver.disconnect(),window._scrollObserver=null),document.getElementById("loadMoreBtn")){window._scrollObserver=new IntersectionObserver(function(e){e[0].isIntersecting&&"function"==typeof window.loadMoreMsgs&&window.loadMoreMsgs()},{root:null,rootMargin:"300px",threshold:0});var e=document.getElementById("loadMoreBtn");e&&window._scrollObserver.observe(e)}}(),document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")});let S=safeJSON("btc_visited_channels",[]);S.includes(e)||(S.push(e),localStorage.setItem("btc_visited_channels",JSON.stringify(S)),Q());try{void 0!==db&&"undefined"!=typeof firebase&&db.collection("stats").doc("global").set({channelVisits:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}if("function"==typeof window._raidContribute&&window._raidContribute("channelVisit",1,e),x.msgs&&x.msgs.length>0){const t='
    Did this help you learn something?
    Your feedback helps Nacho improve the archive!
    ';a.insertAdjacentHTML("beforeend",t)}window._lastChannelOpenTime=Date.now(),"function"==typeof onChannelOpen&&onChannelOpen(e)};let K=!1,$={},Z=null;const ee=[{id:"_irl",title:"🤝 IRL Sync",desc:"Find and create local Bitcoin meetups and events",keywords:"irl meetup events sync meeting community local map gather conference meetup event rsvp",action:"go('irl-sync')"},{id:"_beats",title:"🎸 Bitcoin Beats",desc:"Community music — discover, upload, and listen to Bitcoin tracks. Upload entire albums and EPs.",keywords:"beats music livestream live video radio stream audio upload song track listen discover artist genre community album ep discography bulk batch dj broadcast",action:"go('bitcoin-beats')"},{id:"_nacho",title:"🦌 Nacho Mode",desc:"Interactive AI-powered Bitcoin tutor",keywords:"nacho mode ai chat ask question tutor learn mascot deer",action:"enterNachoMode()"},{id:"_forum",title:"🗣️ PlebTalk",desc:"Discuss Bitcoin with the community",keywords:"forum community chat discuss talk conversation post plebtalk reply thread threaded replies nested conversation",action:"go('forum')"},{id:"_articles",title:"📝 Articles",desc:"Read and write long-form Bitcoin articles",keywords:"article write publish essay blog read long form content author",action:"forumTab='articles';go('forum')"},{id:"_market",title:"⚡ LightningMart",desc:"Buy and sell with Bitcoin",keywords:"marketplace market buy sell trade shop store bitcoin sats lightning wallet hardware merch",action:"go('marketplace')"},{id:"_settings",title:"⚙️ Settings",desc:"Profile, rank, tickets, referral link, theme",keywords:"settings profile account rank level points tickets referral theme dark light audio sound notifications push",action:"showSettings()"},{id:"_spin",title:"🎡 Daily Spin",desc:"Spin the wheel for free Orange Tickets",keywords:"spin wheel daily reward ticket prize free",action:"showSpinWheel()"},{id:"_quest",title:"⚔️ Quest Hub",desc:"Quiz, Trivia, and Poll quests — earn XP!",keywords:"quest mission journey learn guided start challenge quiz trivia poll hub",action:"showQuestHub()"},{id:"_scholar",title:"🎓 Scholar Certification",desc:"Bitcoin Scholar & Protocol Expert Certifications",keywords:"scholar certification exam test certificate diploma bitcoin technical protocol",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_signal",title:"📡 The Signal",desc:"Weekly curated Bitcoin insights newsletter",keywords:"signal newsletter weekly email updates curated insights",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_flashcards",title:"📚 Flashcards",desc:"Study Bitcoin topics with interactive flashcards",keywords:"flashcard study cards learn review quiz prep memorize practice drill test",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_leaderboard",title:"🏆 Leaderboard",desc:"See top ranked Bitcoiners",keywords:"leaderboard ranking top leaders scoreboard competition",action:"toggleLeaderboard()"},{id:"_tickets",title:"🎟️ Orange Tickets",desc:"Earn tickets for giveaways and rewards",keywords:"tickets orange giveaway raffle prize sats reward earn",action:"showSettings()"},{id:"_referral",title:"🔗 Referral Program",desc:"Invite friends and earn 50 tickets each",keywords:"referral invite share link friend earn bonus",action:"showSettings()"},{id:"_closet",title:"🎽 Nacho's Closet",desc:"Dress up Nacho with items you unlock",keywords:"closet outfit clothes dress costume item equip nacho customize color hat scarf sunglasses crown hoodie accessories wardrobe",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_badges",title:"🏅 Badges",desc:"View your earned badges and goals — chat, DJ, discovery, knowledge",keywords:"badges achievement trophy unlock goal progress medal chat dj streak listener",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_story",title:"📖 Nacho's Story",desc:"Read Nacho's Bitcoin adventure — one chapter per day",keywords:"story chapter read book adventure nacho tale",action:"showNachoStory()"},{id:"_predict",title:"📈 Price Prediction",desc:"Predict if Bitcoin goes up or down in 24 hours",keywords:"predict prediction price bitcoin up down forecast",action:"showPricePrediction()"},{id:"_random",title:"🎲 Random Channel",desc:"Jump to a random Bitcoin channel",keywords:"random channel surprise discover explore dice",action:"goRandom()"},{id:"_meme",title:"😂 Random Meme",desc:"See a random Bitcoin meme",keywords:"meme funny joke random humor laugh memes",action:"goRandomMeme()"},{id:"_art",title:"🎨 Random Art",desc:"See random Bitcoin art and inspiration",keywords:"art random artwork creative inspiration gallery",action:"goRandomArt()"},{id:"_graphic",title:"📊 Random Graphic",desc:"See a random Bitcoin graphic or chart",keywords:"graphic chart data visual infographic random graphics",action:"goRandomGraphic()"},{id:"_quiz",title:"🎮 Quiz Me",desc:"Test your Bitcoin knowledge with Nacho",keywords:"quiz question test knowledge trivia game answer",action:"nachoQuizMe()"},{id:"_pvp",title:"⚔️ PVP Battle",desc:"Real-time Bitcoin trivia battles against other players",keywords:"pvp battle fight 1v1 versus trivia quiz compete multiplayer arena duel challenge opponent leaderboard wins losses",action:"_launchPVP()"},{id:"_donate",title:"💛 Donate",desc:"Support Bitcoin Education Archive with sats",keywords:"donate support tip sats lightning contribute funding",action:"showDonateModal()"},{id:"_theme",title:"🌙 Toggle Theme",desc:"Switch between dark and light mode",keywords:"theme dark light mode toggle switch appearance color night day",action:'document.getElementById("themeToggle").click()'},{id:"_audio",title:"🔊 Toggle Audio",desc:"Turn sound effects on or off",keywords:"audio sound music mute volume effects toggle",action:"toggleAudio()"},{id:"_keyboard",title:"⌨️ Keyboard Shortcuts",desc:"View all keyboard shortcuts",keywords:"keyboard shortcut hotkey key binding keys shortcuts help",action:"showKeyboardHelp()"},{id:"_explore",title:"🗺️ Exploration Map",desc:"See which topics you have visited",keywords:"exploration map progress visited topics grid complete coverage",action:"goHome()"},{id:"_globalchat",title:"🌍 Global Chat",desc:"Live global chat room — talk with the community in real time",keywords:"global chat room live talk community message send public chatroom online users presence dm reaction gif emoji sticker emoji picker smiley face emoticon",action:"if(typeof renderChatHub==='function')renderChatHub('global');else if(typeof toggleChatOverlay==='function')toggleChatOverlay()"},{id:"_timechaintv",title:"📺 Timechain TV",desc:"Live Bitcoin television — 8 channels of curated Bitcoin videos playing 24/7",keywords:"tv television video watch live stream channel timechain tube youtube documentary tutorial mining sync broadcast cinema epg guide schedule remote couch nacho",action:"go('timechain-tv')"},{id:"_djmode",title:"🎧 DJ Mode",desc:"Go live as a DJ — broadcast music, use sound effects, crossfade, and play Bitcoin quotes",keywords:"dj mode broadcast live music stream turntable crossfade sound effects horn airhorn scratch mixer controls",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('livestream')},300)"},{id:"_upload_album",title:"📀 Upload Album/EP",desc:"Upload up to 20 songs at once — group as Album or EP with cover art",keywords:"upload album ep discography batch bulk multiple songs tracks artist release collection",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('upload')},300)"},{id:"_messages",title:"💬 Messages / DMs",desc:"Direct messages — chat privately with other users",keywords:"messages dm direct message inbox chat private conversation contact send receive talk",action:"showInbox()"},{id:"_signin",title:"🔐 Sign In",desc:"Sign in or create an account",keywords:"sign in login register create account google twitter github facebook email",action:"showUsernamePrompt()"},{id:"_home",title:"🏠 Home",desc:"Return to the homepage",keywords:"home main start beginning",action:"goHome()"},{id:"_firstpurchase",title:"🛒 Your First Bitcoin Purchase",desc:"Step-by-step guide to buying your first Bitcoin — apps for 11 regions",keywords:"buy purchase first bitcoin exchange app strike river cash coinbase amber wallet region country how to start beginner dca",action:"go('first-purchase')"},{id:"_trails",title:"🦌 Nacho's Trails",desc:"Guided learning paths through Bitcoin education — Meadow, Mountain & Summit",keywords:"trails nacho guided path learning course module meadow mountain summit exam test progress curriculum education beginner intermediate advanced",action:"go('trails')"},{id:"_dashboard",title:"📊 Top Indicators",desc:"Live Bitcoin cycle top indicators — Pi Cycle, NUPL, Puell, Power Law & more",keywords:"dashboard indicators top cycle signal pi cycle nupl puell mayer multiple rsi ahr999 mstr etf power law rainbow reserve risk bitcoin metrics data analytics chart",action:"if(typeof toggleDashboard==='function')toggleDashboard()"},{id:"_meetupbox",title:"📦 Meetup-in-a-Box",desc:"Ready-made meetup templates with agendas and host tips",keywords:"meetup box template agenda host tips lightning workshop self custody mining event organize plan download",action:"go('irl-sync')"},{id:"_buddy",title:"🤝 Bitcoin Buddy",desc:"Find a learning partner — teachers matched with learners",keywords:"buddy partner match learn teach mentor mentee pair connect chat find friend study accountability group",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_certs",title:"📜 Shareable Certificates",desc:"Share your Scholar Certification with a verifiable public link",keywords:"certificate share verify link public proof scholar achievement social media url",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_satsvbits",title:"⚡ Sats vs Bits",desc:"Live community vote — sats or bits for the Bitcoin denomination?",keywords:"sats bits vote poll denomination unit satoshi community debate live",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_newbie",title:"🟢 Brand New to Bitcoin?",desc:"Quick introduction for absolute beginners",keywords:"new beginner brand new start zero nothing know nothing introduction first time newbie noob",action:"go('one-stop-shop')"},{id:"_meetupbuilder",title:"🔨 Meetup Builder",desc:"Plan, share, and discover Bitcoin meetups — resources, venues & guides",keywords:"meetup builder create plan share venue platform resource guide community",action:"go('meetup-builder')"},{id:"_sats",title:"⚡ Claim Sats",desc:"Convert your earned points into real Bitcoin sats via Lightning",keywords:"sats claim withdraw cashout bitcoin lightning faucet earn XP convert redeem payout real btc satoshi",action:"showSettings();setTimeout(function(){showSettingsPage('sats')},100)"},{id:"_tips",title:"⚡ Lightning Tips",desc:"Tip other users with Lightning sats",keywords:"tip tips lightning send sats zap reward give appreciation",action:"if(typeof showTipOverlay==='function')showTipOverlay()"},{id:"_network",title:"📡 Bitcoin Network",desc:"Live mempool, hashrate, difficulty, fees, and block explorer",keywords:"network mempool hashrate difficulty fees block explorer transaction confirmations bitcoin network stats",action:"go('bitcoin-dashboard')"},{id:"_notifications",title:"🔔 Notifications",desc:"Enable push notifications for updates and alerts",keywords:"notifications push alerts notify bell updates permission enable disable",action:"if(typeof requestNotificationPermission==='function')requestNotificationPermission();else showSettings()"},{id:"_streakfreeze",title:"🧊 Streak Freeze",desc:"Protect your visit streak with freeze tickets",keywords:"streak freeze ticket protect miss save guard insurance ice",action:"showSettings();setTimeout(function(){showSettingsPage('data')},100)"},{id:"_cotd",title:"📅 Channel of the Day",desc:"Today's featured Bitcoin education channel",keywords:"channel of the day daily featured recommendation today pick spotlight",action:"goHome()"},{id:"_nostr",title:"🟣 Nostr Login",desc:"Sign in with Nostr — extension, nsec, or npub",keywords:"nostr login sign in nip npub nsec extension relay decentralized identity",action:"showUsernamePrompt()"},{id:"_buddyfind",title:"🤝 Find a Bitcoin Buddy",desc:"Get matched with a learning partner — teachers meet learners",keywords:"buddy partner match learn teach mentor mentee pair connect study group accountability partner friend",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_favor",title:"✨⛏️ Satoshi's Favor",desc:"Community mining game — earn points, activate mining, hash for 21,000 sats",keywords:"satoshi favor mining hash mine community points activate 21 sats game block nonce difficulty target hashing brute force proof of work",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='favor';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_raid",title:"⚔️ Raid Boss",desc:"Monthly community challenge — deal damage by earning badges and completing activities",keywords:"raid boss challenge monthly community damage badge activity quest defeat winner prize leaderboard attack",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='raid';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_charity",title:"❤️ Donate XP for Charity",desc:"Donate your XP points for charity — 1,000 XP = 1,000 sats pledged. 10× more impact than redeeming for yourself.",keywords:"charity donate donation xp points sats bitcoin giving community philanthropy pledge faction badger hornet",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='charity';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_pow",title:"🚶 Proof of Walk",desc:"Connect Strava and earn XP for walking — proof of work with your feet",keywords:"proof of walk strava walking steps exercise fitness health outdoor move earn xp activity sync connect",action:"go('explore');setTimeout(function(){if(typeof renderProofOfWalk==='function')renderProofOfWalk()},300)"},{id:"_pop",title:"🕹️ Proof of Play",desc:"Bitcoin gaming hub — Timechain Arcade games + PVP trivia battles",keywords:"proof of play arcade games pvp battle timechain bitcoin gaming 1v1 trivia lightning to the moon node runner nakamoto knights block hunt",action:'if(typeof enterProofOfPlay==="function")enterProofOfPlay()'}];function te(e){const t=document.getElementById("searchResults"),o=document.getElementById("channelList");if(["searchInput","searchOverlayInput"].forEach(t=>{const o=document.getElementById(t);o&&o.value!==e&&(o.value=e)}),e&&"satoshi"===e.toLowerCase()&&("function"==typeof awardHiddenBadge&&awardHiddenBadge("discovery_satoshi","Found Satoshi! 🦢"),F("I am Satoshi. We are all Satoshi.")),e&&"deer"===e.toLowerCase()&&("function"==typeof setPose&&setPose("celebrate"),F("Fawntastic! You found the secret buck."),"function"==typeof nachoFly&&setTimeout(nachoFly,1e3)),!e||e.length<2){var n=safeJSON("btc_recent_searches",[]);if(n.length>0&&t){var i='
    🕐 Recent Searches
    ';n.forEach(function(e){i+=""}),i+="
    ",t.innerHTML=i,t.classList.add("active")}else t.classList.remove("active"),t.innerHTML="";return void(o&&(o.style.display=""))}e=e.toLowerCase(),o.style.display="none",t.classList.add("active");let a=[];for(const t of ee)(t.title.toLowerCase().includes(e)||t.keywords.includes(e)||t.desc.toLowerCase().includes(e))&&a.push({key:t.id,title:t.title,cat:"⚡ App",match:t.desc,action:t.action});let r=[];for(const[t,o]of Object.entries(CHANNELS))(o.title.toLowerCase().includes(e)||o.desc.toLowerCase().includes(e))&&r.push({key:t,title:o.title,cat:o.cat,match:"Channel match"});ie([...a,...r],t),clearTimeout(Z),Z=setTimeout(async()=>{await async function(){if(K)return;const e=Object.entries(CHANNELS).map(async([e,t])=>{if(V[e])$[e]=V[e];else try{const o=await fetch(t.file),n=await o.json();V[e]=n,$[e]=n}catch(e){}});await Promise.all(e),K=!0}();let o=[];for(const[t,n]of Object.entries($)){const i=CHANNELS[t];if(!i)continue;if(r.some(e=>e.key===t))continue;const a=n.msgs||[];for(let n=0;n0?"...":"")+r.text.substring(s,a+e.length+30).replace(/<[^>]+>/g,"")+"...";o.push({key:t,title:i.title,cat:i.cat,match:l,msgIdx:n});break}}}ie([...a,...r,...o],t)},500)}const oe=[{q:"What is Bitcoin?",icon:"💰",reason:"Most asked"},{q:"Lightning Network",icon:"⚡",reason:"Trending"},{q:"How to buy Bitcoin",icon:"🛒",reason:"Popular"},{q:"Self-custody wallets",icon:"🔐",reason:"Essential"},{q:"Bitcoin vs Ethereum",icon:"🆚",reason:"Hot topic"},{q:"Why 21 million?",icon:"🔢",reason:"Fundamental"},{q:"Mining explained",icon:"⛏️",reason:"Technical"},{q:"Bitcoin security",icon:"🛡️",reason:"Important"}];function ne(){var e=document.getElementById("searchResults");if(e){var t='
    🔥 Trending Topics
    ';oe.forEach(function(e){t+=""}),t+="
    ",e.innerHTML=t,e.classList.add("active")}}function ie(e,t){0!==e.length?t.innerHTML=e.slice(0,30).map(e=>{const t=e.key&&e.key.startsWith("_");return'
    "+e.cat+"
    "+e.title+'
    '+e.match+"
    "}).join(""):t.innerHTML='
    No results found
    Try: "Lightning Network" or "What is Bitcoin?"
    '}function ae(e,t){var o=document.getElementById("searchOverlayInput"),n=document.getElementById("searchInput"),i=o&&o.value||n&&n.value||"";!function(e){if(e&&!(e.length<2)){var t=safeJSON("btc_recent_searches",[]);(t=t.filter(function(t){return t.toLowerCase()!==e.toLowerCase()})).unshift(e.length>40?e.substring(0,40):e),t.length>10&&(t=t.slice(0,10)),localStorage.setItem("btc_recent_searches",JSON.stringify(t))}}(i),n&&(n.value=""),o&&(o.value=""),document.getElementById("searchOverlay").style.display="none",te(""),"number"==typeof t&&t>=0&&(window._searchScrollTarget={channel:e,msgIdx:t,query:i}),go(e)}window._tryScrollToSearchResult=function(){var e=window._searchScrollTarget;if(e){var t=e.msgIdx;if(e.query,window._searchScrollTarget=null,t>=(o()?20:50)&&"function"==typeof window.loadMoreMsgs)for(var n=0;!document.getElementById("msg-"+t)&&document.getElementById("loadMoreBtn")&&n<50;)window.loadMoreMsgs(),n++;var i=document.getElementById("msg-"+t);i&&setTimeout(function(){i.scrollIntoView({behavior:"smooth",block:"center"}),i.style.transition="background 0.3s, box-shadow 0.3s",i.style.background="rgba(249,115,22,0.12)",i.style.boxShadow="inset 3px 0 0 #f97316",i.style.borderRadius="8px",setTimeout(function(){i.style.background="",i.style.boxShadow="",i.style.borderRadius=""},3e3)},300)}},function(){const e=document.getElementById("visitCount");setTimeout(function(){if("undefined"==typeof firebase||!firebase.firestore)return;const t=firebase.firestore(),o=(new Date).toISOString().split("T")[0];for(var n=[screen.width,screen.height,screen.colorDepth,Intl.DateTimeFormat().resolvedOptions().timeZone,navigator.language,navigator.hardwareConcurrency||0,navigator.platform].join("|"),i=0,a=0;a{a.textContent="Submit Suggestion",a.disabled=!1},3e3)}catch(e){i.innerHTML='Error submitting. Please try again.',a.textContent="Submit Suggestion",a.disabled=!1}}else i.innerHTML='Please enter a suggestion!'},function(){const e=Object.keys(CHANNELS),t=new Date,o=e[Math.floor((t-new Date(t.getFullYear(),0,0))/864e5)%e.length],n=CHANNELS[o];if(n){const e=document.getElementById("dailyChannel");e.innerHTML='
    📅 Channel of the Day
    '+n.title+'
    '+n.desc+"
    ",e.onclick=()=>go(o)}}(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof renderExplorationMap&&renderExplorationMap(),window.innerWidth>900&&document.getElementById("main").addEventListener("scroll",function(){const e=this;document.getElementById("backToTop").classList.toggle("visible",e.scrollTop>400);var t=e.scrollTop+e.clientHeight>=e.scrollHeight-200;document.getElementById("scrollToBottom").classList.toggle("visible",!t)}),window._launchPVP=function(){if("function"==typeof enterPVPMode)enterPVPMode();else{"function"==typeof window._loadDeferred&&window._loadDeferred(),"function"==typeof showToast&&showToast("⚔️ Loading PVP arena...");var e=0,t=setInterval(function(){e++,"function"==typeof enterPVPMode?(clearInterval(t),enterPVPMode()):e>15&&(clearInterval(t),"function"==typeof showToast&&showToast("⚠️ PVP failed to load — try refreshing the page"))},200)}},window.toggleAppsMenu=function(e){e&&e.stopPropagation();var t=document.getElementById("appsMenu");if(t&&"block"===t.style.display)t.style.display="none";else{t&&t.remove();var o=safeJSON("btc_visited_channels",[]).length,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i=void 0!==auth?auth:null,a=i&&i.currentUser,r=a&&-1!==["needcreations@gmail.com","info.603btc@gmail.com"].indexOf(a.email||""),s="function"==typeof getOnboardingProfile?getOnboardingProfile():null,l=s&&("advanced"===s.level||"full"===s.level)||r||a&&!a.isAnonymous||n>=10||o>=10,c=l||n>=5||o>=5,d="padding:15px;background:var(--card-bg);border:1px solid var(--border);border-radius:16px;color:var(--text);font-size:0.85rem;font-weight:700;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:8px;transition:0.2s;",u=d+"opacity:0.45;filter:grayscale(0.8);cursor:help;",p={"Nacho Mode":"Chat with our AI Bitcoin tutor","Proof of Play":"Bitcoin gaming hub — Arcade + PVP","Pleb Talk":"Community discussion board for Bitcoin topics","Lightning Mart":"Buy and sell with Lightning sats","IRL Sync":"Find or host local Bitcoin meetups","Bitcoin Beats":"Community music player","Timechain TV":"21 channels of Bitcoin video content","Proof of Walk":"Earn XP by walking — connect Strava","Proof of Play":"Bitcoin gaming hub — Arcade + PVP"},m=!(c||n>=3||o>=3),h=!c,g=!l,f="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Bitcoin Beats!",y="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Pleb Talk!",b="🔒 Explore "+Math.max(0,5-o)+" more topics to unlock IRL Sync!",v="🔒 Explore "+Math.max(0,10-o)+" more topics or sign in to unlock Lightning Mart!",w='";document.body.insertAdjacentHTML("beforeend",w);var x=document.getElementById("appsMenu");document.addEventListener("click",function(e){"block"!==x.style.display||x.contains(e.target)||(x.style.display="none")}),x.style.display="block","function"==typeof playSound&&playSound("pop")}function k(e,t,o,n,i){var a=p[t]||t;return n?"":""}},window.showProofOfWalk=function(){var e=document.getElementById("appsMenu");e&&(e.style.display="none");var t=document.getElementById("main");t&&(t.innerHTML='
    ',window.renderProofOfWalk&&window.renderProofOfWalk())},window.toggleSidebarMenu=function(e){var t=document.getElementById(e);t&&("flex"===t.style.display||"grid"===t.style.display||"block"===t.style.display?t.style.display="none":(e.includes("Flash")?t.style.display="flex":e.includes("homeAppsMenu")?t.style.display="grid":(t.style.display="flex",t.style.flexDirection="column"),"function"==typeof playSound&&playSound("pop")))},window.onload=()=>{"true"!==localStorage.getItem("btc_nacho_mode_default")||window.location.hash||setTimeout(function(){"function"==typeof enterNachoMode&&enterNachoMode()},1500),safeJSON("btc_visited_channels",[]).forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})}),c(),R(),"function"==typeof checkPredictionResult&&setTimeout(checkPredictionResult,4e3);var e=window.location.hash||"";history.state||(history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname+e)),window.addEventListener("popstate",function(e){var t=e.state||{},o=location.hash.slice(1);if(o||"function"!=typeof _parseCleanUrl||(o=_parseCleanUrl()||""),!e.state||t.guard)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);if(!e.state&&!o)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);var n=document.getElementById("notifPanel");if(n&&"translateY(0px)"===n.style.transform)"function"==typeof toggleNotifOverlay&&toggleNotifOverlay();else if(window._chatOverlayOpen)"function"==typeof toggleChatOverlay&&toggleChatOverlay();else{var i=document.getElementById("usernameModal");if(i&&i.classList.contains("open"))return i.classList.remove("open"),void("function"==typeof window._restoreSignUpForm&&window._restoreSignUpForm());var a=document.getElementById("mobileLearnMenu");if(a)a.remove();else{var r=document.getElementById("appsMenu");if(r&&"block"===r.style.display)r.style.display="none";else{var s=document.getElementById("questModal");if(s&&s.classList.contains("open"))s.classList.remove("open");else if(t.returnToGuide)"function"==typeof showGuide&&(showGuide(),setTimeout(function(){var e=document.getElementById("guideOverlay");if(e&&window._guideScrollTop){var t=e.querySelector('div[style*="border-radius:24px"]');t&&(t.scrollTop=window._guideScrollTop)}},500));else{for(var l=["guideOverlay","onboardingOverlay","pvpNameOverlay","pvpOverlay","tipOverlay","donateModal","lnAuthModal","nostrAuthOverlay","spinModal","hostEventModal","eventDetailOverlay","editEventOverlay","nachoColorPicker","articleLinkDialog","articleImageDialog","eli5Prompt","kbHelpModal","forumRulesOverlay","chatRulesOverlay","marketRulesOverlay","irlRulesOverlay"],c=0;c30&&clearInterval(o)},300)},1500)},function(){function e(){var e=window.location.hash.replace("#","");if(e||"function"!=typeof _parseCleanUrl||(e=_parseCleanUrl()||""),e){console.log("[ROUTE] Routing to:",e);var t=0;setTimeout(function o(){if(t>8e3)console.warn("[HASH] Gave up routing to:",e);else{if(!document.getElementById("msgs")||!document.getElementById("home"))return t+=200,void setTimeout(o,200);switch(e){case"nacho":if("function"==typeof enterNachoMode)return void enterNachoMode();break;case"pvp":if("function"==typeof _launchPVP)return void _launchPVP();break;case"forum":if("function"==typeof go)return void go("forum");break;case"marketplace":if("function"==typeof go)return void go("marketplace");break;case"first-purchase":case"buy":if("function"==typeof go)return void go("first-purchase");break;case"trails":case"learn":case"modules":if("function"==typeof go)return void go("trails");break;case"meetup-builder":if(window._mbRouted)return;if("function"==typeof go){window._mbRouted=!0,window._skipIRLRules=!0,localStorage.setItem("btc_irl_rules_accepted","true"),go("irl-sync"),setTimeout(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove()},100),history.replaceState({channel:"meetup-builder"},"","#meetup-builder");var n=0,i=setInterval(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove();var t=document.getElementById("meetupBuilderSection");t&&(clearInterval(i),t.scrollIntoView({behavior:"smooth",block:"start"})),++n>30&&clearInterval(i)},300);return}break;case"irl-sync":case"meet":if("function"==typeof go)return void go("irl-sync");break;case"bitcoin-beats":if("function"==typeof go)return void go("bitcoin-beats");break;case"chat":if("function"==typeof renderChatHub)return void renderChatHub("global");break;case"dms":if("function"==typeof renderChatHub)return void renderChatHub("dms");if("function"==typeof openDMInbox)return void openDMInbox();if("function"==typeof showInbox)return void showInbox();break;case"lightning":if("function"==typeof go)return void go("lightning");break;case"timechain-tv":case"tv":if("function"==typeof go)return void go("timechain-tv");break;case"pow-support":if("function"==typeof renderPOWSupport)return void renderPOWSupport();break;case"quests":if("function"==typeof showQuestHub)return void showQuestHub();break;case"dashboard":case"bitcoin-dashboard":case"metrics":case"network":if("function"==typeof toggleDashboard)return history.replaceState({home:!0},"",window.location.pathname),void toggleDashboard();break;default:if(0===e.indexOf("beats/")&&"function"==typeof go&&!window._beatsRouted){if(0===e.indexOf("beats/playlist/")){var a=e.replace("beats/playlist/","").split("/");2===a.length&&(window._beatsDeepLink={type:"playlist",ownerUid:a[0],playlistId:a[1]})}else{var r=e.replace("beats/","");r&&-1===r.indexOf("/")&&(window._beatsDeepLink={type:"track",trackId:r})}return window._beatsRouted=!0,void go("bitcoin-beats")}if(0===e.indexOf("beats/")&&window._beatsRouted)return;if(0===e.indexOf("cert/")&&"function"==typeof go)return void go(e);if("function"==typeof go&&void 0!==CHANNELS&&CHANNELS[e])return void go(e)}t+=200,setTimeout(o,200)}},500)}}e(),window.addEventListener("load",function(){setTimeout(function(){var t=window.location.hash.replace("#","");t&&document.getElementById("home")&&!document.getElementById("home").classList.contains("hidden")&&(console.log("[HASH] Post-load fallback routing to:",t),e())},800)}),window.addEventListener("hashchange",e)}(),void 0!==r&&(window.toggleCat=r),void 0!==n&&(window.toggleTheme=n),void 0!==J&&(window.toggleAudio=J),void 0!==Y&&(window.setVolume=Y),void 0!==A&&(window.handleSupportClick=A),"undefined"!=typeof showDonateModal&&(window.showDonateModal=showDonateModal),"undefined"!=typeof enterNachoMode&&(window.enterNachoMode=enterNachoMode),"undefined"!=typeof goHome&&(window.goHome=goHome),void 0!==v&&(window.goRandom=v),void 0!==k&&(window.goRandomArt=k),void 0!==x&&(window.goRandomMeme=x),void 0!==B&&(window.goRandomGraphic=B),void 0!==te&&(window.doSearch=te),void 0!==ne&&(window.showTrendingTopics=ne),void 0!==ae&&(window.selectResult=ae),void 0!==i&&(window.toggleMenu=i),void 0!==a&&(window.toggleSidebarCollapse=a),void 0!==t&&(window.openImg=t),void 0!==d&&(window.toggleFav=d),void 0!==T&&(window.shareNostr=T),void 0!==C&&(window.copyLink=C),void 0!==h&&(window.toggleGallery=h),void 0!==g&&(window.renderContent=g),"undefined"!=typeof showBeginnerGuide&&(window.showBeginnerGuide=showBeginnerGuide),void 0!==y&&(window.loadTweetEmbed=y)}(),window._spinSoundCtx=null,window.playSpinTick=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx,t=e.createOscillator(),o=e.createGain();t.connect(o),o.connect(e.destination),t.frequency.value=800+400*Math.random(),t.type="triangle",o.gain.value=.08,o.gain.exponentialRampToValueAtTime(.001,e.currentTime+.08),t.start(e.currentTime),t.stop(e.currentTime+.08)}catch(e){}},window._tctvTimer=null,window._tctvMinutesSession=0,window._tctvStartTracker=function(){if(!window._tctvTimer){window._tctvMinutesSession=0;try{var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_tctv_visited_"+e,"true")}catch(e){}console.log("[TCTV] Watch tracker started."),window._tctvTimer=setInterval(function(){if("timechain-tv"===(window.currentChannelId||"")){if(!document.hidden){var e=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")+1;localStorage.setItem("btc_tctv_watch_time",e.toString()),window._tctvMinutesSession++;try{var t=(new Date).toISOString().split("T")[0],o=parseInt(localStorage.getItem("btc_tctv_minutes_"+t)||"0")+1;localStorage.setItem("btc_tctv_minutes_"+t,String(o))}catch(e){}console.log("[TCTV] Watch time:",e,"min (Session:",window._tctvMinutesSession,"min)");try{void 0!==db&&"undefined"!=typeof firebase&&void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("stats").doc("global").set({watchTimeMinutes:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}e%10==0?("function"==typeof awardPoints&&awardPoints(10,"tctv_watch_10m"),"function"==typeof checkBadges&&checkBadges(),"function"==typeof showToast&&showToast("👁️ +10 Points — Thanks for watching Timechain TV!")):1===e&&"function"==typeof showToast&&showToast("📺 Watching Timechain TV — Points awarded every 10 min!")}}else window._tctvStopTracker()},6e4)}},window._tctvStopTracker=function(){window._tctvTimer&&(clearInterval(window._tctvTimer),window._tctvTimer=null,console.log("[TCTV] Watch tracker stopped. Total minutes watched:",window._tctvMinutesSession))},window._updateSEO=function(e,t,o){if(e){document.title=(t?t+" | ":"")+"Bitcoin Education Archive";var n=document.querySelector('link[rel="canonical"]');if(n){var i="home"===e||"/"===e?"":"/app/"+e;n.setAttribute("href","https://bitcoineducation.quest"+i)}var a=document.querySelector('meta[name="description"]');a&&o&&a.setAttribute("content",o.substring(0,160));var r=window._cleanUrl(e);window.location.href.includes(r)||history.replaceState({channel:e},"",r)}},window.playSpinWin=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx;[523,659,784,1047].forEach(function(t,o){var n=e.createOscillator(),i=e.createGain();n.connect(i),i.connect(e.destination),n.frequency.value=t,n.type="sine",i.gain.value=.1,i.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15*(o+1)+.3),n.start(e.currentTime+.15*o),n.stop(e.currentTime+.15*(o+1)+.3)})}catch(e){}},window._aiToolsOpen=!1,window.toggleAITools=function(){var e=document.getElementById("aiToolsPanel");if(!e){(e=document.createElement("div")).id="aiToolsPanel",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:250000;background:var(--bg,#0a0a0f);border-top:2px solid var(--accent,#f7931a);border-radius:16px 16px 0 0;transform:translateY(100%);transition:transform 0.3s ease;box-shadow:0 -10px 40px rgba(0,0,0,0.6);",e.innerHTML='
    🤖AI Toolspowered by PPQ
    ',document.body.appendChild(e);var t=document.createElement("style");t.id="aiToolsPanelCSS",t.textContent="@media(min-width:901px){#aiToolsPanel{max-width:480px;right:16px;left:auto;border-radius:16px 16px 0 0;}}@media(max-width:900px){#aiToolsPanel iframe{height:calc(70vh - 56px);}}",document.head.appendChild(t)}window._aiToolsOpen=!window._aiToolsOpen,e.style.transform=window._aiToolsOpen?"translateY(0)":"translateY(100%)";var o=document.getElementById("aiToolsBtn");if(o&&(o.style.background=window._aiToolsOpen?"var(--card-bg)":"linear-gradient(135deg,#6366f1,#8b5cf6)",o.style.borderColor=window._aiToolsOpen?"var(--accent)":"transparent"),window._aiToolsOpen&&void 0!==db&&db)try{var n=auth&&auth.currentUser?auth.currentUser.uid:"anon_"+(localStorage.getItem("visitorId")||"unknown");db.collection("ai_tools_opens").add({uid:n,openedAt:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){console.warn("[AI Tools] tracking error",e)}},function(){function e(){var e=document.getElementById("aiToolsBtn");e||((e=document.createElement("button")).id="aiToolsBtn",e.className="fab-btn",e.innerHTML="🤖",document.body.appendChild(e)),e.onclick=toggleAITools}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}(),function(){var e=window.renderBitcoinBeats;e&&(window.renderBitcoinBeats=function(){e(),setTimeout(function(){document.getElementById("beatsLoader");var e=document.getElementById("beatsEmbedArea");if(e){var t=e.querySelector("iframe"),o=e.querySelector(".twitter-tweet-rendered, twitter-widget");t||o||(e.innerHTML='
    🎸
    Stream Unavailable
    The live stream couldn\'t be loaded. Check out these great Bitcoin audio sources instead:
    ')}},8e3)})}(),void 0===window.contactSeller&&(window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to contact sellers!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==db&&db.collection("marketplace").doc(e).get().then(function(e){if(e.exists){var t=e.data(),o=t.sellerUid;o!==auth.currentUser.uid?("function"==typeof openDM?openDM(o,t.sellerName||"Seller"):"function"==typeof showInbox&&(showInbox(),setTimeout(function(){"function"==typeof startNewDM&&startNewDM(o,t.sellerName||"Seller")},500)),void 0!==db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1),"function"==typeof showToast&&showToast("💬 Opening chat with "+(t.sellerName||"seller")+"...")):"function"==typeof showToast&&showToast("That's your own listing!")}})}),window.handleMktImageUploadV2=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var o=document.getElementById("mktImagePreview"),n=document.getElementById("mktImagePreviewImg");if(o&&(o.style.display="block",n&&(n.src=""),o.innerHTML='
    📤 Uploading...
    '),"undefined"!=typeof firebase&&firebase.storage){var i=firebase.storage().ref(),a="marketplace/"+auth.currentUser.uid+"/"+Date.now()+"_"+t.name.replace(/[^a-zA-Z0-9.]/g,"_"),r=i.child(a).put(t,{contentType:t.type});r.on("state_changed",function(e){var t=Math.round(e.bytesTransferred/e.totalBytes*100);o&&(o.innerHTML='
    📤 Uploading... '+t+"%
    ")},function(t){"function"==typeof showToast&&showToast("Upload failed: "+t.message),o&&(o.style.display="none"),handleMktImageUpload(e)},function(){r.snapshot.ref.getDownloadURL().then(function(e){window._mktUploadedImage=e,o&&n&&(o.innerHTML=''),"function"==typeof showToast&&showToast("✅ Image uploaded!")})})}else"function"==typeof handleMktImageUpload&&handleMktImageUpload(e)}else"function"==typeof showToast&&showToast("Sign in to upload images")},function(){var e=[{type:"youtube",id:"UvSnC7P-m-U",title:"What is Bitcoin? — Andreas Antonopoulos",desc:"The best intro talk ever given"},{type:"youtube",id:"l1si5ZWLgy0",title:"Bitcoin for Beginners — BTC Sessions",desc:"Step-by-step Bitcoin guide"},{type:"youtube",id:"ZKwqNgG-Sv4",title:"The Bitcoin Standard — Saifedean Ammous",desc:"Author presentation on sound money"},{type:"youtube",id:"2pDlaOGA2ac",title:"How Bitcoin Works Under the Hood",desc:"Technical deep-dive"},{type:"youtube",id:"bBC-nXj3Ng4",title:"But How Does Bitcoin Actually Work?",desc:"3Blue1Brown explains"},{type:"youtube",id:"Gc2en3nHxA4",title:"Michael Saylor on Why Bitcoin",desc:"The macro case for Bitcoin"},{type:"youtube",id:"xLYhx1z7gC4",title:"This Machine Greens — Bitcoin & Energy",desc:"Bitcoin mining documentary"},{type:"youtube",id:"HCLWDGYnAzk",title:"Running a Bitcoin Node — Ministry of Nodes",desc:"How to verify for yourself"}];window.beatsPlaylistIndex=parseInt(localStorage.getItem("btc_beats_idx")||"0")%e.length,window.renderBeatsPlaylist=function(t){if(t){var o=e[window.beatsPlaylistIndex],n=e.length,i=window.beatsPlaylistIndex,a='
    ';a+='
    ',a+='
    '+o.title+'
    '+o.desc+" • "+(i+1)+"/"+n+'
    ',t.innerHTML=a}},window.beatsNav=function(t){window.beatsPlaylistIndex=(window.beatsPlaylistIndex+t+e.length)%e.length,localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var o=document.getElementById("beatsEmbedArea");o&&renderBeatsPlaylist(o)},window.beatsNavRandom=function(){window.beatsPlaylistIndex=Math.floor(Math.random()*e.length),localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var t=document.getElementById("beatsEmbedArea");t&&renderBeatsPlaylist(t)};var t=8e3,o=setInterval(function(){var e=document.getElementById("beatsEmbedArea");e&&(document.getElementById("beatsLoader")?(t-=500)<=0&&(clearInterval(o),renderBeatsPlaylist(e)):clearInterval(o))},500)}(),window.fuzzyMatch=function(e,t){if(!t||!e)return!0;var o=e.toLowerCase();return t.toLowerCase().split(/\s+/).every(function(e){return-1!==o.indexOf(e)})},function(){function e(){return!(!auth||!auth.currentUser)&&"needcreations@gmail.com"===(auth.currentUser.email||"")}window.forumEditPost=function(t){auth&&auth.currentUser&&void 0!==db&&db.collection("forum_posts").doc(t).get().then(function(o){if(o.exists){var n=o.data();if(n.authorId===auth.currentUser.uid||e()){var i=n.createdAt?n.createdAt.toDate():new Date;if(Date.now()-i.getTime()>9e5&&!e())"function"==typeof showToast&&showToast("Posts can only be edited within 15 minutes of creation");else{var a='
    ✏️ Edit Post
    Edited posts will show an "edited" indicator
    ',r=document.createElement("div");r.innerHTML=a,document.body.appendChild(r.firstChild)}}else"function"==typeof showToast&&showToast("You can only edit your own posts")}})},window.forumSaveEdit=function(e){var t=(document.getElementById("editPostTitle").value||"").trim(),o=(document.getElementById("editPostBody").value||"").trim();!t||t.length<5?"function"==typeof showToast&&showToast("Title must be at least 5 characters"):"function"!=typeof isCleanText||isCleanText(t+" "+o)?db.collection("forum_posts").doc(e).update({title:t.substring(0,120),body:o.substring(0,2e3),editedAt:firebase.firestore.FieldValue.serverTimestamp(),edited:!0}).then(function(){var t=document.getElementById("forumEditOverlay");t&&t.remove(),"function"==typeof showToast&&showToast("✅ Post updated!"),"function"==typeof forumViewPost&&forumViewPost(e,!0)}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))}):"function"==typeof showToast&&showToast("Post contains inappropriate language")}}(),function(){var e=[{level:1,name:"Just Met",emoji:"🦌",threshold:1},{level:2,name:"Getting Acquainted",emoji:"👋",threshold:10},{level:3,name:"Good Friends",emoji:"😊",threshold:100},{level:4,name:"Close Friends",emoji:"🧡",threshold:350},{level:5,name:"Best Buds",emoji:"💛",threshold:750}],t=window.trackNachoInteraction;t&&(window.trackNachoInteraction=function(){for(var o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),n=0,i=e.length-1;i>=0;i--)if(o>=e[i].threshold){n=e[i].level;break}t();for(var a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r=0,s=null,l=e.length-1;l>=0;l--)if(a>=e[l].threshold){r=e[l].level,s=e[l];break}if(r>n&&s){var c=JSON.parse(localStorage.getItem("btc_nacho_level_celebrated")||"[]");-1===c.indexOf(s.level)&&(c.push(s.level),localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(c)),"function"==typeof syncCelebratedState&&syncCelebratedState(),setTimeout(function(){var e="function"==typeof nachoUserName?nachoUserName():"",t=s.emoji+" "+(e?e+", w":"W")+"e just became "+s.name+"! "+(s.level>=3?"New closet items are now available! Check the Closet! 👔✨":"Keep chatting with me to unlock more! 🦌");"function"==typeof forceShowBubble?(forceShowBubble(t),s.level>=3&&setTimeout(function(){var e=document.getElementById("nacho-bubble");e&&(e.style.cursor="pointer",e.onclick=function(){e.classList.remove("show"),window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},300)})},100)):"function"==typeof showToast&&showToast("🦌 Friendship Level Up: "+s.emoji+" "+s.name+"!")},1e3))}})}(),function(){var e=[],t=!1,o=0;function n(){if(!t&&0!==e.length){var i=Date.now();if(i-o<3e4)setTimeout(n,3e4-(i-o)+100);else{t=!0;var a=e.shift();o=i;try{a.show()}catch(e){console.log("Notification error:",e)}setTimeout(function(){t=!1,n()},5e3)}}}window.queueNotification=function(t,o){e.push({type:t,show:o,queued:Date.now()}),n()};var i=window.showToast;i&&(window.showToastQueued=function(e){queueNotification("toast",function(){i(e)})})}(),window.initMiniPlayer=function(){if(!document.getElementById("miniPlayer")){var e=document.createElement("div");e.id="miniPlayer",e.style.cssText="position:fixed;bottom:60px;left:0;right:0;z-index:180;background:rgba(10,10,10,0.95);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-top:1px solid rgba(247,147,26,0.3);padding:8px 16px;display:none;align-items:center;gap:12px;",e.innerHTML='
    Not playing
    Bitcoin Beats
    ',document.body.appendChild(e)}},window._miniPlayerAudio=null,window.playInMiniPlayer=function(e,t,o){initMiniPlayer();var n=document.getElementById("miniPlayer");n&&(window._miniPlayerAudio&&window._miniPlayerAudio.pause(),window._miniPlayerAudio=new Audio(e),window._miniPlayerAudio.play().catch(function(){}),document.getElementById("mpTitle").textContent=t||"Playing...",document.getElementById("mpArtist").textContent=o||"Bitcoin Beats",document.getElementById("mpPlayPause").textContent="⏸",n.style.display="flex")},window.toggleMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.paused?(window._miniPlayerAudio.play(),document.getElementById("mpPlayPause").textContent="⏸"):(window._miniPlayerAudio.pause(),document.getElementById("mpPlayPause").textContent="▶"))},window.closeMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.pause(),window._miniPlayerAudio=null);var e=document.getElementById("miniPlayer");e&&(e.style.display="none")},function(){var e=2592e6;window.isListingExpired=function(t){if(!t||!t.createdAt)return!1;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt);return Date.now()-o.getTime()>e},window.renewListing=function(e){auth&&auth.currentUser&&void 0!==db&&db.collection("marketplace").doc(e).update({createdAt:firebase.firestore.FieldValue.serverTimestamp(),renewed:!0,renewedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){"function"==typeof showToast&&showToast("✅ Listing renewed for 30 more days!"),"function"==typeof renderMarketplace&&renderMarketplace({listingId:e})}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))})},window.getExpiryStatus=function(t){if(!t||!t.createdAt)return null;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt),n=Date.now()-o.getTime(),i=Math.max(0,Math.ceil((e-n)/864e5));return i<=0?{status:"expired",text:"This listing has expired",color:"#ef4444"}:i<=5?{status:"expiring",text:"Expires in "+i+" day"+(1!==i?"s":""),color:"#eab308"}:null}}(),window.renderSellerReputation=function(e,t){e&&t&&void 0!==db&&db.collection("users").doc(e).get().then(function(e){if(e.exists){var o=e.data(),n=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):null,i=n?n.toLocaleDateString("en-US",{month:"short",year:"numeric"}):"Unknown",a="function"==typeof getLevel?getLevel(o.points||0):{emoji:"🟢",name:"Normie"},r='
    '+a.emoji+" "+a.name+'📅 Member since '+i+""+(o.forumPosts?'💬 '+o.forumPosts+" posts":"")+(o.marketListings?'🛒 '+o.marketListings+" listings":"")+"
    ";t.innerHTML+=r}}).catch(function(){})},function(){var e="btc_forum_draft",t="btc_forum_reply_",o=null;window.saveForumDraft=function(){var t=document.getElementById("forumNewTitle"),o=document.getElementById("forumNewBody"),n=document.getElementById("forumNewCategory");if(t||o){var i={title:t?t.value:"",body:o?o.value:"",category:n?n.value:"general",savedAt:Date.now()};localStorage.setItem(e,JSON.stringify(i))}},window.restoreForumDraft=function(){try{var t=JSON.parse(localStorage.getItem(e));return!t||Date.now()-t.savedAt>864e5?null:t}catch(e){return null}},window.clearForumDraft=function(){localStorage.removeItem(e)},window.saveReplyDraft=function(e){var o=document.getElementById("forumReplyInput");o&&o.value.trim()?localStorage.setItem(t+e,o.value):localStorage.removeItem(t+e)},window.restoreReplyDraft=function(e){return localStorage.getItem(t+e)||""},window.clearReplyDraft=function(e){localStorage.removeItem(t+e)};var n=new MutationObserver(function(){var e=document.getElementById("forumNewTitle"),t=document.getElementById("forumNewBody");if(e&&!e._draftBound){e._draftBound=!0,e.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)});var n=restoreForumDraft();n&&(n.title||n.body)&&(e.value=n.title||"",t&&(t.value=n.body||""),"function"==typeof showToast&&showToast("📝 Draft restored"))}t&&!t._draftBound&&(t._draftBound=!0,t.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)}));var i=document.getElementById("forumReplyInput");if(i&&!i._draftBound&&"undefined"!=typeof forumCurrentPost&&forumCurrentPost){i._draftBound=!0;var a=forumCurrentPost.id,r=restoreReplyDraft(a);r&&(i.value=r),i.addEventListener("input",function(){clearTimeout(o),o=setTimeout(function(){saveReplyDraft(a)},3e3)})}});document.body?n.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",function(){n.observe(document.body,{childList:!0,subtree:!0})})}(),window.isCleanTextV2=function(e){if(!e)return!0;for(var t=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","faggot","retard","nazi","hitler","kkk","porn","hentai","rape","pedo","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","jap","paki","wop","slut","whore","cum","dildo","tits","nude","naked","milf","molest","suicide","terrorist","jihad","genocide","lynch","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","supremacy","acab","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","erection","ejaculat","deepthroat","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes"],o=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g,"").split(/\s+/),n=0;n=4&&-1!==o[n].indexOf(t[i]))return!1}return!0},void 0!==window.isCleanText&&(window._origIsCleanText=window.isCleanText,window.isCleanText=window.isCleanTextV2),function(){var e=document.createElement("style");e.id="ux-patch-styles",e.textContent="\n /* Modal overlay */\n .modal-overlay {\n position: fixed; inset: 0;\n background: rgba(0,0,0,0.7);\n backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);\n z-index: 9999;\n display: flex; align-items: center; justify-content: center;\n padding: 16px;\n }\n /* Modal card */\n .modal-card {\n background: var(--bg-side, #1a1a2e);\n border: 1px solid rgba(255,255,255,0.1);\n border-radius: 24px;\n padding: 24px;\n max-width: 480px; width: 100%;\n max-height: 85vh; overflow-y: auto;\n box-shadow: 0 20px 60px rgba(0,0,0,0.5);\n animation: fadeSlideIn 0.3s;\n -webkit-overflow-scrolling: touch;\n }\n /* Pill button */\n .pill-btn {\n padding: 6px 14px;\n border-radius: 20px;\n border: 1px solid var(--border);\n background: var(--card-bg);\n color: var(--text-muted);\n font-size: 0.75rem;\n cursor: pointer;\n font-family: inherit;\n white-space: nowrap;\n font-weight: 600;\n transition: 0.2s;\n }\n .pill-btn.active {\n border-color: var(--accent);\n background: var(--accent);\n color: #fff;\n }\n /* scroll-top-btn removed — using #backToTop in index.html */\n /* Badge progress bar */\n .badge-progress {\n width: 100%; height: 4px;\n background: rgba(255,255,255,0.1);\n border-radius: 2px;\n margin-top: 4px;\n overflow: hidden;\n }\n .badge-progress-fill {\n height: 100%;\n background: var(--accent);\n border-radius: 2px;\n transition: width 0.5s ease;\n }\n ",document.head.appendChild(e)}(),window.renderQuestDashboard=function(){if(void 0===QUESTION_BANK)return"";var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=parseInt(localStorage.getItem("btc_quests_completed")||"0"),o=Object.keys(QUESTION_BANK).filter(function(t){return-1!==e.indexOf(t)}),n=Object.keys(QUESTION_BANK).length;return'
    ⚔️
    Quest Progress
    '+t+' quests completed
    Channels with questions unlocked'+o.length+"/"+n+'
    Visit more topics to unlock new quests! Each topic you read adds its questions to your quest pool.
    '},window.renderBadgeWithProgress=function(e,t){var o="";if(!t&&e.progress&&"function"==typeof e.progress){var n=e.progress(),i=n.match(/(\d+)\/(\d+)/);if(i){var a=parseInt(i[1]),r=parseInt(i[2]);o='
    '+n+"
    "}}return'
    '+e.emoji+'
    '+e.name+'
    '+e.desc+"
    "+(t?'
    ✅ Earned!
    ':"")+o+"
    "},function(){function e(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;for(var o=[],n=0;n<=t.length;n++)o[n]=[n];for(var i=0;i<=e.length;i++)o[0][i]=i;for(n=1;n<=t.length;n++)for(i=1;i<=e.length;i++)t.charAt(n-1)===e.charAt(i-1)?o[n][i]=o[n-1][i-1]:o[n][i]=Math.min(o[n-1][i-1]+1,o[n][i-1]+1,o[n-1][i]+1);return o[t.length][e.length]}window.fuzzyChannelSearch=function(t,o){if(!t||!o)return[];var n=t.toLowerCase().trim().split(/\s+/),i=[];for(var a in o){var r=o[a],s=(r.name||r.title||a).toLowerCase(),l=(r.desc||"").toLowerCase(),c=s+" "+l+" "+a.replace(/-/g," "),d=0,u=0;n.forEach(function(t){if(-1!==s.indexOf(t))d+=10,u++;else if(-1!==c.indexOf(t))d+=5,u++;else if(t.length>3)for(var o=c.split(/\s+/),n=0;n0&&i.push({id:a,channel:r,score:d})}return i.sort(function(e,t){return t.score-e.score}),i}}(),console.log("✅ UX Patches loaded — 24 tasks from the UX Review Report"),new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e].concat(Array.from(e.querySelectorAll('.msg-text, .msg-body, [class*="msg"]'))):[e]).forEach(function(e){e.innerHTML&&-1!==e.innerHTML.indexOf("this Discord")&&(e.innerHTML=e.innerHTML.replace(/this Discord/g,"this App"))})})})}).observe(document.body,{childList:!0,subtree:!0}),function(){var e=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e,...e.querySelectorAll("img.msg-img")]:[e]).forEach(function(e){"IMG"===e.tagName&&e.classList.contains("msg-img")&&!e.dataset.blurUp&&(e.dataset.blurUp="1",e.style.filter="blur(8px)",e.style.transition="filter 0.4s ease",e.complete&&e.naturalWidth>0?e.style.filter="none":(e.addEventListener("load",function(){e.style.filter="none"},{once:!0}),e.addEventListener("error",function(){e.style.filter="none"},{once:!0})))})})})});document.getElementById("main")&&e.observe(document.getElementById("main"),{childList:!0,subtree:!0})}(),function(){var e="btc_nacho_convo_persist",t=window.nachoRemember;"function"==typeof t&&(window.nachoRemember=function(o,n){t(o,n);try{var i=JSON.parse(localStorage.getItem(e)||"[]");i.push({q:o,a:(n||"").substring(0,200),t:Date.now()}),i.length>20&&(i=i.slice(-20)),localStorage.setItem(e,JSON.stringify(i))}catch(e){}}),setTimeout(function(){if(void 0!==window._nachoConvoHistory&&0===window._nachoConvoHistory.length)try{var t=JSON.parse(localStorage.getItem(e)||"[]");if(t.length>0)for(var o=Math.max(0,t.length-5);ot.clientHeight?Math.round(t.scrollTop/(t.scrollHeight-t.clientHeight)*100):100;try{var n=JSON.parse(localStorage.getItem(e)||"{}");o>(n[window.currentChannelId]||0)&&(n[window.currentChannelId]=o,localStorage.setItem(e,JSON.stringify(n)))}catch(e){}},500))},{passive:!0}),window.getChannelProgress=function(t){try{return JSON.parse(localStorage.getItem(e)||"{}")[t]||0}catch(e){return 0}}}}(),function(){var e=0,t=!1;window.addEventListener("unhandledrejection",function(o){if(!(++e>10)){var n=o.reason&&o.reason.message?o.reason.message:"",i=o.reason&&o.reason.code?o.reason.code:"";console.error("[Error Boundary] Unhandled promise rejection:",n||o.reason),/permission.denied|Missing or insufficient|requires an index|PERMISSION_DENIED/i.test(n+i)||!t&&/network|fetch|Failed to fetch|UNAVAILABLE|unavailable/i.test(n+i)&&(t=!0,"function"==typeof showToast&&showToast("⚠️ Connection issue — some features may not work. Try refreshing."))}}),window.addEventListener("error",function(t){++e>5||console.error("[Error Boundary]",t.message,t.filename,t.lineno)})}(),function(){var e="btc_offline_channels";"function"!=typeof window.go||window._offlineCacheHooked||(window._offlineCacheHooked=!0,setInterval(function(){if(window.currentChannelId&&void 0!==CHANNELS){var t=CHANNELS[window.currentChannelId];if(t&&t.file)try{var o=JSON.parse(localStorage.getItem(e)||"{}");if(o[window.currentChannelId]&&Date.now()-o[window.currentChannelId].ts<864e5)return;"caches"in window&&caches.open("btc-offline-channels").then(function(e){e.add(t.file).catch(function(){})}),o[window.currentChannelId]={ts:Date.now()};var n=Object.keys(o);if(n.length>10){n.sort(function(e,t){return o[e].ts-o[t].ts});for(var i=0;iwindow.innerWidth-8&&(n=window.innerWidth-240-8),t.style.left=n+"px",t.style.width="240px",window.innerWidth>900?(t.style.top=o.top-8+"px",t.style.transform="translateY(-100%)"):(t.style.top=o.bottom+8+"px",t.style.transform="none")}}document.addEventListener("mouseover",function(t){var o=t.target.closest(".badge-item");o&&e(o)}),document.addEventListener("click",function(t){var o=t.target.closest(".badge-item");o&&e(o)})}(),function(){"use strict";function e(){var e=function(){if(void 0===window.NACHO_TRAILS)return null;var e=[];try{e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]")}catch(e){}var t={};try{t=JSON.parse(localStorage.getItem("btc_trail_progress")||"{}")}catch(e){}for(var o=0;o0){var r=document.createElement("div");if(r.className="ch-progress",r.style.cssText="position:absolute;bottom:0;left:0;height:2px;background:"+(i>=100?"#22c55e":"var(--accent,#f7931a)")+";width:"+Math.min(i,100)+"%;border-radius:0 1px 0 0;transition:width 0.3s;opacity:0.7;",t.style.position="relative",t.style.overflow="hidden",t.appendChild(r),i>=100&&!t.querySelector(".ch-done")){var s=document.createElement("span");s.className="ch-done",s.style.cssText="position:absolute;right:6px;top:50%;transform:translateY(-50%);font-size:0.6rem;opacity:0.5;",s.textContent="✓",t.appendChild(s)}}}})}catch(e){}}setTimeout(e,2e3);var t=window.goHome;t&&(window.goHome=function(){var o=t.apply(this,arguments);return setTimeout(e,500),o});var o=window.go;o&&(window.go=function(){var t=o.apply(this,arguments);return setTimeout(e,1e3),t}),window.updateSidebarProgress=e}(); \ No newline at end of file diff --git a/bundle.src.js b/bundle.src.js index c2dcd08a1..3445dfc2a 100644 --- a/bundle.src.js +++ b/bundle.src.js @@ -1,4 +1,5 @@ -var CHANNELS = {"decentralized":{"cat":"Properties Layer 1","title":"👪decentralized-censorship-resistant-ungovernable-incorruptible-trustless-unconfiscatable-updatable","desc":"Why no single person, company, or government controls Bitcoin — and why that's the most important feature.","file":"data/D_decentralized.json"},"dominant":{"cat":"Properties Layer 1","title":"🏆dominant-recognizable-brand-legitimate-limitless-infinite-exponential-transformative-revolutionary","desc":"Bitcoin's brand recognition, network effects, and why it has maintained the #1 position since 2009.","file":"data/D_dominant.json"},"money":{"cat":"Properties Layer 1","title":"💰money-deflationary-salable-durable-anti-fragile-divisible-portable-transmittable-verifiable-fair","desc":"What money actually is, how it works, and why Bitcoin satisfies every property of sound money better than anything before it.","file":"data/D_money.json"},"organic":{"cat":"Properties Layer 1","title":"🌳organic-empowering-elegant-freedom-centric-irrefutable-unseizable-irreversible-unbreakable","desc":"How Bitcoin grew from an idea worth nothing to a trillion-dollar network — without marketing, without a company, without a leader.","file":"data/D_organic.json"},"peaceful":{"cat":"Properties Layer 1","title":"☮peaceful-neutral-voluntary-open-universal-permissionless-borderless-global-inevitable-unstoppable","desc":"Bitcoin is voluntary, permissionless, borderless, and unstoppable. No one forces you to use it — and no one can stop you.","file":"data/D_peaceful.json"},"programmable":{"cat":"Properties Layer 1","title":"🤖programable-interoperable-deflationary-pseudonymous-opt-in-resilient-adiabatic-egalitarian","desc":"Bitcoin as programmable money — interoperable, pseudonymous, resilient, and thermodynamically sound.","file":"data/D_programmable.json"},"scarce":{"cat":"Properties Layer 1","title":"🍀scarce-unforgeable-hedge-scalable-p2p-instant-open-source-auditable-inaliable","desc":"Only 21 million will ever exist. Explore what makes Bitcoin the scarcest asset humanity has ever created.","file":"data/D_scarce.json"},"secure":{"cat":"Properties Layer 1","title":"™secure-fungible-immutable-incorruptible-immalleable-infallible-reliable-predictable-irreplicable","desc":"How Bitcoin's network security makes it virtually impossible to hack — protected by more computing power than anything on Earth.","file":"data/D_secure.json"},"supranational":{"cat":"Properties Layer 1","title":"🕊supranational-lindy-inviolate-dilution-proof-frictionless-freely-accessible-settlement-finality","desc":"Bitcoin transcends nations and governments. Explore the Lindy Effect, settlement finality, and dilution-proof money.","file":"data/D_supranational.json"},"use-cases":{"cat":"Properties Layer 1","title":"✔use-cases","desc":"Real-world uses for Bitcoin: savings, payments, remittances, store of value, and more.","file":"data/D_use-cases.json"},"whitepaper":{"cat":"Properties Layer 1","title":"📄whitepaper","desc":"The 9-page document that started it all. Published October 31, 2008 by Satoshi Nakamoto — the foundation of Bitcoin.","file":"data/D_whitepaper.json"},"bitvm":{"cat":"Experienced Topics","title":"🖥bitvm","desc":"BitVM: computation on Bitcoin without changing the protocol. A new frontier for Bitcoin programmability.","file":"data/E_bitvm.json"},"blockchain-timechain":{"cat":"Experienced Topics","title":"⛓blockchain-timechain-transactions-addresses","desc":"How the Bitcoin blockchain (timechain) works — blocks, transactions, timestamps, and the immutable ledger.","file":"data/E_blockchain-timechain.json"},"chaumian-mints":{"cat":"Experienced Topics","title":"💸layer-2-chaumian-mints-ecash","desc":"Chaumian ecash, Cashu, and blinded signatures — the cutting edge of Bitcoin privacy technology.","file":"data/E_chaumian-mints.json"},"consensus":{"cat":"Additional Info","title":"🤝Consensus","desc":"How Bitcoin achieves consensus without a central authority — Nakamoto Consensus and beyond.","file":"data/H_consensus.json"},"core-source-code":{"cat":"Experienced Topics","title":"💾core-source-code-forks-testnet-future-potential-upgrades","desc":"Bitcoin Core's source code, forks, testnet, and the open-source development process.","file":"data/E_core-source-code.json"},"cryptography":{"cat":"Experienced Topics","title":"🔒cryptography-cypherpunks","desc":"The cryptographic foundations of Bitcoin — SHA-256, elliptic curves, digital signatures, and the cypherpunk legacy.","file":"data/E_cryptography.json"},"ctv-covenants":{"cat":"Experienced Topics","title":"📜ctv-bip119-covenants","desc":"BIP-119, CTV, and Bitcoin covenants — proposed upgrades and the debates around them.","file":"data/E_ctv-covenants.json"},"developers":{"cat":"Experienced Topics","title":"🖥developers","desc":"Building on Bitcoin — resources, guides, and paths for developers who want to contribute.","file":"data/E_developers.json"},"difficulty-adjustment":{"cat":"Experienced Topics","title":"😤difficulty-adjustment","desc":"The most elegant part of Bitcoin's design — how the network self-adjusts every 2,016 blocks.","file":"data/E_difficulty-adjustment.json"},"energy":{"cat":"Experienced Topics","title":"💡energy","desc":"The truth about Bitcoin's energy use: 0.1% of global energy, renewable mining, methane capture, and grid stabilization.","file":"data/E_energy.json"},"evidence-against-alts":{"cat":"Experienced Topics","title":"⚠evidence-against-ethereum-other-alt-coins-crypto-defi-nfts-web3-monero-bsv-bch-cbdcs-other-projects","desc":"Why every altcoin fails against Bitcoin — premines, centralization, broken promises, and the evidence.","file":"data/E_evidence-against-alts.json"},"extension-blocks":{"cat":"Experienced Topics","title":"🚧extension-blocks-and-other-proposed-scaling-solutions","desc":"Extension blocks and other proposed scaling solutions for Bitcoin.","file":"data/E_extension-blocks.json"},"fedi-ark":{"cat":"Experienced Topics","title":"🛡layer-2-fedi-ark","desc":"Fedimints, Ark, and Bitcoin's privacy/scaling layers — community custody with enhanced privacy.","file":"data/E_fedi-ark.json"},"investment-strategy":{"cat":"Experienced Topics","title":"🤑investment-strategy-taxes-retirement-inheritance-loans-donate-gift-consulting-remittance","desc":"DCA, HODL, lump sum strategies, taxes, retirement planning, and thinking long-term with Bitcoin.","file":"data/E_investment-strategy.json"},"layer-2-lightning":{"cat":"Experienced Topics","title":"⚡layer-2-lightning","desc":"The Lightning Network: instant, nearly-free Bitcoin payments. How Bitcoin scales without sacrificing decentralization.","file":"data/E_layer-2-lightning.json"},"layer-3-sidechains":{"cat":"Experienced Topics","title":"📱layer-3-sidechain-applications","desc":"Sidechains, Liquid Network, and layer-3 applications built on top of Bitcoin.","file":"data/E_layer-3-sidechains.json"},"maximalism":{"cat":"Experienced Topics","title":"💯maximalism","desc":"Why people who study Bitcoin the most become maximalists. The case for Bitcoin-only.","file":"data/E_maximalism.json"},"mining":{"cat":"Experienced Topics","title":"🌋mining","desc":"How Bitcoin mining actually works — nonces, SHA-256 hashing, difficulty adjustment, and the brute-force lottery.","file":"data/E_mining.json"},"nodes":{"cat":"Experienced Topics","title":"💻nodes","desc":"Run your own Bitcoin node. Don't trust, verify. How 14,000+ nodes keep the network decentralized.","file":"data/E_nodes.json"},"op-codes":{"cat":"Experienced Topics","title":"👨‍💻op-codes-simplicity","desc":"OP_CAT, Simplicity, and Bitcoin's scripting language — the building blocks of smart functionality.","file":"data/E_op-codes.json"},"pow-vs-pos":{"cat":"Experienced Topics","title":"💪proof-of-work-vs-proof-of-stake","desc":"Why Proof of Work is fundamentally superior to Proof of Stake — energy, security, fairness, and decentralization.","file":"data/E_pow-vs-pos.json"},"privacy-nonkyc":{"cat":"Experienced Topics","title":"🤫privacy-nonkyc-stacking-self-sovereignty","desc":"Financial privacy as a human right. KYC, non-KYC stacking, and protecting your sovereignty.","file":"data/E_privacy-nonkyc.json"},"problems-of-money":{"cat":"Experienced Topics","title":"📉the-problems-of-todays-money-and-freedom","desc":"The broken fiat system: inflation, money printing, the Cantillon Effect, and why today's money is failing everyone.","file":"data/E_problems-of-money.json"},"regulation":{"cat":"Experienced Topics","title":"🏛regulation-policy-legal","desc":"Bitcoin and government: bans, adoption, legal tender, ETFs, and why regulation can't stop decentralization.","file":"data/E_regulation.json"},"self-custody":{"cat":"Experienced Topics","title":"🔑personal-storage-self-custody-security","desc":"Not your keys, not your coins. Learn how to truly own your Bitcoin with wallets, seed phrases, and security.","file":"data/E_self-custody.json"},"smart-contracts":{"cat":"Experienced Topics","title":"📱smart-contracts","desc":"Smart contracts on Bitcoin — what's possible, what's coming, and why Bitcoin's approach is different.","file":"data/E_smart-contracts.json"},"stablecoins":{"cat":"Additional Info","title":"🪙Stablecoins","desc":"The role of stablecoins in the Bitcoin economy — and why they're not a threat to Bitcoin.","file":"data/H_stablecoins.json"},"0_mining__hashing":{"cat":"Additional Info","title":"0⃣Mining (Hashing)","desc":"Deep dive into Bitcoin mining and hashing — how SHA-256 works at the bit level.","file":"data/H_0_mining__hashing.json"},"100_sats":{"cat":"Additional Info","title":"💯100 sats","desc":"What can you do with just 100 satoshis? More than you think.","file":"data/H_100_sats.json"},"1_first_principles":{"cat":"Additional Info","title":"1⃣First Principles","desc":"First principles thinking applied to Bitcoin — reasoning from fundamentals, not analogies.","file":"data/H_1_first_principles.json"},"2__solved_technical_problems":{"cat":"Additional Info","title":"2⃣ Solved Technical Problems","desc":"The technical problems Bitcoin solved — digital scarcity, double-spending, and Byzantine fault tolerance.","file":"data/H_2__solved_technical_problems.json"},"analogies":{"cat":"Additional Info","title":"🔋Analogies","desc":"The best analogies for explaining Bitcoin to anyone — from trees to brains to hearts.","file":"data/H_analogies.json"},"austrian_school_of_economics":{"cat":"Additional Info","title":"🇦🇹Austrian School of Economics","desc":"Austrian Economics and Bitcoin: Mises, Hayek, sound money theory, and the intellectual foundation.","file":"data/H_austrian_school_of_economics.json"},"bip119":{"cat":"Additional Info","title":"🚧BIP119","desc":"BIP-119 (CheckTemplateVerify) — what it is, why it's controversial, and the community debate.","file":"data/H_bip119.json"},"bitcoin_exam":{"cat":"Additional Info","title":"🎓Bitcoin Exam","desc":"Test questions for a Bitcoin exam — study material and self-assessment.","file":"data/H_bitcoin_exam.json"},"bitcoin_vs_real_estate":{"cat":"Additional Info","title":"Bitcoin vs Real Estate","desc":"Bitcoin vs. real estate as an investment — comparing the two hardest assets.","file":"data/H_bitcoin_vs_real_estate.json"},"block_time-block-size":{"cat":"Additional Info","title":"⏰Block Time-Block-Size","desc":"Why Bitcoin uses 10-minute blocks and how block size affects the network.","file":"data/H_block_time-block-size.json"},"burn_bitcoin":{"cat":"Additional Info","title":"Burn bitcoin","desc":"How Bitcoin can be burned (made permanently unspendable) and why people do it.","file":"data/H_burn_bitcoin.json"},"byzantine_generals__problem":{"cat":"Additional Info","title":"⚔Byzantine Generals’ Problem","desc":"The Byzantine Generals' Problem — the computer science challenge Satoshi solved.","file":"data/H_byzantine_generals__problem.json"},"chaumian_e-cash_and_blind_signatures":{"cat":"Additional Info","title":"💲Chaumian E-cash and Blind Signatures","desc":"David Chaum's ecash, blind signatures, and the cryptographic foundations of digital privacy.","file":"data/H_chaumian_e-cash_and_blind_signatures.json"},"coin_mixing_coinjoin_coin_control_utxo":{"cat":"Additional Info","title":"🌀Coin Mixing/Coinjoin/Coin Control/UTXO Management","desc":"CoinJoin, coin mixing, UTXO management — advanced Bitcoin privacy techniques.","file":"data/H_coin_mixing_coinjoin_coin_control_utxo.json"},"cyles":{"cat":"Additional Info","title":"🚲Cyles","desc":"Bitcoin's 4-year cycles, Gartner Hype Cycles, and whether the pattern continues.","file":"data/H_cyles.json"},"derivation_path":{"cat":"Additional Info","title":"↕Derivation Path","desc":"HD wallet derivation paths — how your seed phrase generates all your addresses.","file":"data/H_derivation_path.json"},"discrete_log_contracts__dlcs":{"cat":"Additional Info","title":"📝Discrete Log Contracts (DLCs)?","desc":"DLCs (Discrete Log Contracts) — smart contracts on Bitcoin using oracle signatures.","file":"data/H_discrete_log_contracts__dlcs.json"},"dollar-bitcoin_milkshake_theory":{"cat":"Additional Info","title":"🥤Dollar-Bitcoin Milkshake Theory","desc":"The Dollar-Bitcoin Milkshake Theory — how global dollar demand and Bitcoin intersect.","file":"data/H_dollar-bitcoin_milkshake_theory.json"},"dust":{"cat":"Additional Info","title":"⏳Dust","desc":"Dust UTXOs: what they are, why they're a problem, and how to manage them.","file":"data/H_dust.json"},"elevator_pitches":{"cat":"Additional Info","title":"↕Elevator Pitches","desc":"Quick 20-30 second explanations of why Bitcoin matters — for every audience.","file":"data/H_elevator_pitches.json"},"environment___energy":{"cat":"Additional Info","title":"🌳Environment & Energy","desc":"Bitcoin and the environment: energy usage facts, renewable mining, and debunking the FUD.","file":"data/H_environment___energy.json"},"faith___religion":{"cat":"Additional Info","title":"🙏Faith & Religion","desc":"Bitcoin and faith — how sound money relates to religious and spiritual values.","file":"data/H_faith___religion.json"},"fedimints":{"cat":"Additional Info","title":"💚Fedimints","desc":"Fedimints: community custody with enhanced privacy using federated Chaumian mints.","file":"data/H_fedimints.json"},"feedback_loops":{"cat":"Additional Info","title":"➰Feedback Loops","desc":"Bitcoin's feedback loops — the self-reinforcing cycles that drive adoption and security.","file":"data/H_feedback_loops.json"},"free_and_open_source_software__foss":{"cat":"Additional Info","title":"💿Free and Open Source Software (FOSS)","desc":"Free and open source software (FOSS) projects connected to Bitcoin.","file":"data/H_free_and_open_source_software__foss.json"},"game_theory":{"cat":"Additional Info","title":"🏈Game Theory","desc":"Game theory and Bitcoin: Nash equilibrium, prisoner's dilemma, and strategic incentives.","file":"data/H_game_theory.json"},"geopolitics___macroeconomics":{"cat":"Additional Info","title":"💰Geopolitics & Macroeconomics","desc":"Bitcoin's role in geopolitics: nation-state adoption, reserve currencies, and macro trends.","file":"data/H_geopolitics___macroeconomics.json"},"governance":{"cat":"Additional Info","title":"🏛Governance","desc":"How Bitcoin is governed — consensus mechanisms, BIPs, and decentralized decision-making.","file":"data/H_governance.json"},"ham_radio":{"cat":"Additional Info","title":"Ham Radio","desc":"Using Bitcoin without internet — ham radio, mesh networks, and offline transactions.","file":"data/H_ham_radio.json"},"human_rights__social_justice_and_freedo":{"cat":"Additional Info","title":"🗽Human Rights, Social Justice and Freedom","desc":"Bitcoin as a tool for human rights, social justice, and financial freedom worldwide.","file":"data/H_human_rights__social_justice_and_freedo.json"},"improved_incentive_structure":{"cat":"Additional Info","title":"✅Improved Incentive Structure","desc":"How Bitcoin's incentive structure improves civilization — aligning individual and collective interests.","file":"data/H_improved_incentive_structure.json"},"laws_of_thermodynamics":{"cat":"Additional Info","title":"🔥Laws of Thermodynamics","desc":"How Bitcoin follows the laws of thermodynamics — energy, entropy, and proof of work.","file":"data/H_laws_of_thermodynamics.json"},"lightning_node":{"cat":"Additional Info","title":"⚡ Lightning Node","desc":"Running a Lightning Network node — setup guides, routing, and earning sats.","file":"data/H_lightning_node.json"},"lindy_effect":{"cat":"Additional Info","title":"👴Lindy Effect","desc":"The Lindy Effect: the longer Bitcoin survives, the longer it will survive.","file":"data/H_lindy_effect.json"},"market_cap":{"cat":"Additional Info","title":"🧢Market Cap","desc":"Bitcoin's market cap potential — can it reach millions per coin? The math says yes.","file":"data/H_market_cap.json"},"math":{"cat":"Additional Info","title":"➕Math","desc":"The mathematics of Bitcoin — from SHA-256 to elliptic curves to probability.","file":"data/H_math.json"},"mathematics":{"cat":"Additional Info","title":"➕Mathematics","desc":"Advanced mathematical concepts underlying Bitcoin's protocol and security.","file":"data/H_mathematics.json"},"mev":{"cat":"Additional Info","title":"⛏MEV","desc":"MEV (Miner Extractable Value) in Bitcoin — what it is and its implications.","file":"data/H_mev.json"},"network_effects":{"cat":"Additional Info","title":"🌐Network Effects","desc":"Bitcoin's network effects — why the most adopted network wins and keeps winning.","file":"data/H_network_effects.json"},"open_source":{"cat":"Additional Info","title":"⭕Open Source","desc":"What free and open source really means — and why it matters for Bitcoin.","file":"data/H_open_source.json"},"oracle":{"cat":"Additional Info","title":"🔮Oracle","desc":"Oracles in Bitcoin — how external data connects to the blockchain.","file":"data/H_oracle.json"},"orange-pilling":{"cat":"Additional Info","title":"🟠Orange-Pilling","desc":"The art of orange-pilling — strategies for explaining Bitcoin to different audiences.","file":"data/H_orange-pilling.json"},"ordinals":{"cat":"Additional Info","title":"Ordinals","desc":"Bitcoin Ordinals and inscriptions — NFTs on the world's most secure blockchain.","file":"data/H_ordinals.json"},"ordinals__nfts_on_bitcoin__and_block_spa":{"cat":"Additional Info","title":"Ordinals, NFTs on Bitcoin, and Block Space","desc":"The Ordinals debate: NFTs on Bitcoin, block space economics, and community perspectives.","file":"data/H_ordinals__nfts_on_bitcoin__and_block_spa.json"},"peace_and_anti-war":{"cat":"Additional Info","title":"☮Peace and Anti-War","desc":"Can a Bitcoin Standard end wars? The case for Bitcoin as a force for peace.","file":"data/H_peace_and_anti-war.json"},"philosophy":{"cat":"Additional Info","title":"🍎Philosophy","desc":"The philosophy of Bitcoin — from first principles to existential implications.","file":"data/H_philosophy.json"},"politics":{"cat":"Additional Info","title":"🏛Politics","desc":"Bitcoin and politics — how Bitcoin intersects with government policy and elections.","file":"data/H_politics.json"},"predictions":{"cat":"Additional Info","title":"🔮Predictions","desc":"Bitcoin predictions timestamped by the community — bold calls and their outcomes.","file":"data/H_predictions.json"},"public_key_vs_private_key":{"cat":"Additional Info","title":"🗝Public Key vs Private Key","desc":"Public keys vs. private keys — the cryptographic foundation of Bitcoin ownership.","file":"data/H_public_key_vs_private_key.json"},"rbf":{"cat":"Additional Info","title":"↔RBF","desc":"Replace-By-Fee (RBF) — how to speed up stuck Bitcoin transactions.","file":"data/H_rbf.json"},"referral-links":{"cat":"Referral Links","title":"🔗free-btc-referral-links","desc":"Curated Bitcoin referral links — earn free sats with trusted platforms like River, Fold, and Strike.","file":"data/H_referral-links.json"},"risks__threats__attack_vectors__weaknes":{"cat":"Additional Info","title":"⚔Risks, Threats, Attack Vectors, Weaknesses, Issues","desc":"Bitcoin's risks, threats, and attack vectors — what could go wrong and why it probably won't.","file":"data/H_risks__threats__attack_vectors__weaknes.json"},"rollups":{"cat":"Additional Info","title":"🥐Rollups","desc":"Rollups on Bitcoin — scaling and privacy solutions using off-chain computation.","file":"data/H_rollups.json"},"sats__or__bits":{"cat":"Additional Info","title":"\"Sats\" or \"Bits\"?","desc":"The sats vs. bits debate — which denomination should Bitcoin use?","file":"data/H_sats__or__bits.json"},"scalability":{"cat":"Additional Info","title":"🌐Scalability","desc":"Can Bitcoin scale to serve the world? Layers, Lightning, and the path forward.","file":"data/H_scalability.json"},"sidechains":{"cat":"Additional Info","title":"♻Sidechains","desc":"Bitcoin sidechains like Liquid — benefits, tradeoffs, and use cases.","file":"data/H_sidechains.json"},"simplified_payment_verification__spv":{"cat":"Additional Info","title":"✔Simplified Payment Verification (SPV)","desc":"SPV (Simplified Payment Verification) — lightweight Bitcoin verification without a full node.","file":"data/H_simplified_payment_verification__spv.json"},"soft_vs_hard_forks":{"cat":"Additional Info","title":"🍴Soft vs Hard Forks","desc":"Soft forks vs. hard forks — how Bitcoin upgrades while maintaining consensus.","file":"data/H_soft_vs_hard_forks.json"},"softwar":{"cat":"Additional Info","title":"Softwar","desc":"Jason Lowery's Softwar thesis — Bitcoin as a non-lethal alternative to physical warfare.","file":"data/H_softwar.json"},"stratum_v2":{"cat":"Additional Info","title":"🟩Stratum V2","desc":"Stratum V2 — the next-generation mining protocol for better decentralization and efficiency.","file":"data/H_stratum_v2.json"},"submarine_swap":{"cat":"Additional Info","title":"⛵Submarine Swap","desc":"Submarine swaps — trustlessly moving Bitcoin between on-chain and Lightning.","file":"data/H_submarine_swap.json"},"swaps":{"cat":"Additional Info","title":"↔Swaps","desc":"How to swap between on-chain Bitcoin and Lightning — tools, techniques, and protocols.","file":"data/H_swaps.json"},"ta_tips":{"cat":"Additional Info","title":"📈TA Tips","desc":"Technical analysis tips for Bitcoin — chart patterns, indicators, and trading education.","file":"data/H_ta_tips.json"},"tail_emission":{"cat":"Additional Info","title":"🐈Tail Emission","desc":"The tail emission debate — should Bitcoin ever have perpetual block rewards?","file":"data/H_tail_emission.json"},"taproot":{"cat":"Additional Info","title":"🧰Taproot","desc":"Taproot: Bitcoin's latest major upgrade — Schnorr signatures, script improvements, and privacy.","file":"data/H_taproot.json"},"taro":{"cat":"Additional Info","title":"🥕Taro","desc":"Taro (now Taproot Assets) — issuing assets on the Bitcoin and Lightning networks.","file":"data/H_taro.json"},"the_future":{"cat":"Additional Info","title":"🔮The Future","desc":"How Bitcoin could change the future — hyperbitcoinization, global adoption, and beyond.","file":"data/H_the_future.json"},"time":{"cat":"Additional Info","title":"⏰Time","desc":"How Bitcoin keeps time — block time, timestamps, and the decentralized clock.","file":"data/H_time.json"},"time_preference":{"cat":"Additional Info","title":"🕑Time Preference","desc":"Time preference: how sound money encourages long-term thinking and civilization building.","file":"data/H_time_preference.json"},"toxicity":{"cat":"Additional Info","title":"☣ Toxicity","desc":"Is Bitcoin community toxicity real? Or is it integrity? The debate and its meaning.","file":"data/H_toxicity.json"},"transaction_fees":{"cat":"Additional Info","title":"💲Transaction Fees","desc":"Bitcoin transaction fees — how they work, fee markets, and long-term sustainability.","file":"data/H_transaction_fees.json"},"unpopular_opinions":{"cat":"Additional Info","title":"💀Unpopular Opinions","desc":"Unpopular opinions in the Bitcoin space — controversial takes and honest debates.","file":"data/H_unpopular_opinions.json"},"utxos":{"cat":"Additional Info","title":"🕳UTXOs","desc":"UTXOs (Unspent Transaction Outputs) — the fundamental building block of Bitcoin transactions.","file":"data/H_utxos.json"},"vbyte":{"cat":"Additional Info","title":"🏋vByte","desc":"Virtual bytes (vBytes) — how Bitcoin measures transaction weight for fee calculation.","file":"data/H_vbyte.json"},"apps-tools":{"cat":"Resources","title":"🍎apps-tools-services-models","desc":"Bitcoin apps, tools, services, and platforms — everything you need to use Bitcoin daily.","file":"data/R_apps-tools.json"},"art-inspiration":{"cat":"Resources","title":"🤩art-inspiration-motivation","desc":"Bitcoin art, inspiration, and motivational content from the community.","file":"data/R_art-inspiration.json"},"articles-threads":{"cat":"Resources","title":"📃articles-threads","desc":"The best Bitcoin articles and Twitter threads — curated deep dives into every aspect of Bitcoin.","file":"data/R_articles-threads.json"},"books":{"cat":"Resources","title":"📚books","desc":"The essential Bitcoin reading list: The Bitcoin Standard, 21 Lessons, Mastering Bitcoin, and more.","file":"data/R_books.json"},"charts":{"cat":"Resources","title":"📊charts","desc":"Bitcoin price charts, on-chain analytics, stock-to-flow, and data visualizations.","file":"data/R_charts.json"},"curriculum":{"cat":"Resources","title":"🎓curriculum-presentations","desc":"Bitcoin education curriculum and presentations for teachers and students.","file":"data/R_curriculum.json"},"faq-glossary":{"cat":"Resources","title":"❓faq-glossary-search-ai-calendar","desc":"Bitcoin FAQ, glossary of terms, and quick answers to common questions.","file":"data/R_faq-glossary.json"},"fun-facts":{"cat":"Resources","title":"🎉fun-facts","desc":"Mind-blowing Bitcoin trivia: Pizza Day, Satoshi's birthday code, lost coins, and 200+ amazing facts.","file":"data/R_fun-facts.json"},"games":{"cat":"Resources","title":"🎮games","desc":"Bitcoin-themed games and gamified learning experiences.","file":"data/R_games.json"},"giga-chad":{"cat":"Resources","title":"👑giga-chad","desc":"Michael Saylor, MicroStrategy, and the corporate Bitcoin movement.","file":"data/R_giga-chad.json"},"graphics":{"cat":"Resources","title":"🎨graphics","desc":"Bitcoin infographics, charts, diagrams, and visual explanations.","file":"data/R_graphics.json"},"hardware":{"cat":"Resources","title":"💻hardware","desc":"Bitcoin hardware: mining rigs, hardware wallets, nodes, and open-source projects like Bitaxe.","file":"data/R_hardware.json"},"health":{"cat":"Resources","title":"🥩health","desc":"Bitcoin and health: low time preference living, breaking free from the system.","file":"data/R_health.json"},"history":{"cat":"Resources","title":"📆history","desc":"The complete history of Bitcoin — from the cypherpunks to today.","file":"data/R_history.json"},"informational-sites":{"cat":"Resources","title":"📃informational-sites-courses-workshops-newsletters-projects-communities-meetups-conferences","desc":"Bitcoin dashboards, tools, courses, newsletters, communities, and educational websites.","file":"data/R_informational-sites.json"},"international":{"cat":"Resources","title":"🌍international","desc":"Bitcoin resources in multiple languages and global adoption stories.","file":"data/R_international.json"},"jobs-earn":{"cat":"Resources","title":"👷job-postings-employer-info-entrepreneurship-earn-bitcoin-stack-sats","desc":"Bitcoin job boards, entrepreneurship resources, and ways to earn sats.","file":"data/R_jobs-earn.json"},"memes-funny":{"cat":"Resources","title":"😂memes-funny","desc":"The best Bitcoin memes, jokes, and humor from the community. Laugh while you learn.","file":"data/R_memes-funny.json"},"misconceptions-fud":{"cat":"Resources","title":"🤡common-misconceptions-fud-debunked","desc":"Every Bitcoin myth debunked: too volatile, wastes energy, used by criminals, no intrinsic value — all wrong.","file":"data/R_misconceptions-fud.json"},"movies-tv":{"cat":"Resources","title":"🎬movies-tv-documentaries","desc":"Bitcoin documentaries, films, and TV appearances. From The Big Short to Bitcoin-specific docs.","file":"data/R_movies-tv.json"},"music":{"cat":"Resources","title":"🎵music","desc":"Bitcoin-inspired music, songs, and audio content from the community.","file":"data/R_music.json"},"news-adoption":{"cat":"Resources","title":"📰news-adoption","desc":"Latest Bitcoin news, adoption milestones, and real-world usage stories.","file":"data/R_news-adoption.json"},"nostr":{"cat":"Resources","title":"💜nostr","desc":"Nostr: the decentralized social protocol Bitcoiners are building on. Social media you can't be censored from.","file":"data/R_nostr.json"},"one-stop-shop":{"cat":"Resources","title":"🛑one-stop-shop","desc":"The best resources to understand Bitcoin's value as fast as possible. Start here if you're new.","file":"data/R_one-stop-shop.json"},"podcasts":{"cat":"Resources","title":"🔊podcasts","desc":"Top Bitcoin podcasts: Bitcoin Audible, What Bitcoin Did, Stephan Livera, and more.","file":"data/R_podcasts.json"},"poems-stories":{"cat":"Resources","title":"📒poems-stories-jokes","desc":"Bitcoin poetry, short stories, jokes, and creative writing from the community.","file":"data/R_poems-stories.json"},"projects-diy":{"cat":"Resources","title":"🔧projects-diy","desc":"DIY Bitcoin projects: build your own node, Lightning ATM, and more.","file":"data/R_projects-diy.json"},"research-theses":{"cat":"Resources","title":"✍research-theses","desc":"Academic research papers and theses on Bitcoin, monetary policy, and cryptographic systems.","file":"data/R_research-theses.json"},"satoshi-nakamoto":{"cat":"Resources","title":"🦸satoshi-nakamoto","desc":"The mystery of Bitcoin's creator: who was Satoshi Nakamoto? The evidence, theories, and legacy.","file":"data/R_satoshi-nakamoto.json"},"social-media":{"cat":"Resources","title":"👍social-media-proponents","desc":"Bitcoin Twitter/X accounts, influencers, and social media communities to follow.","file":"data/R_social-media.json"},"swag-merch":{"cat":"Resources","title":"👕swag-merch-businesses-spend","desc":"Bitcoin merchandise, clothing, and businesses where you can spend your sats.","file":"data/R_swag-merch.json"},"videos":{"cat":"Resources","title":"📺videos","desc":"Must-watch Bitcoin lectures, talks, and presentations from Andreas Antonopoulos, Michael Saylor, and others.","file":"data/R_videos.json"},"web5":{"cat":"Resources","title":"5⃣web5","desc":"Web5 and decentralized web technologies built on Bitcoin.","file":"data/R_web5.json"}};// ============================================================ +var CHANNELS = {"decentralized":{"cat":"Properties Layer 1","title":"👪decentralized-censorship-resistant-ungovernable-incorruptible-trustless-unconfiscatable-updatable","desc":"Why no single person, company, or government controls Bitcoin — and why that's the most important feature.","file":"data/D_decentralized.json"},"dominant":{"cat":"Properties Layer 1","title":"🏆dominant-recognizable-brand-legitimate-limitless-infinite-exponential-transformative-revolutionary","desc":"Bitcoin's brand recognition, network effects, and why it has maintained the #1 position since 2009.","file":"data/D_dominant.json"},"money":{"cat":"Properties Layer 1","title":"💰money-deflationary-salable-durable-anti-fragile-divisible-portable-transmittable-verifiable-fair","desc":"What money actually is, how it works, and why Bitcoin satisfies every property of sound money better than anything before it.","file":"data/D_money.json"},"organic":{"cat":"Properties Layer 1","title":"🌳organic-empowering-elegant-freedom-centric-irrefutable-unseizable-irreversible-unbreakable","desc":"How Bitcoin grew from an idea worth nothing to a trillion-dollar network — without marketing, without a company, without a leader.","file":"data/D_organic.json"},"peaceful":{"cat":"Properties Layer 1","title":"☮peaceful-neutral-voluntary-open-universal-permissionless-borderless-global-inevitable-unstoppable","desc":"Bitcoin is voluntary, permissionless, borderless, and unstoppable. No one forces you to use it — and no one can stop you.","file":"data/D_peaceful.json"},"programmable":{"cat":"Properties Layer 1","title":"🤖programable-interoperable-deflationary-pseudonymous-opt-in-resilient-adiabatic-egalitarian","desc":"Bitcoin as programmable money — interoperable, pseudonymous, resilient, and thermodynamically sound.","file":"data/D_programmable.json"},"scarce":{"cat":"Properties Layer 1","title":"🍀scarce-unforgeable-hedge-scalable-p2p-instant-open-source-auditable-inaliable","desc":"Only 21 million will ever exist. Explore what makes Bitcoin the scarcest asset humanity has ever created.","file":"data/D_scarce.json"},"secure":{"cat":"Properties Layer 1","title":"™secure-fungible-immutable-incorruptible-immalleable-infallible-reliable-predictable-irreplicable","desc":"How Bitcoin's network security makes it virtually impossible to hack — protected by more computing power than anything on Earth.","file":"data/D_secure.json"},"supranational":{"cat":"Properties Layer 1","title":"🕊supranational-lindy-inviolate-dilution-proof-frictionless-freely-accessible-settlement-finality","desc":"Bitcoin transcends nations and governments. Explore the Lindy Effect, settlement finality, and dilution-proof money.","file":"data/D_supranational.json"},"use-cases":{"cat":"Properties Layer 1","title":"✔use-cases","desc":"Real-world uses for Bitcoin: savings, payments, remittances, store of value, and more.","file":"data/D_use-cases.json"},"whitepaper":{"cat":"Properties Layer 1","title":"📄whitepaper","desc":"The 9-page document that started it all. Published October 31, 2008 by Satoshi Nakamoto — the foundation of Bitcoin.","file":"data/D_whitepaper.json"},"bitvm":{"cat":"Experienced Topics","title":"🖥bitvm","desc":"BitVM: computation on Bitcoin without changing the protocol. A new frontier for Bitcoin programmability.","file":"data/E_bitvm.json"},"blockchain-timechain":{"cat":"Experienced Topics","title":"⛓blockchain-timechain-transactions-addresses","desc":"How the Bitcoin blockchain (timechain) works — blocks, transactions, timestamps, and the immutable ledger.","file":"data/E_blockchain-timechain.json"},"chaumian-mints":{"cat":"Experienced Topics","title":"💸layer-2-chaumian-mints-ecash","desc":"Chaumian ecash, Cashu, and blinded signatures — the cutting edge of Bitcoin privacy technology.","file":"data/E_chaumian-mints.json"},"consensus":{"cat":"Additional Info","title":"🤝Consensus","desc":"How Bitcoin achieves consensus without a central authority — Nakamoto Consensus and beyond.","file":"data/H_consensus.json"},"core-source-code":{"cat":"Experienced Topics","title":"💾core-source-code-forks-testnet-future-potential-upgrades","desc":"Bitcoin Core's source code, forks, testnet, and the open-source development process.","file":"data/E_core-source-code.json"},"cryptography":{"cat":"Experienced Topics","title":"🔒cryptography-cypherpunks","desc":"The cryptographic foundations of Bitcoin — SHA-256, elliptic curves, digital signatures, and the cypherpunk legacy.","file":"data/E_cryptography.json"},"ctv-covenants":{"cat":"Experienced Topics","title":"📜ctv-bip119-covenants","desc":"BIP-119, CTV, and Bitcoin covenants — proposed upgrades and the debates around them.","file":"data/E_ctv-covenants.json"},"developers":{"cat":"Experienced Topics","title":"🖥developers","desc":"Building on Bitcoin — resources, guides, and paths for developers who want to contribute.","file":"data/E_developers.json"},"difficulty-adjustment":{"cat":"Experienced Topics","title":"😤difficulty-adjustment","desc":"The most elegant part of Bitcoin's design — how the network self-adjusts every 2,016 blocks.","file":"data/E_difficulty-adjustment.json"},"energy":{"cat":"Experienced Topics","title":"💡energy","desc":"The truth about Bitcoin's energy use: 0.1% of global energy, renewable mining, methane capture, and grid stabilization.","file":"data/E_energy.json"},"evidence-against-alts":{"cat":"Experienced Topics","title":"⚠evidence-against-ethereum-other-alt-coins-crypto-defi-nfts-web3-monero-bsv-bch-cbdcs-other-projects","desc":"Why every altcoin fails against Bitcoin — premines, centralization, broken promises, and the evidence.","file":"data/E_evidence-against-alts.json"},"extension-blocks":{"cat":"Experienced Topics","title":"🚧extension-blocks-and-other-proposed-scaling-solutions","desc":"Extension blocks and other proposed scaling solutions for Bitcoin.","file":"data/E_extension-blocks.json"},"fedi-ark":{"cat":"Experienced Topics","title":"🛡layer-2-fedi-ark","desc":"Fedimints, Ark, and Bitcoin's privacy/scaling layers — community custody with enhanced privacy.","file":"data/E_fedi-ark.json"},"investment-strategy":{"cat":"Experienced Topics","title":"🤑investment-strategy-taxes-retirement-inheritance-loans-donate-gift-consulting-remittance","desc":"DCA, HODL, lump sum strategies, taxes, retirement planning, and thinking long-term with Bitcoin.","file":"data/E_investment-strategy.json"},"layer-2-lightning":{"cat":"Experienced Topics","title":"⚡layer-2-lightning","desc":"The Lightning Network: instant, nearly-free Bitcoin payments. How Bitcoin scales without sacrificing decentralization.","file":"data/E_layer-2-lightning.json"},"layer-3-sidechains":{"cat":"Experienced Topics","title":"📱layer-3-sidechain-applications","desc":"Sidechains, Liquid Network, and layer-3 applications built on top of Bitcoin.","file":"data/E_layer-3-sidechains.json"},"maximalism":{"cat":"Experienced Topics","title":"💯maximalism","desc":"Why people who study Bitcoin the most become maximalists. The case for Bitcoin-only.","file":"data/E_maximalism.json"},"mining":{"cat":"Experienced Topics","title":"🌋mining","desc":"How Bitcoin mining actually works — nonces, SHA-256 hashing, difficulty adjustment, and the brute-force lottery.","file":"data/E_mining.json"},"nodes":{"cat":"Experienced Topics","title":"💻nodes","desc":"Run your own Bitcoin node. Don't trust, verify. How 14,000+ nodes keep the network decentralized.","file":"data/E_nodes.json"},"op-codes":{"cat":"Experienced Topics","title":"👨‍💻op-codes-simplicity","desc":"OP_CAT, Simplicity, and Bitcoin's scripting language — the building blocks of smart functionality.","file":"data/E_op-codes.json"},"pow-vs-pos":{"cat":"Experienced Topics","title":"💪proof-of-work-vs-proof-of-stake","desc":"Why Proof of Work is fundamentally superior to Proof of Stake — energy, security, fairness, and decentralization.","file":"data/E_pow-vs-pos.json"},"privacy-nonkyc":{"cat":"Experienced Topics","title":"🤫privacy-nonkyc-stacking-self-sovereignty","desc":"Financial privacy as a human right. KYC, non-KYC stacking, and protecting your sovereignty.","file":"data/E_privacy-nonkyc.json"},"problems-of-money":{"cat":"Experienced Topics","title":"📉the-problems-of-todays-money-and-freedom","desc":"The broken fiat system: inflation, money printing, the Cantillon Effect, and why today's money is failing everyone.","file":"data/E_problems-of-money.json"},"regulation":{"cat":"Experienced Topics","title":"🏛regulation-policy-legal","desc":"Bitcoin and government: bans, adoption, legal tender, ETFs, and why regulation can't stop decentralization.","file":"data/E_regulation.json"},"self-custody":{"cat":"Experienced Topics","title":"🔑personal-storage-self-custody-security","desc":"Not your keys, not your coins. Learn how to truly own your Bitcoin with wallets, seed phrases, and security.","file":"data/E_self-custody.json"},"smart-contracts":{"cat":"Experienced Topics","title":"📱smart-contracts","desc":"Smart contracts on Bitcoin — what's possible, what's coming, and why Bitcoin's approach is different.","file":"data/E_smart-contracts.json"},"stablecoins":{"cat":"Additional Info","title":"🪙Stablecoins","desc":"The role of stablecoins in the Bitcoin economy — and why they're not a threat to Bitcoin.","file":"data/H_stablecoins.json"},"0_mining__hashing":{"cat":"Additional Info","title":"0⃣Mining (Hashing)","desc":"Deep dive into Bitcoin mining and hashing — how SHA-256 works at the bit level.","file":"data/H_0_mining__hashing.json"},"100_sats":{"cat":"Additional Info","title":"💯100 sats","desc":"What can you do with just 100 satoshis? More than you think.","file":"data/H_100_sats.json"},"1_first_principles":{"cat":"Additional Info","title":"1⃣First Principles","desc":"First principles thinking applied to Bitcoin — reasoning from fundamentals, not analogies.","file":"data/H_1_first_principles.json"},"2__solved_technical_problems":{"cat":"Additional Info","title":"2⃣ Solved Technical Problems","desc":"The technical problems Bitcoin solved — digital scarcity, double-spending, and Byzantine fault tolerance.","file":"data/H_2__solved_technical_problems.json"},"analogies":{"cat":"Additional Info","title":"🔋Analogies","desc":"The best analogies for explaining Bitcoin to anyone — from trees to brains to hearts.","file":"data/H_analogies.json"},"austrian_school_of_economics":{"cat":"Additional Info","title":"🇦🇹Austrian School of Economics","desc":"Austrian Economics and Bitcoin: Mises, Hayek, sound money theory, and the intellectual foundation.","file":"data/H_austrian_school_of_economics.json"},"bip119":{"cat":"Additional Info","title":"🚧BIP119","desc":"BIP-119 (CheckTemplateVerify) — what it is, why it's controversial, and the community debate.","file":"data/H_bip119.json"},"bitcoin_exam":{"cat":"Additional Info","title":"🎓Bitcoin Exam","desc":"Test questions for a Bitcoin exam — study material and self-assessment.","file":"data/H_bitcoin_exam.json"},"bitcoin_vs_real_estate":{"cat":"Additional Info","title":"Bitcoin vs Real Estate","desc":"Bitcoin vs. real estate as an investment — comparing the two hardest assets.","file":"data/H_bitcoin_vs_real_estate.json"},"block_time-block-size":{"cat":"Additional Info","title":"⏰Block Time-Block-Size","desc":"Why Bitcoin uses 10-minute blocks and how block size affects the network.","file":"data/H_block_time-block-size.json"},"burn_bitcoin":{"cat":"Additional Info","title":"Burn bitcoin","desc":"How Bitcoin can be burned (made permanently unspendable) and why people do it.","file":"data/H_burn_bitcoin.json"},"byzantine_generals__problem":{"cat":"Additional Info","title":"⚔Byzantine Generals’ Problem","desc":"The Byzantine Generals' Problem — the computer science challenge Satoshi solved.","file":"data/H_byzantine_generals__problem.json"},"chaumian_e-cash_and_blind_signatures":{"cat":"Additional Info","title":"💲Chaumian E-cash and Blind Signatures","desc":"David Chaum's ecash, blind signatures, and the cryptographic foundations of digital privacy.","file":"data/H_chaumian_e-cash_and_blind_signatures.json"},"coin_mixing_coinjoin_coin_control_utxo":{"cat":"Additional Info","title":"🌀Coin Mixing/Coinjoin/Coin Control/UTXO Management","desc":"CoinJoin, coin mixing, UTXO management — advanced Bitcoin privacy techniques.","file":"data/H_coin_mixing_coinjoin_coin_control_utxo.json"},"cyles":{"cat":"Additional Info","title":"🚲Cyles","desc":"Bitcoin's 4-year cycles, Gartner Hype Cycles, and whether the pattern continues.","file":"data/H_cyles.json"},"derivation_path":{"cat":"Additional Info","title":"↕Derivation Path","desc":"HD wallet derivation paths — how your seed phrase generates all your addresses.","file":"data/H_derivation_path.json"},"discrete_log_contracts__dlcs":{"cat":"Additional Info","title":"📝Discrete Log Contracts (DLCs)?","desc":"DLCs (Discrete Log Contracts) — smart contracts on Bitcoin using oracle signatures.","file":"data/H_discrete_log_contracts__dlcs.json"},"dollar-bitcoin_milkshake_theory":{"cat":"Additional Info","title":"🥤Dollar-Bitcoin Milkshake Theory","desc":"The Dollar-Bitcoin Milkshake Theory — how global dollar demand and Bitcoin intersect.","file":"data/H_dollar-bitcoin_milkshake_theory.json"},"dust":{"cat":"Additional Info","title":"⏳Dust","desc":"Dust UTXOs: what they are, why they're a problem, and how to manage them.","file":"data/H_dust.json"},"elevator_pitches":{"cat":"Additional Info","title":"↕Elevator Pitches","desc":"Quick 20-30 second explanations of why Bitcoin matters — for every audience.","file":"data/H_elevator_pitches.json"},"environment___energy":{"cat":"Additional Info","title":"🌳Environment & Energy","desc":"Bitcoin and the environment: energy usage facts, renewable mining, and debunking the FUD.","file":"data/H_environment___energy.json"},"faith___religion":{"cat":"Additional Info","title":"🙏Faith & Religion","desc":"Bitcoin and faith — how sound money relates to religious and spiritual values.","file":"data/H_faith___religion.json"},"fedimints":{"cat":"Additional Info","title":"💚Fedimints","desc":"Fedimints: community custody with enhanced privacy using federated Chaumian mints.","file":"data/H_fedimints.json"},"feedback_loops":{"cat":"Additional Info","title":"➰Feedback Loops","desc":"Bitcoin's feedback loops — the self-reinforcing cycles that drive adoption and security.","file":"data/H_feedback_loops.json"},"free_and_open_source_software__foss":{"cat":"Additional Info","title":"💿Free and Open Source Software (FOSS)","desc":"Free and open source software (FOSS) projects connected to Bitcoin.","file":"data/H_free_and_open_source_software__foss.json"},"game_theory":{"cat":"Additional Info","title":"🏈Game Theory","desc":"Game theory and Bitcoin: Nash equilibrium, prisoner's dilemma, and strategic incentives.","file":"data/H_game_theory.json"},"geopolitics___macroeconomics":{"cat":"Additional Info","title":"💰Geopolitics & Macroeconomics","desc":"Bitcoin's role in geopolitics: nation-state adoption, reserve currencies, and macro trends.","file":"data/H_geopolitics___macroeconomics.json"},"governance":{"cat":"Additional Info","title":"🏛Governance","desc":"How Bitcoin is governed — consensus mechanisms, BIPs, and decentralized decision-making.","file":"data/H_governance.json"},"ham_radio":{"cat":"Additional Info","title":"Ham Radio","desc":"Using Bitcoin without internet — ham radio, mesh networks, and offline transactions.","file":"data/H_ham_radio.json"},"human_rights__social_justice_and_freedo":{"cat":"Additional Info","title":"🗽Human Rights, Social Justice and Freedom","desc":"Bitcoin as a tool for human rights, social justice, and financial freedom worldwide.","file":"data/H_human_rights__social_justice_and_freedo.json"},"improved_incentive_structure":{"cat":"Additional Info","title":"✅Improved Incentive Structure","desc":"How Bitcoin's incentive structure improves civilization — aligning individual and collective interests.","file":"data/H_improved_incentive_structure.json"},"laws_of_thermodynamics":{"cat":"Additional Info","title":"🔥Laws of Thermodynamics","desc":"How Bitcoin follows the laws of thermodynamics — energy, entropy, and proof of work.","file":"data/H_laws_of_thermodynamics.json"},"lightning_node":{"cat":"Additional Info","title":"⚡ Lightning Node","desc":"Running a Lightning Network node — setup guides, routing, and earning sats.","file":"data/H_lightning_node.json"},"lindy_effect":{"cat":"Additional Info","title":"👴Lindy Effect","desc":"The Lindy Effect: the longer Bitcoin survives, the longer it will survive.","file":"data/H_lindy_effect.json"},"market_cap":{"cat":"Additional Info","title":"🧢Market Cap","desc":"Bitcoin's market cap potential — can it reach millions per coin? The math says yes.","file":"data/H_market_cap.json"},"math":{"cat":"Additional Info","title":"➕Math","desc":"The mathematics of Bitcoin — from SHA-256 to elliptic curves to probability.","file":"data/H_math.json"},"mathematics":{"cat":"Additional Info","title":"➕Mathematics","desc":"Advanced mathematical concepts underlying Bitcoin's protocol and security.","file":"data/H_mathematics.json"},"mev":{"cat":"Additional Info","title":"⛏MEV","desc":"MEV (Miner Extractable Value) in Bitcoin — what it is and its implications.","file":"data/H_mev.json"},"network_effects":{"cat":"Additional Info","title":"🌐Network Effects","desc":"Bitcoin's network effects — why the most adopted network wins and keeps winning.","file":"data/H_network_effects.json"},"open_source":{"cat":"Additional Info","title":"⭕Open Source","desc":"What free and open source really means — and why it matters for Bitcoin.","file":"data/H_open_source.json"},"oracle":{"cat":"Additional Info","title":"🔮Oracle","desc":"Oracles in Bitcoin — how external data connects to the blockchain.","file":"data/H_oracle.json"},"orange-pilling":{"cat":"Additional Info","title":"🟠Orange-Pilling","desc":"The art of orange-pilling — strategies for explaining Bitcoin to different audiences.","file":"data/H_orange-pilling.json"},"ordinals":{"cat":"Additional Info","title":"Ordinals","desc":"Bitcoin Ordinals and inscriptions — NFTs on the world's most secure blockchain.","file":"data/H_ordinals.json"},"ordinals__nfts_on_bitcoin__and_block_spa":{"cat":"Additional Info","title":"Ordinals, NFTs on Bitcoin, and Block Space","desc":"The Ordinals debate: NFTs on Bitcoin, block space economics, and community perspectives.","file":"data/H_ordinals__nfts_on_bitcoin__and_block_spa.json"},"peace_and_anti-war":{"cat":"Additional Info","title":"☮Peace and Anti-War","desc":"Can a Bitcoin Standard end wars? The case for Bitcoin as a force for peace.","file":"data/H_peace_and_anti-war.json"},"philosophy":{"cat":"Additional Info","title":"🍎Philosophy","desc":"The philosophy of Bitcoin — from first principles to existential implications.","file":"data/H_philosophy.json"},"politics":{"cat":"Additional Info","title":"🏛Politics","desc":"Bitcoin and politics — how Bitcoin intersects with government policy and elections.","file":"data/H_politics.json"},"predictions":{"cat":"Additional Info","title":"🔮Predictions","desc":"Bitcoin predictions timestamped by the community — bold calls and their outcomes.","file":"data/H_predictions.json"},"public_key_vs_private_key":{"cat":"Additional Info","title":"🗝Public Key vs Private Key","desc":"Public keys vs. private keys — the cryptographic foundation of Bitcoin ownership.","file":"data/H_public_key_vs_private_key.json"},"rbf":{"cat":"Additional Info","title":"↔RBF","desc":"Replace-By-Fee (RBF) — how to speed up stuck Bitcoin transactions.","file":"data/H_rbf.json"},"referral-links":{"cat":"Referral Links","title":"🔗free-btc-referral-links","desc":"Curated Bitcoin referral links — earn free sats with trusted platforms like River, Fold, and Strike.","file":"data/H_referral-links.json"},"risks__threats__attack_vectors__weaknes":{"cat":"Additional Info","title":"⚔Risks, Threats, Attack Vectors, Weaknesses, Issues","desc":"Bitcoin's risks, threats, and attack vectors — what could go wrong and why it probably won't.","file":"data/H_risks__threats__attack_vectors__weaknes.json"},"rollups":{"cat":"Additional Info","title":"🥐Rollups","desc":"Rollups on Bitcoin — scaling and privacy solutions using off-chain computation.","file":"data/H_rollups.json"},"sats__or__bits":{"cat":"Additional Info","title":"\"Sats\" or \"Bits\"?","desc":"The sats vs. bits debate — which denomination should Bitcoin use?","file":"data/H_sats__or__bits.json"},"scalability":{"cat":"Additional Info","title":"🌐Scalability","desc":"Can Bitcoin scale to serve the world? Layers, Lightning, and the path forward.","file":"data/H_scalability.json"},"sidechains":{"cat":"Additional Info","title":"♻Sidechains","desc":"Bitcoin sidechains like Liquid — benefits, tradeoffs, and use cases.","file":"data/H_sidechains.json"},"simplified_payment_verification__spv":{"cat":"Additional Info","title":"✔Simplified Payment Verification (SPV)","desc":"SPV (Simplified Payment Verification) — lightweight Bitcoin verification without a full node.","file":"data/H_simplified_payment_verification__spv.json"},"soft_vs_hard_forks":{"cat":"Additional Info","title":"🍴Soft vs Hard Forks","desc":"Soft forks vs. hard forks — how Bitcoin upgrades while maintaining consensus.","file":"data/H_soft_vs_hard_forks.json"},"softwar":{"cat":"Additional Info","title":"Softwar","desc":"Jason Lowery's Softwar thesis — Bitcoin as a non-lethal alternative to physical warfare.","file":"data/H_softwar.json"},"stratum_v2":{"cat":"Additional Info","title":"🟩Stratum V2","desc":"Stratum V2 — the next-generation mining protocol for better decentralization and efficiency.","file":"data/H_stratum_v2.json"},"submarine_swap":{"cat":"Additional Info","title":"⛵Submarine Swap","desc":"Submarine swaps — trustlessly moving Bitcoin between on-chain and Lightning.","file":"data/H_submarine_swap.json"},"swaps":{"cat":"Additional Info","title":"↔Swaps","desc":"How to swap between on-chain Bitcoin and Lightning — tools, techniques, and protocols.","file":"data/H_swaps.json"},"ta_tips":{"cat":"Additional Info","title":"📈TA Tips","desc":"Technical analysis tips for Bitcoin — chart patterns, indicators, and trading education.","file":"data/H_ta_tips.json"},"tail_emission":{"cat":"Additional Info","title":"🐈Tail Emission","desc":"The tail emission debate — should Bitcoin ever have perpetual block rewards?","file":"data/H_tail_emission.json"},"taproot":{"cat":"Additional Info","title":"🧰Taproot","desc":"Taproot: Bitcoin's latest major upgrade — Schnorr signatures, script improvements, and privacy.","file":"data/H_taproot.json"},"taro":{"cat":"Additional Info","title":"🥕Taro","desc":"Taro (now Taproot Assets) — issuing assets on the Bitcoin and Lightning networks.","file":"data/H_taro.json"},"the_future":{"cat":"Additional Info","title":"🔮The Future","desc":"How Bitcoin could change the future — hyperbitcoinization, global adoption, and beyond.","file":"data/H_the_future.json"},"time":{"cat":"Additional Info","title":"⏰Time","desc":"How Bitcoin keeps time — block time, timestamps, and the decentralized clock.","file":"data/H_time.json"},"time_preference":{"cat":"Additional Info","title":"🕑Time Preference","desc":"Time preference: how sound money encourages long-term thinking and civilization building.","file":"data/H_time_preference.json"},"toxicity":{"cat":"Additional Info","title":"☣ Toxicity","desc":"Is Bitcoin community toxicity real? Or is it integrity? The debate and its meaning.","file":"data/H_toxicity.json"},"transaction_fees":{"cat":"Additional Info","title":"💲Transaction Fees","desc":"Bitcoin transaction fees — how they work, fee markets, and long-term sustainability.","file":"data/H_transaction_fees.json"},"unpopular_opinions":{"cat":"Additional Info","title":"💀Unpopular Opinions","desc":"Unpopular opinions in the Bitcoin space — controversial takes and honest debates.","file":"data/H_unpopular_opinions.json"},"utxos":{"cat":"Additional Info","title":"🕳UTXOs","desc":"UTXOs (Unspent Transaction Outputs) — the fundamental building block of Bitcoin transactions.","file":"data/H_utxos.json"},"vbyte":{"cat":"Additional Info","title":"🏋vByte","desc":"Virtual bytes (vBytes) — how Bitcoin measures transaction weight for fee calculation.","file":"data/H_vbyte.json"},"apps-tools":{"cat":"Resources","title":"🍎apps-tools-services-models","desc":"Bitcoin apps, tools, services, and platforms — everything you need to use Bitcoin daily.","file":"data/R_apps-tools.json"},"art-inspiration":{"cat":"Resources","title":"🤩art-inspiration-motivation","desc":"Bitcoin art, inspiration, and motivational content from the community.","file":"data/R_art-inspiration.json"},"articles-threads":{"cat":"Resources","title":"📃articles-threads","desc":"The best Bitcoin articles and Twitter threads — curated deep dives into every aspect of Bitcoin.","file":"data/R_articles-threads.json"},"books":{"cat":"Resources","title":"📚books","desc":"The essential Bitcoin reading list: The Bitcoin Standard, 21 Lessons, Mastering Bitcoin, and more.","file":"data/R_books.json"},"charts":{"cat":"Resources","title":"📊charts","desc":"Bitcoin price charts, on-chain analytics, stock-to-flow, and data visualizations.","file":"data/R_charts.json"},"curriculum":{"cat":"Resources","title":"🎓curriculum-presentations","desc":"Bitcoin education curriculum and presentations for teachers and students.","file":"data/R_curriculum.json"},"faq-glossary":{"cat":"Resources","title":"❓faq-glossary-search-ai-calendar","desc":"Bitcoin FAQ, glossary of terms, and quick answers to common questions.","file":"data/R_faq-glossary.json"},"fun-facts":{"cat":"Resources","title":"🎉fun-facts","desc":"Mind-blowing Bitcoin trivia: Pizza Day, Satoshi's birthday code, lost coins, and 200+ amazing facts.","file":"data/R_fun-facts.json"},"games":{"cat":"Resources","title":"🎮games","desc":"Bitcoin-themed games and gamified learning experiences.","file":"data/R_games.json"},"giga-chad":{"cat":"Resources","title":"👑giga-chad","desc":"Michael Saylor, MicroStrategy, and the corporate Bitcoin movement.","file":"data/R_giga-chad.json"},"graphics":{"cat":"Resources","title":"🎨graphics","desc":"Bitcoin infographics, charts, diagrams, and visual explanations.","file":"data/R_graphics.json"},"hardware":{"cat":"Resources","title":"💻hardware","desc":"Bitcoin hardware: mining rigs, hardware wallets, nodes, and open-source projects like Bitaxe.","file":"data/R_hardware.json"},"health":{"cat":"Resources","title":"🥩health","desc":"Bitcoin and health: low time preference living, breaking free from the system.","file":"data/R_health.json"},"history":{"cat":"Resources","title":"📆history","desc":"The complete history of Bitcoin — from the cypherpunks to today.","file":"data/R_history.json"},"informational-sites":{"cat":"Resources","title":"📃informational-sites-courses-workshops-newsletters-projects-communities-meetups-conferences","desc":"Bitcoin dashboards, tools, courses, newsletters, communities, and educational websites.","file":"data/R_informational-sites.json"},"international":{"cat":"Resources","title":"🌍international","desc":"Bitcoin resources in multiple languages and global adoption stories.","file":"data/R_international.json"},"jobs-earn":{"cat":"Resources","title":"👷job-postings-employer-info-entrepreneurship-earn-bitcoin-stack-sats","desc":"Bitcoin job boards, entrepreneurship resources, and ways to earn sats.","file":"data/R_jobs-earn.json"},"memes-funny":{"cat":"Resources","title":"😂memes-funny","desc":"The best Bitcoin memes, jokes, and humor from the community. Laugh while you learn.","file":"data/R_memes-funny.json"},"misconceptions-fud":{"cat":"Resources","title":"🤡common-misconceptions-fud-debunked","desc":"Every Bitcoin myth debunked: too volatile, wastes energy, used by criminals, no intrinsic value — all wrong.","file":"data/R_misconceptions-fud.json"},"movies-tv":{"cat":"Resources","title":"🎬movies-tv-documentaries","desc":"Bitcoin documentaries, films, and TV appearances. From The Big Short to Bitcoin-specific docs.","file":"data/R_movies-tv.json"},"music":{"cat":"Resources","title":"🎵music","desc":"Bitcoin-inspired music, songs, and audio content from the community.","file":"data/R_music.json"},"news-adoption":{"cat":"Resources","title":"📰news-adoption","desc":"Latest Bitcoin news, adoption milestones, and real-world usage stories.","file":"data/R_news-adoption.json"},"nostr":{"cat":"Resources","title":"💜nostr","desc":"Nostr: the decentralized social protocol Bitcoiners are building on. Social media you can't be censored from.","file":"data/R_nostr.json"},"one-stop-shop":{"cat":"Resources","title":"🛑one-stop-shop","desc":"The best resources to understand Bitcoin's value as fast as possible. Start here if you're new.","file":"data/R_one-stop-shop.json"},"podcasts":{"cat":"Resources","title":"🔊podcasts","desc":"Top Bitcoin podcasts: Bitcoin Audible, What Bitcoin Did, Stephan Livera, and more.","file":"data/R_podcasts.json"},"poems-stories":{"cat":"Resources","title":"📒poems-stories-jokes","desc":"Bitcoin poetry, short stories, jokes, and creative writing from the community.","file":"data/R_poems-stories.json"},"projects-diy":{"cat":"Resources","title":"🔧projects-diy","desc":"DIY Bitcoin projects: build your own node, Lightning ATM, and more.","file":"data/R_projects-diy.json"},"research-theses":{"cat":"Resources","title":"✍research-theses","desc":"Academic research papers and theses on Bitcoin, monetary policy, and cryptographic systems.","file":"data/R_research-theses.json"},"satoshi-nakamoto":{"cat":"Resources","title":"🦸satoshi-nakamoto","desc":"The mystery of Bitcoin's creator: who was Satoshi Nakamoto? The evidence, theories, and legacy.","file":"data/R_satoshi-nakamoto.json"},"social-media":{"cat":"Resources","title":"👍social-media-proponents","desc":"Bitcoin Twitter/X accounts, influencers, and social media communities to follow.","file":"data/R_social-media.json"},"swag-merch":{"cat":"Resources","title":"👕swag-merch-businesses-spend","desc":"Bitcoin merchandise, clothing, and businesses where you can spend your sats.","file":"data/R_swag-merch.json"},"videos":{"cat":"Resources","title":"📺videos","desc":"Must-watch Bitcoin lectures, talks, and presentations from Andreas Antonopoulos, Michael Saylor, and others.","file":"data/R_videos.json"},"web5":{"cat":"Resources","title":"5⃣web5","desc":"Web5 and decentralized web technologies built on Bitcoin.","file":"data/R_web5.json"}}; +// ============================================================ // Bitcoin Education Archive — Shared Utilities // [AUDIT FIX] Extracted from duplicate definitions across files. // Load BEFORE all other local scripts in index.html. @@ -161,6 +162,7 @@ var PREMIUM_CONFIG = { LIFETIME_SATS: 210000, TIER_NAME: 'Bitcoin Maxi' }; + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. // ============================================= @@ -3270,7 +3272,7 @@ async function toggleLeaderboard() { html += '
    ' + '
    ' + '

    ⚔️ PVP Leaderboard

    ' + - '' + + '' + '
    ' + '
    Loading PVP rankings...
    ' + '
    '; @@ -4880,7 +4882,7 @@ function showSettingsPage(tab) { html += statRow('PVP Record', _pvpW + 'W – ' + _pvpL + 'L', '⚔️'); html += statRow('PVP Win Rate', _pvpPct + '%', '📊'); } else { - html += statRow('PVP Record', 'No battles yet — Enter PVP Lobby', '⚔️'); + html += statRow('PVP Record', 'No battles yet — Enter PVP Lobby', '⚔️'); } // Prediction Stats if (typeof getPredictionStats === 'function') { @@ -6296,6 +6298,7 @@ function getLevelFlavor(name) { }; return flavors[name] || 'You\'re leveling up!'; } + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. // ============================================= @@ -7047,6 +7050,7 @@ window._badgeSearchJump = function(badgeId) { // Init setTimeout(initBadges, 2000); + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. // ============================================= @@ -7405,6 +7409,7 @@ if (typeof window !== 'undefined') { // Capture referral code from URL immediately captureReferralCode(); } + // Phase 10: Loyalty & Learning Boosts 🎓 (function() { @@ -7452,6 +7457,7 @@ if (typeof window !== 'undefined') { initBoostUI(); } })(); + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. // ============================================= @@ -7756,6 +7762,7 @@ window.toggleTickerSetting = function() { }; })(); + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. // ============================================= @@ -10249,6 +10256,7 @@ if (_origGo) { } })(); + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. // ============================================= @@ -10822,7 +10830,9 @@ setTimeout(function() { })(); })(); -window.nachoNickname=function(){return localStorage.getItem("btc_nacho_nickname")||"Nacho"};function getEquippedItems(){try{return JSON.parse(localStorage.getItem("btc_nacho_equipped_multi")||"{}")}catch(e){return{}}}function getEquippedItem(){var e=getEquippedItems();return Object.values(e)[0]||localStorage.getItem("btc_nacho_equipped")||null}!function(){const e=[{id:"orange_scarf",category:"shirt",name:"Bitcoin Scarf",emoji:"🧣",desc:"A cozy orange scarf with the ₿ symbol.",level:1,overlay:{top:"68%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"sunglasses",category:"glasses",name:"Cool Shades",emoji:"🕶️",desc:"Sunglasses so cool, even the blockchain can't see through them.",level:1,overlay:{top:"43%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"bowtie",category:"shirt",name:"Fancy Bowtie",emoji:"🎀",desc:"A dapper bowtie for a distinguished buck. Class and sats.",level:1,overlay:{top:"64%",left:"50%",transform:"translateX(-50%)",fontSize:"1.3em"},hidden:!1,colorable:!0},{id:"mining_helmet",category:"hat",name:"Mining Helmet",emoji:"⛑️",desc:"A safety helmet for a hardworking miner. Ready to find the next block!",level:2,overlay:{top:"5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"lightning_chain",category:"glasses",name:"Lightning Chain",emoji:"⚡",desc:"A chain necklace with a Lightning bolt pendant.",level:2,overlay:{top:"65%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"party_hat",category:"hat",name:"Party Hat",emoji:"🎉",desc:"Every day is a party when you're stacking sats!",level:2,overlay:{top:"2%",left:"58%",transform:"translateX(-50%) rotate(15deg)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"hodl_hoodie",category:"shirt",name:"HODL Hoodie",emoji:"🧥",desc:"A hoodie that says HODL on the back. For diamond-handed deer.",level:3,overlay:{top:"72%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1,colorable:!0},{id:"laser_eyes",category:"glasses",name:"Laser Eyes",emoji:"🔴",desc:"The legendary Bitcoin laser eyes. Number go up!",level:3,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"0.9em",custom:"🔴 🔴"},hidden:!1,colorable:!0},{id:"wizard_hat",category:"hat",name:"Wizard Hat",emoji:"🪄",desc:"A mystical wizard hat. Nacho casts spells of financial sovereignty!",level:3,overlay:{top:"-5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!1,colorable:!0},{id:"crown",category:"hat",name:"Royal Crown",emoji:"👑",desc:"Fit for the king of cryptocurrency. There is no second best!",level:3,overlay:{top:"3%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"steak",category:"glasses",name:"Proof of Steak",emoji:"🥩",desc:"A juicy steak for a hardworking buck. Proof of Steak > Proof of Stake!",level:4,overlay:{top:"58%",right:"-18%",fontSize:"1.8em",transform:"rotate(20deg)"},hidden:!1},{id:"diamond_hooves",category:"glasses",name:"Diamond Hooves",emoji:"💎",desc:"Diamond hooves for a deer with diamond hands. Never selling!",level:4,overlay:{bottom:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em",custom:"💎💎"},hidden:!1},{id:"astronaut",category:"hat",name:"Moon Helmet",emoji:"🪖",desc:"To the moon! A space helmet for the ultimate HODLer.",level:4,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1},{id:"cape_permanent",category:"shirt",name:"Hero Cape",emoji:"🦸",desc:"A permanent cape for a Bitcoin hero. Earned, not given!",level:4,overlay:{top:"55%",right:"-15%",fontSize:"2.4em",transform:"rotate(-12deg)"},hidden:!1,colorable:!0},{id:"golden_antlers",category:"hat",name:"???",emoji:"✨",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"0.5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Golden Antlers",revealEmoji:"✨",revealDesc:"Antlers plated in pure gold. Only the closest friends get to see these shine!"},{id:"satoshi_cloak",category:"shirt",name:"???",emoji:"🧥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"68%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Satoshi's Cloak",revealEmoji:"🧥",revealDesc:"A mysterious cloak worn by Satoshi himself. Legend says it grants anonymity to any deer who wears it."},{id:"flame_aura",category:"glasses",name:"???",emoji:"🔥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"25%",left:"50%",transform:"translateX(-50%)",fontSize:"3.5em"},hidden:!0,revealName:"Flame Aura",revealEmoji:"🔥",revealDesc:"A blazing aura of pure Bitcoin energy. The ultimate flex for Nacho's best friend!"},{id:"rainbow_antlers",category:"hat",name:"???",emoji:"🌈",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!0,revealName:"Rainbow Antlers",revealEmoji:"🌈",revealDesc:"Prismatic rainbow antlers that shimmer in every color. Legendary!"},{id:"bitcoin_eyes",category:"glasses",name:"???",emoji:"₿",desc:"How do you find this one?",level:1,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.2em",custom:"₿ ₿"},hidden:!0,revealName:"Bitcoin Eyes",revealEmoji:"₿",revealDesc:"Eyes made of pure Bitcoin. You found the secret! Nacho sees everything in sats now."},{id:"santa_hat",category:"hat",name:"Santa Hat",emoji:"🎅",desc:"Ho ho HODL! A festive Santa hat for the holiday season.",level:1,overlay:{top:"1%",left:"54%",transform:"translateX(-50%) rotate(15deg)",fontSize:"2.2em"},hidden:!1,seasonal:"december"},{id:"pumpkin",category:"hat",name:"Pumpkin Head",emoji:"🎃",desc:"Spooky season! A jack-o-lantern for Halloween.",level:1,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1,seasonal:"october"},{id:"halving_pickaxe",category:"glasses",name:"Golden Pickaxe",emoji:"⛏️",desc:"A golden pickaxe to celebrate the halving! Limited edition.",level:1,overlay:{top:"22%",right:"-15%",fontSize:"2.2em",transform:"rotate(30deg)"},hidden:!1,seasonal:"april"}];var t=document.createElement("style");function o(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?5:e>=350?4:e>=100?3:e>=10?2:e>=1?1:0}t.textContent="\n @keyframes nachoEquipPop {\n 0% { transform: scale(0) rotate(-45deg); opacity: 0; }\n 50% { transform: scale(1.5) rotate(10deg); opacity: 1; }\n 70% { transform: scale(0.9) rotate(-5deg); }\n 100% { transform: scale(1) rotate(0deg); opacity: 1; }\n }\n @keyframes nachoEquipGlow {\n 0% { filter: drop-shadow(0 0 0px transparent); }\n 30% { filter: drop-shadow(0 0 12px rgba(247,147,26,0.8)); }\n 100% { filter: drop-shadow(0 0 4px rgba(247,147,26,0.3)); }\n }\n @keyframes nachoUnequip {\n 0% { transform: scale(1); opacity: 1; }\n 40% { transform: scale(1.3) rotate(15deg); opacity: 0.8; }\n 100% { transform: scale(0) rotate(-30deg); opacity: 0; }\n }\n @keyframes nachoItemFloat {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-3px); }\n }\n @keyframes nachoLaserPulse {\n 0%, 100% { opacity: 0.8; filter: drop-shadow(0 0 4px #ff0000); }\n 50% { opacity: 1; filter: drop-shadow(0 0 10px #ff0000) drop-shadow(0 0 20px #ff3300); }\n }\n @keyframes nachoSparkle {\n 0%, 100% { filter: drop-shadow(0 0 4px rgba(255,215,0,0.3)); }\n 50% { filter: drop-shadow(0 0 10px rgba(255,215,0,0.8)) drop-shadow(0 0 20px rgba(255,215,0,0.4)); }\n }\n @keyframes nachoCloakWave {\n 0%, 100% { transform: translateX(-50%) rotate(-2deg); }\n 50% { transform: translateX(-50%) rotate(2deg); }\n }\n .nacho-overlay-item {\n position: absolute;\n pointer-events: none;\n z-index: 3;\n }\n .nacho-overlay-item.equipping {\n animation: nachoEquipPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards,\n nachoEquipGlow 0.8s ease-out forwards;\n }\n .nacho-overlay-item.unequipping {\n animation: nachoUnequip 0.35s ease-in forwards;\n }\n .nacho-overlay-item.idle-float {\n animation: nachoItemFloat 3s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-laser {\n animation: nachoLaserPulse 1.5s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-sparkle {\n animation: nachoSparkle 2s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-wave {\n animation: nachoCloakWave 4s ease-in-out infinite;\n }\n",document.head.appendChild(t),window.equipNachoItem=function(t){if(!t)return localStorage.removeItem("btc_nacho_equipped_multi"),void renderNachoOverlay();var a=o(),n=e.find(function(e){return e.id===t}),r=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]");if(n&&n.level>a&&-1===r.indexOf(t))showToast("🔒 Need a higher friendship level to wear this!");else{var i=getEquippedItems(),l=n&&n.category||"misc";if(i[l]===t)delete i[l],"function"==typeof forceShowBubble&&forceShowBubble("Back to natural in the "+l+" department! 🦌");else if(i[l]=t,"function"==typeof forceShowBubble){forceShowBubble({orange_scarf:"Looking cozy! This scarf really brings out my orange. 🧣🦌",mining_helmet:"Safety first! Time to mine some blocks! ⛑️⛏️",lightning_chain:"Bling bling! Fast as Lightning! ⚡🦌",hodl_hoodie:"HODL gang! This hoodie makes me feel unstoppable! 🧥💎",laser_eyes:"LASER EYES ACTIVATED! Number go up! 🔴🔴🚀",steak:"Mmm, Proof of Steak! Way better than Proof of Stake! 🥩😋",golden_antlers:"These golden antlers are MAGNIFICENT! Only for my best friends! 👑✨",satoshi_cloak:"Who am I? Nobody knows... I am Satoshi Nachoamoto! 🧙🦌"}[t]||"Looking fresh with my "+(n.hidden?n.revealName:n.name)+"! 🦌")}localStorage.setItem("btc_nacho_equipped_multi",JSON.stringify(i)),renderNachoOverlay(!0),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),document.getElementById("nachoClosetGrid")&&renderNachoClosetUI(document.getElementById("nachoClosetGrid").parentElement)}},window.renderNachoOverlay=function(t){document.querySelectorAll(".nacho-overlay-item").forEach(e=>e.remove());var o=getEquippedItems(),a=document.getElementById("nacho-avatar");a&&(Object.values(o).forEach(function(o){var n=e.find(function(e){return e.id===o});if(n){var r=n.hidden?n.revealEmoji:n.emoji,i=function(e){switch(e){case"laser_eyes":return"idle-laser";case"golden_antlers":case"diamond_hooves":return"idle-sparkle";case"satoshi_cloak":return"idle-wave";default:return"idle-float"}}(n.id),l=document.createElement("span");for(var s in l.className="nacho-overlay-item"+(t?" equipping":" "+i),l.id="nacho-overlay-"+n.id,l.textContent=n.overlay.custom||r,n.overlay.custom&&(l.style.letterSpacing="-0.1em",l.style.whiteSpace="nowrap"),n.overlay)"filter"!==s&&"custom"!==s&&(l.style[s]=n.overlay[s]);if(n.colorable){var d=localStorage.getItem("btc_closet_color_"+n.id);d&&"0deg"!==d&&(l.style.filter="hue-rotate("+d+")")}t&&l.addEventListener("animationend",function e(){l.classList.remove("equipping"),l.classList.add(i),l.removeEventListener("animationend",e)},{once:!0}),a.appendChild(l)}}),t&&function(e){for(var t=e.getBoundingClientRect(),o=["✨","⭐","💫","🌟"],a=0;a<6;a++)(function(e){setTimeout(function(){var a=document.createElement("div");a.className="nacho-trail",a.textContent=o[e%o.length],a.style.left=t.left+Math.random()*t.width+"px",a.style.top=t.top+Math.random()*t.height+"px",a.style.fontSize=.8+.8*Math.random()+"rem",document.body.appendChild(a),setTimeout(function(){a.parentNode&&a.remove()},800)},80*e)})(a)}(a))},window.getNachoFriendship=function(){const e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[{name:"Stranger",emoji:"🦌",min:0},{name:"Acquaintance",emoji:"🤝",min:10},{name:"Pleb Friend",emoji:"🧡",min:50},{name:"HODL Buddy",emoji:"💎",min:150},{name:"Maxi Mentor",emoji:"👑",min:500}];let o=t[0];for(const a of t)e>=a.min&&(o=a);return o},window.renderNachoClosetUI=function(t){for(var a=o(),n=getEquippedItems(),r=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),i="function"==typeof getNachoFriendship?getNachoFriendship():{level:0,name:"Strangers",emoji:"❓"},l=[1,10,100,350,750],s="",d=0;dNext level in '+(l[d]-r)+" more interactions";break}var c="",m=[];Object.values(n).forEach(function(t){var o=e.find(function(e){return e.id===t});if(o){var a=o.hidden?o.revealEmoji:o.emoji;o.overlay.custom&&(a=o.overlay.custom);var n="position:absolute;font-size:"+(o.overlay.fontSize||"1.5rem")+";";if(o.overlay.top&&(n+="top:"+o.overlay.top+";"),o.overlay.bottom&&(n+="bottom:"+o.overlay.bottom+";"),o.overlay.left&&(n+="left:"+o.overlay.left+";"),o.overlay.right&&(n+="right:"+o.overlay.right+";"),o.overlay.transform&&(n+="transform:"+o.overlay.transform+";"),n+="z-index:5;pointer-events:none;",o.colorable){var r=localStorage.getItem("btc_closet_color_"+o.id);r&&"0deg"!==r&&(n+="filter:hue-rotate("+r+");")}c+=''+a+"",m.push(o.hidden?o.revealName:o.name)}});var h="function"==typeof nachoNickname?nachoNickname():"Nacho",f='
    🦌 '+escapeHtml(h)+"'s Closet
    ";f+='
    Nacho'+c+'
    '+(m.length>0?'✨ Wearing: '+m.join(", ")+"":"No item equipped — tap one below!")+"
    ",f+='
    Friendship: '+i.emoji+" "+i.name+''+r+" interactions
    "+s;f+='
    ',f+='
    ';for(var p=(new Date).toLocaleString("en",{month:"long"}).toLowerCase(),u=0;u
    '+w+'
    '+x+"
    "+(y?'
    ✓ EQUIPPED
    ':"")+(y&&g.colorable?"
    🎨 Color
    ':"")+(v||b?"":'
    Lvl '+g.level+"
    ")+(b?'
    🔒
    ':"")+(g.seasonal?'
    🗓️ '+g.seasonal+"
    ":"")+"
    "}}f+="",f+='
    '+(Object.keys(n).length>0?function(){var t=e.find(function(e){return e.id===Object.values(n)[0]});if(!t)return"Tap an item to equip it on "+escapeHtml(h)+"!";var o=t.hidden?t.revealDesc:t.desc;return''+(t.hidden?t.revealName:t.name)+": "+o}():"Tap an unlocked item to equip it on "+escapeHtml(h)+"!
    Tap again to unequip.")+"
    ",t.innerHTML=f};var a="function"==typeof nachoNickname?nachoNickname():"Nacho";window.NACHO_CLOSET_TIPS=[{pose:"cool",text:"Did you know I have a whole closet of outfits, {name}? Check Settings → Stats → "+escapeHtml(a)+"'s Closet to dress me up! 👔🦌"},{pose:"celebrate",text:"The more we interact, the more items you unlock for me to wear! Check my closet in Settings! 🧣⚡"},{pose:"eyes",text:"I heard there are some mystery items in my closet that only my closest friends get to see... 👀🔒"},{pose:"fire",text:"Proof of Steak > Proof of Stake. Ask me about it... or better yet, unlock it in my closet! 🥩🦌"},{pose:"cheese",text:"Fashion tip from a deer: orange goes with everything. Especially Bitcoin orange. Check my closet in Settings! 🟠"}],window.checkNachoNewItems=function(){var t=o(),a=JSON.parse(localStorage.getItem("btc_nacho_items_notified")||"[]"),n=e.filter(function(e){return e.level<=t&&!a.includes(e.id)});if(n.length>0){for(var r=0;r
    '+(r?r.name:"Item")+'
    Choose a color
    ';[{name:"Default",hue:"0deg",color:"#f7931a"},{name:"Bitcoin Orange",hue:"25deg",color:"#ff8c00"},{name:"Crimson",hue:"340deg",color:"#dc2626"},{name:"Royal Purple",hue:"270deg",color:"#7c3aed"},{name:"Ocean Blue",hue:"200deg",color:"#0ea5e9"},{name:"Forest Green",hue:"120deg",color:"#16a34a"},{name:"Gold",hue:"45deg",color:"#eab308"},{name:"Hot Pink",hue:"310deg",color:"#ec4899"},{name:"Cyan",hue:"175deg",color:"#06b6d4"},{name:"Lime",hue:"90deg",color:"#84cc16"}].forEach(function(t){var a=o===t.hue;i+=""}),i+='
    ',n.innerHTML=i,a.appendChild(n),document.body.appendChild(a)},window._applyClosetColor=function(e,t){localStorage.setItem("btc_closet_color_"+e,t);var o=document.querySelector("#nacho-overlay");if(o&&(o.style.filter="0deg"===t?"none":"hue-rotate("+t+")"),"function"==typeof showColorPicker&&showColorPicker(e),"function"==typeof renderNachoClosetUI){var a=document.getElementById("nachoClosetContainer");a&&renderNachoClosetUI(a)}};const QUESTION_BANK = { + +window.nachoNickname=function(){return localStorage.getItem("btc_nacho_nickname")||"Nacho"};function getEquippedItems(){try{return JSON.parse(localStorage.getItem("btc_nacho_equipped_multi")||"{}")}catch(e){return{}}}function getEquippedItem(){var e=getEquippedItems();return Object.values(e)[0]||localStorage.getItem("btc_nacho_equipped")||null}!function(){const e=[{id:"orange_scarf",category:"shirt",name:"Bitcoin Scarf",emoji:"🧣",desc:"A cozy orange scarf with the ₿ symbol.",level:1,overlay:{top:"68%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"sunglasses",category:"glasses",name:"Cool Shades",emoji:"🕶️",desc:"Sunglasses so cool, even the blockchain can't see through them.",level:1,overlay:{top:"43%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"bowtie",category:"shirt",name:"Fancy Bowtie",emoji:"🎀",desc:"A dapper bowtie for a distinguished buck. Class and sats.",level:1,overlay:{top:"64%",left:"50%",transform:"translateX(-50%)",fontSize:"1.3em"},hidden:!1,colorable:!0},{id:"mining_helmet",category:"hat",name:"Mining Helmet",emoji:"⛑️",desc:"A safety helmet for a hardworking miner. Ready to find the next block!",level:2,overlay:{top:"5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"lightning_chain",category:"glasses",name:"Lightning Chain",emoji:"⚡",desc:"A chain necklace with a Lightning bolt pendant.",level:2,overlay:{top:"65%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"party_hat",category:"hat",name:"Party Hat",emoji:"🎉",desc:"Every day is a party when you're stacking sats!",level:2,overlay:{top:"2%",left:"58%",transform:"translateX(-50%) rotate(15deg)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"hodl_hoodie",category:"shirt",name:"HODL Hoodie",emoji:"🧥",desc:"A hoodie that says HODL on the back. For diamond-handed deer.",level:3,overlay:{top:"72%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1,colorable:!0},{id:"laser_eyes",category:"glasses",name:"Laser Eyes",emoji:"🔴",desc:"The legendary Bitcoin laser eyes. Number go up!",level:3,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"0.9em",custom:"🔴 🔴"},hidden:!1,colorable:!0},{id:"wizard_hat",category:"hat",name:"Wizard Hat",emoji:"🪄",desc:"A mystical wizard hat. Nacho casts spells of financial sovereignty!",level:3,overlay:{top:"-5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!1,colorable:!0},{id:"crown",category:"hat",name:"Royal Crown",emoji:"👑",desc:"Fit for the king of cryptocurrency. There is no second best!",level:3,overlay:{top:"3%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"steak",category:"glasses",name:"Proof of Steak",emoji:"🥩",desc:"A juicy steak for a hardworking buck. Proof of Steak > Proof of Stake!",level:4,overlay:{top:"58%",right:"-18%",fontSize:"1.8em",transform:"rotate(20deg)"},hidden:!1},{id:"diamond_hooves",category:"glasses",name:"Diamond Hooves",emoji:"💎",desc:"Diamond hooves for a deer with diamond hands. Never selling!",level:4,overlay:{bottom:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em",custom:"💎💎"},hidden:!1},{id:"astronaut",category:"hat",name:"Moon Helmet",emoji:"🪖",desc:"To the moon! A space helmet for the ultimate HODLer.",level:4,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1},{id:"cape_permanent",category:"shirt",name:"Hero Cape",emoji:"🦸",desc:"A permanent cape for a Bitcoin hero. Earned, not given!",level:4,overlay:{top:"55%",right:"-15%",fontSize:"2.4em",transform:"rotate(-12deg)"},hidden:!1,colorable:!0},{id:"golden_antlers",category:"hat",name:"???",emoji:"✨",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"0.5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Golden Antlers",revealEmoji:"✨",revealDesc:"Antlers plated in pure gold. Only the closest friends get to see these shine!"},{id:"satoshi_cloak",category:"shirt",name:"???",emoji:"🧥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"68%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Satoshi's Cloak",revealEmoji:"🧥",revealDesc:"A mysterious cloak worn by Satoshi himself. Legend says it grants anonymity to any deer who wears it."},{id:"flame_aura",category:"glasses",name:"???",emoji:"🔥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"25%",left:"50%",transform:"translateX(-50%)",fontSize:"3.5em"},hidden:!0,revealName:"Flame Aura",revealEmoji:"🔥",revealDesc:"A blazing aura of pure Bitcoin energy. The ultimate flex for Nacho's best friend!"},{id:"rainbow_antlers",category:"hat",name:"???",emoji:"🌈",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!0,revealName:"Rainbow Antlers",revealEmoji:"🌈",revealDesc:"Prismatic rainbow antlers that shimmer in every color. Legendary!"},{id:"bitcoin_eyes",category:"glasses",name:"???",emoji:"₿",desc:"How do you find this one?",level:1,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.2em",custom:"₿ ₿"},hidden:!0,revealName:"Bitcoin Eyes",revealEmoji:"₿",revealDesc:"Eyes made of pure Bitcoin. You found the secret! Nacho sees everything in sats now."},{id:"santa_hat",category:"hat",name:"Santa Hat",emoji:"🎅",desc:"Ho ho HODL! A festive Santa hat for the holiday season.",level:1,overlay:{top:"1%",left:"54%",transform:"translateX(-50%) rotate(15deg)",fontSize:"2.2em"},hidden:!1,seasonal:"december"},{id:"pumpkin",category:"hat",name:"Pumpkin Head",emoji:"🎃",desc:"Spooky season! A jack-o-lantern for Halloween.",level:1,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1,seasonal:"october"},{id:"halving_pickaxe",category:"glasses",name:"Golden Pickaxe",emoji:"⛏️",desc:"A golden pickaxe to celebrate the halving! Limited edition.",level:1,overlay:{top:"22%",right:"-15%",fontSize:"2.2em",transform:"rotate(30deg)"},hidden:!1,seasonal:"april"}];var t=document.createElement("style");function o(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?5:e>=350?4:e>=100?3:e>=10?2:e>=1?1:0}t.textContent="\n @keyframes nachoEquipPop {\n 0% { transform: scale(0) rotate(-45deg); opacity: 0; }\n 50% { transform: scale(1.5) rotate(10deg); opacity: 1; }\n 70% { transform: scale(0.9) rotate(-5deg); }\n 100% { transform: scale(1) rotate(0deg); opacity: 1; }\n }\n @keyframes nachoEquipGlow {\n 0% { filter: drop-shadow(0 0 0px transparent); }\n 30% { filter: drop-shadow(0 0 12px rgba(247,147,26,0.8)); }\n 100% { filter: drop-shadow(0 0 4px rgba(247,147,26,0.3)); }\n }\n @keyframes nachoUnequip {\n 0% { transform: scale(1); opacity: 1; }\n 40% { transform: scale(1.3) rotate(15deg); opacity: 0.8; }\n 100% { transform: scale(0) rotate(-30deg); opacity: 0; }\n }\n @keyframes nachoItemFloat {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-3px); }\n }\n @keyframes nachoLaserPulse {\n 0%, 100% { opacity: 0.8; filter: drop-shadow(0 0 4px #ff0000); }\n 50% { opacity: 1; filter: drop-shadow(0 0 10px #ff0000) drop-shadow(0 0 20px #ff3300); }\n }\n @keyframes nachoSparkle {\n 0%, 100% { filter: drop-shadow(0 0 4px rgba(255,215,0,0.3)); }\n 50% { filter: drop-shadow(0 0 10px rgba(255,215,0,0.8)) drop-shadow(0 0 20px rgba(255,215,0,0.4)); }\n }\n @keyframes nachoCloakWave {\n 0%, 100% { transform: translateX(-50%) rotate(-2deg); }\n 50% { transform: translateX(-50%) rotate(2deg); }\n }\n .nacho-overlay-item {\n position: absolute;\n pointer-events: none;\n z-index: 3;\n }\n .nacho-overlay-item.equipping {\n animation: nachoEquipPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards,\n nachoEquipGlow 0.8s ease-out forwards;\n }\n .nacho-overlay-item.unequipping {\n animation: nachoUnequip 0.35s ease-in forwards;\n }\n .nacho-overlay-item.idle-float {\n animation: nachoItemFloat 3s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-laser {\n animation: nachoLaserPulse 1.5s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-sparkle {\n animation: nachoSparkle 2s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-wave {\n animation: nachoCloakWave 4s ease-in-out infinite;\n }\n",document.head.appendChild(t),window.equipNachoItem=function(t){if(!t)return localStorage.removeItem("btc_nacho_equipped_multi"),void renderNachoOverlay();var a=o(),n=e.find(function(e){return e.id===t}),r=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]");if(n&&n.level>a&&-1===r.indexOf(t))showToast("🔒 Need a higher friendship level to wear this!");else{var i=getEquippedItems(),l=n&&n.category||"misc";if(i[l]===t)delete i[l],"function"==typeof forceShowBubble&&forceShowBubble("Back to natural in the "+l+" department! 🦌");else if(i[l]=t,"function"==typeof forceShowBubble){forceShowBubble({orange_scarf:"Looking cozy! This scarf really brings out my orange. 🧣🦌",mining_helmet:"Safety first! Time to mine some blocks! ⛑️⛏️",lightning_chain:"Bling bling! Fast as Lightning! ⚡🦌",hodl_hoodie:"HODL gang! This hoodie makes me feel unstoppable! 🧥💎",laser_eyes:"LASER EYES ACTIVATED! Number go up! 🔴🔴🚀",steak:"Mmm, Proof of Steak! Way better than Proof of Stake! 🥩😋",golden_antlers:"These golden antlers are MAGNIFICENT! Only for my best friends! 👑✨",satoshi_cloak:"Who am I? Nobody knows... I am Satoshi Nachoamoto! 🧙🦌"}[t]||"Looking fresh with my "+(n.hidden?n.revealName:n.name)+"! 🦌")}localStorage.setItem("btc_nacho_equipped_multi",JSON.stringify(i)),renderNachoOverlay(!0),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),document.getElementById("nachoClosetGrid")&&renderNachoClosetUI(document.getElementById("nachoClosetGrid").parentElement)}},window.renderNachoOverlay=function(t){document.querySelectorAll(".nacho-overlay-item").forEach(e=>e.remove());var o=getEquippedItems(),a=document.getElementById("nacho-avatar");a&&(Object.values(o).forEach(function(o){var n=e.find(function(e){return e.id===o});if(n){var r=n.hidden?n.revealEmoji:n.emoji,i=function(e){switch(e){case"laser_eyes":return"idle-laser";case"golden_antlers":case"diamond_hooves":return"idle-sparkle";case"satoshi_cloak":return"idle-wave";default:return"idle-float"}}(n.id),l=document.createElement("span");for(var s in l.className="nacho-overlay-item"+(t?" equipping":" "+i),l.id="nacho-overlay-"+n.id,l.textContent=n.overlay.custom||r,n.overlay.custom&&(l.style.letterSpacing="-0.1em",l.style.whiteSpace="nowrap"),n.overlay)"filter"!==s&&"custom"!==s&&(l.style[s]=n.overlay[s]);if(n.colorable){var d=localStorage.getItem("btc_closet_color_"+n.id);d&&"0deg"!==d&&(l.style.filter="hue-rotate("+d+")")}t&&l.addEventListener("animationend",function e(){l.classList.remove("equipping"),l.classList.add(i),l.removeEventListener("animationend",e)},{once:!0}),a.appendChild(l)}}),t&&function(e){for(var t=e.getBoundingClientRect(),o=["✨","⭐","💫","🌟"],a=0;a<6;a++)(function(e){setTimeout(function(){var a=document.createElement("div");a.className="nacho-trail",a.textContent=o[e%o.length],a.style.left=t.left+Math.random()*t.width+"px",a.style.top=t.top+Math.random()*t.height+"px",a.style.fontSize=.8+.8*Math.random()+"rem",document.body.appendChild(a),setTimeout(function(){a.parentNode&&a.remove()},800)},80*e)})(a)}(a))},window.getNachoFriendship=function(){const e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[{name:"Stranger",emoji:"🦌",min:0},{name:"Acquaintance",emoji:"🤝",min:10},{name:"Pleb Friend",emoji:"🧡",min:50},{name:"HODL Buddy",emoji:"💎",min:150},{name:"Maxi Mentor",emoji:"👑",min:500}];let o=t[0];for(const a of t)e>=a.min&&(o=a);return o},window.renderNachoClosetUI=function(t){for(var a=o(),n=getEquippedItems(),r=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),i="function"==typeof getNachoFriendship?getNachoFriendship():{level:0,name:"Strangers",emoji:"❓"},l=[1,10,100,350,750],s="",d=0;dNext level in '+(l[d]-r)+" more interactions";break}var c="",m=[];Object.values(n).forEach(function(t){var o=e.find(function(e){return e.id===t});if(o){var a=o.hidden?o.revealEmoji:o.emoji;o.overlay.custom&&(a=o.overlay.custom);var n="position:absolute;font-size:"+(o.overlay.fontSize||"1.5rem")+";";if(o.overlay.top&&(n+="top:"+o.overlay.top+";"),o.overlay.bottom&&(n+="bottom:"+o.overlay.bottom+";"),o.overlay.left&&(n+="left:"+o.overlay.left+";"),o.overlay.right&&(n+="right:"+o.overlay.right+";"),o.overlay.transform&&(n+="transform:"+o.overlay.transform+";"),n+="z-index:5;pointer-events:none;",o.colorable){var r=localStorage.getItem("btc_closet_color_"+o.id);r&&"0deg"!==r&&(n+="filter:hue-rotate("+r+");")}c+=''+a+"",m.push(o.hidden?o.revealName:o.name)}});var h="function"==typeof nachoNickname?nachoNickname():"Nacho",f='
    🦌 '+escapeHtml(h)+"'s Closet
    ";f+='
    Nacho'+c+'
    '+(m.length>0?'✨ Wearing: '+m.join(", ")+"":"No item equipped — tap one below!")+"
    ",f+='
    Friendship: '+i.emoji+" "+i.name+''+r+" interactions
    "+s;f+='
    ',f+='
    ';for(var p=(new Date).toLocaleString("en",{month:"long"}).toLowerCase(),u=0;u
    '+w+'
    '+x+"
    "+(y?'
    ✓ EQUIPPED
    ':"")+(y&&g.colorable?"
    🎨 Color
    ':"")+(v||b?"":'
    Lvl '+g.level+"
    ")+(b?'
    🔒
    ':"")+(g.seasonal?'
    🗓️ '+g.seasonal+"
    ":"")+"
    "}}f+="",f+='
    '+(Object.keys(n).length>0?function(){var t=e.find(function(e){return e.id===Object.values(n)[0]});if(!t)return"Tap an item to equip it on "+escapeHtml(h)+"!";var o=t.hidden?t.revealDesc:t.desc;return''+(t.hidden?t.revealName:t.name)+": "+o}():"Tap an unlocked item to equip it on "+escapeHtml(h)+"!
    Tap again to unequip.")+"
    ",t.innerHTML=f};var a="function"==typeof nachoNickname?nachoNickname():"Nacho";window.NACHO_CLOSET_TIPS=[{pose:"cool",text:"Did you know I have a whole closet of outfits, {name}? Check Settings → Stats → "+escapeHtml(a)+"'s Closet to dress me up! 👔🦌"},{pose:"celebrate",text:"The more we interact, the more items you unlock for me to wear! Check my closet in Settings! 🧣⚡"},{pose:"eyes",text:"I heard there are some mystery items in my closet that only my closest friends get to see... 👀🔒"},{pose:"fire",text:"Proof of Steak > Proof of Stake. Ask me about it... or better yet, unlock it in my closet! 🥩🦌"},{pose:"cheese",text:"Fashion tip from a deer: orange goes with everything. Especially Bitcoin orange. Check my closet in Settings! 🟠"}],window.checkNachoNewItems=function(){var t=o(),a=JSON.parse(localStorage.getItem("btc_nacho_items_notified")||"[]"),n=e.filter(function(e){return e.level<=t&&!a.includes(e.id)});if(n.length>0){for(var r=0;r
    '+(r?r.name:"Item")+'
    Choose a color
    ';[{name:"Default",hue:"0deg",color:"#f7931a"},{name:"Bitcoin Orange",hue:"25deg",color:"#ff8c00"},{name:"Crimson",hue:"340deg",color:"#dc2626"},{name:"Royal Purple",hue:"270deg",color:"#7c3aed"},{name:"Ocean Blue",hue:"200deg",color:"#0ea5e9"},{name:"Forest Green",hue:"120deg",color:"#16a34a"},{name:"Gold",hue:"45deg",color:"#eab308"},{name:"Hot Pink",hue:"310deg",color:"#ec4899"},{name:"Cyan",hue:"175deg",color:"#06b6d4"},{name:"Lime",hue:"90deg",color:"#84cc16"}].forEach(function(t){var a=o===t.hue;i+=""}),i+='
    ',n.innerHTML=i,a.appendChild(n),document.body.appendChild(a)},window._applyClosetColor=function(e,t){localStorage.setItem("btc_closet_color_"+e,t);var o=document.querySelector("#nacho-overlay");if(o&&(o.style.filter="0deg"===t?"none":"hue-rotate("+t+")"),"function"==typeof showColorPicker&&showColorPicker(e),"function"==typeof renderNachoClosetUI){var a=document.getElementById("nachoClosetContainer");a&&renderNachoClosetUI(a)}}; +const QUESTION_BANK = { 'whitepaper': [ { q: 'When was the Bitcoin Whitepaper published?', a: 'October 31, 2008', wrong: ['January 3, 2009', 'March 15, 2007', 'December 25, 2010'] }, { q: 'How many pages of text is the Bitcoin Whitepaper?', a: '8 pages', wrong: ['20 pages', '50 pages', '2 pages'] }, @@ -15119,6 +15129,7 @@ window._raidOnChannelVisit = function(channelId) { window._raidContribute('uniqueTopicsVisited', 1, channelId); window._raidContribute('uniqueUsers5Topics', 1, channelId); }; + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. // ============================================= @@ -17452,6 +17463,7 @@ if (document.readyState === 'loading') { } })(); + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. // ============================================= @@ -18649,6 +18661,7 @@ function getTimeAgo(date) { } })(); + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. 'use strict'; @@ -20060,6 +20073,7 @@ window.initMessaging = function() { if (typeof auth !== 'undefined' && auth && auth.currentUser) { initMessaging(); } + const HIDDEN_BADGES = [ // === VISIBLE GOALS (shown locked with progress hints) === { id: 'nacho_friend', name: 'Nacho\'s Friend', emoji: '🦌', pts: 25, desc: 'Interact with Nacho', hint: 'Click on Nacho!', hidden: false, check: function() { return localStorage.getItem('btc_nacho_clicked') === 'true'; } }, @@ -21360,6 +21374,7 @@ window.showCelebration = function(opts) { }; } })(); + // © 2024-2026 603BTC LLC. All rights reserved. // This code is proprietary. See LICENSE file. Do not copy or redistribute. // ============================================= @@ -22104,6 +22119,7 @@ if (document.readyState === 'loading') { } })(); + // © 2024-2026 603BTC LLC. All rights reserved. // ============================================= // ₿ Bitcoin Network Dashboard — Real-Time Metrics @@ -24029,6 +24045,7 @@ window._startHalvingTicker = function() { }; })(); + (function() { window._sessionStart = window._sessionStart || Date.now(); var _lastTickerPrice = null; @@ -26858,7 +26875,7 @@ window.nachoQuizAnswer = function(btn, correct) { // P = donate if (key === 'p') { showDonateModal(); return; } // X = PVP Battle - if (key === 'x') { if (typeof enterPVPMode === 'function') enterPVPMode(); return; } + if (key === 'x') { if (typeof _launchPVP === 'function') _launchPVP(); return; } // === Scroll === // J = scroll down @@ -27783,7 +27800,7 @@ window.nachoQuizAnswer = function(btn, correct) { { id: '_art', title: '🎨 Random Art', desc: 'See random Bitcoin art and inspiration', keywords: 'art random artwork creative inspiration gallery', action: 'goRandomArt()' }, { id: '_graphic', title: '📊 Random Graphic', desc: 'See a random Bitcoin graphic or chart', keywords: 'graphic chart data visual infographic random graphics', action: 'goRandomGraphic()' }, { id: '_quiz', title: '🎮 Quiz Me', desc: 'Test your Bitcoin knowledge with Nacho', keywords: 'quiz question test knowledge trivia game answer', action: 'nachoQuizMe()' }, - { id: '_pvp', title: '⚔️ PVP Battle', desc: 'Real-time Bitcoin trivia battles against other players', keywords: 'pvp battle fight 1v1 versus trivia quiz compete multiplayer arena duel challenge opponent leaderboard wins losses', action: 'enterPVPMode()' }, + { id: '_pvp', title: '⚔️ PVP Battle', desc: 'Real-time Bitcoin trivia battles against other players', keywords: 'pvp battle fight 1v1 versus trivia quiz compete multiplayer arena duel challenge opponent leaderboard wins losses', action: '_launchPVP()' }, { id: '_donate', title: '💛 Donate', desc: 'Support Bitcoin Education Archive with sats', keywords: 'donate support tip sats lightning contribute funding', action: 'showDonateModal()' }, { id: '_theme', title: '🌙 Toggle Theme', desc: 'Switch between dark and light mode', keywords: 'theme dark light mode toggle switch appearance color night day', action: 'document.getElementById("themeToggle").click()' }, { id: '_audio', title: '🔊 Toggle Audio', desc: 'Turn sound effects on or off', keywords: 'audio sound music mute volume effects toggle', action: 'toggleAudio()' }, @@ -28441,7 +28458,7 @@ if (locked) { // PVP Battle if (hash === 'pvp' || state.channel === 'pvp') { - if (typeof enterPVPMode === 'function') enterPVPMode(); + if (typeof _launchPVP === 'function') _launchPVP(); return; } @@ -28639,7 +28656,7 @@ if (locked) { if (typeof enterNachoMode === 'function') { enterNachoMode(); return; } break; case 'pvp': - if (typeof enterPVPMode === 'function') { enterPVPMode(); return; } + if (typeof _launchPVP === 'function') { _launchPVP(); return; } break; case 'forum': if (typeof go === 'function') { go('forum'); return; } @@ -28986,6 +29003,7 @@ window.toggleAITools = function() { injectAIToolsBtn(); } })(); + // ============================================= // Bitcoin Education Archive — UX Improvement Patches // Implements all 24 tasks from the UX Review Report diff --git a/ranking.js b/ranking.js index 92b902258..6fae39e6f 100644 --- a/ranking.js +++ b/ranking.js @@ -3107,7 +3107,7 @@ async function toggleLeaderboard() { html += '
    ' + '
    ' + '

    ⚔️ PVP Leaderboard

    ' + - '' + + '' + '
    ' + '
    Loading PVP rankings...
    ' + '
    '; @@ -4717,7 +4717,7 @@ function showSettingsPage(tab) { html += statRow('PVP Record', _pvpW + 'W – ' + _pvpL + 'L', '⚔️'); html += statRow('PVP Win Rate', _pvpPct + '%', '📊'); } else { - html += statRow('PVP Record', 'No battles yet — Enter PVP Lobby', '⚔️'); + html += statRow('PVP Record', 'No battles yet — Enter PVP Lobby', '⚔️'); } // Prediction Stats if (typeof getPredictionStats === 'function') { From b2c7331926e16d3e5ac2c4c69e80a62567e2347f Mon Sep 17 00:00:00 2001 From: 0xrasmp Date: Fri, 12 Jun 2026 13:00:04 +0100 Subject: [PATCH 3/7] feat: centralize firebase config and fix pvp matchmaking race conditions --- bundle.js | 30437 ++++++++++++++++++++++++++++++++++++- bundle.src.js | 33 +- firebase-config.js | 26 + firebase-messaging-sw.js | 11 +- firestore.rules | 9 +- index.html | 5 +- pvp.js | 2 +- pvp.js.src | 170 +- ranking.js | 11 +- 9 files changed, 30587 insertions(+), 117 deletions(-) create mode 100644 firebase-config.js diff --git a/bundle.js b/bundle.js index 368c1bbb4..eac903975 100644 --- a/bundle.js +++ b/bundle.js @@ -1 +1,30436 @@ -var CHANNELS={decentralized:{cat:"Properties Layer 1",title:"👪decentralized-censorship-resistant-ungovernable-incorruptible-trustless-unconfiscatable-updatable",desc:"Why no single person, company, or government controls Bitcoin — and why that's the most important feature.",file:"data/D_decentralized.json"},dominant:{cat:"Properties Layer 1",title:"🏆dominant-recognizable-brand-legitimate-limitless-infinite-exponential-transformative-revolutionary",desc:"Bitcoin's brand recognition, network effects, and why it has maintained the #1 position since 2009.",file:"data/D_dominant.json"},money:{cat:"Properties Layer 1",title:"💰money-deflationary-salable-durable-anti-fragile-divisible-portable-transmittable-verifiable-fair",desc:"What money actually is, how it works, and why Bitcoin satisfies every property of sound money better than anything before it.",file:"data/D_money.json"},organic:{cat:"Properties Layer 1",title:"🌳organic-empowering-elegant-freedom-centric-irrefutable-unseizable-irreversible-unbreakable",desc:"How Bitcoin grew from an idea worth nothing to a trillion-dollar network — without marketing, without a company, without a leader.",file:"data/D_organic.json"},peaceful:{cat:"Properties Layer 1",title:"☮peaceful-neutral-voluntary-open-universal-permissionless-borderless-global-inevitable-unstoppable",desc:"Bitcoin is voluntary, permissionless, borderless, and unstoppable. No one forces you to use it — and no one can stop you.",file:"data/D_peaceful.json"},programmable:{cat:"Properties Layer 1",title:"🤖programable-interoperable-deflationary-pseudonymous-opt-in-resilient-adiabatic-egalitarian",desc:"Bitcoin as programmable money — interoperable, pseudonymous, resilient, and thermodynamically sound.",file:"data/D_programmable.json"},scarce:{cat:"Properties Layer 1",title:"🍀scarce-unforgeable-hedge-scalable-p2p-instant-open-source-auditable-inaliable",desc:"Only 21 million will ever exist. Explore what makes Bitcoin the scarcest asset humanity has ever created.",file:"data/D_scarce.json"},secure:{cat:"Properties Layer 1",title:"™secure-fungible-immutable-incorruptible-immalleable-infallible-reliable-predictable-irreplicable",desc:"How Bitcoin's network security makes it virtually impossible to hack — protected by more computing power than anything on Earth.",file:"data/D_secure.json"},supranational:{cat:"Properties Layer 1",title:"🕊supranational-lindy-inviolate-dilution-proof-frictionless-freely-accessible-settlement-finality",desc:"Bitcoin transcends nations and governments. Explore the Lindy Effect, settlement finality, and dilution-proof money.",file:"data/D_supranational.json"},"use-cases":{cat:"Properties Layer 1",title:"✔use-cases",desc:"Real-world uses for Bitcoin: savings, payments, remittances, store of value, and more.",file:"data/D_use-cases.json"},whitepaper:{cat:"Properties Layer 1",title:"📄whitepaper",desc:"The 9-page document that started it all. Published October 31, 2008 by Satoshi Nakamoto — the foundation of Bitcoin.",file:"data/D_whitepaper.json"},bitvm:{cat:"Experienced Topics",title:"🖥bitvm",desc:"BitVM: computation on Bitcoin without changing the protocol. A new frontier for Bitcoin programmability.",file:"data/E_bitvm.json"},"blockchain-timechain":{cat:"Experienced Topics",title:"⛓blockchain-timechain-transactions-addresses",desc:"How the Bitcoin blockchain (timechain) works — blocks, transactions, timestamps, and the immutable ledger.",file:"data/E_blockchain-timechain.json"},"chaumian-mints":{cat:"Experienced Topics",title:"💸layer-2-chaumian-mints-ecash",desc:"Chaumian ecash, Cashu, and blinded signatures — the cutting edge of Bitcoin privacy technology.",file:"data/E_chaumian-mints.json"},consensus:{cat:"Additional Info",title:"🤝Consensus",desc:"How Bitcoin achieves consensus without a central authority — Nakamoto Consensus and beyond.",file:"data/H_consensus.json"},"core-source-code":{cat:"Experienced Topics",title:"💾core-source-code-forks-testnet-future-potential-upgrades",desc:"Bitcoin Core's source code, forks, testnet, and the open-source development process.",file:"data/E_core-source-code.json"},cryptography:{cat:"Experienced Topics",title:"🔒cryptography-cypherpunks",desc:"The cryptographic foundations of Bitcoin — SHA-256, elliptic curves, digital signatures, and the cypherpunk legacy.",file:"data/E_cryptography.json"},"ctv-covenants":{cat:"Experienced Topics",title:"📜ctv-bip119-covenants",desc:"BIP-119, CTV, and Bitcoin covenants — proposed upgrades and the debates around them.",file:"data/E_ctv-covenants.json"},developers:{cat:"Experienced Topics",title:"🖥developers",desc:"Building on Bitcoin — resources, guides, and paths for developers who want to contribute.",file:"data/E_developers.json"},"difficulty-adjustment":{cat:"Experienced Topics",title:"😤difficulty-adjustment",desc:"The most elegant part of Bitcoin's design — how the network self-adjusts every 2,016 blocks.",file:"data/E_difficulty-adjustment.json"},energy:{cat:"Experienced Topics",title:"💡energy",desc:"The truth about Bitcoin's energy use: 0.1% of global energy, renewable mining, methane capture, and grid stabilization.",file:"data/E_energy.json"},"evidence-against-alts":{cat:"Experienced Topics",title:"⚠evidence-against-ethereum-other-alt-coins-crypto-defi-nfts-web3-monero-bsv-bch-cbdcs-other-projects",desc:"Why every altcoin fails against Bitcoin — premines, centralization, broken promises, and the evidence.",file:"data/E_evidence-against-alts.json"},"extension-blocks":{cat:"Experienced Topics",title:"🚧extension-blocks-and-other-proposed-scaling-solutions",desc:"Extension blocks and other proposed scaling solutions for Bitcoin.",file:"data/E_extension-blocks.json"},"fedi-ark":{cat:"Experienced Topics",title:"🛡layer-2-fedi-ark",desc:"Fedimints, Ark, and Bitcoin's privacy/scaling layers — community custody with enhanced privacy.",file:"data/E_fedi-ark.json"},"investment-strategy":{cat:"Experienced Topics",title:"🤑investment-strategy-taxes-retirement-inheritance-loans-donate-gift-consulting-remittance",desc:"DCA, HODL, lump sum strategies, taxes, retirement planning, and thinking long-term with Bitcoin.",file:"data/E_investment-strategy.json"},"layer-2-lightning":{cat:"Experienced Topics",title:"⚡layer-2-lightning",desc:"The Lightning Network: instant, nearly-free Bitcoin payments. How Bitcoin scales without sacrificing decentralization.",file:"data/E_layer-2-lightning.json"},"layer-3-sidechains":{cat:"Experienced Topics",title:"📱layer-3-sidechain-applications",desc:"Sidechains, Liquid Network, and layer-3 applications built on top of Bitcoin.",file:"data/E_layer-3-sidechains.json"},maximalism:{cat:"Experienced Topics",title:"💯maximalism",desc:"Why people who study Bitcoin the most become maximalists. The case for Bitcoin-only.",file:"data/E_maximalism.json"},mining:{cat:"Experienced Topics",title:"🌋mining",desc:"How Bitcoin mining actually works — nonces, SHA-256 hashing, difficulty adjustment, and the brute-force lottery.",file:"data/E_mining.json"},nodes:{cat:"Experienced Topics",title:"💻nodes",desc:"Run your own Bitcoin node. Don't trust, verify. How 14,000+ nodes keep the network decentralized.",file:"data/E_nodes.json"},"op-codes":{cat:"Experienced Topics",title:"👨‍💻op-codes-simplicity",desc:"OP_CAT, Simplicity, and Bitcoin's scripting language — the building blocks of smart functionality.",file:"data/E_op-codes.json"},"pow-vs-pos":{cat:"Experienced Topics",title:"💪proof-of-work-vs-proof-of-stake",desc:"Why Proof of Work is fundamentally superior to Proof of Stake — energy, security, fairness, and decentralization.",file:"data/E_pow-vs-pos.json"},"privacy-nonkyc":{cat:"Experienced Topics",title:"🤫privacy-nonkyc-stacking-self-sovereignty",desc:"Financial privacy as a human right. KYC, non-KYC stacking, and protecting your sovereignty.",file:"data/E_privacy-nonkyc.json"},"problems-of-money":{cat:"Experienced Topics",title:"📉the-problems-of-todays-money-and-freedom",desc:"The broken fiat system: inflation, money printing, the Cantillon Effect, and why today's money is failing everyone.",file:"data/E_problems-of-money.json"},regulation:{cat:"Experienced Topics",title:"🏛regulation-policy-legal",desc:"Bitcoin and government: bans, adoption, legal tender, ETFs, and why regulation can't stop decentralization.",file:"data/E_regulation.json"},"self-custody":{cat:"Experienced Topics",title:"🔑personal-storage-self-custody-security",desc:"Not your keys, not your coins. Learn how to truly own your Bitcoin with wallets, seed phrases, and security.",file:"data/E_self-custody.json"},"smart-contracts":{cat:"Experienced Topics",title:"📱smart-contracts",desc:"Smart contracts on Bitcoin — what's possible, what's coming, and why Bitcoin's approach is different.",file:"data/E_smart-contracts.json"},stablecoins:{cat:"Additional Info",title:"🪙Stablecoins",desc:"The role of stablecoins in the Bitcoin economy — and why they're not a threat to Bitcoin.",file:"data/H_stablecoins.json"},"0_mining__hashing":{cat:"Additional Info",title:"0⃣Mining (Hashing)",desc:"Deep dive into Bitcoin mining and hashing — how SHA-256 works at the bit level.",file:"data/H_0_mining__hashing.json"},"100_sats":{cat:"Additional Info",title:"💯100 sats",desc:"What can you do with just 100 satoshis? More than you think.",file:"data/H_100_sats.json"},"1_first_principles":{cat:"Additional Info",title:"1⃣First Principles",desc:"First principles thinking applied to Bitcoin — reasoning from fundamentals, not analogies.",file:"data/H_1_first_principles.json"},"2__solved_technical_problems":{cat:"Additional Info",title:"2⃣ Solved Technical Problems",desc:"The technical problems Bitcoin solved — digital scarcity, double-spending, and Byzantine fault tolerance.",file:"data/H_2__solved_technical_problems.json"},analogies:{cat:"Additional Info",title:"🔋Analogies",desc:"The best analogies for explaining Bitcoin to anyone — from trees to brains to hearts.",file:"data/H_analogies.json"},austrian_school_of_economics:{cat:"Additional Info",title:"🇦🇹Austrian School of Economics",desc:"Austrian Economics and Bitcoin: Mises, Hayek, sound money theory, and the intellectual foundation.",file:"data/H_austrian_school_of_economics.json"},bip119:{cat:"Additional Info",title:"🚧BIP119",desc:"BIP-119 (CheckTemplateVerify) — what it is, why it's controversial, and the community debate.",file:"data/H_bip119.json"},bitcoin_exam:{cat:"Additional Info",title:"🎓Bitcoin Exam",desc:"Test questions for a Bitcoin exam — study material and self-assessment.",file:"data/H_bitcoin_exam.json"},bitcoin_vs_real_estate:{cat:"Additional Info",title:"Bitcoin vs Real Estate",desc:"Bitcoin vs. real estate as an investment — comparing the two hardest assets.",file:"data/H_bitcoin_vs_real_estate.json"},"block_time-block-size":{cat:"Additional Info",title:"⏰Block Time-Block-Size",desc:"Why Bitcoin uses 10-minute blocks and how block size affects the network.",file:"data/H_block_time-block-size.json"},burn_bitcoin:{cat:"Additional Info",title:"Burn bitcoin",desc:"How Bitcoin can be burned (made permanently unspendable) and why people do it.",file:"data/H_burn_bitcoin.json"},byzantine_generals__problem:{cat:"Additional Info",title:"⚔Byzantine Generals’ Problem",desc:"The Byzantine Generals' Problem — the computer science challenge Satoshi solved.",file:"data/H_byzantine_generals__problem.json"},"chaumian_e-cash_and_blind_signatures":{cat:"Additional Info",title:"💲Chaumian E-cash and Blind Signatures",desc:"David Chaum's ecash, blind signatures, and the cryptographic foundations of digital privacy.",file:"data/H_chaumian_e-cash_and_blind_signatures.json"},coin_mixing_coinjoin_coin_control_utxo:{cat:"Additional Info",title:"🌀Coin Mixing/Coinjoin/Coin Control/UTXO Management",desc:"CoinJoin, coin mixing, UTXO management — advanced Bitcoin privacy techniques.",file:"data/H_coin_mixing_coinjoin_coin_control_utxo.json"},cyles:{cat:"Additional Info",title:"🚲Cyles",desc:"Bitcoin's 4-year cycles, Gartner Hype Cycles, and whether the pattern continues.",file:"data/H_cyles.json"},derivation_path:{cat:"Additional Info",title:"↕Derivation Path",desc:"HD wallet derivation paths — how your seed phrase generates all your addresses.",file:"data/H_derivation_path.json"},discrete_log_contracts__dlcs:{cat:"Additional Info",title:"📝Discrete Log Contracts (DLCs)?",desc:"DLCs (Discrete Log Contracts) — smart contracts on Bitcoin using oracle signatures.",file:"data/H_discrete_log_contracts__dlcs.json"},"dollar-bitcoin_milkshake_theory":{cat:"Additional Info",title:"🥤Dollar-Bitcoin Milkshake Theory",desc:"The Dollar-Bitcoin Milkshake Theory — how global dollar demand and Bitcoin intersect.",file:"data/H_dollar-bitcoin_milkshake_theory.json"},dust:{cat:"Additional Info",title:"⏳Dust",desc:"Dust UTXOs: what they are, why they're a problem, and how to manage them.",file:"data/H_dust.json"},elevator_pitches:{cat:"Additional Info",title:"↕Elevator Pitches",desc:"Quick 20-30 second explanations of why Bitcoin matters — for every audience.",file:"data/H_elevator_pitches.json"},environment___energy:{cat:"Additional Info",title:"🌳Environment & Energy",desc:"Bitcoin and the environment: energy usage facts, renewable mining, and debunking the FUD.",file:"data/H_environment___energy.json"},faith___religion:{cat:"Additional Info",title:"🙏Faith & Religion",desc:"Bitcoin and faith — how sound money relates to religious and spiritual values.",file:"data/H_faith___religion.json"},fedimints:{cat:"Additional Info",title:"💚Fedimints",desc:"Fedimints: community custody with enhanced privacy using federated Chaumian mints.",file:"data/H_fedimints.json"},feedback_loops:{cat:"Additional Info",title:"➰Feedback Loops",desc:"Bitcoin's feedback loops — the self-reinforcing cycles that drive adoption and security.",file:"data/H_feedback_loops.json"},free_and_open_source_software__foss:{cat:"Additional Info",title:"💿Free and Open Source Software (FOSS)",desc:"Free and open source software (FOSS) projects connected to Bitcoin.",file:"data/H_free_and_open_source_software__foss.json"},game_theory:{cat:"Additional Info",title:"🏈Game Theory",desc:"Game theory and Bitcoin: Nash equilibrium, prisoner's dilemma, and strategic incentives.",file:"data/H_game_theory.json"},geopolitics___macroeconomics:{cat:"Additional Info",title:"💰Geopolitics & Macroeconomics",desc:"Bitcoin's role in geopolitics: nation-state adoption, reserve currencies, and macro trends.",file:"data/H_geopolitics___macroeconomics.json"},governance:{cat:"Additional Info",title:"🏛Governance",desc:"How Bitcoin is governed — consensus mechanisms, BIPs, and decentralized decision-making.",file:"data/H_governance.json"},ham_radio:{cat:"Additional Info",title:"Ham Radio",desc:"Using Bitcoin without internet — ham radio, mesh networks, and offline transactions.",file:"data/H_ham_radio.json"},human_rights__social_justice_and_freedo:{cat:"Additional Info",title:"🗽Human Rights, Social Justice and Freedom",desc:"Bitcoin as a tool for human rights, social justice, and financial freedom worldwide.",file:"data/H_human_rights__social_justice_and_freedo.json"},improved_incentive_structure:{cat:"Additional Info",title:"✅Improved Incentive Structure",desc:"How Bitcoin's incentive structure improves civilization — aligning individual and collective interests.",file:"data/H_improved_incentive_structure.json"},laws_of_thermodynamics:{cat:"Additional Info",title:"🔥Laws of Thermodynamics",desc:"How Bitcoin follows the laws of thermodynamics — energy, entropy, and proof of work.",file:"data/H_laws_of_thermodynamics.json"},lightning_node:{cat:"Additional Info",title:"⚡ Lightning Node",desc:"Running a Lightning Network node — setup guides, routing, and earning sats.",file:"data/H_lightning_node.json"},lindy_effect:{cat:"Additional Info",title:"👴Lindy Effect",desc:"The Lindy Effect: the longer Bitcoin survives, the longer it will survive.",file:"data/H_lindy_effect.json"},market_cap:{cat:"Additional Info",title:"🧢Market Cap",desc:"Bitcoin's market cap potential — can it reach millions per coin? The math says yes.",file:"data/H_market_cap.json"},math:{cat:"Additional Info",title:"➕Math",desc:"The mathematics of Bitcoin — from SHA-256 to elliptic curves to probability.",file:"data/H_math.json"},mathematics:{cat:"Additional Info",title:"➕Mathematics",desc:"Advanced mathematical concepts underlying Bitcoin's protocol and security.",file:"data/H_mathematics.json"},mev:{cat:"Additional Info",title:"⛏MEV",desc:"MEV (Miner Extractable Value) in Bitcoin — what it is and its implications.",file:"data/H_mev.json"},network_effects:{cat:"Additional Info",title:"🌐Network Effects",desc:"Bitcoin's network effects — why the most adopted network wins and keeps winning.",file:"data/H_network_effects.json"},open_source:{cat:"Additional Info",title:"⭕Open Source",desc:"What free and open source really means — and why it matters for Bitcoin.",file:"data/H_open_source.json"},oracle:{cat:"Additional Info",title:"🔮Oracle",desc:"Oracles in Bitcoin — how external data connects to the blockchain.",file:"data/H_oracle.json"},"orange-pilling":{cat:"Additional Info",title:"🟠Orange-Pilling",desc:"The art of orange-pilling — strategies for explaining Bitcoin to different audiences.",file:"data/H_orange-pilling.json"},ordinals:{cat:"Additional Info",title:"Ordinals",desc:"Bitcoin Ordinals and inscriptions — NFTs on the world's most secure blockchain.",file:"data/H_ordinals.json"},ordinals__nfts_on_bitcoin__and_block_spa:{cat:"Additional Info",title:"Ordinals, NFTs on Bitcoin, and Block Space",desc:"The Ordinals debate: NFTs on Bitcoin, block space economics, and community perspectives.",file:"data/H_ordinals__nfts_on_bitcoin__and_block_spa.json"},"peace_and_anti-war":{cat:"Additional Info",title:"☮Peace and Anti-War",desc:"Can a Bitcoin Standard end wars? The case for Bitcoin as a force for peace.",file:"data/H_peace_and_anti-war.json"},philosophy:{cat:"Additional Info",title:"🍎Philosophy",desc:"The philosophy of Bitcoin — from first principles to existential implications.",file:"data/H_philosophy.json"},politics:{cat:"Additional Info",title:"🏛Politics",desc:"Bitcoin and politics — how Bitcoin intersects with government policy and elections.",file:"data/H_politics.json"},predictions:{cat:"Additional Info",title:"🔮Predictions",desc:"Bitcoin predictions timestamped by the community — bold calls and their outcomes.",file:"data/H_predictions.json"},public_key_vs_private_key:{cat:"Additional Info",title:"🗝Public Key vs Private Key",desc:"Public keys vs. private keys — the cryptographic foundation of Bitcoin ownership.",file:"data/H_public_key_vs_private_key.json"},rbf:{cat:"Additional Info",title:"↔RBF",desc:"Replace-By-Fee (RBF) — how to speed up stuck Bitcoin transactions.",file:"data/H_rbf.json"},"referral-links":{cat:"Referral Links",title:"🔗free-btc-referral-links",desc:"Curated Bitcoin referral links — earn free sats with trusted platforms like River, Fold, and Strike.",file:"data/H_referral-links.json"},risks__threats__attack_vectors__weaknes:{cat:"Additional Info",title:"⚔Risks, Threats, Attack Vectors, Weaknesses, Issues",desc:"Bitcoin's risks, threats, and attack vectors — what could go wrong and why it probably won't.",file:"data/H_risks__threats__attack_vectors__weaknes.json"},rollups:{cat:"Additional Info",title:"🥐Rollups",desc:"Rollups on Bitcoin — scaling and privacy solutions using off-chain computation.",file:"data/H_rollups.json"},sats__or__bits:{cat:"Additional Info",title:'"Sats" or "Bits"?',desc:"The sats vs. bits debate — which denomination should Bitcoin use?",file:"data/H_sats__or__bits.json"},scalability:{cat:"Additional Info",title:"🌐Scalability",desc:"Can Bitcoin scale to serve the world? Layers, Lightning, and the path forward.",file:"data/H_scalability.json"},sidechains:{cat:"Additional Info",title:"♻Sidechains",desc:"Bitcoin sidechains like Liquid — benefits, tradeoffs, and use cases.",file:"data/H_sidechains.json"},simplified_payment_verification__spv:{cat:"Additional Info",title:"✔Simplified Payment Verification (SPV)",desc:"SPV (Simplified Payment Verification) — lightweight Bitcoin verification without a full node.",file:"data/H_simplified_payment_verification__spv.json"},soft_vs_hard_forks:{cat:"Additional Info",title:"🍴Soft vs Hard Forks",desc:"Soft forks vs. hard forks — how Bitcoin upgrades while maintaining consensus.",file:"data/H_soft_vs_hard_forks.json"},softwar:{cat:"Additional Info",title:"Softwar",desc:"Jason Lowery's Softwar thesis — Bitcoin as a non-lethal alternative to physical warfare.",file:"data/H_softwar.json"},stratum_v2:{cat:"Additional Info",title:"🟩Stratum V2",desc:"Stratum V2 — the next-generation mining protocol for better decentralization and efficiency.",file:"data/H_stratum_v2.json"},submarine_swap:{cat:"Additional Info",title:"⛵Submarine Swap",desc:"Submarine swaps — trustlessly moving Bitcoin between on-chain and Lightning.",file:"data/H_submarine_swap.json"},swaps:{cat:"Additional Info",title:"↔Swaps",desc:"How to swap between on-chain Bitcoin and Lightning — tools, techniques, and protocols.",file:"data/H_swaps.json"},ta_tips:{cat:"Additional Info",title:"📈TA Tips",desc:"Technical analysis tips for Bitcoin — chart patterns, indicators, and trading education.",file:"data/H_ta_tips.json"},tail_emission:{cat:"Additional Info",title:"🐈Tail Emission",desc:"The tail emission debate — should Bitcoin ever have perpetual block rewards?",file:"data/H_tail_emission.json"},taproot:{cat:"Additional Info",title:"🧰Taproot",desc:"Taproot: Bitcoin's latest major upgrade — Schnorr signatures, script improvements, and privacy.",file:"data/H_taproot.json"},taro:{cat:"Additional Info",title:"🥕Taro",desc:"Taro (now Taproot Assets) — issuing assets on the Bitcoin and Lightning networks.",file:"data/H_taro.json"},the_future:{cat:"Additional Info",title:"🔮The Future",desc:"How Bitcoin could change the future — hyperbitcoinization, global adoption, and beyond.",file:"data/H_the_future.json"},time:{cat:"Additional Info",title:"⏰Time",desc:"How Bitcoin keeps time — block time, timestamps, and the decentralized clock.",file:"data/H_time.json"},time_preference:{cat:"Additional Info",title:"🕑Time Preference",desc:"Time preference: how sound money encourages long-term thinking and civilization building.",file:"data/H_time_preference.json"},toxicity:{cat:"Additional Info",title:"☣ Toxicity",desc:"Is Bitcoin community toxicity real? Or is it integrity? The debate and its meaning.",file:"data/H_toxicity.json"},transaction_fees:{cat:"Additional Info",title:"💲Transaction Fees",desc:"Bitcoin transaction fees — how they work, fee markets, and long-term sustainability.",file:"data/H_transaction_fees.json"},unpopular_opinions:{cat:"Additional Info",title:"💀Unpopular Opinions",desc:"Unpopular opinions in the Bitcoin space — controversial takes and honest debates.",file:"data/H_unpopular_opinions.json"},utxos:{cat:"Additional Info",title:"🕳UTXOs",desc:"UTXOs (Unspent Transaction Outputs) — the fundamental building block of Bitcoin transactions.",file:"data/H_utxos.json"},vbyte:{cat:"Additional Info",title:"🏋vByte",desc:"Virtual bytes (vBytes) — how Bitcoin measures transaction weight for fee calculation.",file:"data/H_vbyte.json"},"apps-tools":{cat:"Resources",title:"🍎apps-tools-services-models",desc:"Bitcoin apps, tools, services, and platforms — everything you need to use Bitcoin daily.",file:"data/R_apps-tools.json"},"art-inspiration":{cat:"Resources",title:"🤩art-inspiration-motivation",desc:"Bitcoin art, inspiration, and motivational content from the community.",file:"data/R_art-inspiration.json"},"articles-threads":{cat:"Resources",title:"📃articles-threads",desc:"The best Bitcoin articles and Twitter threads — curated deep dives into every aspect of Bitcoin.",file:"data/R_articles-threads.json"},books:{cat:"Resources",title:"📚books",desc:"The essential Bitcoin reading list: The Bitcoin Standard, 21 Lessons, Mastering Bitcoin, and more.",file:"data/R_books.json"},charts:{cat:"Resources",title:"📊charts",desc:"Bitcoin price charts, on-chain analytics, stock-to-flow, and data visualizations.",file:"data/R_charts.json"},curriculum:{cat:"Resources",title:"🎓curriculum-presentations",desc:"Bitcoin education curriculum and presentations for teachers and students.",file:"data/R_curriculum.json"},"faq-glossary":{cat:"Resources",title:"❓faq-glossary-search-ai-calendar",desc:"Bitcoin FAQ, glossary of terms, and quick answers to common questions.",file:"data/R_faq-glossary.json"},"fun-facts":{cat:"Resources",title:"🎉fun-facts",desc:"Mind-blowing Bitcoin trivia: Pizza Day, Satoshi's birthday code, lost coins, and 200+ amazing facts.",file:"data/R_fun-facts.json"},games:{cat:"Resources",title:"🎮games",desc:"Bitcoin-themed games and gamified learning experiences.",file:"data/R_games.json"},"giga-chad":{cat:"Resources",title:"👑giga-chad",desc:"Michael Saylor, MicroStrategy, and the corporate Bitcoin movement.",file:"data/R_giga-chad.json"},graphics:{cat:"Resources",title:"🎨graphics",desc:"Bitcoin infographics, charts, diagrams, and visual explanations.",file:"data/R_graphics.json"},hardware:{cat:"Resources",title:"💻hardware",desc:"Bitcoin hardware: mining rigs, hardware wallets, nodes, and open-source projects like Bitaxe.",file:"data/R_hardware.json"},health:{cat:"Resources",title:"🥩health",desc:"Bitcoin and health: low time preference living, breaking free from the system.",file:"data/R_health.json"},history:{cat:"Resources",title:"📆history",desc:"The complete history of Bitcoin — from the cypherpunks to today.",file:"data/R_history.json"},"informational-sites":{cat:"Resources",title:"📃informational-sites-courses-workshops-newsletters-projects-communities-meetups-conferences",desc:"Bitcoin dashboards, tools, courses, newsletters, communities, and educational websites.",file:"data/R_informational-sites.json"},international:{cat:"Resources",title:"🌍international",desc:"Bitcoin resources in multiple languages and global adoption stories.",file:"data/R_international.json"},"jobs-earn":{cat:"Resources",title:"👷job-postings-employer-info-entrepreneurship-earn-bitcoin-stack-sats",desc:"Bitcoin job boards, entrepreneurship resources, and ways to earn sats.",file:"data/R_jobs-earn.json"},"memes-funny":{cat:"Resources",title:"😂memes-funny",desc:"The best Bitcoin memes, jokes, and humor from the community. Laugh while you learn.",file:"data/R_memes-funny.json"},"misconceptions-fud":{cat:"Resources",title:"🤡common-misconceptions-fud-debunked",desc:"Every Bitcoin myth debunked: too volatile, wastes energy, used by criminals, no intrinsic value — all wrong.",file:"data/R_misconceptions-fud.json"},"movies-tv":{cat:"Resources",title:"🎬movies-tv-documentaries",desc:"Bitcoin documentaries, films, and TV appearances. From The Big Short to Bitcoin-specific docs.",file:"data/R_movies-tv.json"},music:{cat:"Resources",title:"🎵music",desc:"Bitcoin-inspired music, songs, and audio content from the community.",file:"data/R_music.json"},"news-adoption":{cat:"Resources",title:"📰news-adoption",desc:"Latest Bitcoin news, adoption milestones, and real-world usage stories.",file:"data/R_news-adoption.json"},nostr:{cat:"Resources",title:"💜nostr",desc:"Nostr: the decentralized social protocol Bitcoiners are building on. Social media you can't be censored from.",file:"data/R_nostr.json"},"one-stop-shop":{cat:"Resources",title:"🛑one-stop-shop",desc:"The best resources to understand Bitcoin's value as fast as possible. Start here if you're new.",file:"data/R_one-stop-shop.json"},podcasts:{cat:"Resources",title:"🔊podcasts",desc:"Top Bitcoin podcasts: Bitcoin Audible, What Bitcoin Did, Stephan Livera, and more.",file:"data/R_podcasts.json"},"poems-stories":{cat:"Resources",title:"📒poems-stories-jokes",desc:"Bitcoin poetry, short stories, jokes, and creative writing from the community.",file:"data/R_poems-stories.json"},"projects-diy":{cat:"Resources",title:"🔧projects-diy",desc:"DIY Bitcoin projects: build your own node, Lightning ATM, and more.",file:"data/R_projects-diy.json"},"research-theses":{cat:"Resources",title:"✍research-theses",desc:"Academic research papers and theses on Bitcoin, monetary policy, and cryptographic systems.",file:"data/R_research-theses.json"},"satoshi-nakamoto":{cat:"Resources",title:"🦸satoshi-nakamoto",desc:"The mystery of Bitcoin's creator: who was Satoshi Nakamoto? The evidence, theories, and legacy.",file:"data/R_satoshi-nakamoto.json"},"social-media":{cat:"Resources",title:"👍social-media-proponents",desc:"Bitcoin Twitter/X accounts, influencers, and social media communities to follow.",file:"data/R_social-media.json"},"swag-merch":{cat:"Resources",title:"👕swag-merch-businesses-spend",desc:"Bitcoin merchandise, clothing, and businesses where you can spend your sats.",file:"data/R_swag-merch.json"},videos:{cat:"Resources",title:"📺videos",desc:"Must-watch Bitcoin lectures, talks, and presentations from Andreas Antonopoulos, Michael Saylor, and others.",file:"data/R_videos.json"},web5:{cat:"Resources",title:"5⃣web5",desc:"Web5 and decentralized web technologies built on Bitcoin.",file:"data/R_web5.json"}},_SAFE_COVER_PLACEHOLDER="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjMWUxYTJlIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZpbGw9IiNmNzkzMWEiIGZvbnQtc2l6ZT0iMjAiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj7wnY61PC90ZXh0Pjwvc3ZnPg==";function _safeCover(e){if(!e||"string"!=typeof e||""===e.trim())return _SAFE_COVER_PLACEHOLDER;var t=e.trim(),o=t.toLowerCase();return/^(javascript|data:text\/html|vbscript|blob):/i.test(o)?(console.warn("[XSS BLOCKED] Malicious image URL scheme rejected:",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER):/^(https:\/\/|data:image\/)/i.test(t)?t.replace(/["'<>\\]/g,""):(console.warn("[XSS BLOCKED] Invalid URL scheme (must be https:// or data:image/):",t.substring(0,50)),_SAFE_COVER_PLACEHOLDER)}function safeJSON(e,t){try{var o=localStorage.getItem(e);return null===o?t:JSON.parse(o)}catch(o){console.warn('safeJSON: corrupted data for key "'+e+'", resetting.',o);try{localStorage.removeItem(e)}catch(e){}return t}}function escapeHtml(e){if(!e)return"";var t=document.createElement("div");return t.appendChild(document.createTextNode(e)),t.innerHTML}function sanitizeUrl(e){return e?(e=e.trim(),/^(javascript|data|vbscript|blob):/i.test(e)?"":e):""}function timeAgo(e){if(!e)return"";var t;t=e.toDate?e.toDate():e instanceof Date?e:new Date(e);var o=Math.floor((Date.now()-t.getTime())/1e3);return o<60?"just now":o<3600?Math.floor(o/60)+"m ago":o<86400?Math.floor(o/3600)+"h ago":o<604800?Math.floor(o/86400)+"d ago":t.toLocaleDateString()}function isPremium(){return void 0!==currentUser&¤tUser&¤tUser.premium&&!0===currentUser.premium.active}function getSatCap(){return isPremium()?21e3:1e4}!function(){var e=[],t=[];window.registerInterval=function(t,o,n){var i=setInterval(t,o);return e.push({id:i,fn:t,ms:o,name:n||"unnamed"}),i},document.addEventListener("visibilitychange",function(){document.hidden?(e.forEach(function(e){clearInterval(e.id)}),t=e.slice(),e=[]):(t.forEach(function(t){t.fn(),t.id=setInterval(t.fn,t.ms),e.push(t)}),t=[])})}(),window._factionNameStyle=function(e){return"cyber_hornets"===e?"color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;font-weight:700;":"honey_badgers"===e?"color:#1a1a1a;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff;font-weight:700;":""};var PREMIUM_CONFIG={FREE_SAT_CAP:1e4,PREMIUM_SAT_CAP:21e3,FREE_SPINS:1,PREMIUM_SPINS:3,MONTHLY_PRICE_USD:4.99,YEARLY_PRICE_USD:42,LIFETIME_SATS:21e4,TIER_NAME:"Bitcoin Maxi"};const FIREBASE_CONFIG={apiKey:"AIzaSyCkUGX2KWaVGmSQXpYJhWDxF_BSiHRX6SM",authDomain:"btc-archive-test.firebaseapp.com",projectId:"btc-archive-test",storageBucket:"btc-archive-test.firebasestorage.app",messagingSenderId:"60810625669",appId:"1:60810625669:web:ea4dacd55333e41429dfec",measurementId:"G-7C2FKDJ8E4"},LEVELS=[{name:"Normie",emoji:"🟢",min:0},{name:"Curious",emoji:"🔵",min:10},{name:"Pleb",emoji:"🟠",min:144},{name:"Pleb II",emoji:"🟠🟠",min:170},{name:"Pleb III",emoji:"🟠🟠🟠",min:256},{name:"Stacker",emoji:"📦",min:500},{name:"Stacker II",emoji:"📦📦",min:1913},{name:"Stacker III",emoji:"📦📦📦",min:2016},{name:"Maxi",emoji:"🔥",min:2140},{name:"Maxi II",emoji:"🔥🔥",min:6102},{name:"Maxi III",emoji:"🔥🔥🔥",min:8888},{name:"Papa John",emoji:"🍕",min:1e4},{name:"Full Node",emoji:"🖥️",min:18333},{name:"Whale",emoji:"🐋",min:5e4},{name:"Sovereign",emoji:"🏴",min:1e5},{name:"Cypherpunk",emoji:"🔒",min:133337},{name:"Satoshi",emoji:"👑",min:21e4}];function _renderQRCode(e,t,o){if(window.qrcode&&"function"==typeof window.qrcode)_drawQR(e,t,o);else{var n=document.createElement("script");n.src="https://cdnjs.cloudflare.com/ajax/libs/qrcode-generator/1.4.4/qrcode.min.js",n.integrity="sha384-mZT2gIty7ZDdOGkxfP6joZcYdMW1Jvj9dRlfpTmaJAKKXTqzygtB22k7FLe+KZC1",n.crossOrigin="anonymous",n.onload=function(){_drawQR(e,t,o)},n.onerror=function(){e.innerHTML='
    '+t+"
    "},document.head.appendChild(n)}}function _drawQR(e,t,o){try{var n=qrcode(0,"M");n.addData(t),n.make();var i=document.createElement("img");i.src=n.createDataURL(6,4),i.width=o,i.height=o,i.alt="QR Code",i.style.cssText="border-radius:8px;image-rendering:pixelated;",e.innerHTML="",e.appendChild(i)}catch(t){e.innerHTML='
    QR generation failed
    '}}const POINTS={visit:5,openChannel:10,readTime:15,explore10:50,streak:100};let db,auth,currentUser=null,signInAttempts=0,signInLockout=0,redirectResultResolved=!1,redirectResultPromise=Promise.resolve(null),sessionChannels=new Set,readTimer=null,readSeconds=0,lastReadAward=0,rankingReady=!1,allTimeChannels=new Set,lastLevelName="",lastLevelMin=0,levelUpReady=!1;function initRanking(){try{firebase.initializeApp(FIREBASE_CONFIG),db=firebase.firestore(),db.enablePersistence({synchronizeTabs:!0}).catch(function(e){"failed-precondition"!==e.code&&"unimplemented"!==e.code&&console.log("Persistence error:",e.code)}),auth=firebase.auth(),auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).catch(function(){}),auth.isSignInWithEmailLink(window.location.href)&&handleEmailSignIn(),redirectResultPromise=auth.getRedirectResult().then(async function(e){if(redirectResultResolved=!0,console.log("[Auth] getRedirectResult:",e?e.user?e.user.uid:"no user":"null"),!e||!e.user)return null;const t=e.user;sessionStorage.setItem("btc_redirect_auth","1");const o=await db.collection("users").doc(t.uid).get(),n=localStorage.getItem("btc_anon_uid");let i=null;try{i=JSON.parse(localStorage.getItem("btc_anon_data"))}catch(e){}if(localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),o.exists){if(i&&!o.data().mergedAnon){await o.ref.update({mergedAnon:!0});var a=Math.min(i.points||0,500);a>0&&"function"==typeof awardPoints&&await awardPoints(a,"🔗 Anonymous progress merged")}}else{i?(i.email=t.email||"",i.username||(i.username=t.displayName||"Bitcoiner"),await db.collection("users").doc(t.uid).set(i)):await db.collection("users").doc(t.uid).set({username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(t.uid)}if(n&&n!==t.uid)try{await db.collection("users").doc(n).delete()}catch(e){}return loadUser(t.uid),updateAuthButton(),"function"==typeof hideUsernamePrompt&&hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(t.displayName||t.email||"Bitcoiner")),t}).catch(function(e){return redirectResultResolved=!0,"auth/popup-closed-by-user"!==e.code&&console.log("Redirect result error:",e),null});let o=!0,n=auth.isSignInWithEmailLink(window.location.href);var e=localStorage.getItem("btc_pwa_auth_pending"),t=!!localStorage.getItem("btc_anon_uid")||"1"===sessionStorage.getItem("btc_redirect_pending")||!!e;e&&(localStorage.removeItem("btc_pwa_auth_pending"),console.log("[Auth] PWA auth pending detected")),t&&console.log("[Auth] Detected pending redirect return"),auth.onAuthStateChanged(e=>{if(console.log("[Auth] onAuthStateChanged:",e?e.isAnonymous?"anon:"+e.uid:"real:"+e.uid:"null","firstEvent:",o,"pendingRedirect:",t),e&&!e.isAnonymous){var i=localStorage.getItem("btc_last_auth_uid");i&&i!==e.uid&&(console.log("[Auth] Account switch detected:",i,"->",e.uid,"— clearing localStorage"),clearUserLocalStorage()),localStorage.setItem("btc_last_auth_uid",e.uid)}if(o){if(o=!1,n)return;if(e&&!e.isAnonymous)console.log("[Auth] Real user on first event:",e.uid),sessionStorage.removeItem("btc_redirect_auth"),loadUser(e.uid).then(function(){currentUser&¤tUser.username&&setTimeout(function(){"function"==typeof showToast&&showToast("👋 Welcome back, "+escapeHtml(currentUser.username||"")+"!")},2e3)}).catch(function(){});else if(e&&e.isAnonymous)if(t){console.log("[Auth] Anon user but pending redirect — waiting 8s for real auth...");var a=setTimeout(function(){auth.currentUser&&!auth.currentUser.isAnonymous?(console.log("[Auth] Real user appeared after wait:",auth.currentUser.uid),loadUser(auth.currentUser.uid)):(console.log("[Auth] No real user after 8s — loading anon"),loadUserLocal(e.uid)),localStorage.removeItem("btc_anon_uid"),localStorage.removeItem("btc_anon_data"),localStorage.removeItem("btc_pwa_auth_pending"),sessionStorage.removeItem("btc_redirect_pending")},8e3);redirectResultPromise.then(function(e){e&&clearTimeout(a)})}else loadUserLocal(e.uid);else if(redirectResultResolved&&!t)auth.signInAnonymously().then(()=>{});else{var r=setTimeout(function(){auth.currentUser||(console.log("[Auth] 10s timeout with no user — going anonymous"),localStorage.removeItem("btc_pwa_auth_pending"),auth.signInAnonymously().then(()=>{}))},1e4);redirectResultPromise.then(function(e){clearTimeout(r),e||auth.currentUser||auth.signInAnonymously().then(()=>{})})}}else if(e){if(currentUser&¤tUser.uid===e.uid)return void updateAuthButton();e.isAnonymous?loadUserLocal(e.uid):loadUser(e.uid)}else currentUser=null,redirectResultResolved?auth.signInAnonymously().then(()=>{}):redirectResultPromise.then(function(e){e||auth.currentUser||auth.signInAnonymously().then(()=>{})})})}catch(e){console.error("Ranking init error:",e),setTimeout(function(){"function"==typeof showToast&&showToast("⚠️ Init error: "+(e.message||e))},2e3)}}async function handleEmailSignIn(){var e=window.location.href;let t=null;var o=new URLSearchParams(window.location.search);return o.get("signin_email")&&(t=decodeURIComponent(o.get("signin_email"))),t||(t=localStorage.getItem("btc_signin_email")),t?finishEmailSignIn(t,e):new Promise(function(o){var n=document.createElement("div");n.id="emailConfirmOverlay",n.style.cssText="position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:20px;",n.innerHTML='
    📧
    Confirm Your Email
    It looks like you opened this link on a different device. Enter the email you used to sign up:
    Cancel
    ',document.body.appendChild(n);var i=document.getElementById("crossDeviceEmail");function a(){var a=i.value.trim().toLowerCase();a&&a.includes("@")?(n.remove(),t=a,o(finishEmailSignIn(t,e))):"function"==typeof showToast&&showToast("Please enter a valid email")}document.getElementById("crossDeviceSubmit").onclick=a,i.addEventListener("keydown",function(e){"Enter"===e.key&&a()}),setTimeout(function(){i.focus()},100)})}async function finishEmailSignIn(e,t){if(e)try{const i=auth.currentUser;let a=null,r=null;if(i&&i.isAnonymous){a=i.uid,console.log("[Email Sign-In] Anon user found:",a);try{const e=await db.collection("users").doc(a).get();e.exists&&(r=e.data()),console.log("[Email Sign-In] Anon data loaded:",!!r)}catch(e){console.log("[Email Sign-In] Anon data load failed (non-fatal):",e.code)}}console.log("[Email Sign-In] Starting signInWithEmailLink for:",e);const s=await auth.signInWithEmailLink(e,t);console.log("[Email Sign-In] Sign-in result:",s.user?s.user.uid:"no user"),localStorage.removeItem("btc_signin_email");const l=s.user.uid;console.log("[Email Sign-In] Waiting for auth token propagation...");for(var o=0;o<5;o++){await new Promise(e=>setTimeout(e,200));try{await db.collection("users").doc(l).get(),console.log("[Email Sign-In] Firestore auth ready after",200*(o+1),"ms");break}catch(e){if("permission-denied"===e.code){console.log("[Email Sign-In] Permission denied on retry "+(o+1)+", waiting for token propagation...");continue}throw e}}console.log("[Email Sign-In] Fetching existing user doc:",l);const c=await db.collection("users").doc(l).get();if(console.log("[Email Sign-In] Existing doc exists:",c.exists),!c.exists&&r)r.email=e,await db.collection("users").doc(l).set(r);else if(c.exists&&r){const e=c.data();var n=Math.min(r.points||0,500);!e.mergedAnon&&n>(e.points||0)&&await c.ref.update({points:Math.max(n,e.points||0),channelsVisited:Math.max(r.channelsVisited||0,e.channelsVisited||0),totalVisits:(e.totalVisits||0)+(r.totalVisits||0),mergedAnon:!0})}if(a&&a!==l)try{await db.collection("users").doc(a).delete()}catch(e){}window.history.replaceState(null,"",window.location.pathname+window.location.hash);const d=localStorage.getItem("btc_pending_username"),u=(localStorage.getItem("btc_pending_email"),localStorage.getItem("btc_pending_ln_address")||"");if(d&&!c.exists){const t={username:d,email:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};u&&(t.lightning=u,t.lightningAddress=u),await db.collection("users").doc(l).set(t);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}"function"==typeof attachReferral&&attachReferral(l)}localStorage.removeItem("btc_pending_username"),localStorage.removeItem("btc_pending_email"),localStorage.removeItem("btc_pending_ln_address"),localStorage.removeItem("btc_wallet_enc"),localStorage.removeItem("btc_wallet_addrs"),loadUser(l),showToast("✅ Email verified! Signed in as "+escapeHtml(d||e))}catch(e){console.error("[Email Sign-In] Full error:",e.code,e.message,e.stack),"permission-denied"===e.code?(showToast("⚠️ Permission denied. Try refreshing the page or clearing cache."),console.error("[Email Sign-In] Firestore permission denied - auth state may not be ready")):"auth/invalid-action-code"===e.code||"auth/expired-action-code"===e.code?showToast("⚠️ This sign-in link has expired. Please request a new one."):"auth/invalid-email"===e.code?showToast("⚠️ Email mismatch. Make sure you enter the same email you signed up with."):showToast("Sign-in error ("+(e.code||"unknown")+"). Please try again."),window.history.replaceState(null,"",window.location.pathname+window.location.hash),auth.signInAnonymously()}else showToast("⚠️ Could not determine your email. Please sign in again from the app.")}var GOOGLE_CLIENT_ID="1055248200518-jcn5efjp7vhk0vm8cbmj4mfsgc0edkga.apps.googleusercontent.com";async function signInWithGIS(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){var n=e.anonUid,i=e.anonData;google.accounts.id.initialize({client_id:GOOGLE_CLIENT_ID,callback:async function(e){if(e&&e.credential)try{var a=firebase.auth.GoogleAuthProvider.credential(e.credential),r=await auth.signInWithCredential(a);try{google.accounts.id.cancel()}catch(e){}var s=document.getElementById("gsi-temp-btn");if(s){var l=s.closest('div[style*="position:fixed"]');l?l.remove():s.remove()}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()}),await _handleSignInResultGlobal(r.user,n,i),t(r.user)}catch(e){o(e)}else o(new Error("No credential received"))},auto_select:!1,cancel_on_tap_outside:!0,context:"signin",ux_mode:"popup"}),google.accounts.id.prompt(function(e){(e.isNotDisplayed()||e.isSkippedMoment())&&(console.log("[Auth] One Tap not shown, falling back to Firebase popup"),o(new Error("One Tap unavailable")))})})}function showPWAAuthFallback(e){var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='
    🔐
    '+e+' Sign-In
    '+e+' sign-in requires a browser window. Open the site in your browser to sign in.
    ',document.body.appendChild(t)}window.signInWithGoogle=async function(){if(!/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||"")&&"undefined"!=typeof google&&google.accounts&&google.accounts.id)try{return void await signInWithGIS()}catch(e){console.warn("[Auth] GIS failed, falling back to Firebase popup:",e);try{google.accounts.id.cancel()}catch(e){}document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(e){e.remove()})}await signInWithProvider(new firebase.auth.GoogleAuthProvider)},window.signInWithTwitter=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.TwitterAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("Twitter")}await signInWithProvider(new firebase.auth.TwitterAuthProvider)},window.signInWithGithub=async function(){if(window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone)try{var e=await _saveAnonDataGlobal(),t=await auth.signInWithPopup(new firebase.auth.GithubAuthProvider);return void await _handleSignInResultGlobal(t.user,e.anonUid,e.anonData)}catch(e){if("auth/popup-closed-by-user"===e.code)return;return void showPWAAuthFallback("GitHub")}await signInWithProvider(new firebase.auth.GithubAuthProvider)};var FB_APP_ID="1400842698021858";async function signInWithFBSDK(){var e=await _saveAnonDataGlobal();return new Promise(function(t,o){FB.login(function(n){if(n.authResponse){var i=firebase.auth.FacebookAuthProvider.credential(n.authResponse.accessToken);auth.signInWithCredential(i).then(async function(o){await _handleSignInResultGlobal(o.user,e.anonUid,e.anonData),t(o.user)}).catch(o)}else o(new Error("Facebook login cancelled"))},{scope:"email,public_profile"})})}function checkRateLimit(){const e=Date.now();return e5&&(signInLockout=e+6e4,signInAttempts=0,showToast("⏳ Too many attempts. Please wait 60 seconds."),1)))}function isInAppBrowser(){var e=navigator.userAgent||"";return/FBAN|FBAV|Instagram|Twitter|Line\/|Snapchat|BytedanceWebview|musical_ly|TikTok|Weibo|MicroMessenger|LinkedInApp|Telegram/i.test(e)}async function _saveAnonDataGlobal(){var e=auth.currentUser,t=null,o=null;if(e&&e.isAnonymous){t=e.uid;try{var n=await db.collection("users").doc(t).get();n.exists&&(o=n.data())}catch(e){}}return{anonUid:t,anonData:o}}async function _handleSignInResultGlobal(e,t,o){var n=localStorage.getItem("btc_pending_ln_address")||"";localStorage.removeItem("btc_pending_ln_address");var i=await db.collection("users").doc(e.uid).get();if(i.exists){if(n&&!i.data().lightningAddress&&!i.data().lightning)try{await i.ref.update({lightning:n,lightningAddress:n})}catch(e){}if(o){var a=i.data(),r=Math.min(o.points||0,500);!a.mergedAnon&&r>(a.points||0)&&await i.ref.update({points:Math.max(r,a.points||0),channelsVisited:Math.max(o.channelsVisited||0,a.channelsVisited||0),totalVisits:(a.totalVisits||0)+(o.totalVisits||0),mergedAnon:!0})}!i.data().email&&e.email&&await i.ref.update({email:e.email})}else if(o)o.email=e.email||"",o.username||(o.username=e.displayName||"Bitcoiner"),n&&(o.lightning=n,o.lightningAddress=n),await db.collection("users").doc(e.uid).set(o);else{var s={username:e.displayName||"Bitcoiner",email:e.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};n&&(s.lightning=n,s.lightningAddress=n),await db.collection("users").doc(e.uid).set(s)}if(t&&t!==e.uid)try{await db.collection("users").doc(t).delete()}catch(e){}if(loadUser(e.uid),i.exists)hideUsernamePrompt(),showToast("✅ Signed in as "+escapeHtml(e.displayName||e.email||"Bitcoiner"));else{"function"==typeof attachReferral&&attachReferral(e.uid),hideUsernamePrompt(),showToast("✅ Welcome, "+escapeHtml(e.displayName||e.email||"Bitcoiner")+"!");try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},1500)}catch(e){}}}async function signInWithProvider(e){if(checkRateLimit()){if(isInAppBrowser()){var t=navigator.userAgent||"",o=/iPhone|iPad/i.test(t)?'Tap the share icon (↑) → "Open in Safari"':/Android/i.test(t)?'Tap ⋮ (menu) → "Open in Browser"':"Open this page in your default browser",n=document.createElement("div");return n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.9);padding:20px;",n.innerHTML='
    🌐

    Open in Browser

    Sign-in doesn\'t work inside apps. '+o+'

    ',void document.body.appendChild(n)}var i=/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent||""),a=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(i||a)try{showToast("⏳ Opening sign-in...");const t=auth.currentUser;t&&t.isAnonymous&&(localStorage.setItem("btc_anon_uid",t.uid),db.collection("users").doc(t.uid).get().then(function(e){e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}).catch(function(){}));try{const t=await auth.signInWithPopup(e);if(t&&t.user){const{anonUid:e,anonData:o}=await s();return void await r(t.user,e,o)}}catch(t){return console.log("[Auth] Mobile popup failed, falling back to redirect:",t.code),sessionStorage.setItem("btc_redirect_pending","1"),localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}}catch(e){return console.error("Mobile sign-in error:",e),void showToast("Sign-in failed: "+(e.message||"Unknown error"))}try{const{anonUid:t,anonData:o}=await s(),n=await auth.signInWithPopup(e);await r(n.user,t,o)}catch(t){if(console.error("Provider sign-in error:",t.code,t.message,t),"auth/popup-blocked"===t.code||"auth/cancelled-popup-request"===t.code||"auth/popup-closed-by-user"===t.code||"auth/internal-error"===t.code){try{showToast("⏳ Opening sign-in page...");const t=auth.currentUser;if(t&&t.isAnonymous){localStorage.setItem("btc_anon_uid",t.uid);try{const e=await db.collection("users").doc(t.uid).get();e.exists&&localStorage.setItem("btc_anon_data",JSON.stringify(e.data()))}catch(e){}}return localStorage.setItem("btc_pwa_auth_pending","1"),void await auth.signInWithRedirect(e)}catch(e){console.error("Redirect fallback also failed:",e),showToast("Sign-in failed. Please try a different browser.")}return}if("auth/popup-closed-by-user"===t.code)return;"auth/unauthorized-domain"===t.code?showToast("⚠️ This domain is not authorized for sign-in. Please contact support."):"auth/operation-not-allowed"===t.code?showToast("⚠️ This sign-in method is not enabled. Try a different option."):"auth/account-exists-with-different-credential"===t.code?showToast("⚠️ An account with this email exists using a different sign-in method. Try another option."):"auth/network-request-failed"===t.code?showToast("⚠️ Network error. Check your connection and try again."):showToast("Sign-in error ("+(t.code||"unknown")+"). Please try again.")}}async function r(e,t,o){return _handleSignInResultGlobal(e,t,o)}async function s(){return _saveAnonDataGlobal()}}async function sendMagicLink(e){const t={url:window.location.origin+window.location.pathname+"?signin_email="+encodeURIComponent(e),handleCodeInApp:!0};try{return await auth.sendSignInLinkToEmail(e,t),localStorage.setItem("btc_signin_email",e),!0}catch(e){return console.log("Magic link error:",e),!1}}function loadUserLocal(e){var t=parseInt(localStorage.getItem("btc_points")||"0"),o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");currentUser={uid:e,points:t,channelsVisited:o.length,readChannels:o,totalVisits:parseInt(localStorage.getItem("btc_total_visits")||"1"),streak:parseInt(localStorage.getItem("btc_streak")||"0"),lastVisit:localStorage.getItem("btc_last_visit")||"",_isLocal:!0},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,restoreVisitedUI(),updateRankUI(),_checkCapOnLoad(),updateAuthButton(),"function"==typeof renderProgressRings&&renderProgressRings(),"function"==typeof renderExplorationMap&&renderExplorationMap(),startReadTimer()}async function loadUser(e,t){const o=t||await db.collection("users").doc(e).get();if(o.exists){currentUser={uid:e,...o.data()},currentUser.visitedChannelsList&¤tUser.visitedChannelsList.forEach(e=>allTimeChannels.add(e));const t=auth.currentUser&&!auth.currentUser.isAnonymous;var n=[...new Set([...Array.isArray(currentUser.visitedChannelsList)?currentUser.visitedChannelsList:[],...Array.isArray(currentUser.readChannels)?currentUser.readChannels:[]])];if(n.length>0){if(t)localStorage.setItem("btc_visited_channels",JSON.stringify(n));else{let e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=[...new Set([...e,...n])];localStorage.setItem("btc_visited_channels",JSON.stringify(t))}restoreVisitedUI()}else t&&(localStorage.setItem("btc_visited_channels","[]"),restoreVisitedUI());if(currentUser.favorites){if(t)localStorage.setItem("btc_favs",JSON.stringify(currentUser.favorites));else{let e=JSON.parse(localStorage.getItem("btc_favs")||"[]"),t=[...new Set([...e,...currentUser.favorites])];localStorage.setItem("btc_favs",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else t&&(localStorage.setItem("btc_favs","[]"),"function"==typeof renderFavs&&renderFavs());if(currentUser.bookmarks){if(t)localStorage.setItem("btc_bookmarks",JSON.stringify(currentUser.bookmarks));else{let e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]"),t=currentUser.bookmarks.concat(e.filter(function(e){return!currentUser.bookmarks.some(function(t){return t.channel===e.channel&&t.idx===e.idx})}));localStorage.setItem("btc_bookmarks",JSON.stringify(t))}"function"==typeof renderFavs&&renderFavs()}else if(t){var i=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");i.length>0&&db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({bookmarks:i}).catch(function(){})}if(currentUser.username&&localStorage.setItem("btc_username",currentUser.username),currentUser.streak>0&&!currentUser.bestStreak&&(currentUser.bestStreak=currentUser.streak),rankingReady=!0,updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),awardVisitPoints(),startReadTimer(),auth.currentUser.isAnonymous||db.collection("users").doc(e).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),t){if(currentUser.hiddenBadges){var a=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),r=[...new Set([...a,...currentUser.hiddenBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(r))}if(currentUser.donationBadges&¤tUser.donationBadges.length>0){var s=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),l=[...new Set([...s,...currentUser.donationBadges])];localStorage.setItem("btc_hidden_badges",JSON.stringify(l))}if(currentUser.visibleBadges){var c=JSON.parse(localStorage.getItem("btc_badges")||"[]"),d=[...new Set([...c,...currentUser.visibleBadges])];localStorage.setItem("btc_badges",JSON.stringify(d))}if(currentUser.spinClosetItems){var u=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]"),p=[...new Set([...u,...currentUser.spinClosetItems])];localStorage.setItem("btc_spin_closet_items",JSON.stringify(p))}if(currentUser.scholarPassed&&localStorage.setItem("btc_scholar_passed","true"),currentUser.nachoMilestones&&localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(currentUser.nachoMilestones)),currentUser.celebratedState){var h=currentUser.celebratedState;h.nachoMilestones&&localStorage.setItem("btc_nacho_milestones",JSON.stringify(h.nachoMilestones)),h.nachoCatComplete&&localStorage.setItem("btc_nacho_cat_complete",JSON.stringify(h.nachoCatComplete)),h.nachoLevelCelebrated&&localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(h.nachoLevelCelebrated)),h.nachoItemsNotified&&localStorage.setItem("btc_nacho_items_notified",JSON.stringify(h.nachoItemsNotified))}if(currentUser.nachoInteractions){var m=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),g=currentUser.nachoInteractions||0;localStorage.setItem("btc_nacho_interactions",Math.max(m,g).toString())}if(currentUser.nachoQuestions){var f=parseInt(localStorage.getItem("btc_nacho_questions")||"0"),y=currentUser.nachoQuestions||0;localStorage.setItem("btc_nacho_questions",Math.max(f,y).toString())}}if(localStorage.setItem("btc_pvp_wins",String(currentUser.pvpWins||0)),localStorage.setItem("btc_pvp_losses",String(currentUser.pvpLosses||0)),currentUser.nachoNickname&&(localStorage.setItem("btc_nacho_nickname",currentUser.nachoNickname),"function"==typeof updateNachoNameUI&&updateNachoNameUI(currentUser.nachoNickname)),t){if(currentUser.lastSpinDate){var b=localStorage.getItem("btc_last_spin")||"";currentUser.lastSpinDate>b&&localStorage.setItem("btc_last_spin",currentUser.lastSpinDate),"function"==typeof updateSpinBanner&&updateSpinBanner()}if(currentUser.prediction&&(localStorage.getItem("btc_prediction")||localStorage.setItem("btc_prediction",JSON.stringify(currentUser.prediction))),currentUser.nachoStoryDays&&Array.isArray(currentUser.nachoStoryDays)){var v=safeJSON("btc_nacho_story_days",[]);currentUser.nachoStoryDays.length>v.length&&localStorage.setItem("btc_nacho_story_days",JSON.stringify(currentUser.nachoStoryDays))}if(currentUser.nachoStoryProgress){var w=parseInt(localStorage.getItem("btc_nacho_story_highest")||"0");currentUser.nachoStoryProgress>w&&localStorage.setItem("btc_nacho_story_highest",currentUser.nachoStoryProgress.toString())}if(currentUser.nachoStoryDate){var x=localStorage.getItem("btc_nacho_story_date")||"";currentUser.nachoStoryDate>x&&localStorage.setItem("btc_nacho_story_date",currentUser.nachoStoryDate)}}window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0;var k=getLevel(currentUser.points||0);lastLevelName=k.name,lastLevelMin=k.min,localStorage.getItem("btc_highest_level_seen")||localStorage.setItem("btc_highest_level_seen",k.min.toString()),setTimeout(function(){levelUpReady=!0},3e3),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showContinueReading&&showContinueReading(),updateAuthButton(),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging()}else{const t=auth.currentUser;if(t&&!t.isAnonymous){const o={username:t.displayName||"Bitcoiner",email:t.email||"",points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};await db.collection("users").doc(e).set(o),currentUser={uid:e,...o},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton()}}}window.fbAsyncInit=function(){FB.init({appId:FB_APP_ID,cookie:!0,xfbml:!1,version:"v19.0"})},window.signInWithFacebook=async function(){if("undefined"!=typeof FB)try{return void await signInWithFBSDK()}catch(e){if("Facebook login cancelled"===e.message)return;console.warn("[Auth] FB SDK failed:",e)}await signInWithProvider(new firebase.auth.FacebookAuthProvider)},window.signInWithNostr=async function(){if(checkRateLimit()){var e=!!window.nostr,t=document.createElement("div");t.id="nostrAuthOverlay",t.style.cssText="position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto;",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

    🟣 Sign in with Nostr

    '+(e?'':'
    🔌
    No Extension Detected
    Install Alby or nos2x for one-click login
    ')+'
    or
    🔒 Your nsec is used only in your browser to sign a one-time login event. It is never sent to our servers or stored anywhere.
    or
    ',document.body.appendChild(t)}},window.nostrSignInWithExtension=async function(){if(window.nostr){var e=document.getElementById("nostrAuthStatus");e&&(e.innerHTML='Requesting key from extension...');try{var t=await window.nostr.getPublicKey();if(!t||!/^[a-f0-9]{64}$/.test(t))return void(e&&(e.innerHTML='Could not get public key'));e&&(e.innerHTML='Signing auth event...');var o=await window.nostr.signEvent({kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:t});if(!o||!o.sig)return void(e&&(e.innerHTML='Signing cancelled'));await nostrCompleteAuth(t,o.sig,o)}catch(t){console.error("Nostr extension error:",t),e&&(e.innerHTML='Extension error: '+(t.message||"Unknown")+"")}}else showToast("Extension not found")},window.nostrSignInWithNsec=async function(){var e=(document.getElementById("nostrNsecInput").value||"").trim(),t=document.getElementById("nostrAuthStatus"),o=document.getElementById("nostrNsecBtn");if(e)if(e.startsWith("nsec1")){o.disabled=!0,o.textContent="Loading crypto library...",t&&(t.innerHTML='Loading...');try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.integrity="sha384-GwmNxV/GnZt+zRBR/Hhtu5D4MKfbxeJSApW44ARryGYtj3MFheHMFgiEZ7tVnrln",o.crossOrigin="anonymous",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools;t&&(t.innerHTML='Decoding nsec...'),o.textContent="Signing...";var i=n.nip19.decode(e);if(!i||"nsec"!==i.type)return t&&(t.innerHTML='Invalid nsec'),o.disabled=!1,void(o.textContent="Sign In with nsec");var a=i.data;"string"!=typeof a&&(a=Array.from(new Uint8Array(a)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""));var r=n.getPublicKey(a),s={kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["challenge","btc-edu-"+Date.now()]],content:"Sign in to Bitcoin Education Archive",pubkey:r};s.id=n.getEventHash(s),s.sig=n.signEvent(s,a),document.getElementById("nostrNsecInput").value="",t&&(t.innerHTML='Verifying signature...'),await nostrCompleteAuth(r,s.sig,s)}catch(e){console.error("Nostr nsec error:",e),t&&(t.innerHTML='Error: '+(e.message||"Failed to sign")+""),o.disabled=!1,o.textContent="Sign In with nsec"}}else t&&(t.innerHTML='Invalid nsec format. Must start with nsec1');else showToast("Please paste your nsec")},window.nostrSignInWithNpub=async function(){var e=(document.getElementById("nostrNpubInput").value||"").trim(),t=document.getElementById("nostrAuthStatus");if(e){var o=e;if(e.startsWith("npub1"))try{window.NostrTools||await new Promise(function(e,t){var o=document.createElement("script");o.src="https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js",o.onload=e,o.onerror=function(){t(new Error("Failed to load nostr-tools"))},document.head.appendChild(o)});var n=window.NostrTools.nip19.decode(e);n&&"npub"===n.type&&"string"!=typeof(o=n.data)&&(o=Array.from(new Uint8Array(o)).map(function(e){return e.toString(16).padStart(2,"0")}).join(""))}catch(e){return void(t&&(t.innerHTML='Invalid npub format'))}if(/^[a-f0-9]{64}$/.test(o)){t&&(t.innerHTML='Linking Nostr identity...');try{auth.currentUser||await auth.signInAnonymously();var i=auth.currentUser.uid;await db.collection("users").doc(i).set({nostr:o,lastLogin:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0}),currentUser&&(currentUser.nostr=o);var a=document.getElementById("nostrAuthOverlay");a&&a.remove(),showToast("🟣 Nostr identity linked! (npub)")}catch(e){t&&(t.innerHTML='Error: '+(e.message||"Unknown")+"")}}else t&&(t.innerHTML='Invalid public key')}else showToast("Please paste your npub")},window.nostrCompleteAuth=async function(e,t,o){var n=document.getElementById("nostrAuthStatus");try{var i=firebase.functions().httpsCallable("nostrAuth"),a=await i({pubkey:e,sig:t,event:o});if(a.data&&a.data.token){await auth.signInWithCustomToken(a.data.token);var r=a.data.uid,s=await db.collection("users").doc(r).get();if(!s.exists||!s.data().username){var l={username:"npub..."+e.substring(0,8),nostr:e,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};s.exists||(l.points=0,l.channelsVisited=0,l.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(r).set(l,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(r),hideUsernamePrompt();var c=document.getElementById("nostrAuthOverlay");c&&c.remove(),showToast("🟣 Signed in with Nostr!")}else n&&(n.innerHTML='Auth failed — no token received')}catch(e){console.error("Nostr auth error:",e),n&&(n.innerHTML='Verification failed: '+(e.message||"Unknown")+"")}},window.signInWithLightning=async function(){if(checkRateLimit()){var e=document.createElement("div");e.id="lnAuthModal",e.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.8);",e.onclick=function(t){t.target===e&&e.remove()},e.innerHTML='

    Lightning Login

    Scan this QR code with your Lightning wallet (Alby, Zeus, Phoenix, BlueWallet, etc.)

    Generating challenge...

    Connecting to server...

    ',document.body.appendChild(e);try{var t=firebase.functions().httpsCallable("lnAuthChallenge"),o=await t();if(!document.getElementById("lnAuthModal"))return;if(!o.data||!o.data.k1||!o.data.lnurl)return"function"==typeof showToast&&showToast("Failed to generate login challenge"),void e.remove();var n=o.data.k1,i=o.data.lnurl,a=document.getElementById("lnAuthQR");if(a)if(a.innerHTML="",a.style.display="inline-block","function"==typeof _renderQRCode)_renderQRCode(a,"lightning:"+i,220);else{var r=document.createElement("img");r.src="https://api.qrserver.com/v1/create-qr-code/?size=220x220&data="+encodeURIComponent("lightning:"+i),r.width=220,r.height=220,r.alt="Lightning Auth QR",r.style.cssText="border-radius:8px;",a.appendChild(r)}var s=document.getElementById("lnAuthCopyWrap");s&&(s.style.display="block",s.innerHTML="");var l=document.getElementById("lnAuthStatus");l&&(l.textContent="Waiting for wallet...",l.style.color="var(--accent)");var c=firebase.functions().httpsCallable("lnAuthVerify"),d=0,u=setInterval(async function(){if(++d>60||!document.getElementById("lnAuthModal"))clearInterval(u);else try{var e=await c({k1:n});if(e.data&&e.data.token){clearInterval(u);var t=document.getElementById("lnAuthStatus");t&&(t.textContent="✅ Authenticated!"),await auth.signInWithCustomToken(e.data.token);var o=e.data.uid,i=await db.collection("users").doc(o).get();if(!i.exists||!i.data().username){var a={username:"⚡anon-"+n.substring(0,8),authMethod:"lightning",totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0]};i.exists||(a.points=0,a.channelsVisited=0,a.created=firebase.firestore.FieldValue.serverTimestamp()),await db.collection("users").doc(o).set(a,{merge:!0});try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}}loadUser(o),hideUsernamePrompt(),setTimeout(function(){var e=document.getElementById("lnAuthModal");e&&e.remove()},1e3),"function"==typeof showToast&&showToast("⚡ Signed in with Lightning!")}}catch(e){"not-found"!==e.code&&console.log("LN auth poll:",e.message)}},2e3)}catch(e){console.error("Lightning auth error:",e),"function"==typeof showToast&&showToast("Lightning sign-in failed. Try again.");var p=document.getElementById("lnAuthModal");p&&p.remove()}}},window.sendReturningMagicLink=async function(){var e=document.getElementById("returningEmailInput");if(e){var t=e.value.trim();if(!t||!t.includes("@"))return showToast("📧 Please enter a valid email address"),void(e&&(e.style.borderColor="#ef4444"));e.disabled=!0;var o=e.nextElementSibling;o&&(o.disabled=!0,o.textContent="Sending..."),await sendMagicLink(t)?(showToast("📧 Magic link sent! Check your email to sign in."),o&&(o.textContent="✅ Sent!"),hideUsernamePrompt()):(showToast("❌ Could not send magic link. Try again."),e.disabled=!1,o&&(o.disabled=!1,o.textContent="Send Link"))}};var _authBtnSignedIn=!1;function updateAuthButton(){const e=document.getElementById("authBtn");if(e){var t=auth&&auth.currentUser,o=t&&!t.isAnonymous,n=currentUser&¤tUser.username,i=localStorage.getItem("btc_username"),a=n||i||t&&t.displayName||"",r=t&&t.uid&&(t.uid.startsWith("nostr:")||t.uid.startsWith("ln:"));if(o||r||a)_authBtnSignedIn=!0;else{if(_authBtnSignedIn&&t)return;t||(_authBtnSignedIn=!1)}if(_authBtnSignedIn){var s=a||"My Account";e.innerHTML="⚙️ "+("function"==typeof escapeHtml?escapeHtml(s):s)+" — Settings",e.onclick=function(){showSettings()},e.style.display=window.innerWidth<=900?"none":"block",e.style.background="none",e.style.border="2px solid #3b82f6",e.style.color="#3b82f6",e.onmouseover=function(){this.style.background="#3b82f6",this.style.color="#fff"},e.onmouseout=function(){this.style.background="none",this.style.color="#3b82f6"}}else(!t||t&&t.isAnonymous)&&(e.textContent="Create Free Account / Sign In",e.style.display="block",e.style.background="var(--accent)",e.style.border="none",e.style.color="#000",e.onmouseover=function(){this.style.transform="scale(1.02)"},e.onmouseout=function(){this.style.transform="scale(1)"});var l=document.getElementById("guestPointsBanner");l&&_authBtnSignedIn&&(l.style.display="none")}}function sanitizeInput(e){return e.replace(/<[^>]*>/g,"").replace(/[<>"'&]/g,"").trim()}window.sanitizeInput=sanitizeInput,window.syncCelebratedState=function(){if(void 0!==db&&auth&&auth.currentUser){var e={nachoMilestones:safeJSON("btc_nacho_milestones",[]),nachoCatComplete:safeJSON("btc_nacho_cat_complete",[]),nachoLevelCelebrated:safeJSON("btc_nacho_level_celebrated",[]),nachoItemsNotified:safeJSON("btc_nacho_items_notified",[])};db.collection("users").doc(auth.currentUser.uid).update({celebratedState:e}).catch(function(){})}};const PROFANITY_LIST=["fuck","shit","ass","bitch","dick","cock","pussy","cunt","damn","hell","bastard","slut","whore","fag","faggot","nigger","nigga","retard","retarded","penis","vagina","porn","sex","anal","cum","jizz","dildo","tits","boob","nude","naked","hentai","milf","orgasm","erect","molest","rape","pedo","nazi","hitler","kkk","jihad","terrorist","kill","murder","suicide","die","stfu","gtfo","wank","twat","bollocks","arse","shag","piss","crap","douche","skank","thot","incel","simp","onlyfans","xnxx","pornhub","xvideos","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","aroused","erection","erectile","climax","ejaculat","deepthroat","rimjob","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes","twerk","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","zipperhead","jap","paki","wop","dago","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","acab","supremacy","genocide","lynch"];function containsProfanity(e){const t=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g," "),o=t.split(/\s+/);for(const e of o)if(PROFANITY_LIST.includes(e))return!0;const n=t.replace(/\s/g,"");for(const e of PROFANITY_LIST)if(e.length>=4&&n.includes(e))return!0;return!1}async function createUser(e,t,o,n,i){if(void 0===auth||!auth)return showToast("⏳ Loading... please try again in a moment."),void("function"==typeof initRanking&&initRanking());if(!auth.currentUser)try{await auth.signInAnonymously(),auth.currentUser||await new Promise(e=>{const t=auth.onAuthStateChanged(o=>{o&&(t(),e())});setTimeout(()=>{e()},3e3)})}catch(e){return console.log("Anonymous sign-in error:",e),void showToast("Error creating account. Please try again.")}if(!auth.currentUser)return void showToast("Error: Could not authenticate. Please refresh and try again.");const a=auth.currentUser.uid;if(clearUserData(),!(e=(e=sanitizeInput(e)).replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim())||e.length<2)return void showToast("⚠️ Username must be at least 2 characters (letters, numbers, basic symbols only).");if(containsProfanity(e))return void showToast("⚠️ That username is not allowed. Please choose another.");t&&(t=sanitizeInput(t));const r={username:e,points:0,channelsVisited:0,totalVisits:1,streak:1,lastVisit:(new Date).toISOString().split("T")[0],created:firebase.firestore.FieldValue.serverTimestamp()};t&&(r.email=t),i&&(r.country=i);var s=n||"";s||(s=localStorage.getItem("btc_pending_ln_address")||"",localStorage.removeItem("btc_pending_ln_address")),s&&(r.lightningAddress=s),window._signupFaction&&(r.faction=window._signupFaction,window._signupFaction=null),await db.collection("users").doc(a).set(r);try{db.collection("stats").doc("global").set({userCount:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}currentUser={uid:a,...r},rankingReady=!0,window._badgesReady=!0,"function"==typeof markVisibleBadgesReady&&markVisibleBadgesReady(),window._hiddenBadgesReady=!0,updateRankUI(),updateAuthButton(),awardPoints(POINTS.visit,"Welcome bonus!"),startReadTimer(),hideUsernamePrompt(),s&&setTimeout(function(){showToast("⚡ Lightning address saved to your profile!")},1200);try{localStorage.removeItem("guide_dismissed"),localStorage.removeItem("guide_seen"),"function"==typeof showGuide&&setTimeout(function(){showGuide()},800)}catch(e){}"function"==typeof attachReferral&&attachReferral(a),"function"==typeof onUserLoadedTickets&&onUserLoadedTickets(),"function"==typeof initMessaging&&initMessaging();try{var l=JSON.parse(localStorage.getItem("btc_buddy_pending")||"null");l&&l.goal&&(localStorage.removeItem("btc_buddy_pending"),"function"==typeof _submitBuddyFromOnboarding&&setTimeout(function(){_submitBuddyFromOnboarding(l.level||"beginner",l.goal)},2e3))}catch(e){}}async function awardVisitPoints(){if(!currentUser)return;const e=(new Date).toISOString().split("T")[0],t=new Date(Date.now()-864e5).toISOString().split("T")[0];if(currentUser.lastVisit===e)return;let o=!1,n=0,i=POINTS.visit,a=1;if(currentUser.lastVisit===t)a=(currentUser.streak||0)+1,a%7==0?(n=Math.min(25,5*Math.floor(a/7)),o=!0):a%5==0&&(i+=POINTS.streak,o=!0);else if(currentUser.lastVisit!==e){var r=currentUser.streak||0;currentUser.streakFreezes>0?(a=r+1,currentUser.streakFreezes--,o=!0,setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze ticket was used to save your "+a+"-day streak! ("+(currentUser.streakFreezes||0)+" freezes remaining)")},3e3)):r>1&&setTimeout(function(){showToast("💔 Your "+r+"-day streak was broken! Earn 🧊 Freeze Tickets from the Daily Spin to protect your streak next time.")},3e3)}if(currentUser._isLocal);else{try{var s=firebase.functions().httpsCallable("recordDailyVisit"),l=await s({});if(l.data&&l.data.success&&!l.data.alreadyVisited){a=l.data.streak||1,n=l.data.bonusTickets||0;var c=l.data.bestStreak||a;currentUser.streak=a,currentUser.bestStreak=c,currentUser.lastVisit=e,currentUser.totalVisits=l.data.totalVisits||(currentUser.totalVisits||0)+1,n>0&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+n),l.data.usedFreeze&&(currentUser.streakFreezes=Math.max(0,(currentUser.streakFreezes||0)-1),setTimeout(function(){showToast("🧊 STREAK FROZEN! A freeze was used to save your "+a+"-day streak!")},3e3))}}catch(e){console.warn("[VISIT] Cloud Function failed:",e.message)}var d=i+5*n;d>0&&await awardPoints(d,"✅ Daily visit"+(a>1?" ("+a+"-day streak!)":""))}n>0?("function"==typeof notifySelfStreak&¬ifySelfStreak(a),setTimeout(function(){showToast("🔥 STREAK MILESTONE! Day "+a+": Earned +"+n+" Bonus Tickets! 🎟️")},3500)):o&&showToast("🔥 Day "+currentUser.streak+" streak! +"+(POINTS.visit+POINTS.streak)+" XP"),updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen()}async function awardPoints(e,t,o,n,i,a){if(currentUser&&rankingReady&&(e=parseInt(e),!(isNaN(e)||e<0||e>2200)&&(0!==e||n||i))){window._pointAwardTimes=window._pointAwardTimes||[];var r=Date.now();if(window._pointAwardTimes=window._pointAwardTimes.filter(function(e){return r-e<6e4}),!(window._pointAwardTimes.length>=20)){if(window._pointAwardTimes.push(r),currentUser._isLocal){var s=500,l=(new Date).toISOString().split("T")[0],c="btc_daily_pts_"+l,d=parseInt(localStorage.getItem(c)||"0",10);isNaN(d)&&(d=0);var u={tctv_watch_10m:6e5,daily_spin:864e5,daily_visit:72e6}[t];if(u){var p="btc_cd_"+t,h=parseInt(localStorage.getItem(p)||"0",10);if(h&&Date.now()-h0&&y&&y!==l){f-=b=Math.min(f,s);try{localStorage.setItem(m,String(f))}catch(e){}}var v=e,w=0;if(d>=s?(v=0,w=e):d+e>s&&(w=e-(v=s-d)),(I=v+b)>0){var x=(parseInt(localStorage.getItem("btc_points")||"0",10)||0)+I;try{localStorage.setItem("btc_points",String(x)),v>0&&localStorage.setItem(c,String(d+v))}catch(e){}currentUser.points=x,_showPointsToast(v,t),"function"==typeof notifySelfPoints&¬ifySelfPoints(v,t),b>0&&"function"==typeof showToast&&setTimeout(function(){showToast("♻️ +"+b+" overflow pts redeemed from prior day!",4e3)},1200)}if(w>0){f+=w;try{localStorage.setItem(m,String(f)),localStorage.setItem(g,l)}catch(e){}var k="btc_overflow_notified_"+l;if(!localStorage.getItem(k)){try{localStorage.setItem(k,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap reached (500)! +"+w+" XP banked as overflow — they roll over tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}else if(d+v>=s){var B="btc_daily_cap_notified_"+l;if(!localStorage.getItem(B)){try{localStorage.setItem(B,"1")}catch(e){}"function"==typeof showToast&&showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow. Sign in to convert to sats.",8e3),"function"==typeof _updateCapIndicator&&_updateCapIndicator(!0)}}return updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),void("function"==typeof nachoOnPoints&&nachoOnPoints(e))}auth.currentUser.isAnonymous||db.collection("users").doc(auth.currentUser.uid).update({lastActive:firebase.firestore.FieldValue.serverTimestamp()}).catch(function(){}),e>0&&t&&"function"==typeof notifySelfPoints&¬ifySelfPoints(e,t);try{var S=firebase.functions().httpsCallable("awardPoints"),T={pts:e,action:t||"",reason:t||""};o&&(T.channelId=o),n&&(T.tickets=n),i&&(T.streakFreezes=i),a&&(T.badgeId=a);var _=await S(T);if(_.data&&_.data.dailyActionCapped&&"function"==typeof showToast&&showToast("⏳ "+(_.data.error||"Daily limit reached for this action."),6e3),_.data&&_.data.cooldown&&"function"==typeof showToast&&showToast("⏳ "+(_.data.error||"Slow down a bit."),4e3),_.data&&_.data.success){v=_.data.awarded||0,b=_.data.overflowRedeemed||0,w=_.data.overflowAdded||0;var I,C=_.data.pendingOverflow||0;if((I=v+b)>0&&(currentUser.points=(currentUser.points||0)+I,_showPointsToast(v,t),b>0&&setTimeout(function(){showToast("♻️ +"+b+" overflow pts redeemed from prior day!",4e3)},1200)),w>0){m="btc_overflow_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(m)||(localStorage.setItem(m,"1"),showToast("🎯 Daily cap reached (500)! +"+w+" XP banked as overflow — they roll over tomorrow.",8e3),_updateCapIndicator(!0));try{localStorage.setItem("btc_pts_overflow",String(C))}catch(e){}}else _.data.capped&&(B="btc_daily_cap_notified_"+(new Date).toISOString().split("T")[0],localStorage.getItem(B)||(localStorage.setItem(B,"1"),showToast("🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow.",8e3),_updateCapIndicator(!0)))}}catch(e){console.warn("[POINTS] Cloud Function failed:",e.message),"function"==typeof showToast&&showToast("⏳ XP will sync when connection restores")}updateRankUI(),"function"==typeof renderProgressRings&&renderProgressRings(),refreshLeaderboardIfOpen(),"function"==typeof nachoOnPoints&&nachoOnPoints(e)}}}function _showPointsToast(e,t){var o=!1;e>=25?o=!0:t&&t.length>0&&(window._lastPtsToast=window._lastPtsToast||0,Date.now()-window._lastPtsToast>3e4&&(o=!0)),o&&t&&(window._lastPtsToast=Date.now(),showToast("+"+e+" XP — "+t,2500))}function refreshLeaderboardIfOpen(){var e=document.getElementById("leaderboard");if(e&&e.classList.contains("open")&&!e.classList.contains("minimized")){window._lbCache=null,window._lbCacheTime=null;var t=e.querySelector(".lb-me .lb-score");t&¤tUser&&(t.textContent=(currentUser.points||0).toLocaleString()+" XP")}}async function onChannelOpen(e){if("function"==typeof nachoOnChannel&&nachoOnChannel(e),currentUser&&rankingReady){if(!allTimeChannels.has(e)){allTimeChannels.add(e),sessionChannels.add(e);let t=POINTS.openChannel;if(window._dailyBoosts&&window._dailyBoosts.includes(e)&&(t*=2,setTimeout(()=>{showToast("⚡ 2X XP! Daily boost applied! +"+t+" XP")},2e3)),currentUser._isLocal,currentUser.channelsVisited=(currentUser.channelsVisited||0)+1,currentUser.readChannels?-1===currentUser.readChannels.indexOf(e)&¤tUser.readChannels.push(e):currentUser.readChannels=[e],Array.isArray(currentUser.visitedChannelsList)||(currentUser.visitedChannelsList=[]),-1===currentUser.visitedChannelsList.indexOf(e)&¤tUser.visitedChannelsList.push(e),await awardPoints(t,"📖 New channel explored",e),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof showToast){const e=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,t=Math.round(allTimeChannels.size/e*100);showToast("🗺️ Exploration Map: "+allTimeChannels.size+" channels reached ("+t+"%)")}10===allTimeChannels.size&&await awardPoints(POINTS.explore10,"Explorer bonus! 10 topics 🎉")}readSeconds=0,lastReadAward=0,syncReadToFirebase(e),"function"==typeof onChannelVisitForQuest&&onChannelVisitForQuest(e)}}async function syncReadToFirebase(e){}async function syncFavsToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_favs")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({favorites:e})}catch(e){}}async function syncBookmarksToFirebase(){if(currentUser&&db&&auth.currentUser&&!currentUser._isLocal)try{const e=JSON.parse(localStorage.getItem("btc_bookmarks")||"[]");await db.collection("users").doc(auth.currentUser.uid).update({bookmarks:e})}catch(e){}}function restoreVisitedUI(){JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})})}window.notifySelfPoints=function(e,t){if(e&&!(e<1)&&t&&""!==t){var o={pts:e,reason:t,ts:Date.now(),read:!1};try{var n=JSON.parse(localStorage.getItem("btc_points_log")||"[]");n.push(o),n.length>100&&(n=n.slice(n.length-100)),localStorage.setItem("btc_points_log",JSON.stringify(n))}catch(e){}"function"==typeof _updatePointsBadge&&_updatePointsBadge()}},window.syncBookmarksToFirebase=syncBookmarksToFirebase;let lastActivityTime=Date.now(),lastScrollPos=0,hasScrolledSinceLastAward=!1;function trackActivity(){lastActivityTime=Date.now()}function trackScroll(){const e=document.getElementById("main");e&&Math.abs(e.scrollTop-lastScrollPos)>30&&(lastScrollPos=e.scrollTop,hasScrolledSinceLastAward=!0,lastActivityTime=Date.now())}function startReadTimer(){readTimer&&clearInterval(readTimer),readTimer=setInterval(async()=>{if(currentUser&&rankingReady&&!document.hidden&&!((Date.now()-lastActivityTime)/1e3>45)&&hasScrolledSinceLastAward&&(readSeconds++,sessionStorage.setItem("btc_channel_read_seconds",readSeconds.toString()),readSeconds-lastReadAward>=30)){lastReadAward=readSeconds,hasScrolledSinceLastAward=!1;var e="btc_read_cap_"+(window.currentChannelId||"unknown")+"_"+(new Date).toISOString().split("T")[0],t=parseInt(localStorage.getItem(e)||"0");if(t>=5)return;localStorage.setItem(e,(t+1).toString()),await awardPoints(POINTS.readTime,"")}},1e3)}function getLevel(e){let t=LEVELS[0];for(const o of LEVELS)e>=o.min&&(t=o);const o=LEVELS.indexOf(t)+1,n=o
    '+o.emoji+''+t.toLocaleString()+' XP
    Sign in to keep your XP & get on the leaderboard!
    Sign Up Free →
    ",e.style.display="flex"}}else e&&(e.style.display="none");else e&&(e.style.display="none")}function _updateCapIndicator(e){var t=document.getElementById("userDisplay");if(t){var o,n="btc_daily_pts_"+(new Date).toISOString().split("T")[0],i=parseInt(localStorage.getItem(n)||"0"),a=parseInt(localStorage.getItem("btc_pts_overflow")||"0");e||i>=500?(t.style.borderColor="#ef4444",t.style.boxShadow="0 0 12px rgba(239,68,68,0.3)",t.title="🎯 Daily XP cap reached (500/500)"+(a>0?"\n💫 Overflow: "+a+" pts (rolls over tomorrow)":""),document.getElementById("dailyCapBadge")||((o=document.createElement("span")).id="dailyCapBadge",o.style.cssText="position:absolute;top:-6px;left:-6px;background:#ef4444;color:#fff;font-size:0.55rem;font-weight:800;padding:2px 6px;border-radius:8px;z-index:2;pointer-events:none;",o.textContent="CAP",t.style.position="fixed",t.appendChild(o))):(t.style.borderColor="var(--border)",t.style.boxShadow="0 2px 10px rgba(0,0,0,0.2)",t.title="",(o=document.getElementById("dailyCapBadge"))&&o.remove())}}function _checkCapOnLoad(){var e="btc_daily_pts_"+(new Date).toISOString().split("T")[0];parseInt(localStorage.getItem(e)||"0")>=500&&setTimeout(function(){_updateCapIndicator(!0)},2e3)}function updateRankUI(){if(!currentUser)return;const e=getLevel(currentUser.points||0);!lastLevelName&&e.name&&(lastLevelName=e.name,lastLevelMin=e.min),updateGuestPointsBanner(),updateUserDisplay(e);const t=parseInt(localStorage.getItem("btc_highest_level_seen")||"0");if(levelUpReady&&lastLevelName&&lastLevelName!==e.name&&e.min>lastLevelMin&&e.min>t){showLevelUpCelebration(e),localStorage.setItem("btc_highest_level_seen",e.min.toString()),"function"==typeof notifySelfLevelUp&¬ifySelfLevelUp(e.min,e.name,e.emoji);var o=currentUser&¤tUser.username?currentUser.username:null,n=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:"";if(o&&"function"==typeof window.nachoGlobalAnnounce&&window.nachoGlobalAnnounce(e.emoji+" @"+o+" just leveled up to "+e.emoji+" "+e.name+"! Congrats! 🎉",n),"function"==typeof window.contributeSatoshiFavor){var i=e.name||"",a=null;["Pleb","Pleb II","Pleb III","Stacker","Stacker II","Stacker III"].includes(i)?a="level_up":["Maxi","Maxi II","Maxi III"].includes(i)?a="level_up_5":["Papa John","Full Node","Whale","Sovereign","Cypherpunk","Satoshi"].includes(i)&&(a="level_up_10"),a&&window.contributeSatoshiFavor(a,i)}}lastLevelName=e.name,lastLevelMin=e.min;const r=document.getElementById("rankBar");if(!r)return;let s="";e.next&&(s='
    '+(e.next.min-currentUser.points)+" XP to "+e.next.emoji+" "+e.next.name+"
    ");const l=auth.currentUser&&auth.currentUser.isAnonymous&¤tUser.username?'':"",c=currentUser.streak||0,d=c>0&&(c%7==0||30===c||100===c||365===c),u=currentUser.bestStreak||0,p=c>0||u>0?'🔥 '+c+(u>0?"("+u+")":"")+" day streak"+(d?" ✨":"")+"":"",h=(currentUser.orangeTickets||0)>0?''+currentUser.orangeTickets+"":"";r.innerHTML='
    '+e.emoji+" "+e.name+''+escapeHtml(currentUser.username||"Anon")+''+(currentUser.points||0).toLocaleString()+" XP"+p+h+"
    "+s+l,r.style.display="flex"}function getUserDisplayEmoji(e){var t=void 0!==currentUser&¤tUser?currentUser.displayBadge:null;if(t){if(void 0!==BADGE_DEFS)for(var o=0;o0?'🔥'+currentUser.streak+"":"",s=getUserDisplayEmoji(e);let l=document.getElementById("userDisplay");if(l||(l=document.createElement("div"),l.id="userDisplay",document.body.appendChild(l)),n||auth.currentUser&&auth.currentUser.isAnonymous&&!i){if(u=window.innerWidth<=900)return l.setAttribute("data-mob-hidden","1"),void(l.style.display="none");if("1"===sessionStorage.getItem("btc_signin_banner_dismissed"))return l.classList.add("user-hidden"),void(l.style.display="none");l.classList.remove("user-hidden"),l.setAttribute("data-anon","1"),u?l.style.cssText="position:fixed;bottom:70px;left:12px;right:12px;z-index:200;display:flex;align-items:center;gap:10px;padding:10px 16px;background:linear-gradient(135deg,#1a1a2e,#2d1f4e);border:2px solid #f7931a;border-radius:14px;box-shadow:0 4px 20px rgba(247,147,26,0.3);font-size:0.85rem;cursor:pointer;":((c=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((d=document.createElement("div")).id="userDisplayContainer",d.style.padding="0 20px 16px",d.style.borderBottom="1px solid var(--border)",c.parentNode.insertBefore(d,c.nextSibling),d.appendChild(l)),l.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:12px;background:rgba(247,147,26,0.05);border:1px solid rgba(247,147,26,0.2);border-radius:12px;cursor:default;transition:0.3s;width:100%;"),l.onclick=function(e){!u&&e.target.closest("button")||showSettingsPage("account")},l.innerHTML=(u?'':"")+'
    '+e.emoji+'GUEST'+a.toLocaleString()+" XP
    "+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
    ';return e&&(o+='
    $'+Math.round(e).toLocaleString()+"
    "),t&&(o+='⛓️ '+t.toLocaleString()+""),o+"
    "}()+(u?'
    Sign in to keep your XP!
    ':"")+"
    "+(u?"":'
    ')+(u?"":'
    SIGN UP
    ')+(u?'
    Sign Up →
    ':"")}else{l.removeAttribute("data-anon"),l.removeAttribute("data-mob-hidden");var c,d,u=window.innerWidth<=900,p=document.getElementById("dashboardFloatBtn");if(p||((p=document.createElement("div")).id="dashboardFloatBtn",p.className="fab-btn",p.innerHTML="📊",p.title="Bitcoin Metrics",document.body.appendChild(p)),p.onclick=function(){"function"==typeof toggleDashboard&&toggleDashboard()},u)return void(l.style.display="none");if(u)l.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:8px;padding:8px 14px;background:var(--bg-side);border:1px solid var(--border);border-radius:10px;font-size:0.8rem;cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,0.2);";else(c=document.querySelector(".sidebar-header"))&&!document.getElementById("userDisplayContainer")&&((d=document.createElement("div")).id="userDisplayContainer",d.style.padding="0 20px 16px",d.style.borderBottom="1px solid var(--border)",c.parentNode.insertBefore(d,c.nextSibling),d.appendChild(l)),l.style.cssText="position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:10px;background:rgba(255,255,255,0.03);border:1px solid var(--border);border-radius:10px;cursor:pointer;width:100%;";l.onclick=function(e){e.target.closest("a")||showSettings()};var h,m=currentUser.username||auth.currentUser&&auth.currentUser.displayName||"Anon";h=currentUser.displayBadge?''+s+' '+e.emoji+"":''+e.emoji+"",l.innerHTML='
    '+h+''+escapeHtml(m)+""+(r?''+r+"":"")+"
    "+function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0,t=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(e=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(t=nachoLiveData.blockHeight);var o='
    ';return e&&(o+='
    $'+Math.round(e).toLocaleString()+"
    "),t&&(o+='⛓️ '+t.toLocaleString()+""),(o+=''+a.toLocaleString()+" XP")+"
    "}()+"
    "+(u?"":'
    ')}l.style.display="flex";const g=document.getElementById("mobileUserInfo");if(g&&window.innerWidth<=900){var f=s;currentUser.displayBadge&&(f+=" "+e.emoji),a=currentUser.points||0;var y=parseFloat(localStorage.getItem("btc_last_price"))||0,b=parseInt(localStorage.getItem("btc_last_height"))||0;"undefined"!=typeof nachoLiveData&&nachoLiveData.price&&(y=nachoLiveData.price),"undefined"!=typeof nachoLiveData&&nachoLiveData.blockHeight&&(b=nachoLiveData.blockHeight);var v=''+f+" "+escapeHtml(currentUser.username||(n?"Anonymous":"Anon"))+"";y&&(v+=' $'+Math.round(y).toLocaleString()+""),b&&(v+=' ⛓️ '+b.toLocaleString()+""),v+=' '+a.toLocaleString()+" XP",g.innerHTML=v,g.style.display="inline",g.style.maxWidth="none"}const w=document.getElementById("welcomeBanner");if(w&¤tUser.username){updateAuthButton();const t=currentUser.streak||0,o=currentUser.bestStreak||0,n=t>0||o>0?' · 🔥 '+t+(o>0?"("+o+")":"")+" day streak":"";w.innerHTML=''+e.emoji+' Welcome back, '+escapeHtml(currentUser.username||"Anon")+'! · '+e.name+" · "+(currentUser.points||0).toLocaleString()+" XP"+n+'
    ⚙️ Tap here for Account & Settings
    ',w.style.display="block",w.removeAttribute("data-simplified-hidden")}}document.addEventListener("mousemove",trackActivity),document.addEventListener("keydown",trackActivity),document.addEventListener("touchstart",trackActivity,{passive:!0}),document.addEventListener("click",trackActivity),setInterval(trackScroll,2e3),window.toggleGuestPointsBanner=function(){var e=document.getElementById("guestPointsBanner");if(e){var t=!e.classList.contains("banner-min");e.classList.toggle("banner-min",t);try{localStorage.setItem("btc_signin_banner_min",t?"1":"0")}catch(e){}updateGuestPointsBanner()}};let lbAutoShown=!1;function showLeaderboardAuto(){lbAutoShown||(lbAutoShown=!0,document.getElementById("leaderboard").classList.contains("open")||toggleLeaderboard())}function expandLeaderboard(e){e&&e.stopPropagation(),document.querySelectorAll(".lb-extra").forEach(e=>e.style.display="flex");const t=document.getElementById("lbShowMore");t&&t.remove()}function minimizeLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}function hideLeaderboard(){const e=document.getElementById("leaderboard"),t=document.getElementById("lbFloatBtn");e.classList.remove("open"),e.classList.remove("minimized"),t&&(t.style.display="flex")}var _lbSearchTimer=null,_lbSearchQuery="",_lbSearchLastRank=0,_lbSearchHasMore=!1,_lbSearchLoading=!1;function _lbBuildResultRow(e){var t=(e.points||0).toLocaleString(),o="function"==typeof getLevel?getLevel(e.points||0):{emoji:""},n=e.faction&&"function"==typeof window._factionNameStyle?' style="'+window._factionNameStyle(e.faction)+'"':"";return'
    '+o.emoji+""+escapeHtml(e.username||"Anon")+''+t+" XP · #"+e.rank+"
    "}async function _lbSearchLoad(e,t,o){if(!_lbSearchLoading){_lbSearchLoading=!0;var n=document.getElementById("lbSearchResult");if(n){var i=document.getElementById("lbSearchMoreBtn");if(i&&i.remove(),o){var a=document.createElement("div");a.id="lbSearchLoadingRow",a.className="lb-search-none",a.textContent="Loading more...",n.appendChild(a)}else n.innerHTML='
    Searching...
    ';try{var r=firebase.functions().httpsCallable("searchUsers"),s=await r({query:e,pageSize:10,afterRank:t}),l=s.data&&s.data.users||[],c=!(!s.data||!s.data.hasMore),d=document.getElementById("lbSearchLoadingRow");if(d&&d.remove(),!o&&!l.length)return n.innerHTML='
    No users found matching "'+escapeHtml(e)+'"
    ',void(_lbSearchLoading=!1);if(o||(n.innerHTML=""),l.forEach(function(e){n.insertAdjacentHTML("beforeend",_lbBuildResultRow(e))}),_lbSearchLastRank=l.length?l[l.length-1].rank:t,_lbSearchHasMore=c,c){var u=document.createElement("button");u.id="lbSearchMoreBtn",u.style.cssText="width:100%;padding:8px;background:none;border:1px solid var(--border);border-radius:8px;color:var(--text-muted);font-size:0.8rem;cursor:pointer;font-family:inherit;margin:4px 0 2px;",u.textContent="Show more results ▼",u.onclick=function(){_lbSearchLoad(_lbSearchQuery,_lbSearchLastRank,!0)},n.appendChild(u)}}catch(e){console.warn("[lbSearch]",e);var p=document.getElementById("lbSearchLoadingRow");p&&p.remove(),o||(n.innerHTML='
    Search error — try again
    ')}_lbSearchLoading=!1}else _lbSearchLoading=!1}}function _lbOutsideClose(e){var t=document.getElementById("leaderboard");if(t&&t.classList.contains("open")&&!t.classList.contains("minimized")&&!t.contains(e.target)){var o=document.getElementById("rankBar");if(!o||!o.contains(e.target)){var n=document.getElementById("lbFloatBtn");n&&n.contains(e.target)||document.getElementById("userProfileModal")||(t.classList.remove("open"),t.classList.remove("minimized"),n&&(n.style.display="flex"))}}}function applyOLEDTheme(){const e="true"===localStorage.getItem("btc_theme_oled"),t="light"!==document.body.getAttribute("data-theme");e&&t?document.body.classList.add("oled-theme"):document.body.classList.remove("oled-theme")}function _lbBadgeEmoji(e){var t=[],o="undefined"!=typeof Intl&&Intl.Segmenter?Array.from(new Intl.Segmenter("en",{granularity:"grapheme"}).segment(e)).map(function(e){return e.segment}):null;o?t=o:t=e.match(/\p{Emoji_Presentation}(\u200d\p{Emoji_Presentation})*/gu)||[e];if(t.length<=1)return e;var n=2===t.length?"0.6rem":"0.5rem";return''+t.map(function(e){return""+e+""}).join("")+""}async function toggleLeaderboard(){const e=document.getElementById("leaderboard");if(!e)return;const t=document.getElementById("lbFloatBtn");if(e.classList.contains("open")&&!e.classList.contains("minimized"))return e.classList.remove("open"),e.classList.remove("minimized"),void(t&&(t.style.display="flex"));if(e.classList.remove("minimized"),e.innerHTML='
    Loading leaderboard...
    ',e.classList.add("open"),t&&(t.style.display="none"),("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{window._sharedAudioCtx||(window._sharedAudioCtx=new(window.AudioContext||window.webkitAudioContext));var o=window._sharedAudioCtx;"suspended"===o.state&&o.resume();const e="undefined"!=typeof audioVolume?audioVolume:.5,t=o.currentTime,n=o.createOscillator(),i=o.createGain();n.connect(i),i.connect(o.destination),n.type="sine",n.frequency.setValueAtTime(200,t),n.frequency.exponentialRampToValueAtTime(800,t+.15),i.gain.setValueAtTime(.08*e,t),i.gain.exponentialRampToValueAtTime(.001,t+.2),n.start(t),n.stop(t+.2),[880,1175].forEach((n,i)=>{const a=o.createOscillator(),r=o.createGain();a.connect(r),r.connect(o.destination),a.type="triangle",a.frequency.value=n,r.gain.setValueAtTime(.1*e,t+.1+.08*i),r.gain.exponentialRampToValueAtTime(.001,t+.1+.08*i+.3),a.start(t+.1+.08*i),a.stop(t+.1+.08*i+.3)})}catch(e){}try{var n=Date.now(),i=window._lbCache&&window._lbCacheTime&&n-window._lbCacheTime<12e4;let t=[];i?t=window._lbCache:((await db.collection("users").orderBy("points","desc").limit(150).get()).forEach(e=>{const o=e.data(),n=auth.currentUser&&e.id===auth.currentUser.uid;o.points>0&&(!o.ghostMode||n)&&t.push({id:e.id,...o})}),window._lbCache=t,window._lbCacheTime=n);let o='
    🏆 Leaderboard — tap to expand
    ';o+='

    🏆 Leaderboard

    ',o+='
    ',o+='
    ',o+='
    ',Math.min(10,t.length),t.forEach((e,t)=>{const n=t+1,i=getLevel(e.points||0),a=auth.currentUser&&e.id===auth.currentUser.uid;a&¤tUser&&(e.points||0)>(currentUser.points||0)&&(currentUser.points=e.points,updateRankUI());const r=1===n?"🥇":2===n?"🥈":3===n?"🥉":"#"+n,s=n>10?' style="display:none;" class="lb-row lb-extra'+(a?" lb-me":"")+'"':' class="lb-row'+(a?" lb-me":"")+'"';var l="function"==typeof onlineStatusDot?onlineStatusDot(e.lastSeen):"";let c="";e.earnedHidden&&e.earnedHidden.includes("cert_scholar")&&(c+=" 🎓"),e.earnedHidden&&e.earnedHidden.includes("cert_tech")&&(c+=" 🛠️");var d=e.profilePic?'':"",u=JSON.stringify({recipientName:e.username||"Anon",recipientUid:e.id,lightningAddress:e.lightningAddress||e.lightning||"",context:"leaderboard",label:"Tip "+(e.username||"Anon")}).replace(/'/g,"'").replace(/"/g,"""),p=e.faction?window._factionNameStyle(e.faction):"";o+="'+r+''+_lbBadgeEmoji(i.emoji)+'"+(d?d+" ":"")+escapeHtml(e.username||"Anon")+l+c+''+(e.points||0).toLocaleString()+' XP
    '}),t.length>10&&(o+='"),o+="","function"==typeof getBadgeHTML&&(o+='

    Your Badges

    '+getBadgeHTML()+"
    "),o+='

    ⚔️ PVP Leaderboard

    Loading PVP rankings...
    ',o+='

    Levels

    ';for(const e of LEVELS)o+='
    '+e.emoji+" "+e.name+""+(0===e.min?"0 XP":e.min+"+ XP")+"
    ";o+="
    ",e.innerHTML=o,_loadPVPLeaderboard()}catch(t){console.error("[Leaderboard] Error:",t),e.innerHTML='
    Error loading leaderboard: '+(t.message||"Unknown error")+"
    "}}async function _loadPVPLeaderboard(){var e=document.getElementById("pvpLeaderboardList");if(e)try{var t,o,n=Date.now();window._pvpLbCache&&window._pvpLbCacheTime&&n-window._pvpLbCacheTime<3e5?(t=window._pvpLbCache.wins,o=window._pvpLbCache.losses):([t,o]=await Promise.all([db.collection("users").where("pvpWins",">",0).orderBy("pvpWins","desc").limit(50).get(),db.collection("users").where("pvpLosses",">",0).orderBy("pvpLosses","desc").limit(50).get()]),window._pvpLbCache={wins:t,losses:o},window._pvpLbCacheTime=n);var i={},a=auth.currentUser?auth.currentUser.uid:null;function r(e){if(!i[e.id]){var t=e.data();if(!t.ghostMode||e.id===a){var o=t.pvpWins||0,n=t.pvpLosses||0,r=o+n;if(0!==r){var s=r>0?o/r*100:0;i[e.id]={id:e.id,username:escapeHtml(t.username||"Anon"),wins:o,losses:n,total:r,winRate:s,isMe:e.id===a,lightningAddress:t.lightningAddress||t.lightning||""}}}}}t.forEach(r),o.forEach(r);var s=Object.values(i);if(0===s.length)return void(e.innerHTML='
    No PVP battles yet — be the first to compete!
    ');s.sort(function(e,t){return t.winRate-e.winRate||t.wins-e.wins});var l="";s.forEach(function(e,t){var o=t+1,n=1===o?"🥇":2===o?"🥈":3===o?"🥉":"#"+o,i=e.wins>=100?"👑":e.wins>=50?"🏆":e.wins>=25?"🏟️":e.wins>=5?"🥊":"⚔️",a=o>10?' style="display:none;" class="lb-row pvp-lb-extra'+(e.isMe?" lb-me":"")+'"':' class="lb-row'+(e.isMe?" lb-me":"")+'"',r=JSON.stringify({recipientName:e.username,recipientUid:e.id,lightningAddress:e.lightningAddress,context:"pvp",label:"Tip "+e.username}).replace(/'/g,"'").replace(/"/g,""");l+="'+n+''+i+''+e.username+''+e.wins+"W – "+e.losses+'L'}),s.length>10&&(l+=""),e.innerHTML=l||'
    No PVP battles yet!
    '}catch(c){e.innerHTML='
    No PVP battles yet — be the first to compete!
    '}}window.lbSearchUser=function(e){var t=document.getElementById("lbSearchResult");if(t){if(!(e=(e||"").trim())||e.length<2)return t.innerHTML="",void(_lbSearchQuery="");clearTimeout(_lbSearchTimer),_lbSearchTimer=setTimeout(function(){_lbSearchQuery=e,_lbSearchLastRank=0,_lbSearchHasMore=!1,_lbSearchLoading=!1,_lbSearchLoad(e,0,!1)},350)}},document.addEventListener("mousedown",_lbOutsideClose,!0),document.addEventListener("touchstart",_lbOutsideClose,!0),window.toggleOLEDTheme=function(){const e="true"===localStorage.getItem("btc_theme_oled");localStorage.setItem("btc_theme_oled",!e),applyOLEDTheme(),showSettingsPage("prefs"),showToast(e?"Deep sea mode disabled":"🖤 Midnight OLED enabled!")},document.addEventListener("DOMContentLoaded",applyOLEDTheme),window.showDeleteAccountConfirm=function(){var e=document.createElement("div");e.id="deleteAccountOverlay",e.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;",e.onclick=function(t){t.target===e&&e.remove()};var t=currentUser&¤tUser.username?currentUser.username:"your account",o=currentUser&¤tUser.points||0,n=currentUser&¤tUser.streak||0;e.innerHTML='
    ⚠️

    Delete Your Account?

    This will permanently delete everything associated with '+escapeHtml(t)+':
    '+o.toLocaleString()+" XP and all badges
    "+(n>0?"
    "+n+"-day streak
    ":"")+'
    ❌ All forum posts and replies
    ❌ Marketplace listings
    ❌ DM conversations
    ❌ Nacho chat history
    ❌ Leaderboard ranking
    ❌ Orange Tickets and quest progress
    ⚠️ This action is IRREVERSIBLE. There is no undo.
    ',document.body.appendChild(e)},window.confirmDeleteAccount=async function(){var e=document.getElementById("deleteConfirmInput");if(e&&"DELETE"===e.value){var t=document.getElementById("deleteConfirmBtn");t&&(t.disabled=!0,t.textContent="Deleting...");try{var o=auth.currentUser;if(!o)throw new Error("Not signed in");var n=o.uid;try{await db.collection("users").doc(n).delete()}catch(e){console.warn("User doc delete failed:",e)}try{var i=await db.collection("forum_posts").where("authorId","==",n).get(),a=db.batch();i.forEach(function(e){a.delete(e.ref)}),i.empty||await a.commit()}catch(e){console.warn("Forum posts delete failed:",e)}try{var r=await db.collection("forum_replies").where("authorId","==",n).get(),s=db.batch();r.forEach(function(e){s.delete(e.ref)}),r.empty||await s.commit()}catch(e){console.warn("Forum replies delete failed:",e)}try{var l=await db.collection("marketplace").where("sellerUid","==",n).get(),c=db.batch();l.forEach(function(e){c.delete(e.ref)}),l.empty||await c.commit()}catch(e){console.warn("Marketplace delete failed:",e)}try{var d=await db.collection("conversations").where("participants","array-contains",n).get(),u=db.batch();d.forEach(function(e){u.delete(e.ref)}),d.empty||await u.commit()}catch(e){console.warn("DM delete failed:",e)}try{var p=await db.collection("suggestions").where("uid","==",n).get(),h=db.batch();p.forEach(function(e){h.delete(e.ref)}),p.empty||await h.commit()}catch(e){console.warn("Suggestions delete failed:",e)}for(var m=[],g=0;gclick to ask!'),document.querySelectorAll('[id*="nachoCloset"]').forEach(function(t){var o=t.querySelector('[style*="letter-spacing"]');o&&-1!==o.textContent.indexOf("'s Closet")&&(o.textContent="🦌 "+e+"'s Closet")}),document.querySelectorAll('[style*="font-weight:800"]').forEach(function(t){-1!==t.textContent.indexOf("'s Story")&&(t.textContent=e+"'s Story")})}};var _toastQueue=[];function showToast(e,t){window._directLinkMode||(window._nachoBusy?_toastQueue.push({msg:e,duration:t}):_showToastNow(e,t))}function _showToastNow(e,t){var o=t||2500;const n=document.createElement("div");n.className="rank-toast";var i="object"==typeof e?e.msg:e;n.innerHTML=i.replace(/<(script|svg|img|iframe|object|embed|form|input|link|style|meta|base)[^>]*>/gi,"").replace(/on\w+\s*=/gi,"data-blocked="),"object"==typeof e&&e.duration&&(o=e.duration),document.body.appendChild(n),requestAnimationFrame(()=>n.classList.add("show")),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>n.remove(),400)},o)}function showUsernamePrompt(){try{if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)return void showAccountInfo();if(currentUser&¤tUser.username)return void showAccountInfo();if(!redirectResultResolved)return showToast("⏳ Loading account..."),void redirectResultPromise.then(function(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous||currentUser&¤tUser.username?showAccountInfo():(document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash))});document.getElementById("usernameModal").classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash)}catch(e){"function"==typeof showToast&&showToast("Settings error: "+e.message),console.error("showUsernamePrompt error:",e)}}function showAccountInfo(){showSettingsPage("account")}setInterval(function(){!window._nachoBusy&&_toastQueue.length>0&&_showToastNow(_toastQueue.shift())},2e3),window.showSignInOnly=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)showAccountInfo();else{var e=document.getElementById("usernameModal");e&&(e.classList.add("open"),history.pushState({modal:"signin"},"",window.location.pathname+window.location.hash),setTimeout(function(){var t=e.querySelector(".username-box");if(t){var o=t.querySelector("h2"),n=t.querySelector("p"),i=document.getElementById("usernameInput"),a=document.getElementById("emailInput"),r=t.querySelector('button[onclick="submitUsername()"]'),s=a?a.nextElementSibling:null;s&&"P"===s.tagName&&(s.style.display="none");var l=document.getElementById("signupLnSection");l&&(l.style.display="none");var c=document.getElementById("factionPickerSignup");c&&(c.style.display="none"),o&&(o.style.display="none"),n&&(n.style.display="none"),i&&(i.style.display="none"),a&&(a.style.display="none"),r&&(r.style.display="none");var d=document.getElementById("signInOnlyHeader");d||((d=document.createElement("div")).id="signInOnlyHeader",d.innerHTML='
    🔐

    Welcome Back!

    Sign in to your account

    ',t.insertBefore(d,t.firstChild));var u=document.getElementById("emailSignInSection");if(u){var p=u.querySelector("p");p&&(p.innerHTML='Sign in with your email:')}var h=document.getElementById("signInOnlyNewHere");if(!h){(h=document.createElement("div")).id="signInOnlyNewHere",h.innerHTML='
    ';var m=t.querySelector(".skip");m?t.insertBefore(h,m):t.appendChild(h)}}},50))}},window._restoreSignUpForm=function(){var e=document.getElementById("usernameModal");if(e){var t=e.querySelector(".username-box");if(t){var o=document.getElementById("signInOnlyHeader");o&&o.remove();var n=document.getElementById("signInOnlyNewHere");n&&n.remove();var i=t.querySelector("h2"),a=t.querySelector("p"),r=document.getElementById("usernameInput"),s=document.getElementById("emailInput"),l=t.querySelector('button[onclick="submitUsername()"]'),c=s?s.nextElementSibling:null;c&&"P"===c.tagName&&(c.style.display="");var d=document.getElementById("signupLnSection");d&&(d.style.display="");var u=document.getElementById("factionPickerSignup");u&&(u.style.display=""),i&&(i.style.display=""),a&&(a.style.display=""),r&&(r.style.display=""),s&&(s.style.display=""),l&&(l.style.display="");var p=document.getElementById("emailSignInSection");if(p){var h=p.querySelector("p");h&&(h.innerHTML="Already have an account? Sign in with your email:")}}}};let settingsTab="account";function shortcutRow(e,t){return'
    '+e+'
    '+t+"
    "}function showSettingsPage(e){try{settingsTab=e||"account";const Ye=document.getElementById("usernameModal"),Xe=Ye.querySelector(".username-box");if(!Ye)return void("function"==typeof showToast&&showToast("Error: modal not found"));if(!Xe)return void("function"==typeof showToast&&showToast("Error: username-box not found"));const Ke=void 0!==auth&&auth?auth.currentUser:null;if(!Ke)return void Ye.classList.add("open");const $e=getLevel(currentUser&¤tUser.points||0);let Ze="";if(Ze+='
    ',["account","scholar","sats","prefs","security","data"].forEach(e=>{const t=settingsTab===e;Ze+=""}),Ze+="
    ","account"===settingsTab){var t=Ke.isAnonymous,o=getUserDisplayEmoji($e),n=currentUser&¤tUser.profilePic||"",i=n?'':'
    '+o+"
    ";Ze+='
    '+i+'
    '+(currentUser&¤tUser.username||"Bitcoiner")+'
    '+$e.name+" · "+(currentUser&¤tUser.points||0).toLocaleString()+" XP"+(currentUser&¤tUser.faction?" · "+("cyber_hornets"===currentUser.faction?"🐝 Cyber Hornets":"🦡 Honey Badgers"):"")+"
    ";var a=currentUser&¤tUser.country||"";Ze+='
    🌍 Country'+(a?"":' +100 XP + badge')+'
    '+(a?"Optional · Shown on your public profile":"🌟 Add your country → earn +100 XP + 🌍 Global Citizen badge")+"
    ";var r=currentUser&¤tUser.faction||"";Ze+='
    ⚔️ Faction
    Choose your allegiance! New faction features coming soon — no competitive advantage to either choice.
    🐝
    Cyber Hornets
    The swarm protects the network
    '+("cyber_hornets"===r?'
    ✓ Joined
    ':"")+'
    🦡
    Honey Badgers
    Honey badger don\'t care
    '+("honey_badgers"===r?'
    ✓ Joined
    ':"")+"
    ",Ze+='
    📷 Profile Picture
    '+(n?'':'
    👤
    ')+'
    "+(n?' ':"")+'
    Square image recommended · Max 2MB
    ';var s="",l='
    Account Details
    ';Ke.email&&(l+='
    Email'+Ke.email+"
    "),Ke.displayName&&(l+='
    Name'+Ke.displayName+"
    ");let et="Anonymous";if(Ke.providerData&&Ke.providerData.length>0){const tt=Ke.providerData[0].providerId;"google.com"===tt?et="Google":"twitter.com"===tt?et="Twitter/X":"github.com"===tt?et="GitHub":"facebook.com"===tt?et="Facebook":"password"===tt&&(et="Email")}if(l+='
    Sign-in method'+et+"
    ",currentUser&¤tUser.created&&(l+='
    Member since'+(currentUser.created.toDate?currentUser.created.toDate().toLocaleDateString():new Date(currentUser.created).toLocaleDateString())+"
    "),s+=l+="
    ",!t){var c=currentUser&¤tUser.displayBadge||"",d=[];void 0!==earnedBadges&&void 0!==BADGE_DEFS&&BADGE_DEFS.forEach(function(e){earnedBadges.has(e.id)&&d.push({id:e.id,emoji:e.emoji,name:e.name})});var u=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]");if(void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){-1!==u.indexOf(e.id)&&d.push({id:e.id,emoji:e.hidden&&e.revealEmoji||e.emoji,name:e.hidden&&e.revealName||e.name})}),d.length>0){var p=$e.emoji+" Rank (default)";if(c){var h=d.find(function(e){return e.id===c});h&&(p=h.emoji+" "+h.name)}var m='
    Choose a badge to show next to your name instead of your rank emoji.
    ';m+='
    '+$e.emoji+'
    '+$e.name+' (Default)
    Your current rank emoji
    '+(c?"":'')+"
    ";for(var g=0;g'+f.emoji+'
    '+f.name+"
    "+(y?'':"")+"
    "}s+="
    🏅 Display Badge
    "+p+'
    ")+"
    "}}s+='
    ✏️ Change Username
    Current username: '+(currentUser&¤tUser.username||"")+'
    ',s+='';var b=currentUser&¤tUser.bio||"",v=[],w=[];[{k:"website",e:"🌐",l:"Website",p:"https://yoursite.com",m:100,t:"url"},{k:"twitter",e:"𝕏",l:"Twitter/X",p:"@yourusername",m:30},{k:"nostr",e:"🟣",l:"Nostr",p:"npub... or NIP-05",m:80},{k:"instagram",e:"📸",l:"Instagram",p:"@yourusername",m:30},{k:"tiktok",e:"🎵",l:"TikTok",p:"@yourusername",m:30},{k:"github",e:"🐙",l:"GitHub",p:"yourusername",m:40},{k:"contactEmail",e:"📧",l:"Email",p:"you@example.com",m:80,t:"email",note:"public"},{k:"lightning",e:"⚡",l:"Lightning",p:"you@walletofsatoshi.com",m:80}].forEach(function(e){currentUser&¤tUser[e.k]?v.push(e):w.push(e)}),Ze+='
    📝 Public Profile
    Visible when someone clicks your name on the leaderboard
    ",Ze+='
    🔗 Links & Socials
    ',Ze+='
    ',v.forEach(function(e){var t=currentUser&¤tUser[e.k]||"";Ze+=''}),Ze+="
    ",w.length>0&&(Ze+='
    "),Ze+='
    ',currentUser&&(currentUser.lightning||currentUser.lightningAddress)||(Ze+='
    Connect a Lightning Wallet
    Tip other users and receive tips from the community!
    '),Ze+="",Ze+='",Ze+=''}else if("_artist_removed"===settingsTab){var x=currentUser&¤tUser.artistProfile||{};void 0!==db&&auth&&auth.currentUser&&auth.currentUser.uid,Ze+='
    🎸
    Artist Profile
    Set up your artist presence on Bitcoin Beats
    ',Ze+='
    🎤 Stage Name
    Shows on your tracks and artist page. Leave blank to use your username.
    ',Ze+='
    📝 Artist Bio
    Music-specific bio. Your general bio is in Account tab.
    ',Ze+='
    🎵 Genres
    Comma-separated. Shows as tags on your artist page.
    ',Ze+='
    🔗 Music Links
    🌊
    🟢
    🎵
    📺
    🔗
    ',Ze+='
    Lightning Tips
    '+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?"✅ Lightning Address set: "+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ No Lightning Address set. Go to Account tab or set up in ⚡ Wallet to receive tips!")+"
    ",Ze+='',Ze+="'}else if("scholar"===settingsTab){Ze+='
    🎓
    Bitcoin Scholar

    Master Bitcoin through quests, certifications, and flashcards.

    ',Ze+='
    Channel Quests

    Test your knowledge on any Bitcoin topic with guided quiz questions.

    ';var k="true"===localStorage.getItem("btc_scholar_prop_passed");Ze+='
    '+(k?"✅":"📜")+'
    Bitcoin Scholar Certification

    25 questions on the economic properties and scarcity of Bitcoin. 80% to pass. One attempt per day.

    ";var B="true"===localStorage.getItem("btc_scholar_tech_passed");Ze+='
    '+(B?"✅":"🛠️")+'
    Bitcoin Protocol Expert

    25 questions on highly technical topics: BIPs, Script, SegWit, Taproot, and Networking.

    ",Ze+="

    Prepare for quests and exams with interactive flashcards.

    ",[{name:"Bitcoin Basics",emoji:"₿"},{name:"Security & Storage",emoji:"🔑"},{name:"Lightning Network",emoji:"⚡"},{name:"Mining & Energy",emoji:"⛏️"},{name:"Economics & Money",emoji:"💰"},{name:"History & Culture",emoji:"📜"},{name:"Privacy & Sovereignty",emoji:"🕵️"},{name:"Nodes & P2P",emoji:"📡"},{name:"Wallets & Tools",emoji:"💼"},{name:"Common Myths",emoji:"🚫"},{name:"Austrian Economics",emoji:"🇦🇹"},{name:"Cypherpunk History",emoji:"🔐"},{name:"Bitcoin Governance",emoji:"🏛️"},{name:"Satoshi Nakamoto",emoji:"🦸"},{name:"Global Impact",emoji:"🌍"},{name:"El Salvador & Adoption",emoji:"🇸🇻"},{name:"Technical Deep Dives",emoji:"🔬"}].forEach(function(e){Ze+=""}),Ze+="
    ",Ze+="",Ze+='"}else if("signal"===settingsTab){var _;Ze+='
    📡
    The Weekly Signal

    Curated Bitcoin insights and site updates.

    ',S=null===(_=localStorage.getItem("btc_ticker_enabled"))?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===_,Ze+="
    📊Live Ticker on Home
    ",Ze+='
    📡 Live Signals
    ',Ze+='
    ',Ze+="",Ze+='
    📚 Featured Deep Dives
    ',[{date:"Feb 26, 2026",title:"Why Proof of Stake is just Fiat 2.0",snippet:"Most cryptos claim to be better than Bitcoin because they use less energy. But Gigi explains why energy IS the point — PoW converts real-world resources into unforgeable security.",channel:"pow-vs-pos"},{date:"Feb 19, 2026",title:"The Great Definancialization",snippet:"Parker Lewis breaks down why we don't need thousands of stocks, bonds, and derivatives if we have one form of hard money that can't be debased.",channel:"problems-of-money"},{date:"Feb 12, 2026",title:"The 21 Million Cap is Inviolate",snippet:"Why even if every miner in the world wanted to change the supply, they couldn't. The users run the rules.",channel:"scarce"},{date:"Feb 5, 2026",title:"Not Your Keys, Not Your Coins",snippet:"After another exchange collapse, the importance of self-custody has never been clearer. Here's how to take control.",channel:"self-custody"},{date:"Jan 29, 2026",title:"The Halving: Scarcity You Can Verify",snippet:"Every 210,000 blocks, the supply issuance gets cut in half. No vote. No committee. Just code.",channel:"difficulty-adjustment"}].forEach(function(e){Ze+='
    '+e.date.toUpperCase()+'
    '+e.title+'
    '+e.snippet+"
    '}),setTimeout(function(){var e=document.getElementById("signalLiveNews");e&&fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=(e.snippet||"").replace(/<[^>]+>/g,""),a=e.link||"";n+='
    SIGNAL #'+(t+1)+''+(e.date||"").toUpperCase()+'
    '+o+"
    "+(i?'
    '+i+"
    ":"")+(a?'
    Read full article →
    ':"")+"
    "}),o.innerHTML=n;var i=function(){var t=document.getElementById("signalArrowL"),o=document.getElementById("signalArrowR");t&&o&&(e.scrollWidth>e.clientWidth+10?(t.style.display=e.scrollLeft>10?"flex":"none",o.style.display=e.scrollLeft+e.clientWidth✅ You\'re subscribed to The Signal!':'
    📧
    Get The Signal via Email

    Weekly curated Bitcoin insights. No spam, pure signal.

    '}else if("tickets"===settingsTab){const ot=!Ke||Ke.isAnonymous;ot?Ze+='
    Orange Tickets
    Sign in with Google, Twitter, or GitHub to start earning Orange Tickets and get your referral link!
    ':(Ze+="function"==typeof renderTicketsSection?renderTicketsSection():"",Ze+="function"==typeof renderReferralSection?renderReferralSection():"",Ze+='
    How to Earn Tickets
    📅 Daily Login: +1 ticket just for visiting.
    🎡 Spin the Wheel: Spin daily for bonus tickets!
    👥 Referrals: Earn 50 tickets per friend who signs up and reaches Maxi rank (2,140+ pts). Verified automatically.
    🏅 Badges: Unlock at 25 🐟, 50 🦈, and 100 🐋 tickets.
    ⭐ Bonus: Each ticket = +5 XP towards your rank.
    🏆 Giveaways: More tickets = higher chance of winning sats!
    '),ot||"function"!=typeof loadReferralStatsUI||setTimeout(loadReferralStatsUI,100)}else if("sats"===settingsTab){var I=window._satsSubTab||"claim",C=(t=Ke.isAnonymous,currentUser&¤tUser.points||0),A=currentUser&¤tUser.pointsClaimed||0,E=currentUser&¤tUser.pointsDonated||0,z=C-A,L=currentUser&¤tUser.satsWithdrawn||0,M=Math.floor(Math.max(0,z)/10),P="function"==typeof getSatCap?getSatCap():1e4,U=Math.max(0,P-L),q=Math.min(M,500,U),N=currentUser&¤tUser.lastSatsClaim||null,H=N?new Date(N.seconds?1e3*N.seconds:N).getTime()+864e5:0,D=Date.now(),O=N&&DW&&(W=F.length)}catch(nt){}var V=Ke.metadata&&Ke.metadata.creationTime?new Date(Ke.metadata.creationTime):null,G=V?Math.floor((D-V.getTime())/864e5):0,Q=Ke.email&&Ke.emailVerified,J=!t&&Q&&G>=7&&W>=10,Y=M>=100;if(Ze+='
    ',Ze+='',Ze+='',Ze+="
    ","donate"!==I){Ze+='
    ',Ze+='
    ',Ze+='
    Claim Real Sats
    ',Ze+='
    Earn XP → Convert to real Bitcoin over Lightning
    ',Ze+="
    ",Ze+='
    ',Ze+='
    Your Balance
    ',Ze+='
    ⚡ '+M.toLocaleString()+" claimable sats
    ",Ze+='
    '+z.toLocaleString()+" unclaimed XP of "+C.toLocaleString()+" total
    ",Ze+='
    Lifetime withdrawn: '+L.toLocaleString()+" / 10,000 sats
    ",Ze+="
    ",Ze+=!t&&J&&Y&&!O&&q>=100?'":O?'
    ⏳ Next claim in '+j+"
    ":!Y&&J?'
    Need '+(100-M)+" more sats ("+10*(100-M)+" XP) to reach minimum claim
    ":'
    Complete requirements below to claim
    ',Ze+='
    ',Ze+='
    📋 Requirements
    ',[{met:!t,label:"Signed in (not anonymous)",detail:t?"Sign in with email, Google, etc.":"✓ Signed in"},{met:Q,label:"Email verified",detail:Q?"✓ "+Ke.email:"Link & verify your email in Account tab"},{met:G>=7,label:"Account age ≥ 7 days",detail:G>=7?"✓ "+G+" days old":G+"/7 days — "+(7-G)+" more to go"},{met:W>=10,label:"Read ≥ 10 topics",detail:W>=10?"✓ "+W+" topics read":W+"/10 topics — read "+(10-W)+" more"},{met:Y,label:"Minimum 100 sats (1,000 pts)",detail:Y?"✓ "+M+" sats available":M+"/100 sats — earn "+10*(100-M)+" more XP"}].forEach(function(e){Ze+='
    ',Ze+=''+(e.met?"✅":"⬜")+"",Ze+='
    '+e.label+"
    ",Ze+='
    '+e.detail+"
    "}),Ze+="
    ",Ze+='
    ',Ze+='
    ⚡ How It Works
    ',Ze+='
    ',Ze+="• 1,000 XP = 100 sats — earn XP by reading, quests, and daily visits
    ",Ze+="• Min claim: 100 sats (1,000 XP)
    ",Ze+="• Max claim: 500 sats/day
    ",Ze+="• 1 claim per 24 hours
    ",Ze+="• Lifetime max: 10,000 sats per account
    ",Ze+="• Daily XP cap: 500 XP (50 sats worth) to prevent abuse
    ",Ze+="• Unclaimed sats roll over — no expiration
    ",Ze+="• Payouts via Lightning Network ⚡
    ",Ze+="
    ",Ze+='
    ',Ze+="💚 Zero fees for you! We pay all Lightning network fees so you receive the full amount you claim. You earned it!",Ze+="
    ",Ze+='
    ',Ze+="",Ze+='
    ",Ze+='
    ',Ze+='
    📜 Withdrawal History
    ',Ze+='
    Loading...
    ',Ze+="
    ";var K=currentUser&&(currentUser.lightning||currentUser.lightningAddress)||"";Ze+='
    ',Ze+='
    Lightning Address
    For receiving tips from other users
    ',K&&(Ze+='
    '+escapeHtml(K)+"
    "),Ze+='
    ',Ze+='
    ',K||(Ze+='
    💡 Get one from Wallet of Satoshi, Alby, Coinos, or Strike.
    '),Ze+="
    "}else{var $=Math.max(0,C-A-E);r=currentUser&¤tUser.faction||"",Ze+='
    ',Ze+='
    ❤️
    ',Ze+='
    Donate XP for Charity
    ',Ze+='
    1,000 XP = 1,000 sats donated — 10× more impact than claiming
    ',Ze+="
    ",Ze+='
    ',Ze+='
    Available to Donate
    ',Ze+='
    ❤️ '+$.toLocaleString()+" XP
    ",Ze+='
    '+C.toLocaleString()+" total − "+A.toLocaleString()+" claimed − "+E.toLocaleString()+" donated
    ",Ze+="
    ",t?Ze+='
    🔐 Sign in to donate XP
    ':r?(Ze+='
    ',[5,10,25,50,100].forEach(function(e){var t=Math.floor($*e/100);Ze+='"}),Ze+="
    ",Ze+='
    ',Ze+='',Ze+="
    ",Ze+='
    ',Ze+='',Ze+="
    ",Ze+='',E>0&&(Ze+='
    '+E.toLocaleString()+" XP already donated — thank you! ❤️
    ")):(Ze+='
    ',Ze+='
    ⚔️
    ',Ze+='
    Choose Your Faction First
    ',Ze+='
    Your faction’s donation total is tracked for the community leaderboard.
    ',Ze+='',Ze+="
    "),Ze+='
    ',Ze+='',Ze+='',Ze+="
    "}}else if("prefs"===settingsTab){const it="light"!==document.body.getAttribute("data-theme"),at="true"===localStorage.getItem("btc_theme_oled"),rt=localStorage.getItem("btc_font_size")||"medium";Ze+="
    🎨 Appearance
    Theme
    Font Size
    ',["small","medium","large"].forEach(function(e){var t=rt===e,o=e.charAt(0).toUpperCase()+e.slice(1);Ze+=""}),Ze+="
    ",Ze+='
    🌐 Language
    Translate the site to your preferred language
    ',setTimeout(function(){const e=document.getElementById("langSelect"),t=localStorage.getItem("btc_lang")||"";e&&(e.value=t)},50);const st="undefined"==typeof audioEnabled||audioEnabled,lt="undefined"!=typeof audioVolume?audioVolume:.5;Ze+='
    🔊 Sound
    Sound Effects
    Volume
    ',Ze+="",Ze+='"}else Ze+=""}var Fe=localStorage.getItem("btc_nacho_nickname")||"Nacho";if(Ze+='
    🏷️ Name Your Buck
    Currently: '+escapeHtml(Fe)+'
    ',"function"==typeof getNachoStoryProgress){var Ve=getNachoStoryProgress(),Ge=Ve>=10,Qe=escapeHtml(Fe);Ze+='
    📖
    '+Qe+'\'s Story
    '+(Ge?"✅ Complete!":"A new chapter unlocks every day!")+'
    '+Ve+'/10
    "}"function"==typeof renderNachoClosetUI&&(void 0===window._expanded_closet&&(window._expanded_closet=!1),window._pendingClosetScroll&&(window._expanded_closet=!0),Ze+='
    👗 '+escapeHtml(Fe)+'\'s Closet
    '+(window._expanded_closet?"▾":"▸")+"
    ",window._expanded_closet&&(Ze+='
    '),Ze+="
    "),"function"==typeof renderStickerBook&&(Ze+='
    🎨 Sticker Book
    '+(window._expanded_stickers?"▾":"▸")+"
    ",window._expanded_stickers&&(Ze+='
    '+renderStickerBook()+"
    "),Ze+="
    "),Ze+='
    🔒 Privacy
    We do not sell, share, or monetize your data. Ever.
    The only data we store is your username, points, and progress — just enough to power your experience. No tracking, no ads, no third-party analytics. Your data is yours.
    ',Ze+="",Ze+='",Ze+="",Ze+='"}if(Ze+='Close',Xe.innerHTML=Ze,Ye.classList.add("open"),"sats"===settingsTab&&"function"==typeof loadSatsHistory&&setTimeout(loadSatsHistory,100),"sats"===settingsTab&&(window._toggleSatsCharityNote=function(){var e=document.getElementById("satsCharityNote"),t=document.getElementById("satsCharityNoteArrow");if(e){var o="none"!==e.style.display;e.style.display=o?"none":"block",t&&(t.textContent=o?"▼":"▲")}},window._satsCharitySetAmt=function(e){var t=document.getElementById("satsCharityAmtInput");t&&(t.value=e>0?e:"")},window._satsCharitySubmit=function(){if("undefined"!=typeof firebase&&firebase.functions){var e=document.getElementById("satsCharityAmtInput"),t=parseInt(e?e.value:"")||0,o=void 0!==currentUser&¤tUser?Math.max(0,(currentUser.points||0)-(currentUser.pointsClaimed||0)-(currentUser.pointsDonated||0)):0;if(!t||t<1)"function"==typeof showToast&&showToast("Enter a valid amount");else if(t>o)"function"==typeof showToast&&showToast("Not enough available XP ("+o.toLocaleString()+" available)");else{var n=!!document.getElementById("satsCharityAnonToggle")&&document.getElementById("satsCharityAnonToggle").checked,i=document.querySelector('[onclick="window._satsCharitySubmit()"]');i&&(i.disabled=!0,i.textContent="Donating..."),firebase.functions().httpsCallable("donatePoints")({amount:t,anonymous:n}).then(function(e){void 0!==currentUser&¤tUser&&(currentUser.pointsDonated=(currentUser.pointsDonated||0)+t,e.data&&e.data.bonusPts&&(currentUser.points=(currentUser.points||0)+e.data.bonusPts));var o=e.data&&e.data.newBadges&&e.data.newBadges.length>0?" +"+e.data.newBadges.length+" badge"+(e.data.newBadges.length>1?"s":"")+" unlocked!":"";"function"==typeof showToast&&showToast("❤️ Thank you! "+t.toLocaleString()+" XP donated ("+t.toLocaleString()+" sats pledged to charity)."+o,5e3),"function"==typeof window._charityThankYou&&window._charityThankYou(t,e.data&&e.data.newBadges||[],e.data&&e.data.bonusPts||0);var n=e.data&&e.data.newBadges||[];if(n.length>0&&"function"==typeof window.contributeSatoshiFavor){var i={donor_100:"🤷 Giving Pleb",donor_500:"💛 Stack Sharer",donor_1000:"🧡 Community Builder",donor_5000:"❤️ Archive Patron",donor_10000:"🔥 Sats Saint",donor_25000:"⚡ Lightning Philanthropist",donor_50000:"🏆 Satoshi's Steward",donor_100000:"👑 Legend of the Archive"};n.forEach(function(e){i[e]&&window.contributeSatoshiFavor("badge_earned",i[e]).catch(function(){})})}void 0!==window._charityStatsLoaded&&(window._charityStatsLoaded=!1),showSettingsPage("sats")}).catch(function(e){i&&(i.disabled=!1,i.textContent="❤️ Donate XP for Charity"),"function"==typeof showToast&&showToast("❌ "+(e.message||"Donation failed. Try again."),4e3)})}}}),"data"===settingsTab&&"function"==typeof loadReferralStatsUI&&Ke&&!Ke.isAnonymous&&setTimeout(loadReferralStatsUI,100),"data"===settingsTab&&"function"==typeof renderNachoClosetUI){var Je=document.getElementById("nachoClosetContainer");Je&&(renderNachoClosetUI(Je),window._pendingClosetScroll&&setTimeout(function(){Je.scrollIntoView({behavior:"smooth",block:"center"}),window._pendingClosetScroll=!1},300))}}catch(_t){"function"==typeof showToast&&showToast("Settings page error: "+_t.message),console.error("showSettingsPage error:",_t)}}function changeLanguage(e){const t=document.getElementById("langStatus");if(!e){const e=document.querySelector(".goog-te-banner-frame");e&&e.remove();var o=document.querySelector("iframe.goog-te-banner-frame");o&&o.remove();var n=document.querySelector(".skiptranslate");return n&&n.remove(),document.body.style.top="",document.body.style.position="",document.documentElement.style.overflow="",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",document.cookie="googtrans=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=."+location.hostname,localStorage.setItem("btc_lang",""),t&&(t.innerHTML='✅ Switched to English'),document.documentElement.classList.remove("translated-ltr","translated-rtl"),document.querySelectorAll('font[style*="vertical-align: inherit"]').forEach(function(e){var t=e.parentNode;t&&t.replaceChild(document.createTextNode(e.textContent),e)}),void setTimeout(function(){showSettingsPage("prefs")},200)}if(localStorage.setItem("btc_lang",e),document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname,t&&(t.innerHTML='Translating...'),document.getElementById("gtranslate"))triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!');else{const o=document.createElement("script");o.id="gtranslate",o.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(o),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget"),setTimeout(()=>{triggerGoogleTranslate(e),t&&(t.innerHTML='✅ Translated!')},1500)};const n=document.createElement("div");n.id="gtranslateWidget",n.style.display="none",document.body.appendChild(n)}}function triggerGoogleTranslate(e){const t=document.querySelector(".goog-te-combo");t&&(t.value=e,t.dispatchEvent(new Event("change")))}function setFontSize(e){localStorage.setItem("btc_font_size",e);const t="small"===e?"14px":"medium"===e?"16px":"18px";document.documentElement.style.fontSize=t,showSettingsPage("prefs")}async function saveProfile(){var e=document.getElementById("profileStatus");if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in with Google, Facebook, Twitter, or email to save your profile!"),e&&(e.innerHTML='🔒 Create a free account to save your profile'),void("function"==typeof showUsernamePrompt&&setTimeout(showUsernamePrompt,1500));var t=auth.currentUser.uid,o=document.getElementById("profileBio")?document.getElementById("profileBio").value.trim():"",n=document.getElementById("countryInput"),i=n?n.value.trim().substring(0,60):"";if(i&&window._countryList&&-1===window._countryList.indexOf(i))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void n.focus();var a={bio:o,country:i};["website","twitter","nostr","instagram","tiktok","github","contactEmail","lightning"].forEach(function(e){var t,o=document.getElementById("profile_"+e);if(o){var n=o.value.trim();"lightning"===e?(n=n.replace(/[\\'"<>]/g,""))&&!n.match(/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)&&(n=""):n="contactEmail"===e||"nostr"===e?n.replace(/[\\'"<>]/g,""):(t=n)?(t=t.trim(),/^(javascript|data|vbscript|blob):/i.test(t)?"":t):"",a[e]=n}else currentUser&&void 0!==currentUser[e]&&(document.querySelector('.pf-link-row[data-key="'+e+'"]')||(a[e]=""))});try{e&&(e.innerHTML='Saving...'),await db.collection("users").doc(t).update(a);var r=currentUser&¤tUser.country||"";i&&!r&&("function"==typeof awardPoints&&awardPoints(100,"badge_earned",null,null,null,"country_set"),"function"==typeof checkBadges&&setTimeout(function(){checkBadges()},500)),Object.assign(currentUser,a),e&&(e.innerHTML='✅ Profile saved!'),"function"==typeof showToast&&showToast("✅ Profile saved successfully!"),setTimeout(function(){e&&(e.innerHTML=""),showSettingsPage("account")},1500)}catch(t){console.error("Error saving profile:",t),e&&(e.innerHTML='❌ Error saving'),"function"==typeof showToast&&showToast("❌ Error saving profile")}}function _pasteFieldFallback(e){e.focus(),e.value="",e.setSelectionRange(0,0);try{document.execCommand("paste")}catch(e){}"function"==typeof showToast&&showToast("📋 Field ready — tap and hold, then tap Paste",5e3)}function clearUserLocalStorage(){for(var e=["btc_theme_oled","btc_font_size","btc_volume","btc_lang","btc_haptic","btc_soundscape","btc_ticker_enabled","btc_ios_a2hs_dismissed","btc_pwa_dismissed","btc_swipe_hint_shown","btc_last_auth_uid","btc_signin_email","btc_pending_email","btc_pending_username"],t=[],o=0;o
    Scan this QR code with your authenticator app:
    Or enter this key manually: '+(t.data.secret||"")+'
    ')}}catch(e){showToast("Error setting up authenticator: "+(e.message||"try again"))}}async function verifyTotpSetup(){var e=document.getElementById("totpVerifyCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpVerify");await t({code:e.value.trim()}),showToast("✅ Authenticator app enabled!"),showSettingsPage("security")}catch(e){showToast("Invalid code. Try again.")}else showToast("Enter a 6-digit code")}async function disableTotp(){var e=document.getElementById("totpDisableCode");if(e&&6===e.value.trim().length)try{var t=firebase.functions().httpsCallable("totpDisable");await t({code:e.value.trim()}),showToast("Authenticator app disabled"),showSettingsPage("security")}catch(e){showToast("Invalid code")}else showToast("Enter your current code")}function clearUserData(){["btc_visited_channels","btc_favs","btc_hidden_badges","btc_asked_questions","btc_scholar_passed","btc_scholar_attempt_date","btc_badges","btc_last_channel","btc_signin_email","btc_nacho_equipped","btc_nacho_items_notified","btc_points","btc_total_visits","btc_streak","btc_last_visit"].forEach(function(e){localStorage.removeItem(e)}),currentUser=null}function showSignInPrompt(){auth&&auth.currentUser&&!auth.currentUser.isAnonymous?showSettings():showUsernamePrompt()}function _generateDeviceFingerprint(){try{var e=document.createElement("canvas"),t=e.getContext("2d");t.textBaseline="top",t.font="14px Arial",t.fillText("Bitcoin Education 🦌",2,2);for(var o=e.toDataURL(),n=[navigator.userAgent||"",screen.width+"x"+screen.height,screen.colorDepth,(new Date).getTimezoneOffset(),navigator.language||"",navigator.hardwareConcurrency||0,(navigator.deviceMemory||0).toString(),void 0!==window.ontouchstart?"touch":"no-touch",o.substring(o.length-50)].join("|"),i=0,a=0;a{const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.frequency.value=o,i.type=n<3?"sine":"triangle",a.gain.setValueAtTime(.12*e,t.currentTime+.1*n),a.gain.exponentialRampToValueAtTime(.001,t.currentTime+.1*n+.6),i.start(t.currentTime+.1*n),i.stop(t.currentTime+.1*n+.6)})}catch(e){}"function"==typeof launchConfetti&&launchConfetti();const o=document.createElement("div");o.id="levelUpModal",o.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;animation:fadeIn 0.4s;",o.innerHTML='
    '+e.emoji+'
    ⬆️ LEVEL UP!
    '+e.name+'
    You\'ve reached '+e.min.toLocaleString()+'+ XP!
    '+getLevelFlavor(e.name)+'
    ',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function getLevelFlavor(e){return{Curious:"You're starting to see what all the fuss is about.",Pleb:"Welcome to the pleb life. You're one of us now.","Pleb II":"170 — the block height when Satoshi mined the first 1,000 blocks. You're going deeper.","Pleb III":"256 — the number of bits in a private key. You're becoming unbreakable.",Stacker:"Stacking sats and stacking knowledge. Impressive.","Stacker II":"Double stacking! 1913 — the year the Fed was born. You know why that matters.","Stacker III":"Triple stack mode. 2016 — the year the halving changed everything.",Maxi:"2140 — when the last sat is mined. There is no second best. You know it.","Maxi II":"6102 — Executive Order 6102 banned gold. They can't ban Bitcoin. Double the conviction.","Maxi III":"8888 — triple maxi. The signal only gets stronger.","Papa John":"10,000 BTC for two pizzas. Never forget. 🍕 You've earned your slice.","Full Node":"18,333 — port 18333. You verify everything yourself. Don't trust, verify.",Whale:"50,000 strong. You move markets. Unstoppable, just like Bitcoin.",Sovereign:"Self-sovereign. 100K channels deep. No permission needed. You ARE the bank.",Cypherpunk:"133,337 — leet beyond leet. Privacy is a right, not a privilege. Code is law.",Satoshi:"The pinnacle. You've achieved legendary status."}[e]||"You're leveling up!"}window.showSettings=function(){if(void 0===auth||!auth)return"function"==typeof showToast&&showToast("⚠️ Firebase not ready. Retrying..."),"function"==typeof initRanking&&initRanking(),void setTimeout(function(){void 0!==auth&&auth?showUsernamePrompt():"function"==typeof showToast&&showToast("❌ Could not load. Please refresh the page.")},2e3);showUsernamePrompt()},window._countryList=["Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burundi","Cabo Verde","Cambodia","Cameroon","Canada","Central African Republic","Chad","Chile","China","Colombia","Comoros","Congo","Costa Rica","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Eswatini","Ethiopia","Fiji","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Grenada","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Ivory Coast","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","North Korea","North Macedonia","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","Sudan","Suriname","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor-Leste","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Yemen","Zambia","Zimbabwe"],window._filterCountryList=function(){var e=document.getElementById("countryInput"),t=document.getElementById("countryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
    '+l+"
    "}n.length>8&&(i+='
    +'+(n.length-8)+" more — keep typing
    "),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectCountry=function(e){var t=document.getElementById("countryInput"),o=document.getElementById("countryDropdown");t&&(t.value=e),o&&(o.style.display="none")},window._selectFaction=async function(e){try{var t=auth?auth.currentUser:null;if(!t)return void("function"==typeof showToast&&showToast("Sign in to choose a faction"));if(t.isAnonymous)return void("function"==typeof showToast&&showToast("Create an account to choose a faction"));var o=currentUser&¤tUser.faction||null,n=!o;await db.collection("users").doc(t.uid).update({faction:e}),currentUser&&(currentUser.faction=e),"function"==typeof showToast&&showToast("cyber_hornets"===e?"🐝 Welcome to the Cyber Hornets!":"🦡 Welcome to the Honey Badgers!"),showSettingsPage("account"),n&&"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("syncUserFactionPoints")({newFaction:e,previousFaction:o}).then(function(e){e.data&&e.data.pointsSynced>0&&"function"==typeof showToast&&showToast("⚡ "+e.data.pointsSynced+" past SF point"+(1!==e.data.pointsSynced?"s":"")+" credited to your faction!")}).catch(function(e){console.warn("[FACTION] syncUserFactionPoints failed:",e)})}catch(e){console.error("Faction select error:",e),"function"==typeof showToast&&showToast("Error saving faction")}},window._filterSignupCountry=function(){var e=document.getElementById("signupCountryInput"),t=document.getElementById("signupCountryDropdown");if(e&&t){var o=e.value.trim().toLowerCase();if(0!==o.length){var n=window._countryList.filter(function(e){return-1!==e.toLowerCase().indexOf(o)});if(0===n.length||1===n.length&&n[0].toLowerCase()===o)t.style.display="none";else{for(var i="",a=0;a'+("function"==typeof escapeHtml?escapeHtml(r.substring(s,s+o.length)):r.substring(s,s+o.length))+""+("function"==typeof escapeHtml?escapeHtml(r.substring(s+o.length)):r.substring(s+o.length));i+="
    '+l+"
    "}n.length>8&&(i+='
    +'+(n.length-8)+" more — keep typing
    "),t.innerHTML=i,t.style.display="block"}}else t.style.display="none"}},window._selectSignupCountry=function(e){var t=document.getElementById("signupCountryInput"),o=document.getElementById("signupCountryDropdown");t&&(t.value=e),o&&(o.style.display="none")},document.addEventListener("click",function(e){[["countryDropdown","countryAutocomplete"],["signupCountryDropdown","signupCountryAutocomplete"]].forEach(function(t){var o=document.getElementById(t[0]),n=document.getElementById(t[1]);o&&n&&!n.contains(e.target)&&(o.style.display="none")})}),function(){const e=localStorage.getItem("btc_lang");if(e){document.cookie="googtrans=/en/"+e+"; path=/;",document.cookie="googtrans=/en/"+e+"; path=/; domain=."+location.hostname;const t=document.createElement("script");t.id="gtranslate",t.src="https://translate.google.com/translate_a/element.js?cb=googleTranslateReady",document.head.appendChild(t),window.googleTranslateReady=function(){new google.translate.TranslateElement({pageLanguage:"en",autoDisplay:!1},"gtranslateWidget")};const o=document.createElement("div");o.id="gtranslateWidget",o.style.display="none",document.body.appendChild(o)}}(),window.setSoundscape=function(e){localStorage.setItem("btc_soundscape",e),"function"==typeof updateSoundscape&&updateSoundscape(e),showSettingsPage("prefs")},window._removedProfileLinks={},window.profileLinkRemoved=function(e){window._removedProfileLinks[e]=!0},window.addProfileLink=function(e,t,o,n,i,a){var r=document.getElementById("profileLinksArea");if(r){var s=document.createElement("div");s.className="pf-link-row",s.setAttribute("data-key",e),s.style.cssText="display:flex;align-items:center;gap:12px;margin-bottom:12px;background:rgba(255,255,255,0.02);padding:10px;border-radius:12px;border:1px solid var(--border);",s.innerHTML=''+t+'',r.appendChild(s);var l=document.getElementById("addLinkMenu");l&&(l.style.display="none");var c=document.getElementById("profile_"+e);c&&c.focus()}},window.handleProfilePicUpload=function(e){var t=e.files&&e.files[0];if(t){var o=document.getElementById("pfpUploadStatus");if(t.type.match(/^image\//))if(t.size>2097152)o&&(o.innerHTML='❌ Image too large (max 2MB)');else{o&&(o.innerHTML='Processing...');var n=new FileReader;n.onload=function(e){var t=new Image;t.onload=function(){var e=128,n=document.createElement("canvas");n.width=e,n.height=e;var i,a,r=n.getContext("2d"),s=Math.min(t.width,t.height);i=(t.width-s)/2,a=(t.height-s)/2,r.drawImage(t,i,a,s,s,0,0,e,e);var l=n.toDataURL("image/jpeg",.8);auth&&auth.currentUser?db.collection("users").doc(auth.currentUser.uid).update({profilePic:l}).then(function(){currentUser&&(currentUser.profilePic=l),window._lbCache=null,o&&(o.innerHTML='✅ Profile picture saved!'),"function"==typeof showToast&&showToast("📷 Profile picture updated!"),setTimeout(function(){showSettingsPage("account")},1e3)}).catch(function(e){o&&(o.innerHTML='❌ Save failed: '+e.message+"")}):o&&(o.innerHTML='❌ Not signed in')},t.onerror=function(){o&&(o.innerHTML='❌ Could not load image')},t.src=e.target.result},n.readAsDataURL(t)}else o&&(o.innerHTML='❌ Please select an image file')}},window.removeProfilePic=function(){auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({profilePic:""}).then(function(){currentUser&&(currentUser.profilePic=""),window._lbCache=null,"function"==typeof showToast&&showToast("📷 Profile picture removed"),showSettingsPage("account")}).catch(function(){})},window.showArtistProfileModal=function(){if(auth&&auth.currentUser){var e=document.getElementById("artistProfileModal");e&&e.remove();var t=currentUser&¤tUser.artistProfile||{},o=auth.currentUser.uid,n=document.createElement("div");n.id="artistProfileModal",n.style.cssText="position:fixed;inset:0;z-index:500000;background:rgba(0,0,0,0.85);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",n.onclick=function(e){e.target===n&&n.remove()},n.innerHTML='
    🎸
    Artist Profile
    Set up your artist presence on Bitcoin Beats
    🎤 Stage Name
    Leave blank to use your username.
    📝 Artist Bio
    🎵 Genres
    🔗 Music Links
    🌐
    𝕏
    📸
    '+(currentUser&&(currentUser.lightningAddress||currentUser.lightning)?'✅ Lightning: '+escapeHtml(currentUser.lightningAddress||currentUser.lightning)+"":"⚠️ Set a Lightning Address in Account or Wallet to receive tips!")+'
    ',document.body.appendChild(n)}else"function"==typeof showToast&&showToast("Sign in first")},window.saveArtistProfile=function(){if(auth&&auth.currentUser&&void 0!==db){var e=document.getElementById("artistSaveBtn");e&&(e.disabled=!0,e.textContent="Saving...");var t={stageName:(document.getElementById("artistStageName").value||"").trim().substring(0,40),bio:(document.getElementById("artistBio").value||"").trim().substring(0,500),genres:(document.getElementById("artistGenres").value||"").trim().substring(0,100),website:(document.getElementById("artistLinkWebsite").value||"").trim().substring(0,200),x:(document.getElementById("artistLinkX").value||"").trim().substring(0,50),instagram:(document.getElementById("artistLinkInstagram").value||"").trim().substring(0,50)};db.collection("users").doc(auth.currentUser.uid).update({artistProfile:t}).then(function(){currentUser&&(currentUser.artistProfile=t),"function"==typeof showToast&&showToast("🎸 Artist profile saved!"),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")}).catch(function(t){console.error("Artist profile save error:",t),"function"==typeof showToast&&showToast("Error saving: "+(t.message||"Unknown")),e&&(e.disabled=!1,e.textContent="💾 Save Artist Profile")})}else"function"==typeof showToast&&showToast("Sign in to save your artist profile")},window.pasteToField=function(e){var t=document.getElementById(e);t&&(navigator.clipboard&&navigator.clipboard.readText?navigator.clipboard.readText().then(function(e){e?(t.value=e.trim(),t.style.borderColor="var(--accent)",t.dispatchEvent(new Event("input",{bubbles:!0})),"function"==typeof showToast&&showToast("📋 Pasted!")):_pasteFieldFallback(t)}).catch(function(){_pasteFieldFallback(t)}):_pasteFieldFallback(t))},window.loadSignalContent=function(){var e=document.getElementById("signalLiveNews");e&&!e.getAttribute("data-loaded")&&(e.setAttribute("data-loaded","1"),fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(t){if(t&&t.news&&0!==t.news.length){var o=e.querySelector("div")||e,n="";t.news.slice(0,3).forEach(function(e,t){var o=(e.title||"").replace(/<[^>]+>/g,""),i=e.link||"";n+='
    SIGNAL #'+(t+1)+'
    '+o+"
    "+(i?'
    Read →
    ':"")+"
    "}),o.innerHTML=n}}).catch(function(){}))},window.expandSignUpBanner=function(){sessionStorage.removeItem("btc_signin_banner_dismissed");var e=document.getElementById("mobileSignUpPill");e&&e.remove();var t=document.getElementById("userDisplay");t&&t.classList.remove("user-hidden"),"function"==typeof updateUserDisplay&&updateUserDisplay()},window.minimizeSignUpBanner=function(){sessionStorage.setItem("btc_signin_banner_dismissed","1");var e=document.getElementById("userDisplay");if(window.innerWidth<=900){e&&(e.classList.add("user-hidden"),e.style.display="none");var t=document.getElementById("mobileSignUpPill");t||((t=document.createElement("div")).id="mobileSignUpPill",document.body.appendChild(t)),t.style.cssText="position:fixed;bottom:70px;left:12px;z-index:200;display:flex;align-items:center;gap:6px;padding:8px 12px 8px 16px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",t.innerHTML='🔐 Sign Up',t.onclick=function(){window.expandSignUpBanner()}}else{if(!e)return;e.style.cssText="position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:6px;padding:6px 14px;background:var(--bg-side,#1a1a2e);border:2px solid #f7931a;border-radius:10px;box-shadow:0 2px 10px rgba(247,147,26,0.2);cursor:pointer;transition:0.3s;",e.innerHTML='🔐 Sign Up',e.onclick=function(){window.expandSignUpBanner()}}},window.clearUserLocalStorage=clearUserLocalStorage,window.hideUsernamePrompt=function(){const e=document.getElementById("usernameModal");if(e&&e.classList.remove("open"),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn(),"function"==typeof window._onSettingsClose){var t=window._onSettingsClose;window._onSettingsClose=null,setTimeout(t,150)}},window.submitUsername=async function(){try{var e=document.getElementById("usernameInput")||document.getElementById("newUsername");if(!e)return void console.error("[submitUsername] No input found");var t=e.value.trim();if(!t)return void showToast("Please enter a username!");if(t.length<2)return void showToast("Username must be at least 2 characters");if(t.length>20)return void showToast("Username must be 20 characters or less");if(containsProfanity(t))return void showToast("⚠️ That username is not allowed.");if(document.getElementById("usernameInput")){var o=document.getElementById("emailInput"),n=o?o.value.trim():"",i=document.getElementById("signupCountryInput"),a=i?i.value.trim().substring(0,60):"";if(a&&window._countryList&&-1===window._countryList.indexOf(a))return"function"==typeof showToast&&showToast("⚠️ Please select a valid country from the dropdown list."),void i.focus();var r=!1,s=document.getElementById("signupLnAddress"),l=s?s.value.trim():"";return l&&!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(l)?(s&&(s.style.borderColor="#ef4444",s.focus()),void showToast("⚡ Please enter a valid Lightning address (e.g. you@wallet.com) or leave it blank.")):(l&&localStorage.setItem("btc_pending_ln_address",l),n&&await sendMagicLink(n)?(localStorage.setItem("btc_pending_username",t),localStorage.setItem("btc_pending_email",n),showToast("📧 Check your email for a verification link!"),hideUsernamePrompt(),void await createUser(t,n,r,l,a)):void await createUser(t,n,r,l,a))}if(!currentUser||currentUser._isLocal)return void showToast("Sign in first to change username");var c=document.getElementById("usernameStatus");c&&(c.innerHTML="Saving...");try{await db.collection("users").doc(currentUser.uid).update({username:t,username_lower:t.toLowerCase()}),currentUser.username=t,updateAuthButton(),updateRankUI(),c&&(c.innerHTML="✅ Username updated!"),showToast("✅ Username changed to "+t)}catch(e){c&&(c.innerHTML="❌ Error saving"),showToast("Error updating username. Try again.")}}catch(e){console.error("[submitUsername] Uncaught error:",e),"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown error. Please try again."))}},window.exportUserData=function(){if(!currentUser)return;const e=JSON.stringify(currentUser,null,2),t=new Blob([e],{type:"application/json"}),o=URL.createObjectURL(t),n=document.createElement("a");n.href=o,n.download="bitcoin_archive_user_data.json",n.click()},(!localStorage.getItem("btc_last_price")||Date.now()-parseInt(localStorage.getItem("btc_price_ts")||"0")>3e5)&&fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd&&(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),localStorage.setItem("btc_price_ts",Date.now().toString()))}).catch(function(){}),(!localStorage.getItem("btc_last_height")||Date.now()-parseInt(localStorage.getItem("btc_height_ts")||"0")>3e5)&&fetch("https://mempool.space/api/blocks/tip/height").then(function(e){return e.text()}).then(function(e){var t=parseInt(e);t&&(localStorage.setItem("btc_last_height",t.toString()),localStorage.setItem("btc_height_ts",Date.now().toString()))}).catch(function(){}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",initRanking):initRanking(),void 0!==toggleLeaderboard&&(window.toggleLeaderboard=toggleLeaderboard),void 0!==showUsernamePrompt&&(window.showUsernamePrompt=showUsernamePrompt),window.setDisplayBadge=function(e){if(currentUser){currentUser.displayBadge=e||"",void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({displayBadge:e||""}).catch(function(){}),localStorage.setItem("btc_display_badge",e||""),updateRankUI(),updateAuthButton(),showToast(e?"🏅 Display badge updated!":"🏅 Using default rank emoji");var t=document.getElementById("badgePickerPanel");if(t){var o="function"==typeof getLevel?getLevel(currentUser&¤tUser.points||0):{emoji:"🌱",name:"Newbie"},n=[];void 0!==earnedBadges&&void 0!==BADGE_DEFS&&BADGE_DEFS.forEach(function(e){earnedBadges.has(e.id)&&n.push({id:e.id,emoji:e.emoji,name:e.name})});var i=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]");void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){-1!==i.indexOf(e.id)&&n.push({id:e.id,emoji:e.hidden&&e.revealEmoji||e.emoji,name:e.hidden&&e.revealName||e.name})});var a=e||"",r='
    Choose a badge to show next to your name instead of your rank emoji.
    ';r+='
    '+o.emoji+'
    '+o.name+' (Default)
    Your current rank emoji
    '+(a?"":'')+"
    ",n.forEach(function(e){var t=a===e.id;r+="
    '+e.emoji+'
    '+e.name+"
    "+(t?'':"")+"
    "}),r+="
    ",t.innerHTML=r,t.style.display="block"}}},"undefined"==typeof changeUsername&&(window.changeUsername=async function(e){if(!e){var t=document.getElementById("newUsername");t&&(e=t.value.trim())}if(e&&(e=e.replace(/[^\x20-\x7E]/g,"").replace(/[\\'"<>]/g,"").trim()),!e||e.length<2)showToast("Username must be at least 2 characters (ASCII only)");else if(e.length>20)showToast("Username max 20 characters");else if(containsProfanity(e))showToast("⚠️ That username is not allowed.");else if("function"!=typeof isCleanText||isCleanText(e)){if(localStorage.setItem("btc_username",e),currentUser&&(currentUser.username=e),updateAuthButton(),updateRankUI(),auth&&auth.currentUser&&db)try{await db.collection("users").doc(auth.currentUser.uid).update({username:e,username_lower:e.toLowerCase()})}catch(e){console.warn("Username Firestore save failed:",e)}showToast("✅ Username updated to "+e);var o=document.querySelector('[id="currentUsernameLabel"]');o||document.querySelectorAll("div, span").forEach(function(e){-1===e.textContent.indexOf("Current username:")||o||(o=e)}),o&&(o.innerHTML='Current username: '+("function"==typeof escapeHtml?escapeHtml(e):e)+"");var n=document.querySelector('button[onclick*="changeUsername"]');n&&(n.textContent="✅ Saved!",n.style.background="#22c55e",setTimeout(function(){n.textContent="Save New Username",n.style.background="var(--accent)"},2e3))}else showToast("Username contains inappropriate language")}),window.togglePushNotifications=async function(){try{if(!("Notification"in window))return void showToast("Notifications not supported in this browser");"granted"===await Notification.requestPermission()?(localStorage.setItem("btc_push_enabled","true"),showToast("🔔 Notifications Enabled!")):(localStorage.setItem("btc_push_enabled","false"),showToast("❌ Notification permission denied")),showSettingsPage("prefs")}catch(e){console.error(e)}},"undefined"==typeof sendEmailVerification&&(window.sendEmailVerification=function(){auth&&auth.currentUser&&auth.currentUser.sendEmailVerification&&auth.currentUser.sendEmailVerification().then(function(){showToast("📧 Verification email sent!")}).catch(function(){showToast("Could not send verification email")})}),"undefined"==typeof disable2FA&&(window.disable2FA=function(){showToast("2FA management coming soon")}),"undefined"==typeof startMFAEnroll&&(window.startMFAEnroll=function(){showToast("2FA enrollment coming soon")}),"undefined"==typeof verifyMFACode&&(window.verifyMFACode=function(){showToast("2FA verification coming soon")}),"undefined"==typeof sendPasswordReset&&(window.sendPasswordReset=function(){auth&&auth.currentUser&&auth.currentUser.email&&auth.sendPasswordResetEmail(auth.currentUser.email).then(function(){showToast("📧 Password reset email sent!")}).catch(function(){showToast("Could not send reset email")})}),"undefined"==typeof confirmDeleteAccount&&(window.confirmDeleteAccount=function(){if(confirm("Are you sure you want to delete your account? This cannot be undone.")&&auth&&auth.currentUser){var e=auth.currentUser.uid;db.collection("users").doc(e).delete().then(function(){return auth.currentUser.delete()}).then(function(){localStorage.clear(),location.reload()}).catch(function(e){showToast("Error: "+e.message)})}}),window.saveSatsLnAddress=async function(){var e=document.getElementById("satsLnAddrInput"),t=document.getElementById("satsLnAddrStatus");if(e){var o=e.value.trim();if(o&&(!o.includes("@")||o.length<5))t&&(t.innerHTML='Enter a valid Lightning Address (e.g. you@walletofsatoshi.com)');else if(void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{t&&(t.innerHTML='Saving…'),await db.collection("users").doc(auth.currentUser.uid).update({lightning:o,lightningAddress:o}),void 0!==currentUser&¤tUser&&(currentUser.lightning=o,currentUser.lightningAddress=o),o?(t&&(t.innerHTML='✅ Lightning Address saved!'),"function"==typeof showToast&&showToast("⚡ Lightning Address saved!"),"true"!==localStorage.getItem("btc_lightning_setup")&&(localStorage.setItem("btc_lightning_setup","true"),"function"==typeof awardPoints&&awardPoints(100,"⚡ Lightning wallet setup!"),"function"==typeof showToast&&setTimeout(function(){showToast("⚡🏅 Lightning Rod badge earned! +100 pts")},1500),"function"==typeof initBadges&&setTimeout(initBadges,2e3))):t&&(t.innerHTML='Lightning Address removed.')}catch(e){t&&(t.innerHTML='Error saving — try again')}else t&&(t.innerHTML='Sign in to save your Lightning Address')}},window.initSatsClaim=function(){if(console.log("[SATS] initSatsClaim called",{currentUser:!!currentUser,auth:!!auth,authUser:!!auth?.currentUser,isAnon:auth?.currentUser?.isAnonymous}),!currentUser||!auth||!auth.currentUser||auth.currentUser.isAnonymous)return console.log("[SATS] BLOCKED: auth check failed"),void showToast("Sign in to claim sats");var e=(currentUser.points||0)-(currentUser.pointsClaimed||0),t=Math.floor(Math.max(0,e)/10),o=currentUser.satsWithdrawn||0,n="function"==typeof getSatCap?getSatCap():1e4,i=Math.max(0,n-o),a=Math.min(t,500,i);if(console.log("[SATS] maxClaim:",a,"| satsBalance:",t,"| lifetimeLeft:",i,"| satsWithdrawn:",o),a<100)return console.log("[SATS] BLOCKED: maxClaim < 100"),void showToast("⚡ Need at least 100 claimable sats (1,000 unclaimed XP) to withdraw. Keep earning!",5e3);console.log("[SATS] Passed all checks, showing overlay");var r=document.createElement("div");r.id="satsClaimOverlay",r.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:10002;display:flex;align-items:center;justify-content:center;padding:16px;",setTimeout(function(){r.onclick=function(e){e.target===r&&r.remove()}},200);var s='
    ';s+='
    Claim Sats
    ',s+='
    ',s+='
    You can claim up to
    ',s+='
    ⚡ '+a+" sats
    ",s+="
    ",s+='',s+='',s+='
    Open your Lightning wallet, create an invoice for the amount you want (100-'+a+' sats), and paste it here.
    💚 Zero fees — we pay all Lightning network fees so you receive the full amount!
    ',s+='',s+='',s+='',s+="
    ",r.innerHTML=s,document.body.appendChild(r)},window._satsClaimInProgress=!1,window.submitSatsClaim=async function(){if(!window._satsClaimInProgress){var e=document.getElementById("satsClaimBtn"),t=document.getElementById("satsClaimInvoice"),o=document.getElementById("satsClaimError");if(e&&t){var n=t.value.trim();if(n&&n.toLowerCase().startsWith("lnbc")){o&&(o.style.display="none"),window._satsClaimInProgress=!0,e.disabled=!0,e.textContent="⏳ Sending sats...",e.style.opacity="0.6";try{var i=firebase.functions().httpsCallable("claimSats"),a=_generateDeviceFingerprint(),r=await i({invoice:n,fingerprint:a});if(r.data&&r.data.success){var s=r.data.amount||0;currentUser.pointsClaimed=(currentUser.pointsClaimed||0)+10*s,currentUser.satsWithdrawn=(currentUser.satsWithdrawn||0)+s,currentUser.lastSatsClaim=new Date,document.getElementById("satsClaimOverlay").remove(),window._satsClaimInProgress=!1,"function"==typeof notifySelfSatsClaim&¬ifySelfSatsClaim(s),"function"==typeof launchConfetti&&launchConfetti();var l=currentUser.satsWithdrawn||s,c="function"==typeof getSatCap?getSatCap():1e4,d=Math.max(0,c-l),u=document.createElement("div");u.id="satsCelebration",u.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.3s;",u.onclick=function(e){e.target===u&&u.remove()},u.innerHTML='
    ⚡🎉

    Sats Claimed!

    '+s+' sats
    sent to your Lightning wallet ⚡
    Check your wallet to confirm!
    ⚡ '+d.toLocaleString()+' sats remaining to claim!
    '+l.toLocaleString()+' / 10,000 lifetime total claimed
    🧡 Thank you for learning Bitcoin with us!
    ',document.body.appendChild(u),setTimeout(function(){showSettingsPage("sats")},500)}else{var p=r.data&&r.data.error?r.data.error:"Claim failed — try again";o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}catch(t){console.error("Sats claim error:",t),p=t.message||"Claim failed — try again",o&&(o.textContent=p,o.style.display="block"),window._satsClaimInProgress=!1,e.disabled=!1,e.textContent="⚡ Send Sats to My Wallet",e.style.opacity="1"}}else o&&(o.textContent="Please paste a valid Lightning invoice (starts with lnbc...)",o.style.display="block")}}},window.loadSatsHistory=function(){var e=document.getElementById("satsHistory");e&¤tUser&&db?db.collection("users").doc(currentUser.uid).collection("sats_withdrawals").orderBy("timestamp","desc").get().then(function(t){if(t.empty)e.textContent="No withdrawals yet";else{var o=0,n="function"==typeof getSatCap?getSatCap():1e4,i="";t.forEach(function(e){var t=e.data(),n=parseInt(t.amount)||0;o+=n;var a=t.timestamp?new Date(1e3*t.timestamp.seconds).toLocaleDateString():"—";i+='
    '+a+'⚡ '+n+" sats
    "});var a=Math.max(0,n-o),r=Math.min(100,Math.round(o/n*100)),s=r>=90?"#ef4444":r>=60?"#eab308":"#22c55e",l='
    Lifetime Claimed⚡ '+o.toLocaleString()+" / "+n.toLocaleString()+' sats
    '+r+'% used'+a.toLocaleString()+" sats remaining
    ";e.innerHTML=l+i}}).catch(function(){e.textContent="Could not load history"}):e&&(e.textContent="Sign in to view history")};const BADGE_DEFS=[{id:"pow_first_step",name:"First Step",emoji:"👟",desc:"Synced your first walk via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_marathoner",name:"Marathoner",emoji:"🏃‍♂️",desc:"Hit the 42km daily cap in Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_streak_3",name:"3-Day Streak",emoji:"🔥",desc:"Synced walks 3 days in a row via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_streak_7",name:"7-Day Streak",emoji:"🔥",desc:"Synced walks 7 days in a row via Proof of Walk",check:()=>!1,pts:300,hidden:!1},{id:"pow_streak_30",name:"30-Day Streak",emoji:"💎",desc:"Synced walks 30 days in a row via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_10",name:"10 km Club",emoji:"🥾",desc:"Walked 10 km lifetime via Proof of Walk",check:()=>!1,pts:50,hidden:!1},{id:"pow_km_50",name:"50 km Club",emoji:"🚶",desc:"Walked 50 km lifetime via Proof of Walk",check:()=>!1,pts:100,hidden:!1},{id:"pow_km_100",name:"Century Walker",emoji:"🏅",desc:"Walked 100 km lifetime via Proof of Walk",check:()=>!1,pts:200,hidden:!1},{id:"pow_km_500",name:"500 km Legend",emoji:"🏔️",desc:"Walked 500 km lifetime via Proof of Walk",check:()=>!1,pts:500,hidden:!1},{id:"pow_km_1000",name:"1,000 km Titan",emoji:"🌍",desc:"Walked 1,000 km lifetime via Proof of Walk",check:()=>!1,pts:1e3,hidden:!1},{id:"pow_km_5000",name:"To the Moon",emoji:"🌕",desc:"Walked 5,000 km lifetime via Proof of Walk",check:()=>!1,pts:2500,hidden:!1},{id:"first_channel",name:"First Steps",emoji:"👶",desc:"Opened your first channel",check:e=>e.length>=1,pts:10},{id:"explorer_10",name:"Explorer",emoji:"🧭",desc:"Visited 10 topics",check:e=>e.length>=10,pts:15},{id:"explorer_25",name:"Trailblazer",emoji:"🗺️",desc:"Visited 25 topics",check:e=>e.length>=25,pts:30},{id:"explorer_50",name:"Pathfinder",emoji:"🏕️",desc:"Visited 50 topics",check:e=>e.length>=50,pts:50},{id:"explorer_100",name:"Cartographer",emoji:"🌍",desc:"Visited 100 topics",check:e=>e.length>=100,pts:100},{id:"explorer_all",name:"Completionist",emoji:"🗝️",desc:"Visited every single topic",check:(e,t)=>e.length>=t,pts:500},{id:"foundation_builder",name:"Foundation Builder",emoji:"🧱",desc:"Read all Layer 1 Properties (Orange)",check:e=>["whitepaper","decentralized","scarce","secure","money","peaceful","dominant","organic","supranational","programmable","use-cases"].every(t=>e.includes(t)),pts:75},{id:"experienced_pro",name:"Deep Diver",emoji:"🤿",desc:"Read all Experienced Topics (Purple)",check:e=>["maximalism","problems-of-money","self-custody","privacy-nonkyc","nodes","mining","pow-vs-pos","energy","difficulty-adjustment","layer-2-lightning","fedi-ark","chaumian-mints","ctv-covenants","extension-blocks","op-codes","bitvm","layer-3-sidechains","stablecoins","smart-contracts","blockchain-timechain","regulation","cryptography","core-source-code","developers","investment-strategy","evidence-against-alts","consensus"].every(t=>e.includes(t)),pts:150},{id:"librarian",name:"The Librarian",emoji:"📚",desc:"Read all Resource topics (Blue)",check:e=>["one-stop-shop","faq-glossary","nostr","misconceptions-fud","books","videos","podcasts","articles-threads","informational-sites","curriculum","research-theses","games","music","movies-tv","hardware","poems-stories","apps-tools","projects-diy","art-inspiration","graphics","charts","swag-merch","jobs-earn","social-media","fun-facts","news-adoption","history","international","satoshi-nakamoto","giga-chad","health","web5","memes-funny"].every(t=>e.includes(t)),pts:150},{id:"quest_1",name:"Quester",emoji:"⚔️",desc:"Completed your first Quest",check:(e,t,o)=>o>=1,pts:10},{id:"quest_3",name:"Quest Seeker",emoji:"📜",desc:"Completed 3 Quests",check:(e,t,o)=>o>=3,pts:25},{id:"quest_5",name:"Quest Champion",emoji:"🏆",desc:"Completed 5 Quests",check:(e,t,o)=>o>=5,pts:50},{id:"quest_10",name:"Quest Veteran",emoji:"🗡️",desc:"Completed 10 Quests",check:(e,t,o)=>o>=10,pts:100},{id:"quest_25",name:"Quest Crusader",emoji:"⚜️",desc:"Completed 25 Quests",check:(e,t,o)=>o>=25,pts:200},{id:"quest_50",name:"Quest Master",emoji:"👑",desc:"Completed 50 Quests",check:(e,t,o)=>o>=50,pts:400},{id:"quest_100",name:"Quest Legend",emoji:"🏰",desc:"Completed 100 Quests",check:(e,t,o)=>o>=100,pts:750},{id:"bookworm",name:"Bookworm",emoji:"📖",desc:"Saved 5 topics to favorites",check:()=>JSON.parse(localStorage.getItem("btc_favs")||"[]").length>=5,pts:20},{id:"night_owl",name:"Night Owl",emoji:"🦉",desc:"Browsing between midnight and 5am",check:()=>{const e=(new Date).getHours();return e>=0&&e<5},pts:15},{id:"early_bird",name:"Early Bird",emoji:"🐦",desc:"Browsing between 5am and 7am",check:()=>{const e=(new Date).getHours();return e>=5&&e<7},pts:15},{id:"cert_scholar",name:"Bitcoin Scholar",emoji:"🎓",desc:"Passed the Bitcoin Scholar Certification",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed"),pts:50},{id:"tctv_tuned_in",name:"Tuned In",emoji:"📺",desc:"Watched 10 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=10,pts:10},{id:"tctv_couch_potato",name:"Couch Potato",emoji:"🛋️",desc:"Watched 60 min of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=60,pts:25},{id:"tctv_binge_watcher",name:"Binge Watcher",emoji:"🍿",desc:"Watched 5 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=300,pts:50},{id:"tctv_couch_king",name:"Couch King",emoji:"🛌",desc:"Watched 24 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=1440,pts:100},{id:"tctv_satellite",name:"Satellite",emoji:"🛰️",desc:"Watched 100 hours of Timechain TV",check:()=>parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")>=6e3,pts:750},{id:"cert_tech",name:"Protocol Expert",emoji:"🛠️",desc:"Passed the Technical Protocol Expert Certification",check:()=>"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:100},{id:"nacho_chatterbox",name:"Nacho Chatterbox",emoji:"🦌",desc:"Interacted with Nacho 50+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=50,pts:30},{id:"nacho_bestie",name:"Nacho's Bestie",emoji:"🧡",desc:"Interacted with Nacho 250+ times",check:()=>parseInt(localStorage.getItem("btc_nacho_interactions")||"0")>=250,pts:200},{id:"chat_first",name:"First Words",emoji:"💦",desc:"Sent your first message in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=1,pts:10},{id:"chat_10",name:"Chatty",emoji:"🗣️",desc:"Sent 10 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=10,pts:15},{id:"chat_50",name:"Conversationalist",emoji:"💬",desc:"Sent 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=50,pts:25},{id:"chat_100",name:"Town Crier",emoji:"📢",desc:"Sent 100 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=100,pts:50},{id:"chat_500",name:"Chat Legend",emoji:"📯",desc:"Sent 500 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_msgs")||"0")>=500,pts:250},{id:"chat_streak_3",name:"Regular",emoji:"📅",desc:"Chatted 3 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=3,pts:20},{id:"chat_streak_7",name:"Devoted Chatter",emoji:"💪",desc:"Chatted 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=7,pts:50},{id:"chat_streak_30",name:"Chat Addict",emoji:"💠",desc:"Chatted 30 days in a row",check:()=>parseInt(localStorage.getItem("btc_chat_streak")||"0")>=30,pts:300},{id:"dj_first",name:"First Set",emoji:"🎧",desc:"DJed for the first time in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=1,pts:25},{id:"dj_5",name:"Resident DJ",emoji:"🎛️",desc:"DJed 5 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=5,pts:50},{id:"dj_25",name:"Club Legend",emoji:"🎶",desc:"DJed 25 sets in Global Chat",check:()=>parseInt(localStorage.getItem("btc_dj_sets")||"0")>=25,pts:300},{id:"dj_songs_10",name:"Playlist Pro",emoji:"📻",desc:"Broadcast 10 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=10,pts:30},{id:"dj_songs_50",name:"Jukebox Hero",emoji:"🎵",desc:"Broadcast 50 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=50,pts:75},{id:"dj_songs_100",name:"Vinyl Master",emoji:"🎼",desc:"Broadcast 100 songs as DJ",check:()=>parseInt(localStorage.getItem("btc_dj_songs")||"0")>=100,pts:400},{id:"dj_listener",name:"Good Listener",emoji:"🔊",desc:"Tuned in to 10 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=10,pts:20},{id:"dj_listener_50",name:"Groupie",emoji:"🤘",desc:"Tuned in to 50 DJ sets",check:()=>parseInt(localStorage.getItem("btc_dj_listens")||"0")>=50,pts:150},{id:"producer_1",name:"Producer",emoji:"🎤",desc:"Uploaded your first song to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=1,pts:50},{id:"producer_10",name:"Discographer",emoji:"💿",desc:"Uploaded 10 songs to Bitcoin Beats",check:()=>parseInt(localStorage.getItem("btc_beats_uploads")||"0")>=10,pts:100},{id:"pvp_first",name:"First Blood",emoji:"🩸",desc:"Won your first PVP battle",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=1,pts:25},{id:"pvp_5",name:"Contender",emoji:"🥊",desc:"Won 5 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=5,pts:50},{id:"pvp_25",name:"Gladiator",emoji:"🏟️",desc:"Won 25 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=25,pts:100},{id:"pvp_50",name:"Champion",emoji:"🏆",desc:"Won 50 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=50,pts:200},{id:"pvp_100",name:"PVP Legend",emoji:"🥇",desc:"Won 100 PVP battles",check:()=>parseInt(localStorage.getItem("btc_pvp_wins")||"0")>=100,pts:1e3},{id:"forum_5",name:"Voice of the People",emoji:"📣",desc:"Made 5 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=5,pts:25},{id:"forum_25",name:"Thought Leader",emoji:"🧠",desc:"Made 25 forum posts",check:()=>parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=25,pts:75},{id:"article_1",name:"Author",emoji:"✍️",desc:"Published your first article",check:()=>parseInt(localStorage.getItem("btc_articles_published")||"0")>=1,pts:50},{id:"streak_7",name:"Week Warrior",emoji:"🔥",desc:"7-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=7,pts:50},{id:"streak_30",name:"Monthly Maxi",emoji:"🦾",desc:"30-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=30,pts:150},{id:"streak_100",name:"Diamond Hands",emoji:"💎",desc:"100-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=100,pts:1e3},{id:"streak_365",name:"HODLer Supreme",emoji:"🪩",desc:"365-day visit streak",check:()=>void 0!==currentUser&¤tUser&&(currentUser.bestStreak||0)>=365,pts:5e3},{id:"irl_host",name:"Event Host",emoji:"🎪",desc:"Hosted your first IRL event",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=1,pts:50},{id:"irl_host_5",name:"Community Builder",emoji:"🏗️",desc:"Hosted 5 IRL events",check:()=>parseInt(localStorage.getItem("btc_irl_hosted")||"0")>=5,pts:150},{id:"sats_first",name:"First Sats",emoji:"🪙",desc:"Claimed your first sats from the faucet",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1,pts:25},{id:"sats_1k",name:"Stacker",emoji:"📦",desc:"Claimed 1,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e3,pts:100},{id:"sats_5k",name:"Sat Whale",emoji:"🧊",desc:"Claimed 5,000 sats total",check:()=>void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=5e3,pts:250},{id:"predict_1",name:"Oracle",emoji:"🎱",desc:"Made your first price prediction",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.total||0)>=1,pts:10},{id:"predict_correct_5",name:"Crystal Ball",emoji:"🏐",desc:"5 correct predictions",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.correct||0)>=5,pts:75},{id:"first_purchase",name:"Bitcoiner",emoji:"🛒",desc:"Completed the First Bitcoin Purchase guide",check:()=>"true"===localStorage.getItem("btc_fp_completed"),pts:100},{id:"lightning_setup",name:"Lightning Rod",emoji:"⚡",desc:"Set up a Lightning wallet or added a Lightning address",check:()=>"true"===localStorage.getItem("btc_lightning_setup"),pts:100},{id:"global_citizen",name:"Global Citizen",emoji:"🌍",desc:"Added your country to your profile — representing Bitcoin worldwide",check:()=>void 0!==currentUser&¤tUser&&!!currentUser.country,pts:100},{id:"trail_meadow",name:"Meadow Walker",emoji:"🌿",desc:"Completed The Meadow trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("meadow")}catch(e){return!1}},pts:200},{id:"trail_mountain",name:"Mountain Climber",emoji:"⛰️",desc:"Completed The Mountain trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("mountain")}catch(e){return!1}},pts:400},{id:"trail_summit",name:"Summit Conqueror",emoji:"🏔️",desc:"Completed The Summit trail",check:()=>{try{return JSON.parse(localStorage.getItem("btc_trail_passed")||"[]").includes("summit")}catch(e){return!1}},pts:750},{id:"trail_all",name:"Trail Master",emoji:"🏁",desc:"Completed all three Nacho's Trails",check:()=>{try{var e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]");return e.includes("meadow")&&e.includes("mountain")&&e.includes("summit")}catch(e){return!1}},pts:500},{id:"tip_first",name:"First Tip",emoji:"💸",desc:"Sent your first Lightning tip",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=1,pts:25},{id:"tip_10",name:"Generous Pleb",emoji:"💛",desc:"Tipped 10 times",check:()=>parseInt(localStorage.getItem("btc_tips_sent")||"0")>=10,pts:75},{id:"tip_whale",name:"Whale Tipper",emoji:"🐳",desc:"Tipped 1,000+ sats total",check:()=>parseInt(localStorage.getItem("btc_tips_total_sats")||"0")>=1e3,pts:150},{id:"tip_magnet",name:"Tip Magnet",emoji:"🧲",desc:"Received 10 tips from others",check:()=>parseInt(localStorage.getItem("btc_tips_received")||"0")>=10,pts:100},{id:"referral_1",name:"First Referral",emoji:"🔗",desc:"Referred 1 friend who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=1,pts:50},{id:"referral_5",name:"Connector",emoji:"🤝",desc:"Referred 5 friends who reached Maxi rank",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=5,pts:100},{id:"referral_10",name:"Network Effect",emoji:"🌐",desc:"Referred 10 friends to Bitcoin education",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=10,pts:200},{id:"referral_25",name:"Orange Pill Machine",emoji:"💊",desc:"Orange-pilled 25 people via your link",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=25,pts:500},{id:"referral_50",name:"Super Spreader",emoji:"📡",desc:"Referred 50 people — legend status",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=50,pts:1e3},{id:"referral_100",name:"Viral Plebian",emoji:"👑",desc:"Referred 100 people — you are the movement",check:()=>void 0!==currentUser&¤tUser&&(currentUser.referralCount||0)>=100,pts:2500},{id:"referred",name:"Referred Friend",emoji:"🫂",desc:"Joined Bitcoin Education Archive via a referral link",check:()=>void 0!==currentUser&¤tUser&&!!currentUser.referredBy,pts:25},{id:"dm_first",name:"DM Starter",emoji:"✉️",desc:"Sent your first direct message",check:()=>parseInt(localStorage.getItem("btc_dms_sent")||"0")>=1,pts:15},{id:"react_50",name:"Reaction King",emoji:"❤️",desc:"Reacted to 50 messages in Global Chat",check:()=>parseInt(localStorage.getItem("btc_chat_reactions")||"0")>=50,pts:50},{id:"predict_streak_3",name:"Oracle Streak",emoji:"🎯",desc:"3 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=3,pts:50},{id:"predict_streak_10",name:"Nostradamus",emoji:"🔮",desc:"10 correct predictions in a row",check:()=>void 0!==currentUser&¤tUser&&(currentUser.predictions&¤tUser.predictions.bestStreak||0)>=10,pts:250},{id:"spin_30",name:"Lucky Spinner",emoji:"🎰",desc:"Spun the wheel 30 days total",check:()=>parseInt(localStorage.getItem("btc_spin_count")||"0")>=30,pts:75},{id:"spin_streak_7",name:"Spin Streak",emoji:"🎡",desc:"Spun 7 days in a row",check:()=>parseInt(localStorage.getItem("btc_spin_streak")||"0")>=7,pts:50},{id:"spin_jackpot",name:"Jackpot Winner",emoji:"🌟",desc:"Hit the RARE drop on the spin wheel",check:()=>"true"===localStorage.getItem("btc_spin_hit_rare"),pts:100},{id:"cert_double",name:"Double Scholar",emoji:"🏛️",desc:"Earned both Scholar AND Protocol Expert certifications",check:()=>"true"===localStorage.getItem("btc_scholar_prop_passed")&&"true"===localStorage.getItem("btc_scholar_tech_passed"),pts:250},{id:"sf_first_hash",name:"First Hash",emoji:"⛏️",desc:"Generated your first hash during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1,pts:10},{id:"sf_10_hashes",name:"Pickaxe Swinger",emoji:"💥",desc:"Generated 10 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=10,pts:25},{id:"sf_50_hashes",name:"Mine Foreman",emoji:"🪨",desc:"Generated 50 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=50,pts:75},{id:"sf_100_hashes",name:"Hash Machine",emoji:"🔩",desc:"Generated 100 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=100,pts:150},{id:"sf_500_hashes",name:"ASIC Mode",emoji:"🖥️",desc:"Generated 500 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=500,pts:500},{id:"sf_1000_hashes",name:"Mining Rig",emoji:"🏭",desc:"Generated 1,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e3,pts:1e3},{id:"sf_10000_hashes",name:"Hash Lord",emoji:"☄️",desc:"Generated 10,000 hashes during Satoshi's Favor",check:()=>parseInt(localStorage.getItem("btc_sf_hashes")||"0")>=1e4,pts:2100},{id:"sf_low_hash",name:"Lucky Strike",emoji:"⭐",desc:"Mined a hash under 1,000,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e6,pts:50},{id:"sf_ultra_low",name:"Golden Nonce",emoji:"✨",desc:"Mined a hash under 100,000",check:()=>parseInt(localStorage.getItem("btc_sf_best_hash")||"999999999")<1e5,pts:200},{id:"sf_block_solver",name:"Block Solver",emoji:"🌞",desc:"Solved a block! Hash under the difficulty target",check:()=>"true"===localStorage.getItem("btc_sf_solved_block"),pts:1e3},{id:"sf_contributor",name:"Community Miner",emoji:"🤝",desc:"Contributed to activating Satoshi's Favor 3 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=3,pts:50},{id:"sf_contributor_10",name:"Favor Champion",emoji:"🏅",desc:"Contributed to activating Satoshi's Favor 10 times",check:()=>parseInt(localStorage.getItem("btc_sf_activations")||"0")>=10,pts:200},{id:"raid_first",name:"Raid Recruit",emoji:"🛡️",desc:"Dealt damage to your first Raid Boss",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=1,pts:10},{id:"raid_5",name:"Raid Warrior",emoji:"🗡️",desc:"Dealt 5 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=5,pts:50},{id:"raid_10",name:"Raid Veteran",emoji:"⚙️",desc:"Dealt 10 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=10,pts:100},{id:"raid_25",name:"Raid Commander",emoji:"⚜️",desc:"Dealt 25 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=25,pts:250},{id:"raid_50",name:"Raid Legend",emoji:"👑",desc:"Dealt 50 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=50,pts:750},{id:"raid_100",name:"Raid Warlord",emoji:"🔱",desc:"Dealt 100 total raid damage",check:()=>void 0!==currentUser&¤tUser&&(currentUser.raidDamageAllTime||0)>=100,pts:1500},{id:"raid_boss_slayer",name:"Boss Slayer",emoji:"💀",desc:"Participated in defeating a Raid Boss",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=1,pts:50},{id:"raid_boss_slayer_5",name:"Boss Hunter",emoji:"🐉",desc:"Participated in defeating 5 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=5,pts:150},{id:"raid_boss_slayer_10",name:"Dragon Slayer",emoji:"🐲",desc:"Participated in defeating 10 Raid Bosses",check:()=>parseInt(localStorage.getItem("btc_raid_bosses_defeated")||"0")>=10,pts:500},{id:"raid_winner",name:"Raid Champion",emoji:"🎖️",desc:"Won the sats lottery after a Raid Boss defeat",check:()=>"true"===localStorage.getItem("btc_raid_winner"),pts:250}];let earnedBadges=new Set,badgeCheckInterval=null;function initBadges(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(e=>earnedBadges.add(e)),badgeCheckInterval=setInterval(checkBadges,3e4),setInterval(function(){if(window._visibleBadgeQueue&&0!==window._visibleBadgeQueue.length&&!window._nachoBusy){var e=document.getElementById("nacho-bubble");e&&e.classList.contains("show")||document.getElementById("badgeCelebration")||showBadgeToast(window._visibleBadgeQueue.shift())}},5e3)}function checkBadges(){if(!window._visibleBadgesReady)return;if(window._nachoBusy)return;const e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=void 0!==completedQuests?completedQuests.size:0;for(const a of BADGE_DEFS)if(!earnedBadges.has(a.id))try{if(a.check(e,t,o)){earnedBadges.add(a.id),localStorage.setItem("btc_badges",JSON.stringify([...earnedBadges])),"function"==typeof window._raidOnBadgeEarned&&window._raidOnBadgeEarned(),"function"==typeof window.contributeSatoshiFavor&&(void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username,window.contributeSatoshiFavor("badge_earned",a.emoji+" "+a.name).catch(function(){}));var n=document.getElementById("nacho-bubble");window._nachoBusy||n&&n.classList.contains("show")?(window._visibleBadgeQueue||(window._visibleBadgeQueue=[]),window._visibleBadgeQueue.push(a)):showBadgeToast(a);var i=a.pts||20;if("function"==typeof awardPoints&&awardPoints(i,"Badge: "+a.name+" "+a.emoji,null,null,null,a.id),void 0!==db&&void 0!==auth&&auth.currentUser)try{db.collection("users").doc(auth.currentUser.uid).update({visibleBadges:firebase.firestore.FieldValue.arrayUnion(a.id)})}catch(e){}}}catch(e){}}window._visibleBadgesReady=!1,window.markVisibleBadgesReady=function(){JSON.parse(localStorage.getItem("btc_badges")||"[]").forEach(function(e){earnedBadges.add(e)});var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]");void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>e.length&&(e=currentUser.readChannels),void 0!==CHANNELS&&Object.keys(CHANNELS).length,void 0!==completedQuests&&completedQuests.size;var t=!1,o=[];void 0!==currentUser&¤tUser&¤tUser.visibleBadges&&(o=currentUser.visibleBadges);for(var n=0;n𝕏 Share on Twitter'),o.innerHTML='
    '+e.emoji+'
    🎉 Badge Earned!
    '+e.name+'
    '+e.desc+'
    +20 XP
    '+r+'
    ',document.body.appendChild(o),o.addEventListener("click",function(e){e.target===o&&o.remove()})}function copyBadgeLink(e,t){const o="I earned the "+e+" "+t+" badge on Bitcoin Education Archive!\nhttps://bitcoineducation.quest";navigator.clipboard.writeText(o).then(()=>{"function"==typeof showToast&&showToast("📋 Copied to clipboard!")})}function launchConfetti(){const e=document.createElement("canvas");e.id="confettiCanvas",e.style.cssText="position:fixed;inset:0;z-index:500;pointer-events:none;",e.width=window.innerWidth,e.height=window.innerHeight,document.body.appendChild(e);const t=e.getContext("2d"),o=[],n=["#f7931a","#ea580c","#fbbf24","#f59e0b","#ff6b00","#ff9500","#ffb800","#fff"];for(let t=0;t<120;t++)o.push({x:e.width/2+100*(Math.random()-.5),y:e.height/2,vx:16*(Math.random()-.5),vy:16*(Math.random()-1)-4,size:8*Math.random()+3,color:n[Math.floor(Math.random()*n.length)],rotation:360*Math.random(),rotSpeed:12*(Math.random()-.5),gravity:.12+.08*Math.random(),opacity:1,shape:Math.random()>.5?"rect":"circle"});let i=0;requestAnimationFrame(function n(){t.clearRect(0,0,e.width,e.height);let a=!1;o.forEach(o=>{o.x+=o.vx,o.vy+=o.gravity,o.y+=o.vy,o.rotation+=o.rotSpeed,o.vx*=.99,i>40&&(o.opacity-=.015),o.opacity>0&&o.y{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=o,i.type="sine",a.gain.setValueAtTime(.15*t,e.currentTime+.12*n),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.12*n+.5),i.start(e.currentTime+.12*n),i.stop(e.currentTime+.12*n+.5)})}catch(e){}}function getBadgeHTML(){var e={};function t(t,o){var n=t.filter(function(t){return!e[t.id]&&o(t)});return n.forEach(function(t){e[t.id]=!0}),n}const o={"🧭 Discovery":t(BADGE_DEFS,e=>e.id.includes("explorer")||"first_channel"===e.id||"bookworm"===e.id),"🧠 Knowledge":t(BADGE_DEFS,e=>e.id.includes("builder")||e.id.includes("diver")||e.id.includes("librarian")||e.id.includes("quest")||e.id.includes("cert_")),"🦌 Trails":t(BADGE_DEFS,e=>e.id.startsWith("trail_")),"💬 Global Chat":t(BADGE_DEFS,e=>e.id.startsWith("chat_")),"🦌 Nacho":t(BADGE_DEFS,e=>e.id.startsWith("nacho_")),"📺 Timechain TV":t(BADGE_DEFS,e=>e.id.startsWith("tctv_")),"🎧 DJ Mode":t(BADGE_DEFS,e=>e.id.startsWith("dj_")),"🎵 Music":t(BADGE_DEFS,e=>e.id.startsWith("producer")),"⚔️ PVP":t(BADGE_DEFS,e=>e.id.startsWith("pvp_")),"📝 Forum":t(BADGE_DEFS,e=>e.id.startsWith("forum_")||e.id.startsWith("article_")),"🔥 Streaks":t(BADGE_DEFS,e=>e.id.startsWith("streak_")),"🤝 Community":t(BADGE_DEFS,e=>e.id.startsWith("irl_")||e.id.startsWith("referral_")||"global_citizen"===e.id||"referred"===e.id),"⚡ Sats & Lightning":t(BADGE_DEFS,e=>e.id.startsWith("sats_")||"lightning_setup"===e.id||e.id.startsWith("tip_")),"🔮 Predictions":t(BADGE_DEFS,e=>e.id.startsWith("predict_")),"💬 Social":t(BADGE_DEFS,e=>e.id.startsWith("dm_")||"react_50"===e.id),"🎡 Spin Wheel":t(BADGE_DEFS,e=>e.id.startsWith("spin_")),"⛏️ Satoshi's Favor":t(BADGE_DEFS,e=>e.id.startsWith("sf_")),"🐲 Raid Boss":t(BADGE_DEFS,e=>e.id.startsWith("raid_")),"🌙 Fun":t(BADGE_DEFS,e=>"night_owl"===e.id||"early_bird"===e.id),"🏆 Milestones":t(BADGE_DEFS,t=>!e[t.id])};window._badgeCatMap={},Object.keys(o).forEach(function(e){(o[e]||[]).forEach(function(t){window._badgeCatMap[t.id]=e})}),void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){window._badgeCatMap[e.id]||(window._badgeCatMap[e.id]="🏆 Milestones")});let n='';n+='
    ';var i=0;for(const[e,t]of Object.entries(o)){if(0===t.length)continue;var a="bc_"+ ++i;const o=t.filter(e=>earnedBadges.has(e.id)).length,r=o===t.length;n+='
    ',n+="",n+='
    "}if(void 0!==HIDDEN_BADGES){const e=JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]"),t=HIDDEN_BADGES.filter(function(e){return!e.hidden});if(t.length>0){var r="bc_"+ ++i,s=t.filter(function(t){return e.includes(t.id)}).length,l=s===t.length;n+='
    ',n+="",n+='
    "}const o=HIDDEN_BADGES.filter(function(e){return e.hidden}),a=o.some(function(t){return e.includes(t.id)}),u=o.length,p=o.filter(function(t){return e.includes(t.id)}).length;var c="bc_"+ ++i,d=p===u;if(n+='
    ',n+="",n+='
    "}return n}window._showBadgeTip=function(e,t){e.stopPropagation();var o=document.getElementById("badgeFloatTip");if(o){var n=t.querySelector(".badge-tooltip"),i=n?n.innerHTML:t.getAttribute("title")||"";if(i){var a=t.getAttribute("data-badge-cat")||window._badgeCatMap&&window._badgeCatMap[t.getAttribute("data-badge-id")];if(a&&(i+='
    Category'+escapeHtml(a)+"
    "),"block"===o.style.display&&o._srcEl===t)return o.style.display="none",o._srcEl=null,void t.classList.remove("tapped");document.querySelectorAll(".badge-item.tapped").forEach(function(e){e.classList.remove("tapped")}),t.classList.add("tapped"),o._srcEl=t,o.innerHTML=i,o.style.display="block";var r=(e.touches?e.touches[0].clientX:e.clientX)||0,s=(e.touches?e.touches[0].clientY:e.clientY)||0;o.style.left="0px",o.style.top="0px";var l=o.offsetWidth||220,c=o.offsetHeight||80,d=window.innerWidth,u=window.innerHeight,p=Math.min(r-l/2,d-l-10);p=Math.max(p,10);var h=s-c-12;h<10&&(h=s+24),h+c>u-10&&(h=u-c-10),o.style.left=p+"px",o.style.top=h+"px"}}},document.addEventListener("click",function(e){var t=document.getElementById("badgeFloatTip");t&&"none"!==t.style.display&&(e.target.closest(".badge-item")||(t.style.display="none",t._srcEl=null,document.querySelectorAll(".badge-item.tapped").forEach(function(e){e.classList.remove("tapped")})))},!0),window._badgeSearch=function(e){var t=(e||"").trim().toLowerCase(),o=document.getElementById("badgeSearchResults");if(o){if(document.querySelectorAll(".badge-item.badge-search-highlight").forEach(function(e){e.classList.remove("badge-search-highlight")}),!t)return o.style.display="none",void(o.innerHTML="");var n=[];void 0!==BADGE_DEFS&&(n=n.concat(BADGE_DEFS)),void 0!==HIDDEN_BADGES&&HIDDEN_BADGES.forEach(function(e){e.hidden||n.push(e)});var i=n.filter(function(e){return e.name.toLowerCase().includes(t)||(e.desc||"").toLowerCase().includes(t)}).slice(0,8);if(0===i.length)return o.innerHTML='
    No badges found for "'+escapeHtml(e)+'"
    ',void(o.style.display="block");var a="";i.forEach(function(e){var t=earnedBadges.has(e.id)||JSON.parse(localStorage.getItem("btc_hidden_badges")||"[]").includes(e.id),o=window._badgeCatMap&&window._badgeCatMap[e.id]||"",n=e.pts||20,i=e.id.replace(/[^a-zA-Z0-9_]/g,"_");a+='
    ',a+="
    '+(t?e.emoji:e.lockedEmoji||"🔘")+'
    '+escapeHtml(e.name)+'
    '+(t?"✅ ":"🔒 ")+escapeHtml(e.desc)+'
    ',a+='',a+="
    "}),o.innerHTML=a,o.style.display="block"}},window._badgeSearchToggle=function(e,t){var o=document.getElementById("bsr_detail_"+t);if(o){var n="none"!==o.style.display;document.querySelectorAll('[id^="bsr_detail_"]').forEach(function(e){if(e!==o){e.style.display="none";var t=e.previousElementSibling;if(t){var n=t.querySelector("span:last-child");n&&(n.textContent="▾")}}}),o.style.display=n?"none":"block";var i=o.previousElementSibling;if(i){var a=i.querySelector("span:last-child");a&&(a.textContent=n?"▾":"▴")}}},window._badgeSearchJump=function(e){var t=document.getElementById("badgeSearchResults"),o=document.getElementById("badgeSearchInput");t&&(t.style.display="none",t.innerHTML=""),o&&(o.value=""),document.querySelectorAll(".badge-item.badge-search-highlight").forEach(function(e){e.classList.remove("badge-search-highlight")});var n=document.querySelector('.badge-item[data-badge-id="'+e+'"]');if(n){var i=n.closest(".badges-grid");if(i&&"none"===i.style.display){i.style.display="grid";var a=i.previousElementSibling;if(a){var r=a.querySelector(".bca");r&&(r.textContent="▼")}}n.classList.add("badge-search-highlight"),setTimeout(function(){n.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(function(){n.classList.remove("badge-search-highlight")},2500)},100)}},setTimeout(initBadges,2e3);const TICKET_CONFIG={dailyLogin:1,referral:50,referralSignupBonus:50,referralPointsThreshold:2140,pointsPerTicket:5};function getReferralCode(){return currentUser&¤tUser.uid?currentUser.uid.substring(0,8):null}function getReferralLink(){const e=getReferralCode();return e?window.location.origin+window.location.pathname+"?ref="+e:""}function captureReferralCode(){const e=new URLSearchParams(window.location.search).get("ref");if(e&&e.length>=6&&(localStorage.setItem("btc_referral_code",e),window.history&&window.history.replaceState)){const e=window.location.pathname+window.location.hash;window.history.replaceState({},"",e)}}async function awardDailyTicket(){try{if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;const e=(new Date).toISOString().split("T")[0];if(currentUser.lastTicketDate===e)return;const t=TICKET_CONFIG.dailyLogin,o=t*TICKET_CONFIG.pointsPerTicket,n=(currentUser.orangeTickets||0)+t;if("function"==typeof awardPoints){const e=await awardPoints(o,"🎟️ Daily tickets",null,t);if(!e||!e.success)return}currentUser.lastTicketDate=e,currentUser.orangeTickets=(currentUser.orangeTickets||0)+t,setTimeout(function(){"function"==typeof showToast&&showToast("🎟️ +1 Orange Ticket — Welcome back! (Total: "+n+")")},2500),"function"==typeof updateRankUI&&updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}catch(e){console.warn("Daily ticket error:",e)}}async function attachReferral(e){const t=localStorage.getItem("btc_referral_code");if(t&&!e.startsWith(t))try{const o=await db.collection("users").where("referralCode","==",t).limit(1).get();let n=null;n=o.empty?null:o.docs[0].id,await db.collection("users").doc(e).update({referredBy:t,referralVerified:!1}),await db.collection("referrals").doc(e).set({referredUser:e,referrerCode:t,referrerUid:n||"",createdAt:firebase.firestore.FieldValue.serverTimestamp(),verified:!1,ticketsAwarded:!1}),localStorage.removeItem("btc_referral_code")}catch(e){console.log("Referral attach error:",e)}}async function checkReferralQualifications(){if(!(currentUser&&db&&auth&&auth.currentUser))return;if(auth.currentUser.isAnonymous)return;if(window._referralChecked)return;window._referralChecked=!0;const e=getReferralCode();if(e)try{const t=await db.collection("referrals").where("referrerCode","==",e).where("ticketsAwarded","==",!1).get();if(t.empty)return;let o=0;for(const e of t.docs){const t=e.data().referredUser,n=await db.collection("users").doc(t).get();if(!n.exists)continue;const i=n.data();(i.points||0)>=TICKET_CONFIG.referralPointsThreshold&&(i.totalVisits||0)>=2&&(o+=TICKET_CONFIG.referral,await db.collection("referrals").doc(e.id).update({verified:!0,ticketsAwarded:!0,verifiedAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("users").doc(t).update({referralVerified:!0}))}if(o>0){const e=o*TICKET_CONFIG.pointsPerTicket;currentUser.orangeTickets,"function"==typeof awardPoints&&await awardPoints(e,"🎟️ Referral tickets",null,o),currentUser.orangeTickets=(currentUser.orangeTickets||0)+o,showToast("🎟️ +"+o+" Orange Tickets — Referral"+(o>50?"s":"")+" verified!"),"function"==typeof notifySelfReferral&¬ifySelfReferral(o),updateRankUI(),"function"==typeof checkHiddenBadges&&checkHiddenBadges()}}catch(e){console.log("Referral check error:",e)}}async function ensureReferralCode(){if(currentUser&&db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&!currentUser.referralCode){const e=getReferralCode();e&&(await db.collection("users").doc(currentUser.uid).update({referralCode:e}),currentUser.referralCode=e)}}async function getReferralStats(){if(!currentUser||!db)return{total:0,verified:0,pending:0};const e=getReferralCode();if(!e)return{total:0,verified:0,pending:0};try{const t=await db.collection("referrals").where("referrerCode","==",e).get();let o=t.size,n=0,i=0;return t.forEach(e=>{e.data().verified?n++:i++}),{total:o,verified:n,pending:i}}catch(e){return{total:0,verified:0,pending:0}}}function renderTicketsSection(){return'
    Orange Tickets
    '+(currentUser&¤tUser.orangeTickets||0)+'
    Earn tickets by logging in daily (+1), spinning the daily wheel, and referring friends (+50 per verified referral!). Each ticket earned also awards 5 bonus points!

    🏆 The more tickets you have, the higher your chances in future giveaways!
    📅
    Daily Login
    +1 ticket
    🤝
    Referral
    +50 tickets
    '}function renderReferralSection(){const e=getReferralLink();return getReferralCode()?'
    🔗 Referral Program
    Share your link with friends. Earn 50 Orange Tickets for each referral who logs in and earns 2,140+ points (Maxi rank).
    Loading referral stats...
    ':""}function copyReferralLink(){const e=document.getElementById("referralLinkInput");e&&(navigator.clipboard?navigator.clipboard.writeText(e.value).then(function(){showToast("🔗 Referral link copied!")}):(e.select(),document.execCommand("copy"),showToast("🔗 Referral link copied!")))}async function loadReferralStatsUI(){const e=document.getElementById("referralStats");if(!e)return;const t=await getReferralStats();0===t.total?e.innerHTML='No referrals yet. Share your link to start earning!':e.innerHTML='
    👥 Total: '+t.total+'✅ Verified: '+t.verified+'⏳ Pending: '+t.pending+"
    "}async function onUserLoadedTickets(){currentUser&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(await ensureReferralCode(),await awardDailyTicket(),checkReferralQualifications().catch(function(){}))}function getEquippedItems(){try{return JSON.parse(localStorage.getItem("btc_nacho_equipped_multi")||"{}")}catch(e){return{}}}function getEquippedItem(){var e=getEquippedItems();return Object.values(e)[0]||localStorage.getItem("btc_nacho_equipped")||null}window.awardTickets=async function(e,t){if(e&&!(e<1)&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&void 0!==currentUser&¤tUser){currentUser.orangeTickets;var o=e*TICKET_CONFIG.pointsPerTicket;try{"function"==typeof awardPoints&&await awardPoints(o,"🎟️ "+(t||"Orange Tickets"),null,e),currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,"function"==typeof updateRankUI&&updateRankUI()}catch(e){console.warn("[tickets] Award error:",e)}"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Tickets! "+(t||""))}},"undefined"!=typeof window&&captureReferralCode(),function(){const e=function(){const e=(new Date).toISOString().split("T")[0];if(void 0===CHANNELS)return[];const t=Object.keys(CHANNELS),o=[];let n=0;for(let t=0;t{const t=document.querySelector("[onclick*=\"go('"+e+"'\"]");if(t){const e=document.createElement("span");e.style.cssText="position:absolute;top:4px;right:4px;background:#f7931a;color:#fff;font-size:0.55rem;font-weight:900;padding:2px 5px;border-radius:4px;box-shadow:0 0 10px rgba(247,147,26,0.4);",e.textContent="2X PTS",t.style.position="relative",t.appendChild(e)}}),window._dailyBoosts=e}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}(),function(){let e={price:null,blockHeight:null,fees:null,mempoolSize:null,lastFetch:0};const t=3e5;async function o(){const o=Date.now();if(!(o-e.lastFetch900:"true"===e)){var t=document.getElementById("btcTicker");return t&&t.remove(),void document.body.classList.remove("ticker-visible")}var n=document.getElementById("btcTicker");n||((n=document.createElement("div")).id="btcTicker",document.body.prepend(n)),document.body.classList.add("ticker-visible"),n.style.cssText="position:fixed;top:0;left:0;right:0;z-index:10005;background:#030712;border-bottom:1px solid #f7931a;padding:0;height:32px;overflow:hidden;display:flex;align-items:center;font-family:inherit;font-size:0.75rem;color:#94a3b8;line-height:32px;";var i=document.createElement("div");i.id="tickerScroller",i.style.cssText="display:flex;white-space:nowrap;width:max-content;animation:btcTickerScroll 25s linear infinite;will-change:transform;";const a='\n
    \n \n 📡 LOADING SIGNAL...\n \n
    ';i.innerHTML=a+a+a+a,n.innerHTML="",n.appendChild(i);var r=document.getElementById("btcTickerStyle");r||((r=document.createElement("style")).id="btcTickerStyle",document.head.appendChild(r)),r.textContent="\n @keyframes btcTickerScroll { 0% { transform: translateX(0); } 100% { transform: translateX(-50%); } }\n #btcTicker:hover #tickerScroller { animation-play-state: paused; }\n @media(max-width:900px) { \n body.ticker-visible .mobile-bar { top: 32px !important; }\n body.ticker-visible main { padding-top: 130px !important; }\n body.ticker-visible aside { top: 130px !important; z-index: 10006; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n #btcTicker { font-size: 0.65rem; height: 32px; }\n body.ticker-visible .progress-bar { top: 118px !important; }\n }\n @media(min-width:901px) { \n body.ticker-visible aside { padding-top: 32px; }\n body.ticker-visible main { padding-top: 32px; }\n body.ticker-visible #nachoModeScreen { height: calc(100vh - 32px) !important; margin-top: 32px; }\n body.ticker-visible .progress-bar { top: 32px !important; }\n }",fetch("newsletter-data.json?v="+Date.now()).then(e=>e.json()).then(e=>{const t=n.querySelectorAll(".t-news-items");if(t&&e.news){let o="";e.news.forEach((e,t)=>{var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #"+(t+1)+""+n+""}),t.forEach(e=>e.innerHTML=o)}}).catch(e=>{n.querySelectorAll(".t-news-items").forEach(e=>e.innerHTML="📡 TECHNICAL SIGNAL OFFLINE")}),o(),setInterval(function(){o()},6e4);var s="";setInterval(function(){fetch("newsletter-data.json?v="+Date.now()).then(function(e){return e.json()}).then(function(e){var t=document.querySelectorAll(".t-news-items");if(t.length>0&&e.news&&e.news.length>0){var o="";if(e.news.slice(0,3).forEach(function(e,t){var n=("function"==typeof escapeHtml?escapeHtml(e.title):e.title.replace(/<[^>]+>/g,"")).toUpperCase(),i=e.link&&/^https:\/\//.test(e.link)?e.link:"#";o+='SIGNAL #"+(t+1)+""+n+""}),o!==s){s=o;var n=document.getElementById("tickerScroller");t.forEach(function(e){e.innerHTML=o}),n&&(n.style.animation="none",n.offsetHeight,n.style.animation="btcTickerScroll 25s linear infinite")}}}).catch(function(){})},18e5)}function i(e){return e?e>=1e3?"$"+Math.round(e).toLocaleString():"$"+e.toFixed(2):null}window.getNachoLiveData=function(){return e},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",n):n(),window.nachoLiveAnswer=function(t){var o=t.toLowerCase();if(/price|how much is|what.?s bitcoin at|current price|btc price|bitcoin worth|bitcoin cost/.test(o)){var n,a=e.price;if(a||(n=parseFloat(localStorage.getItem("btc_last_price")))&&n>0&&(a=n),!a)return null;var r=i(a),s=["Bitcoin is currently at "+r+"! Still early, {name}. 📈🦌","The current BTC price is "+r+". Number go up technology! 📊","Right now, 1 BTC = "+r+". How many sats are you stacking, {name}? ⚡"];return{answer:s[Math.floor(Math.random()*s.length)],channel:"charts",channelName:"Charts"}}if(/block height|current block|what block|how many blocks|latest block/.test(o))return e.blockHeight?{answer:"We're currently at block "+e.blockHeight.toLocaleString()+"! Every block is history being written, {name}. ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:(n=localStorage.getItem("btc_last_height"))?{answer:"I'm still syncing, but the last block I saw was "+parseInt(n).toLocaleString()+"! ⛓️",channel:"blockchain-timechain",channelName:"Blockchain / Timechain"}:null;if(/halving|halvening|next halving|when.*halving|halving countdown/.test(o)){var l=function(){var t=e.blockHeight;if(!t)return null;var o=21e4*Math.ceil(t/21e4),n=o-t;return{nextHalving:o,blocksLeft:n,daysLeft:Math.round(10*n/1440)}}();return l?{answer:"The next halving is at block "+l.nextHalving.toLocaleString()+" -- that's "+l.blocksLeft.toLocaleString()+" blocks away (~"+l.daysLeft+" days). Tick tock, {name}! ⏰",channel:"scarce",channelName:"Scarce"}:null}return null},window.nachoLiveMessage=function(){if(Math.random()>.15)return null;if(o(),!e.price)return null;var t=[];if(e.price){var n=i(e.price);t.push({pose:"cool",text:"BTC is at "+n+" right now, {name}. Just thought you should know. 😎📈"})}return e.blockHeight&&t.push({pose:"brain",text:"We just passed block "+e.blockHeight.toLocaleString()+". Every block is a heartbeat of the network. ⛓️💓"}),0===t.length?null:t[Math.floor(Math.random()*t.length)]},setTimeout(o,3e3),setInterval(o,t),window.toggleTickerSetting=function(){var e=localStorage.getItem("btc_ticker_enabled");if(null===e?"function"==typeof isMobile?!isMobile():window.innerWidth>900:"true"===e){localStorage.setItem("btc_ticker_enabled","false");var t=document.getElementById("btcTicker");t&&t.remove(),document.body.classList.remove("ticker-visible"),"function"==typeof showToast&&showToast("📡 Signal ticker hidden. Refresh to fully apply.")}else localStorage.setItem("btc_ticker_enabled","true"),window._tickerInitialized=!1,n(),"function"==typeof showToast&&showToast("📡 Signal ticker enabled!");"function"==typeof showSettingsPage&&showSettingsPage("prefs")}}(),function(){const e="\"Nacho\"🦌');\">",t='
    🛋️
    🍿
    ';function o(){return"timechain-tv"===window.currentPage||"#timechain-tv"===window.location.hash}const n={default:"🦌",wave:"👋",think:"🤔",celebrate:"🎉",point:"👆",eyes:"👀",fire:"🔥",brain:"🧠",cool:"😎",sleep:"💤",cheese:"🧀",love:"🧡"};window._btcData={price:null,height:null,halvingBlocks:null,lastUpdate:0};const i={whitepaper:{pose:"brain",text:"It looks like you're reading the whitepaper! This is where it all started — 9 pages that changed the world! 📜"},"self-custody":{pose:"point",text:"It looks like you're learning about self-custody! Remember: Nacho keys, nacho cheese. 🧀🔑"},"investment-strategy":{pose:"think",text:"It looks like you're planning your stack strategy! Pro tip: DCA and chill. Time in the market beats timing the market. 📈"},mining:{pose:"fire",text:"It looks like you're exploring mining! Every 10 minutes a new block is born. Beautiful, isn't it? ⛏️"},"privacy-nonkyc":{pose:"eyes",text:"It looks like you value your privacy! Good. A wise buck never reveals his forest location. 🕵️"},"layer-2-lightning":{pose:"celebrate",text:"It looks like you're exploring Lightning! This is how Bitcoin scales to millions of transactions per second! ⚡⚡"},"fun-facts":{pose:"cool",text:"It looks like you're browsing fun facts! This channel is my personal favorite. Don't tell the others. 🤫"},history:{pose:"brain",text:"It looks like you're studying Bitcoin history! Those who don't learn history are doomed to repeat it. 📚"},charts:{pose:"eyes",text:"It looks like you're checking the charts! Number go up technology, am I right? 📊"},"problems-of-money":{pose:"think",text:"It looks like you're learning why fiat is broken! This is where many people get orange-pilled. 🟠"},"giga-chad":{pose:"fire",text:"It looks like you're in the Giga Chad channel! Based and orange-pilled. 💪"},"memes-funny":{pose:"celebrate",text:"It looks like you're looking at memes! A deer of culture, I see. 😏"},"evidence-against-alts":{pose:"cool",text:"It looks like you're reading about altcoins! Spoiler: there's only Bitcoin. 🦌"},scarce:{pose:"brain",text:"It looks like you're learning about scarcity! Only 21 million will ever exist. Even I can't make more. 💎"},decentralized:{pose:"fire",text:"It looks like you're exploring decentralization! No single point of failure. Like a forest — cut one tree, the rest stand strong. 🌲"},secure:{pose:"point",text:"It looks like you're reading about Bitcoin's security! More computing power secures this network than anything else on Earth. 🔒"},money:{pose:"think",text:"It looks like you're learning what money really is! Hint: it's not what the government tells you. 💰"},programmable:{pose:"brain",text:"It looks like you're exploring programmable money! Smart contracts on Bitcoin — the future is being built right here. 🔧"},consensus:{pose:"think",text:"It looks like you're studying consensus! This is how thousands of nodes agree without a boss. Democracy at the protocol level. 🤝"},"difficulty-adjustment":{pose:"brain",text:"It looks like you're learning about the difficulty adjustment! The most elegant part of Bitcoin's design, in my humble deer opinion. ⚙️"},"blockchain-timechain":{pose:"fire",text:"It looks like you're reading about the timechain! Fun fact: many Bitcoiners prefer 'timechain' over 'blockchain.' ⛓️"},"pow-vs-pos":{pose:"cool",text:"It looks like you're comparing PoW vs PoS! Spoiler: Proof of Work wins. Always has. 🏆"},"articles-threads":{pose:"brain",text:"It looks like you're browsing articles! This channel has some of the best Bitcoin writing ever published. Take your time! 📰"},books:{pose:"love",text:"It looks like you're checking out Bitcoin books! The Bitcoin Standard changed my life. Well, my deer life. 📖"},podcasts:{pose:"cool",text:"It looks like you're browsing podcasts! Great for learning while you graze... I mean, commute. 🎧"},"movies-tv":{pose:"celebrate",text:"It looks like you're looking at Bitcoin movies! Grab some popcorn (and cheese). 🍿🧀"},"one-stop-shop":{pose:"point",text:"It looks like you're in the one-stop shop! This is the starter pack — everything a newcomer needs. 🎁"},regulation:{pose:"think",text:"It looks like you're reading about regulation! Governments are slowly figuring out they can't stop Bitcoin. 🏛️"},nodes:{pose:"fire",text:"It looks like you're learning about nodes! Running your own node = verifying everything yourself. Trust no one! 🖥️"},geopolitics___macroeconomics:{pose:"brain",text:"It looks like you're exploring the macro picture! Bitcoin isn't just money — it's a geopolitical shift. 🌍"},"jobs-earn":{pose:"celebrate",text:"It looks like you're checking out Bitcoin jobs! Get paid in sats — the dream! 💼⚡"},"apps-tools-services-models":{pose:"point",text:"It looks like you're browsing Bitcoin tools and apps! So many ways to use the network. 🛠️"},music:{pose:"celebrate",text:"It looks like you're checking Bitcoin music! Yes, there are Bitcoin songs. And yes, they slap. 🎵"},"art-inspiration":{pose:"love",text:"It looks like you're browsing Bitcoin art! Creativity meets sound money. Beautiful. 🎨"},games:{pose:"cool",text:"It looks like you're checking out Bitcoin games! Learn while you play — my kind of strategy. 🎮"},health:{pose:"love",text:"It looks like you're in the health channel! Sound money, sound body, sound mind. 🏋️"},nostr:{pose:"fire",text:"It looks like you're exploring Nostr! Decentralized social media — Bitcoin's best friend. 💜"},curriculum:{pose:"brain",text:"It looks like you're looking at Bitcoin education materials! Perfect for teachers and students! 📝"},"misconceptions-fud":{pose:"cool",text:"It looks like you're fighting FUD! Arm yourself with facts. This channel is your ammo. 🛡️"},cryptography:{pose:"brain",text:"It looks like you're diving into cryptography! This is the math that makes Bitcoin unbreakable. 🔢"},"tail-emission":{pose:"think",text:"It looks like you're reading about tail emission! A big debate in the Bitcoin world. What do you think? 🤔"},stablecoins:{pose:"eyes",text:"It looks like you're reading about stablecoins! Useful on-ramps, but remember — Bitcoin is the exit. 🚪"}},a=[{pose:"brain",text:"📜 Have you read Bitcoin's Whitepaper? It's only 9 pages and it started a revolution! Read it here → 🦌"},{pose:"fire",text:'🔥 Pro tip: Read the Bitcoin Whitepaper — it\'s the Genesis document! Only 9 pages changed the world forever. Check it out →'},{pose:"point",text:"💡 Tip: The sidebar on the left has ALL topics organized by category. Tap a category to expand it!"},{pose:"point",text:"💡 Tip: Click the 🎲 dice button to jump to a random channel — great for discovering new topics!"},{pose:"point",text:"💡 Tip: Use the 🔍 search button to find any subject across all 146+ topics instantly!"},{pose:"point",text:"💡 Tip: Click the Bitcoin logo at the top to return to the homepage anytime!"},{pose:"point",text:"💡 Tip: Hit the ⭐ button on any channel to save it to your favorites for quick access!"},{pose:"point",text:"💡 Tip: Your Exploration Map on the homepage shows every channel you've visited. Try to light them all up! 🗺️"},{pose:"point",text:"💡 Tip: Channels you've already read get a ✓ checkmark in the sidebar. Track your progress!"},{pose:"brain",text:"💡 Tip: You earn XP by visiting daily (+5), opening new topics (+10), and reading (+15 per 30 sec)!"},{pose:"point",text:"💡 Tip: Check the leaderboard to see how you rank against other Bitcoiners! Click your rank bar at the bottom."},{pose:"fire",text:"💡 Tip: Keep a daily streak going! Every 5 days in a row = bonus 100 points! 🔥"},{pose:"point",text:"💡 Tip: There are 9 rank levels from Normie to Satoshi. What level are you? Check Settings → Data!"},{pose:"cheese",text:"💡 Tip: Earn Orange Tickets daily just by logging in and exploring! 🎟️"},{pose:"point",text:"💡 Tip: Share your referral link (Settings → Tickets) and earn 50 tickets for each verified friend!"},{pose:"celebrate",text:"💡 Tip: Each Orange Ticket also gives you 5 bonus XP! Tickets + points = double reward! 🎟️⭐"},{pose:"brain",text:"💡 Tip: Hit 'Start a Quest' in the sidebar to test your Bitcoin knowledge and earn XP! ⚡"},{pose:"fire",text:"💡 Tip: The Bitcoin Scholar Certification Quest is the ultimate test — pass it to earn the 🎓 badge + 300 points!"},{pose:"eyes",text:"💡 Tip: There are 9 hidden badges to unlock! Each one awards points. Explore the site to discover them all! 🏅"},{pose:"point",text:"💡 Tip: Badges scale in points from 25 to 1,000! The hardest ones are worth the most! 💰"},{pose:"point",text:"💡 Tip: Click your username or the sign-in button to access your Settings — Account, Tickets, Prefs, Security, Data!"},{pose:"point",text:"💡 Tip: You can switch between dark and light theme in Settings → Prefs! 🌙☀️"},{pose:"point",text:"💡 Tip: The site works offline too! Add it to your home screen as an app! 📱"},{pose:"point",text:"💡 Tip: You can export all your data anytime in Settings → Data. Your data is yours! 📥"},{pose:"point",text:"💡 Tip: Don't like me? Long-press to hide me. But I'll miss you. 🥺 (You can bring me back in Settings → Prefs)"},{pose:"brain",text:"💡 Tip: YouTube videos are embedded right in the channels — click to play without leaving the site! 🎬"},{pose:"point",text:"💡 Tip: Tweets are embedded too! Click '▶ Click to display tweet' to expand them. 🐦"},{pose:"fire",text:'📺 Tip: Timechain TV streams 21 curated channels 24/7 — earn 10 pts per 10 min watched! Tune in →'},{pose:"cheese",text:'🛋️ Tip: Couch with me on Timechain TV — I react to every channel you tune into! 🍿 Let\'s chill →'},{pose:"point",text:"💡 Tip: Timechain TV has a global clock — every viewer on the same channel sees the same moment. True synchronized TV! ⏰"},{pose:"celebrate",text:"👑 Tip: Watch 24 hours on Timechain TV to unlock the 👑 Couch King badge + 100 points!"},{pose:"point",text:"💡 Tip: The Quote of the Day on the homepage changes daily — click it to jump to the related channel! 💬"},{pose:"point",text:"💡 Tip: New to Bitcoin? Start with the 'one-stop-shop' channel — it has everything to get you started! 🎯"},{pose:"brain",text:"💡 Tip: Channels are organized into Properties, Experienced Topics, Resources, and Additional Info. Start with Properties!"},{pose:"point",text:"💡 Tip: Post in the PlebTalk to earn the 📣 Town Crier badge + 100 points! Press T or find it in the sidebar."},{pose:"point",text:"💡 Tip: Reply to PlebTalk posts to earn the 💬 Conversationalist badge + 75 points! Join the discussion!"},{pose:"cheese",text:"💡 Tip: LightningMart lets you buy and sell with Bitcoin! List an item to earn the 🏪 Merchant badge! Press S to check it out."},{pose:"point",text:"💡 Tip: Found something cool on LightningMart? Contact the seller to earn the 🛍️ Shopper badge!"},{pose:"celebrate",text:"💡 Tip: Check out my closet in Settings → Nacho! You can dress me up with items you unlock! 🎽🦌"},{pose:"point",text:"💡 Tip: Closet items are colorable! Equip an item, then tap 🎨 Color to customize it! 🌈"},{pose:"fire",text:"💡 Tip: Spin the Daily Wheel every day for free Orange Tickets! Look for the banner at the top of the homepage! 🎡"},{pose:"fire",text:"💡 Tip: Press N to enter Nacho Mode — a full chat experience where I answer your Bitcoin questions with AI! 🦌🧠"},{pose:"point",text:"💡 Tip: In Nacho Mode, press ↑ to recall your previous questions — just like in a chat app!"},{pose:"brain",text:"💡 Tip: Nacho Mode shows the live Bitcoin price in the header! Check it anytime! ₿"},{pose:"point",text:"💡 Tip: Tap the 🧒 button in Nacho Mode to toggle ELI5 mode — I'll explain everything in super simple language!"},{pose:"celebrate",text:"💡 Tip: In Nacho Mode, tap '🗺️ Start Bitcoin Journey' for a guided 10-step learning path from beginner to pro!"},{pose:"point",text:"💡 Tip: Tap '🎮 Quiz Me' in Nacho Mode to test your knowledge and earn XP! 🏆"},{pose:"point",text:"💡 Tip: Nacho Mode has topic chips — tap them if you don't know what to ask! ⚡ Lightning, ⛏️ Mining, and more!"},{pose:"brain",text:"💡 Tip: Every answer in Nacho Mode has 👍👎 buttons — your feedback helps me get smarter!"},{pose:"point",text:"💡 Tip: You can share any Nacho answer with the 📤 Share button — spread the Bitcoin knowledge! 🌍"},{pose:"fire",text:"💡 Tip: Use your voice! Tap 🎙️ in Nacho Mode to ask me questions by speaking! 🗣️"},{pose:"point",text:"💡 Tip: Nacho Mode saves your full chat history — come back anytime to pick up where you left off!"},{pose:"celebrate",text:"💡 Tip: Ask me 10, 25, 50, or 100 questions in Nacho Mode to unlock special milestones! 🎉"},{pose:"fire",text:"💡 Tip: We have a PlebTalk! Press T or click '🗣️ PlebTalk' in the sidebar to discuss Bitcoin! 💬"},{pose:"point",text:"💡 Tip: In PlebTalk, upvote great posts with ⚡ and earn +10 points for posting, +5 for replying!"},{pose:"brain",text:"💡 Tip: PlebTalk posts can include links! Share interesting Bitcoin articles or resources with the community! 🔗"},{pose:"point",text:"💡 Tip: Set up your profile in Settings → Account! Add a bio, website, Twitter, Nostr, and Lightning address! 📝"},{pose:"eyes",text:"💡 Tip: Click any user on the leaderboard to see their profile — including their bio and social links! 👀"},{pose:"fire",text:"💡 Tip: The Scholar Certification awards 2,100 points — that's 21 million in sats! The magic number! 🎓"},{pose:"cheese",text:"💡 Tip: Dress me up! Check out Nacho's Closet in Settings → Stats/Nacho. Unlock items as our friendship grows! 👔🦌"},{pose:"cool",text:"💡 Tip: I wear my closet items in Nacho Mode too! Equip something and check out my hero section! 🦸"},{pose:"point",text:"💡 Tip: Press ? to see ALL keyboard shortcuts! N=Nacho, T=PlebTalk, P=Donate, L=Leaderboard, and more! ⌨️"},{pose:"point",text:"💡 Tip: Press A to quickly ask me a question from any page — no need to enter Nacho Mode! 🦌"},{pose:"cool",text:"💡 Tip: You can sign in with Nostr! If you have Alby or nos2x, click the 🟣 Nostr button on the sign-in page! ⚡"},{pose:"love",text:"💡 Tip: Press P to open the donation page — support the archive with Lightning! Every sat counts! ⚡🧡"},{pose:"point",text:"💡 Tip: The site supports 15+ languages! Change it in Settings → Prefs. I can even answer in your language! 🌍"},{pose:"point",text:"💡 Tip: You can DM any user! Tap their name on the leaderboard → 💬 Message. Your inbox is in the DMs tab! 📬"},{pose:"eyes",text:"💡 Tip: DMs are protected — you need 50 points and a 24h-old account to message. No scammers allowed! 🛡️"},{pose:"point",text:"💡 Tip: Never share your seed phrase, private keys, or send Bitcoin to strangers in DMs! Stay safe! 🔒"},{pose:"fire",text:"💡 Tip: Challenge other Bitcoiners to PVP trivia battles! Press X or find ⚔️ PVP in the sidebar! Who knows more? 🏆"},{pose:"celebrate",text:"💡 Tip: Win PVP battles to climb the PVP leaderboard! Your wins and losses show on your profile! ⚔️"},{pose:"fire",text:"💡 Tip: Bitcoin Beats is our community music platform! Listen, upload, and discover tracks made by Bitcoiners! 🎸🦌"},{pose:"point",text:"💡 Tip: Tap a song title on Bitcoin Beats to see full track details — artist, genre, play count, and more! 🎵"},{pose:"celebrate",text:"💡 Tip: Upload your own music on Bitcoin Beats! Hit the Upload tab and share your sound with the community! 🎤"},{pose:"point",text:"💡 Tip: Like tracks on Bitcoin Beats with ❤️ and leave comments! Support Bitcoin musicians! 🎶"},{pose:"fire",text:"💡 Tip: IRL Sync helps you find Bitcoin meetups near you! Create events, RSVP, and meet Bitcoiners in person! 🤝"},{pose:"point",text:"💡 Tip: Can't find a meetup near you? Create one on IRL Sync! Be the node that connects your local community! 🌐"},{pose:"point",text:"💡 Tip: Try the Price Prediction game! Guess if Bitcoin goes up or down in 24h and track your accuracy! 📈📉"},{pose:"celebrate",text:"💡 Tip: I have a story to tell! Tap the 📖 next to me for a new chapter every day. It's an adventure! 🦌✨"}],r=[{pose:"celebrate",text:"You're doing great, {name}! Most people never even start learning about Bitcoin. You're already ahead. 🦌💪"},{pose:"fire",text:"Keep going, {name}! You're stacking knowledge like a true pleb! 📚🔥"},{pose:"love",text:"Nacho is proud of your progress, {name}! You're further down the rabbit hole than most. 🐇"},{pose:"cool",text:"Stay humble, stack sats, stack knowledge. You're doing all three, {name}. 😎"},{pose:"celebrate",text:"Every channel you read makes the FUD weaker, {name}! Keep it up! 💪"},{pose:"brain",text:"{name}, your brain is getting more orange-pilled by the minute! 🧠🟠"},{pose:"fire",text:"Tick tock, next block... and you're getting smarter with each one, {name}! ⏰"},{pose:"love",text:"The fact that you're here learning puts you ahead of 99% of people, {name}. For real. 🧡"},{pose:"celebrate",text:"Imagine telling your future self you were learning about Bitcoin in 2026, {name}. They'll thank you! 🙏"},{pose:"fire",text:"{name}, you're building generational knowledge right now. No big deal. 🏗️"},{pose:"cool",text:"Diamond hands start with a diamond mind. You're forging yours right now, {name}! 💎🧠"},{pose:"love",text:"The journey of a thousand sats begins with a single channel, {name}. You've read way more than that! 🦌"},{pose:"celebrate",text:"You're not just learning Bitcoin, {name} — you're opting out of the broken system. Respect. ✊"},{pose:"fire",text:"Number go up, knowledge go up. You're winning on both fronts, {name}! 📈🧠"},{pose:"brain",text:"Every nocioner who ever became a maxi started exactly where you are, {name}. Keep reading! 📖"}],s=[{pose:"cheese",text:"Nacho keys, nacho cheese. It's not just a tagline, it's a lifestyle. 🧀🔑"},{pose:"fire",text:"Nacho sats... They're all mine! 💰🦌"},{pose:"cheese",text:"My seed phrase? 24 different types of cheese. Very secure. Very delicious. 🔐🧀"},{pose:"cheese",text:"Bitcoin fixes everything. Except my cheese addiction. Some things are unfixable. 🧀"},{pose:"cool",text:"Live Free or Die — that's the New Hampshire motto. Also my approach to Bitcoin. 🦌🗻"},{pose:"fire",text:"These antlers aren't just for show. I'm the strongest buck in NH and the most orange-pilled. 💪🦌"},{pose:"default",text:"In a world of unlimited printing, be a limited supply. Like Bitcoin. And like me — there's only one Nacho. 🦌"},{pose:"default",text:"Some people have angel investors. You have an angel deer. You're welcome. 😇🦌"},{pose:"cool",text:"I'm not saying I'm Satoshi, but have you ever seen us in the same room? 🤫"},{pose:"eyes",text:"I've been watching you learn, {name}. Not in a creepy way. In a proud buck way. 👀"},{pose:"sleep",text:"*yawns* Don't mind me, just HODLing this corner of your screen... 💤"},{pose:"fire",text:"Few understand this... but YOU will, {name}. That's why you're here. 🔥"},{pose:"think",text:"What's a deer's favorite block? The next one! ⛏️"},{pose:"celebrate",text:"Why did Bitcoin break up with the dollar? It found someone with less baggage and a fixed supply! 💔😂"},{pose:"cool",text:"I told my friend to buy Bitcoin in 2015. He bought Dogecoin instead. We don't talk anymore. 🐕"},{pose:"think",text:"An altcoiner walks into a bar. Orders a round for everyone. Card declines. 😂"},{pose:"cheese",text:"How does a Bitcoiner cut their pizza? Into 100 million slices. 🍕"},{pose:"cool",text:"My financial advisor said diversify. So I have Bitcoin on a hardware wallet AND a paper backup. 😎"},{pose:"celebrate",text:"Knock knock. Who's there? Fiat. Fiat who? Exactly. Nobody remembers it either. 🪦"},{pose:"think",text:"What's the difference between a dollar and a Bitcoin? One goes to zero, the other came from zero. 📉📈"},{pose:"default",text:"I tried to explain Bitcoin to a goldfish once. Went about as well as explaining it to Peter Schiff. 🐟"},{pose:"cool",text:"Bitcoiners don't have FOMO. They have FONGO — Fear Of Not Getting Orange-pilled. 🟠"},{pose:"brain",text:"₿ Fact: Satoshi Nakamoto's identity is still unknown. Could be one person, could be a group. Could be a deer. 🦌"},{pose:"brain",text:"₿ Fact: The Bitcoin pizza transaction in 2010 used 10,000 BTC for two pizzas. That's billions today. 🍕"},{pose:"brain",text:"₿ Fact: There will only ever be 21 million Bitcoin. About 19.5 million have already been mined! 💎"},{pose:"brain",text:"₿ Fact: Bitcoin's network has never been hacked. Not once. 13+ years of perfect security. 🔒"},{pose:"brain",text:"₿ Fact: The smallest unit of Bitcoin is called a 'satoshi' — 0.00000001 BTC. You can own sats! ⚡"},{pose:"brain",text:"₿ Fact: El Salvador was the first country to make Bitcoin legal tender in 2021! 🇸🇻"},{pose:"brain",text:"₿ Fact: Bitcoin mining uses less energy than clothes dryers in the US. But nobody writes angry articles about dryers. 🧺"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is only 9 pages long. The US tax code is over 75,000 pages. Which one works better? 📜"},{pose:"brain",text:"₿ Fact: 'HODL' came from a typo in a passionate forum post in 2013. It became the most famous word in crypto. 😂"},{pose:"brain",text:"₿ Fact: Bitcoin processes over $10 billion in transactions daily. And it never takes a day off! 💰"},{pose:"brain",text:"₿ Fact: The genesis block contains a hidden message: 'Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"₿ Fact: You can run a full Bitcoin node on a Raspberry Pi for about $50. Be your own bank! 🖥️"},{pose:"brain",text:"₿ Fact: Bitcoin's inflation rate is now lower than gold's. Digital gold? More like better-than-gold. 🥇"},{pose:"brain",text:"₿ Fact: The Lightning Network can handle millions of transactions per second. Visa does about 1,700. ⚡"},{pose:"brain",text:"₿ Fact: About 20% of all Bitcoin is estimated to be permanently lost. That makes yours even more scarce! 🔑"},{pose:"brain",text:"₿ Fact: Bitcoin's first price was $0.000994 — less than a tenth of a penny! For 10 months it had NO price at all. 💰"},{pose:"brain",text:"₿ Fact: The chance of guessing someone's private key is the same as winning Powerball 7 times in a row! 🎰🔐"},{pose:"brain",text:"₿ Fact: The first Bitcoin faucet gave away 5 WHOLE BITCOINS per person just for solving a captcha! 🤯"},{pose:"brain",text:"₿ Fact: You only need the FIRST 4 LETTERS of each seed word to restore your wallet. All 2,048 BIP39 words have unique first 4 letters! 🔑"},{pose:"brain",text:"₿ Fact: 'Bacon' repeated 24 times is technically a valid Bitcoin seed phrase. It passes the checksum! 🥓"},{pose:"brain",text:"₿ Fact: Bitcoin has 99.987% uptime — only 14 hours of downtime in 15+ years. That rivals Google and Amazon! 🏆"},{pose:"brain",text:"₿ Fact: Satoshi's birthday (April 5) is the date of Executive Order 6102, when the US made it ILLEGAL to own gold! 🎂📜"},{pose:"brain",text:"₿ Fact: The difficulty adjustment happens every 2,016 blocks. Read that backwards: 6102 — the gold confiscation order! 🤯"},{pose:"brain",text:"₿ Fact: 2-3 million Bitcoin are permanently lost forever. That makes YOUR sats even more scarce! 💎"},{pose:"brain",text:"₿ Fact: Satoshi wrote 575 forum posts, 31,000 lines of code, used 22,000+ addresses, and never reused one! 📝"},{pose:"brain",text:"₿ Fact: Satoshi's ~1 million Bitcoin have NEVER moved. Not one satoshi. Worth tens of billions. 👑"},{pose:"brain",text:"₿ Fact: 70% of ALL US dollars in circulation were created after 2008. Over 40% since 2020 alone! 💸"},{pose:"brain",text:"₿ Fact: One dollar today buys what 4 CENTS bought in 1913. That's a 96% loss in purchasing power! 📉"},{pose:"brain",text:"₿ Fact: In August 2010, a bug created 184 BILLION fake Bitcoin. The community fixed it in hours! The largest reorg ever — 53 blocks. 😱"},{pose:"brain",text:"₿ Fact: 61% of Ethereum nodes run in the cloud. Amazon alone hosts ~25% of them. Bitcoin nodes run on Raspberry Pis worldwide! ☁️🆚🖥️"},{pose:"brain",text:"₿ Fact: Milton Friedman, Nobel Prize economist, predicted Bitcoin in 1999 — 10 years before it existed! 🔮"},{pose:"brain",text:"₿ Fact: The Bitcoin whitepaper is encoded IN the blockchain at block 230,009. It will exist as long as Bitcoin does! 📄⛓️"},{pose:"brain",text:"₿ Fact: In July 2024, a tiny Bitaxe miner with just 3 TH/s found a block — a 1-in-3,500 YEAR chance! ⛏️🎯"},{pose:"brain",text:"₿ Fact: 99% of all Bitcoin will be mined by 2035. The very last fraction won't be mined until ~2140! ⏳"},{pose:"brain",text:"₿ Fact: The original Bitcoin code contained the beginnings of a POKER GAME that Satoshi started but never finished! 🃏"},{pose:"brain",text:"₿ Fact: Only 0.06% of Bitcoin Core's code remains unchanged from what Satoshi originally wrote. Open source at its finest! 💻"},{pose:"brain",text:"₿ Fact: Christmas lights in the US alone consume more energy than the entire Bitcoin network! 🎄⚡"},{pose:"brain",text:"₿ Fact: Bitcoin mining captures methane that's 84x more warming than CO2, turning waste into sound money! 🌱"},{pose:"brain",text:"₿ Fact: NO ONE who bought Bitcoin and held for 4+ years has EVER lost money. Not once in 15+ years! 📈 (NFA)"},{pose:"brain",text:"₿ Fact: Michael Saylor said The Bitcoin Standard was 'the most impactful on our way of thinking at MicroStrategy.' 📚"},{pose:"brain",text:"₿ Fact: Gigi calls Bitcoin 'an inexhaustible teacher.' His 21 Lessons is free at 21lessons.com! 📖🧡"},{pose:"brain",text:"₿ Fact: Tomer Strolight says Satoshi's coins aren't the real treasure. The real treasure is the journey Bitcoin sends you on! 👑"},{pose:"brain",text:"₿ Fact: Bitcoin is to money what zero was to mathematics — the missing piece that makes everything work better! 🔢"},{pose:"brain",text:"₿ Fact: Every aspect of Bitcoin is TEXT — and text is speech, protected by the First Amendment! You can't ban math. 🗽"},{pose:"brain",text:"₿ Fact: Only about 2-4% of the world owns any Bitcoin. If you hold sats, you're still incredibly early! 🌍"},{pose:"think",text:'"The root problem with conventional currency is all the trust that\'s required to make it work." — Satoshi 🧠'},{pose:"think",text:'"Give me control of a nation\'s money and I care not who makes its laws." — Mayer Rothschild 🏦'},{pose:"think",text:'"We have elected to put our money and faith in a mathematical framework free of politics." — Tyler Winklevoss 🔢'},{pose:"think",text:'"Bitcoin is the most important invention since the internet." 🌐'},{pose:"fire",text:'"Fix the money, fix the world." Simple as that. 🔧🌍'},{pose:"think",text:'"Bitcoin is a swarm of cyber hornets serving the goddess of wisdom." — Michael Saylor 🐝'},{pose:"cool",text:'"Running Bitcoin." — Hal Finney, January 10, 2009. The first tweet about Bitcoin. 🏃'},{pose:"celebrate",text:"HODL your knowledge. Never sell what you've learned! 💎🙌"},{pose:"think",text:"Roses are red, fiat is dead, stack sats instead! 🌹"},{pose:"cool",text:"I've been orange-pilled since the day I grew these antlers. 🟠🦌"},{pose:"celebrate",text:"What's stronger — my antlers or Bitcoin's security? Trick question. Both unbreakable. 💪🔒"},{pose:"default",text:"The deer in New Hampshire are talking about Bitcoin. Okay, it's just me. But still. 🗻🦌"},{pose:"cheese",text:"If I had a satoshi for every time someone asked me about crypto... I'd tell them it's Bitcoin, not crypto. 🧀"},{pose:"cool",text:"My antlers pick up the Bitcoin network signal. That's not true, but it sounds cool. 📡🦌"},{pose:"fire",text:"They said Bitcoin was dead 477 times, {name}. And here we are. Still stacking. 🦌💪"},{pose:"eyes",text:"The forest is full of distractions. I stick to the trail marked ₿. 🌲"},{pose:"celebrate",text:"When in doubt, zoom out, {name}. That goes for the chart AND the rabbit hole. 🔭"},{pose:"cool",text:"Oh deer, another all-time high? I'm not surprised. 🦌📈"},{pose:"cheese",text:"What do you call a deer who loves Bitcoin? A buck-hodler! 🦌💎"},{pose:"celebrate",text:"I'm fawned of Bitcoin. Get it? ...I'll see myself out. 🦌😂"},{pose:"think",text:"People say Bitcoin is hard to understand. I say it's deer-ly obvious! 🦌💡"},{pose:"cool",text:"I don't always check the charts, but when I doe, I HODL. 🦌😎"},{pose:"fire",text:"Just earned some sats! Another buck in the wallet! 💰🦌"},{pose:"cheese",text:"Why do deer make great Bitcoiners? Because we never sell — we just stag-ger through the dips! 🦌📉📈"},{pose:"celebrate",text:"This site really helps you get to the hart of Bitcoin! ...Sorry, deer puns are my specialty. 🦌❤️"},{pose:"think",text:"Fiat currency is on its last legs. Lucky for me, I have four of them! 🦌🏃"},{pose:"cool",text:"Did you hear about the deer who understood Bitcoin? He was considered a doe-cipherpunk! 🦌🛡️"},{pose:"fire",text:"Some say the Bitcoin market is wild. Well, I AM a wild animal, so I fit right in! 🦌🔥"},{pose:"cheese",text:"I tried mining Bitcoin with my hooves. It was un-fawn-tunately not very efficient. ⛏️🦌"},{pose:"celebrate",text:"What's a deer's favorite cryptocurrency? Bit-coin, because we love our bits of grass too! 🌿🦌"},{pose:"think",text:"My financial advice? Be a deer and HODL. That's not real advice though, I'm literally a deer. 🦌📜"},{pose:"cool",text:"They call me a stag-ger-ing intellect when it comes to Bitcoin. Okay, I call myself that. 🦌🧠"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 That's not just my catchphrase — it's financial wisdom from a deer."},{pose:"cheese",text:"Remember folks: Nacho keys, nacho cheese! If you don't hold the keys, you don't hold the cheddar. 🧀"},{pose:"fire",text:"I'm not just any deer. I'm a New Hampshire buck — Live Free or Die. And I choose Bitcoin. 🗻🦌"},{pose:"cool",text:"Why did the deer buy a hardware wallet? Because he was tired of getting buck-ed by exchanges! 🦌🔐"},{pose:"think",text:"What do you call a deer who understands monetary policy? A buck who knows his doe! 🦌💰"},{pose:"celebrate",text:"I told my doe friend about Bitcoin. Now she's a whole doe-llar maximalist! 🦌🟠"},{pose:"cheese",text:"I'm not fawning over altcoins. I'm a Bitcoin-only buck. Always have been, always will be. 🦌"},{pose:"fire",text:"My antlers pick up the Bitcoin signal better than any antenna. Built-in orange frequency! 📡🦌"},{pose:"cool",text:"They say a buck in the hand is worth two in the bush. I say a sat stacked is worth a thousand fiat notes. 💎"},{pose:"think",text:"What's a deer's favorite consensus mechanism? Proof of Antlers! 🦌⛏️ ...okay, it's Proof of Work."},{pose:"celebrate",text:"Just a buck from the Granite State, orange-pilling the internet one human at a time! 🗻🟠"},{pose:"cheese",text:"I tried explaining multisig to a squirrel. He said he'd rather just bury his nuts. Different strokes! 🐿️🦌"},{pose:"default",text:"Some deer migrate south for winter. I migrate to the blockchain. It's warmer there. ⛓️🦌"},{pose:"fire",text:"These antlers have been HODLing since block 1. Diamond antlers. 💎🦌"},{pose:"cool",text:"New Hampshire motto: Live Free or Die. Bitcoin motto: Don't Trust, Verify. Same energy. 🦌🗽"},{pose:"think",text:"What do you get when a deer reads the whitepaper? An un-fawn-gettable experience! 📄🦌"},{pose:"cheese",text:"A buck walks into a bar. Orders a round for everyone. Pays in Lightning. ⚡🦌 Instant. Nearly free."},{pose:"celebrate",text:"I'm the most antler-preneurial deer you'll ever meet. My business? Bitcoin education! 🦌📚"},{pose:"default",text:"Fun deer fact: I shed my antlers every year and grow them back bigger. Just like Bitcoin sheds FUD and grows back stronger! 🦌📈"},{pose:"fire",text:"The forest has bears and bulls. I'm a buck — and bucks are ALWAYS bullish on Bitcoin! 🦌🚀"},{pose:"cool",text:"In NH we have no sales tax and no income tax. We also have me, the most based buck in the state. 🗻🦌"},{pose:"cheese",text:"Nacho keys, nacho cheese! Nacho node, nacho rules! Nacho seed phrase, nacho sats! 🧀🔑🦌"},{pose:"think",text:"What's a deer's least favorite thing? A central bank. We prefer de-deer-centralization! 🦌🏛️"},{pose:"celebrate",text:"Why am I orange? Because I was born orange-pilled, {name}! It's in my fur! 🟠🦌"},{pose:"brain",text:"🧠 Bitcoin fact: The first Bitcoin transaction was 10,000 BTC for two pizzas on May 22, 2010. We celebrate it as Bitcoin Pizza Day every year! 🍕"},{pose:"brain",text:"🧠 Did you know? Satoshi Nakamoto mined ~1.1 million BTC and never moved a single one. That's conviction. 🦌"},{pose:"brain",text:"🧠 Fact: Bitcoin's code has been running since January 3, 2009 with 99.99% uptime. No CEO, no office, no downtime. 🏆"},{pose:"brain",text:"🧠 The Genesis Block contains the message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰"},{pose:"brain",text:"🧠 There will only ever be 21 million Bitcoin. Currently ~19.6 million have been mined, and ~4 million are estimated lost forever. 🔢"},{pose:"brain",text:"🧠 Bitcoin's difficulty adjustment happens every 2,016 blocks (~2 weeks). It's the most elegant part of the protocol! ⚙️"},{pose:"brain",text:"🧠 Hal Finney received the first-ever Bitcoin transaction from Satoshi on January 12, 2009. His tweet: 'Running bitcoin.' 🏃"},{pose:"brain",text:"🧠 Bitcoin mining doesn't solve 'complex math problems.' Miners guess random nonces and hash them through SHA-256. It's a brute-force lottery! 🎲"},{pose:"brain",text:"🧠 The Lightning Network can process millions of transactions per second. Visa does about 65,000. ⚡"},{pose:"brain",text:"🧠 Bitcoin uses less than 0.1% of global energy. And over 50% of mining uses renewable energy sources. 🌱"},{pose:"brain",text:"🧠 The smallest unit of Bitcoin is called a 'satoshi' — 1 BTC = 100,000,000 sats. Named after the creator! ⚡"},{pose:"brain",text:"🧠 In 2021, El Salvador became the first country to adopt Bitcoin as legal tender. 🇸🇻"},{pose:"brain",text:"🧠 Fact: Bitcoin has survived over 470+ 'obituaries' — media declaring it dead. It's still here. It's still growing. 💀→🚀"},{pose:"brain",text:"🧠 The Bitcoin network is secured by more computational power than all the world's supercomputers combined. 🛡️"},{pose:"brain",text:"🧠 'Not your keys, not your coins' — this phrase became famous after the Mt. Gox hack in 2014 where 850,000 BTC were lost. 🔑"},{pose:"brain",text:"🧠 Bitcoin's stock-to-flow ratio after the 2024 halving is higher than gold's. It's the hardest money ever created. 💎"},{pose:"brain",text:"🧠 The Blocksize Wars of 2015-2017 proved that users — not miners or corporations — control Bitcoin's rules. 🏛️"},{pose:"brain",text:"🧠 Fun fact: You can run a full Bitcoin node on a $50 Raspberry Pi. Don't trust, verify! 🖥️"},{pose:"brain",text:"🧠 Bitcoin was worth $0 in 2009. If you bought $1 of Bitcoin at $0.001, you'd have billions today. Time in the market beats timing the market! ⏰"},{pose:"brain",text:"🧠 The Cantillon Effect: when governments print money, those closest to the printer benefit first. Bitcoin eliminates this unfair advantage. 💡"},{pose:"brain",text:"🧠 CoinJoin transactions mix multiple users' inputs together, making it nearly impossible to trace who sent what to whom. Privacy matters! 🤫"},{pose:"brain",text:"🧠 Satoshi's last known message was in April 2011: 'I've moved on to other things.' The greatest mic drop in history. 🎤⬇️"},{pose:"brain",text:"🧠 Taproot, activated in 2021, brought Schnorr signatures to Bitcoin — improving privacy and enabling more complex smart contracts. 🧰"},{pose:"brain",text:"🧠 The Bitcoin whitepaper is only 9 pages long. Nine pages that changed the world. Have you read it? 📄"},{pose:"brain",text:"🧠 Bitcoin's hash rate is measured in exahashes per second. One exahash = 1 quintillion hashes. Per SECOND. 🤯"}],l=[{pose:"wave",text:"👋 Hey, {name}! I'm Nacho — a strong buck from New Hampshire! Click me anytime for Bitcoin tips and wisdom. 🦌💪"},{pose:"wave",text:"👋 Welcome back, {name}! Your friendly NH buck missed you! Ready to tackle some Bitcoin knowledge today? 💪"},{pose:"wave",text:"👋 Nacho here, {name}! The strongest buck in New Hampshire and your Bitcoin guide. Let's learn something! 🦌"},{pose:"wave",text:"Hey {name}! 🦌 Back for more? I've got 145 channels of Bitcoin knowledge waiting for you!"},{pose:"cool",text:"Yo {name}! 😎 Nacho's in the house. What are we learning about today?"},{pose:"fire",text:"🔥 {name}! Another day, another sat stacked. Let's make today count!"},{pose:"celebrate",text:"{name}! 🎉 Great to see you. Did you know this archive has over 8,800 Bitcoin messages? Dig in!"},{pose:"brain",text:"Welcome, {name}! 🧠 Fun fact: the more you learn about Bitcoin, the more you realize there's always more to learn."},{pose:"love",text:"🧡 {name}! Nacho here. I've been guarding this archive for you. Let's explore together!"},{pose:"default",text:"Hey {name}! Tick tock, next block. What's on your mind today? 🦌⏰"},{pose:"cheese",text:"Nacho keys, nacho cheese! 🧀🔑 Welcome back, {name}. What are we diving into?"},{pose:"wave",text:"👋 Good to see you, {name}! Remember — every channel you read makes you harder to scam. Knowledge is armor!"},{pose:"fire",text:"{name}! 🦌🔥 The orange pill hits different when you study the fundamentals. Let's go!"}],c=[{pose:"eyes",text:"Great choice, {name}! I'll be over here if you need me. 👀"},{pose:"cool",text:"Ooh, excellent pick, {name}! You've got good taste. 😎"},{pose:"brain",text:"This one's a good read, {name}! Take your time. 🧠"},{pose:"fire",text:"One of my favorites! Dig in, {name}! 🦌🔥"},{pose:"love",text:"Nice, {name}! This channel has great stuff in it. 🧡"}],d=[{pose:"celebrate",text:"Nice, {name}! Points are stacking up! 🎉"},{pose:"fire",text:"{name}, you're on fire! Nacho approves! 🔥"},{pose:"celebrate",text:"Cha-ching, {name}! The knowledge is paying off! 💰"}],u=["default","eyes","default","think","default","cheese","default","cool","default","sleep","default"];let p=0,h=null,m=!0,g=null;window.clearNachoBubbleTimeout=function(){clearTimeout(g),g=null};let f=0,y=0,b=new Set,v=0,w="default";function x(){var n=localStorage.getItem("btc_nacho_hidden");"true"!==n&&"user"!==n||(m=!1);const i=document.createElement("style");i.textContent="\n #nacho-container {\n position: fixed;\n bottom: 80px;\n left: 330px;\n z-index: 250;\n display: flex;\n align-items: flex-end;\n gap: 0;\n pointer-events: none;\n transition: opacity 0.3s, transform 0.3s;\n }\n #nacho-container.hidden { opacity: 0; transform: translateY(30px); pointer-events: none; }\n\n #nacho-avatar {\n width: 110px;\n height: 110px;\n background: none;\n border-radius: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n pointer-events: auto;\n filter: drop-shadow(0 6px 16px rgba(0,0,0,0.5));\n transition: transform 0.15s;\n user-select: none;\n position: relative;\n flex-shrink: 0;\n z-index: 2;\n overflow: visible;\n }\n #nacho-avatar { -webkit-user-select: none; }\n #nacho-avatar:hover { transform: scale(1.08) rotate(-3deg); }\n #nacho-avatar:active { transform: scale(0.93); }\n #nacho-avatar .nacho-btn-stack {\n position: absolute;\n top: -5px;\n right: -4px;\n display: flex;\n flex-direction: column;\n gap: 4px;\n z-index: 5;\n }\n #nacho-avatar .nacho-closet-btn, #nacho-avatar .nacho-story-btn {\n font-size: 0.85rem;\n cursor: pointer;\n pointer-events: auto;\n background: var(--card-bg, #1a1a2e);\n border: 1px solid var(--border, #333);\n border-radius: 50%;\n width: 26px;\n height: 26px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: 0.2s;\n opacity: 0.5;\n position: relative;\n }\n #nacho-avatar .nacho-closet-btn:hover, #nacho-avatar .nacho-story-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n border-color: #f7931a;\n }\n .nacho-notif-dot {\n position: absolute;\n top: -2px;\n right: -2px;\n width: 8px;\n height: 8px;\n background: #ef4444;\n border-radius: 50%;\n border: 1.5px solid var(--card-bg, #1a1a2e);\n z-index: 6;\n pointer-events: none;\n }\n #nacho-avatar .nacho-name {\n position: absolute;\n bottom: -46px;\n left: 50%;\n transform: translateX(-50%);\n font-size: 0.7rem;\n color: #f7931a;\n font-weight: 800;\n letter-spacing: 1.5px;\n white-space: nowrap;\n text-transform: uppercase;\n text-shadow: 0 1px 4px rgba(0,0,0,0.5);\n line-height: 1.3;\n text-align: center;\n pointer-events: auto;\n cursor: pointer;\n padding: 4px 12px;\n border-radius: 8px;\n transition: background 0.2s;\n }\n #nacho-avatar .nacho-name:hover {\n background: rgba(247,147,26,0.15);\n }\n\n /* Nacho speech bubble — high contrast, always readable */\n #nacho-bubble {\n background: #111827;\n border: 2px solid #f7931a;\n border-radius: 16px;\n padding: 16px 20px 16px 18px;\n max-width: 300px;\n min-width: 200px;\n color: #f8f8f8;\n font-size: 0.9rem;\n line-height: 1.55;\n pointer-events: none;\n box-shadow: 0 8px 32px rgba(0,0,0,0.7), 0 0 12px rgba(247,147,26,0.25);\n opacity: 0;\n transform: translateY(8px) scale(0.9);\n transition: opacity 0.35s cubic-bezier(0.34, 1.56, 0.64, 1), transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);\n cursor: pointer;\n position: relative;\n margin-left: -6px;\n margin-bottom: 16px;\n z-index: 1000;\n }\n #nacho-bubble::before {\n content: '';\n position: absolute;\n bottom: 10px;\n left: -10px;\n width: 0; height: 0;\n border-top: 10px solid transparent;\n border-bottom: 10px solid transparent;\n border-right: 10px solid #f7931a;\n }\n #nacho-bubble::after {\n content: '';\n position: absolute;\n bottom: 12px;\n left: -7px;\n width: 0; height: 0;\n border-top: 8px solid transparent;\n border-bottom: 8px solid transparent;\n border-right: 8px solid #111827;\n }\n #nacho-bubble.show { opacity: 1; transform: translateY(0) scale(1); pointer-events: auto; }\n\n .nacho-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 6px;\n }\n .nacho-label {\n font-size: 0.65rem;\n color: #f7931a;\n font-weight: 800;\n text-transform: uppercase;\n letter-spacing: 1px;\n }\n .nacho-x {\n color: var(--text-faint, #666);\n font-size: 0.75rem;\n cursor: pointer;\n opacity: 0.4;\n transition: opacity 0.2s;\n padding: 2px 4px;\n }\n .nacho-x:hover { opacity: 1; }\n #nacho-text { word-wrap: break-word; max-height: 60vh; overflow-y: auto; -webkit-overflow-scrolling: touch; padding-right: 4px; }\n\n /* Clippy-style idle animations — mimic the paper clip's fidgeting */\n\n /* 1. Tap tap — like Clippy tapping on the screen */\n /* Nacho victory flight — Lightning bolt ⚡ across the full screen! */\n @keyframes nachoFly {\n /* ⚡ Lightning bolt: high-energy erratic takeoff, zigzag, and sonic boom reentry \n */\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 5% { transform: translate(-5px, 10px) rotate(-10deg) scale(0.9); }\n 10% { transform: translate(15vw, -20vh) rotate(20deg) scale(1.1); }\n 20% { transform: translate(40vw, -5vh) rotate(-15deg) scale(1); }\n 30% { transform: translate(65vw, -45vh) rotate(35deg) scale(1.2); }\n 45% { transform: translate(90vw, -10vh) rotate(-20deg) scale(1.1); }\n 60% { transform: translate(110vw, -60vh) rotate(45deg) scale(1.4); opacity: 1; }\n 61% { transform: translate(110vw, -60vh); opacity: 0; }\n /* Sonic boom reentry from the top left */\n 85% { transform: translate(-50vw, -50vh) rotate(-45deg) scale(2); opacity: 0; }\n 90% { transform: translate(-10vw, -10vh) rotate(-20deg) scale(1.5); opacity: 1; filter: brightness(3) blur(2px); }\n 95% { transform: translate(0, -20px) rotate(0deg) scale(1.1); filter: brightness(1); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n @keyframes nachoFlyMobile {\n 0% { transform: translate(0, 0) rotate(0deg) scale(1); opacity: 1; }\n 8% { transform: translate(-2vw, 5vh) rotate(-10deg) scale(0.9); }\n 15% { transform: translate(25vw, -30vh) rotate(15deg) scale(1.1); }\n 30% { transform: translate(60vw, -5vh) rotate(-15deg) scale(1); }\n 50% { transform: translate(85vw, -50vh) rotate(30deg) scale(1.3); }\n 65% { transform: translate(105vw, -20vh) rotate(10deg) scale(1.2); opacity: 1; }\n 66% { transform: translate(105vw, -20vh); opacity: 0; }\n /* Reentry from top */\n 88% { transform: translate(0, -80vh) rotate(0deg) scale(1.5); opacity: 0; }\n 94% { transform: translate(0, -10px) rotate(0deg) scale(1.1); opacity: 1; filter: brightness(2); }\n 100% { transform: translate(0, 0) scale(1); opacity: 1; }\n }\n #nacho-avatar.flying {\n animation: nachoFly 2.8s linear forwards;\n z-index: 999;\n filter: drop-shadow(0 0 20px rgba(247,147,26,0.8)) drop-shadow(0 0 40px rgba(234,88,12,0.4));\n }\n @media (max-width: 900px) {\n #nacho-avatar.flying {\n animation: nachoFlyMobile 2.4s linear forwards;\n }\n }\n /* Lightning trail particles */\n .nacho-trail {\n position: fixed;\n pointer-events: none;\n z-index: 998;\n font-size: 1.2rem;\n opacity: 1;\n transition: none;\n animation: nachoTrailFade 0.8s ease-out forwards;\n }\n .nacho-trail.stuck-cleanup { display: none !important; }\n @keyframes nachoTrailFade {\n 0% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(1.3); }\n 100% { opacity: 0; transform: scale(0.3); }\n }\n\n @keyframes nachoTap {\n 0%, 100% { transform: translateY(0); }\n 10% { transform: translateY(-6px); }\n 20% { transform: translateY(0); }\n 30% { transform: translateY(-4px); }\n 40% { transform: translateY(0); }\n }\n /* 2. Lean and look — Clippy tilting to peek at your screen */\n @keyframes nachoLean {\n 0%, 100% { transform: rotate(0deg) translateX(0); }\n 30% { transform: rotate(8deg) translateX(3px); }\n 50% { transform: rotate(8deg) translateX(3px); }\n 80% { transform: rotate(0deg) translateX(0); }\n }\n /* 3. Bored wiggle — Clippy fidgeting when idle */\n @keyframes nachoWiggle {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-6deg); }\n 30% { transform: rotate(5deg); }\n 45% { transform: rotate(-4deg); }\n 60% { transform: rotate(3deg); }\n 75% { transform: rotate(-2deg); }\n 90% { transform: rotate(0deg); }\n }\n /* 4. Bounce — Clippy's excited hop */\n @keyframes nachoBounce {\n 0%, 100% { transform: translateY(0) scale(1); }\n 20% { transform: translateY(-8px) scale(1.05); }\n 40% { transform: translateY(0) scale(0.97); }\n 55% { transform: translateY(-4px) scale(1.02); }\n 70% { transform: translateY(0) scale(0.99); }\n 85% { transform: translateY(-2px) scale(1.01); }\n }\n /* 5. Stretch — Clippy stretching/yawning */\n @keyframes nachoStretch {\n 0%, 100% { transform: scaleY(1) scaleX(1); }\n 25% { transform: scaleY(1.12) scaleX(0.92); }\n 50% { transform: scaleY(0.92) scaleX(1.08); }\n 75% { transform: scaleY(1.05) scaleX(0.97); }\n }\n /* 6. Look around — Clippy looking left and right */\n @keyframes nachoLook {\n 0%, 100% { transform: translateX(0); }\n 20% { transform: translateX(-5px); }\n 40% { transform: translateX(-5px); }\n 60% { transform: translateX(5px); }\n 80% { transform: translateX(5px); }\n }\n /* 7. Wave — Clippy waving at you */\n @keyframes nachoWave {\n 0%, 100% { transform: rotate(0deg); }\n 15% { transform: rotate(-12deg); }\n 30% { transform: rotate(10deg); }\n 45% { transform: rotate(-8deg); }\n 60% { transform: rotate(6deg); }\n 75% { transform: rotate(-3deg); }\n }\n /* 8. Sleepy bob — Clippy nodding off */\n @keyframes nachoSleepy {\n 0%, 100% { transform: translateY(0) rotate(0deg); }\n 30% { transform: translateY(2px) rotate(3deg); }\n 50% { transform: translateY(3px) rotate(5deg); }\n 70% { transform: translateY(2px) rotate(3deg); }\n }\n /* 9. Couch sway — for Timechain TV */\n @keyframes nachoSway {\n 0%, 100% { transform: rotate(-1deg) translateY(0); }\n 50% { transform: rotate(1deg) translateY(-3px); }\n }\n\n #nacho-avatar.anim-tap { animation: nachoTap 2s ease-in-out infinite; }\n #nacho-avatar.anim-lean { animation: nachoLean 3.5s ease-in-out infinite; }\n #nacho-avatar.anim-wiggle { animation: nachoWiggle 2.5s ease-in-out infinite; }\n #nacho-avatar.anim-bounce { animation: nachoBounce 1.8s ease-in-out infinite; }\n #nacho-avatar.anim-stretch { animation: nachoStretch 3s ease-in-out infinite; }\n #nacho-avatar.anim-look { animation: nachoLook 4s ease-in-out infinite; }\n #nacho-avatar.anim-wave { animation: nachoWave 1.5s ease-in-out infinite; }\n #nacho-avatar.anim-sleepy { animation: nachoSleepy 4s ease-in-out infinite; }\n\n /* Tablet — sidebar is 280px */\n @media (max-width: 1100px) {\n #nacho-container { left: 290px; }\n #nacho-avatar { width: 95px; height: 95px; }\n }\n /* Mobile — sidebar hidden, Nacho goes bottom-left, above clutter */\n @media (max-width: 900px) {\n #nacho-container { bottom: calc(50vh - 30px); left: 12px; }\n #nacho-avatar { width: 68px; height: 68px; }\n #nacho-bubble {\n position: fixed;\n bottom: calc(50vh + 50px);\n left: 12px;\n right: 12px;\n max-width: calc(100vw - 24px);\n max-height: 40vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n min-width: unset;\n width: auto;\n font-size: 0.9rem;\n padding: 16px 18px;\n margin-left: 0;\n border-radius: 14px;\n }\n #nacho-bubble::before, #nacho-bubble::after { display: none; }\n #nacho-avatar .nacho-name { font-size: 0.7rem; bottom: -44px; padding: 5px 14px; }\n }\n @media (max-width: 480px) {\n #nacho-container { bottom: calc(50vh - 40px); left: 10px; }\n #nacho-avatar { width: 60px; height: 60px; }\n #nacho-bubble {\n bottom: calc(50vh + 30px);\n left: 10px;\n right: 10px;\n max-width: calc(100vw - 20px);\n max-height: 38vh;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n font-size: 0.85rem;\n padding: 14px 16px;\n }\n #nacho-avatar .nacho-name { font-size: 0.65rem; bottom: -40px; padding: 5px 12px; }\n }\n\n /* Bring-back toggle */\n #nacho-toggle {\n position: fixed; bottom: 80px; left: 330px; z-index: 250;\n width: 52px; height: 52px;\n background: radial-gradient(circle, #fff 60%, rgba(255,255,255,0.85) 100%);\n border: 2px solid rgba(247,147,26,0.5);\n border-radius: 50%; display: none; align-items: center; justify-content: center;\n font-size: 1.6rem; cursor: pointer; opacity: 0.9; transition: all 0.3s;\n box-shadow: 0 2px 12px rgba(0,0,0,0.3), 0 0 0 3px rgba(247,147,26,0.15);\n }\n #nacho-toggle:hover { opacity: 1; transform: scale(1.1); box-shadow: 0 4px 20px rgba(247,147,26,0.4), 0 0 0 4px rgba(247,147,26,0.25); }\n @media (max-width: 1100px) { #nacho-toggle { left: 290px; } }\n @media (max-width: 900px) { #nacho-toggle { bottom: calc(50vh - 30px); left: 12px; width: 46px; height: 46px; font-size: 1.3rem; } }\n @media (max-width: 480px) { #nacho-toggle { bottom: calc(50vh - 40px); left: 10px; width: 44px; height: 44px; font-size: 1.2rem; } }\n ",document.head.appendChild(i);const a=document.createElement("div");a.id="nacho-container",m||a.classList.add("hidden");const r=o()?t:e,s=o()?"width:120px;height:100px;":"";a.innerHTML='
    '+r+'Nacho
    click to ask!
    👔📖
    🦌 '+("function"==typeof nachoNickname?nachoNickname():"Nacho")+' says
    ',document.body.appendChild(a);var c=document.getElementById("nachoClosetBtn");if(c){var d=!1;function g(){window._expanded_closet=!0,window._pendingClosetScroll=!0;try{"function"==typeof showSettings&&showSettings();var e=0;setTimeout(function t(){e++;var o=document.getElementById("usernameModal");o&&o.classList.contains("open")&&"function"==typeof showSettingsPage?showSettingsPage("data"):e<10&&setTimeout(t,150)},200)}catch(e){}"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear()}c.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),c.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d=!0},{passive:!1}),c.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),d&&(d=!1,g())},{passive:!1}),c.addEventListener("click",function(e){e.stopPropagation(),e.stopImmediatePropagation(),d||g(),d=!1},!1)}window.updateNachoNotifs=function(){var e=document.getElementById("nachoStoryNotif");if(e){var t=safeJSON("btc_nacho_story_days",[]),o=(new Date).toISOString().split("T")[0],n=t.length,i=-1===t.indexOf(o)&&n<7,a=0===n,r=localStorage.getItem("btc_nacho_story_notif_dismissed")===o;e.style.display=r||!i&&!a?"none":"block"}var s=document.getElementById("nachoClosetNotif");if(s){var l=safeJSON("btc_spin_closet_items",[]),c=safeJSON("btc_closet_viewed",[]),d=l.some(function(e){return-1===c.indexOf(e)});s.style.display=d?"block":"none"}},window.nachoStoryNotifClear=function(){var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_nacho_story_notif_dismissed",e);var t=document.getElementById("nachoStoryNotif");t&&(t.style.display="none")},window.nachoClosetNotifClear=function(){var e=safeJSON("btc_spin_closet_items",[]);localStorage.setItem("btc_closet_viewed",JSON.stringify(e));var t=document.getElementById("nachoClosetNotif");t&&(t.style.display="none")},setTimeout(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},2e3),setInterval(function(){"function"==typeof updateNachoNotifs&&updateNachoNotifs()},6e4);const f=document.createElement("div");function b(){const e=document.getElementById("nachoModeContainer"),t=document.getElementById("irl-sync-view"),o=document.getElementById("searchOverlay"),n=document.querySelector(".ticker-wrap"),i=e&&"none"!==e.style.display||t&&null!==t.offsetParent||o&&"flex"===o.style.display;if(n){n.style.transition="transform 0.4s ease",n.style.transform=i?"translateY(-100%)":"translateY(0)";const e=document.getElementById("menuToggle");e&&(e.style.opacity=i?"0.2":"1")}}f.id="nacho-toggle",f.innerHTML="🦌",f.title="Bring back Nacho",f.onclick=function(){showNacho()},m||(f.style.display="flex"),document.body.appendChild(f),function(){var e=document.getElementById("nacho-avatar");if(e){var t=null,o=!1;e.addEventListener("touchstart",function(e){o=!1,t=setTimeout(function(){o=!0,"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t),o&&(o=!1)}),e.addEventListener("touchmove",function(){clearTimeout(t)}),e.addEventListener("contextmenu",function(e){e.preventDefault(),"function"==typeof hideNacho&&hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho hidden! Tap the 🦌 icon to bring him back.")})}}(),setTimeout(function(){if(m){var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=0;try{o=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length}catch(e){}if(t<=3&&o<5){var n=parseInt(localStorage.getItem("btc_nacho_onboarding")||"1");if(k("wave"),1===n?(S('
    Hey there! I\'m Nacho, your Bitcoin education buddy! 🦌🧡

    Here\'s what you can do here:
    📚 Read 145+ Bitcoin topics — tap any in the sidebar
    🎡 Spin daily for free tickets & rewards
    Take quests to test your knowledge

    '),localStorage.setItem("btc_nacho_onboarding","2")):2===n&&o>=1?(S('
    Nice, you explored your first channel! 🎉

    Keep going — every channel you read earns you +10 XP. Here are some popular ones:

    '),localStorage.setItem("btc_nacho_onboarding","3")):3===n&&o>=3?(k("celebrate"),S('
    You\'re on fire! 🔥 '+o+' channels explored!

    Did you know you can:
    🗣️ Chat in PlebTalk — discuss Bitcoin with the community
    Browse LightningMart — buy & sell for sats
    🎓 Take the Scholar Exam — earn your Bitcoin certification

    '),localStorage.setItem("btc_nacho_onboarding","4")):4===n&&o>=5&&(k("brain"),S('
    You\'re becoming a real Bitcoiner! 🧡

    Pro tips:
    📖 Read Nacho\'s Story — a new chapter unlocks each day
    📚 Study with Flashcards to prepare for quests
    🏆 Check the Leaderboard — see where you rank
    💬 Ask me anything about Bitcoin anytime!

    — End of tour. I\'ll still be here if you need me! 🦌
    '),localStorage.setItem("btc_nacho_onboarding","5")),n<=4)return}k((e="function"==typeof nachoTimeGreeting&&Math.random()<.6?nachoTimeGreeting():U(l)).pose),S(e.text),"function"==typeof nachoPlaySound&&nachoPlaySound("pop"),setTimeout(function(){if("function"==typeof nachoStreakMessage){var e=nachoStreakMessage();e&&B(e.text,e.pose)}},12e3)}},2e3),clearInterval(h),h=setInterval(function(){if(!m)return;const e=document.getElementById("nacho-bubble");if(e&&e.classList.contains("show"))return;const t=document.getElementById("nacho-avatar");if(!t)return;p=(p+1)%u.length,k(u[p]),["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(e=>t.classList.remove(e));const o={default:["anim-tap","anim-look","anim-wiggle"],eyes:["anim-lean","anim-look"],think:["anim-lean","anim-tap"],cheese:["anim-bounce","anim-wiggle"],cool:["anim-lean","anim-tap"],sleep:["anim-sleepy"],wave:["anim-wave"],celebrate:["anim-bounce"],fire:["anim-bounce","anim-wiggle"],love:["anim-stretch","anim-tap"],brain:["anim-lean","anim-look"],point:["anim-tap","anim-lean"]}[w]||["anim-tap","anim-wiggle"];t.classList.add(U(o))},8e3),setInterval(z,55e3);const v=window.enterNachoMode;window.enterNachoMode=function(e){"function"==typeof v&&v(e),setTimeout(b,100)};const x=window.exitNachoMode;window.exitNachoMode=function(e){"function"==typeof x&&x(e),setTimeout(b,100)};const T=window.go;window.go=function(e,t,o){"function"==typeof T&&T(e,t,o),setTimeout(b,100)};const _=window.goHome;window.goHome=function(e){"function"==typeof _&&_(e),setTimeout(b,100)},setTimeout(function(){"undefined"!=typeof APP_PAGES&&APP_PAGES.forEach(e=>{"PlebTalk"===e.title&&(e.title="Pleb Talk"),"LightningMart"===e.title&&(e.title="Lightning Mart")})},2e3),window.addEventListener("beforeunload",function(e){const t=document.getElementById("questModal");t&&t.classList.contains("open")&&(e.preventDefault(),e.returnValue="You have an active Quest! Your progress will be lost.")}),window.showSkeletonLoader=function(e,t){const o=document.getElementById(e);if(!o)return;let n='
    ';for(let e=0;e<(t||6);e++)n+='
    ';n+="
    ",o.innerHTML=n},setInterval(function(){var e=document.getElementById("nacho-bubble");if(!m||e&&e.classList.contains("show"))return;const t=Math.random();if(t<.3)k("wave"),setTimeout(()=>k("neutral"),400);else if(t<.6){const e=document.getElementById("nacho-avatar");e&&(e.style.transform="scale(1.1) rotate(5deg)",setTimeout(()=>e.style.transform="",500))}},2e4),setInterval(function(){if(m&&!(y>=12)&&!(Math.random()>.2||window._lastChannelOpenTime&&Date.now()-window._lastChannelOpenTime<3e4)){var e=document.getElementById("nacho-bubble");if(!(e&&e.classList.contains("show")&&"true"===e.getAttribute("data-interactive")||window._nachoMode)){var t=document.getElementById("questModal");t&&t.classList.contains("open")||"function"==typeof showNachoTrivia&&showNachoTrivia()}}},18e4)}function k(e){w=e||"default";const t=document.getElementById("nacho-pose-emoji");t&&(t.textContent=n[w]||n.default)}function B(e,t){!m||y>=12||Date.now()-f<5e4||b.has(e)||T(e,t)}function S(e,t){if(m){var o=document.getElementById("questModal");o&&o.classList.contains("open")||T(e,t)}}function T(e,t){if(window._nachoDirectLinkCooldown&&Date.now()s.classList.remove(e));var l="";if(-1===e.indexOf("'+c[d].label+"";break}var u=-1!==e.indexOf("60&&Math.abs(o)>2*Math.abs(n)&&hideBubble(!0)}},{passive:!0}),function(){var e=!1,t=0,o=0,n=0,i=0,a=!1,r=null;function s(){return document.getElementById("nacho-container")}function l(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;var n=window.innerWidth-40,i=window.innerHeight-40;t.left>=0&&t.left<=n&&t.top>=0&&t.top<=i&&(o.style.left=t.left+"px",o.style.bottom="auto",o.style.top=t.top+"px",o.style.right="auto")}catch(e){}}function c(){var e=s();if(e){var t=document.getElementById("nacho-bubble");if(t){var o=e.getBoundingClientRect(),n=window.innerWidth;window.innerHeight,o.left>n/2?(t.style.marginLeft="",t.style.marginRight="-6px",t.style.alignSelf="flex-end",t.querySelector(":scope"),t.style.setProperty("--bubble-side","right")):(t.style.marginLeft="-6px",t.style.marginRight="",t.style.alignSelf=""),o.top<200?(t.style.order="2",t.style.marginBottom="0",t.style.marginTop="8px"):(t.style.order="",t.style.marginBottom="16px",t.style.marginTop="")}}}setTimeout(l,500),window.addEventListener("resize",function(){var e=localStorage.getItem("btc_nacho_position");if(e)try{var t=JSON.parse(e),o=s();if(!o)return;t.left=Math.max(0,Math.min(t.left,window.innerWidth-60)),t.top=Math.max(0,Math.min(t.top,window.innerHeight-60)),o.style.left=t.left+"px",o.style.top=t.top+"px",localStorage.setItem("btc_nacho_position",JSON.stringify(t))}catch(e){}}),document.addEventListener("touchstart",function(l){var c=document.getElementById("nachoDragHandle");if(c&&c.contains(l.target)){l.preventDefault();var d=s();if(d){a=!1,r=d,t=l.touches[0].clientX,o=l.touches[0].clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,e=!0,d.style.transition="none",d.style.opacity="0.85",c.style.background="rgba(247,147,26,0.9)",c.querySelector("span").style.color="#fff"}}},{passive:!1}),document.addEventListener("touchmove",function(s){if(e&&r){var l=s.touches[0].clientX-t,c=s.touches[0].clientY-o;if(!(!a&&Math.abs(l)<8&&Math.abs(c)<8)){a=!0,s.preventDefault(),s.stopPropagation();var d=Math.max(0,Math.min(n+l,window.innerWidth-60)),u=Math.max(0,Math.min(i+c,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}},{passive:!1}),document.addEventListener("touchend",function(t){if(e){e=!1,r&&(r.style.transition="",r.style.opacity="");var o=document.getElementById("nachoDragHandle");if(o){o.style.background="rgba(255,255,255,0.9)";var n=o.querySelector("span");n&&(n.style.color="#888")}if(a&&r){var i=r.getBoundingClientRect(),s=Math.max(0,Math.min(Math.round(i.left),window.innerWidth-60)),l=Math.max(0,Math.min(Math.round(i.top),window.innerHeight-60));r.style.left=s+"px",r.style.top=l+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:s,top:l})),setTimeout(c,50),t.preventDefault()}r=null}},{passive:!1}),document.addEventListener("mousedown",function(l){var c=document.getElementById("nachoDragHandle");if(c&&c.contains(l.target)){var d=s();if(d){e=!0,a=!1,r=d,t=l.clientX,o=l.clientY;var u=d.getBoundingClientRect();n=u.left,i=u.top,d.style.transition="none",l.preventDefault()}}}),document.addEventListener("mousemove",function(s){if(e&&r){var l=s.clientX-t,c=s.clientY-o;if(!(!a&&Math.abs(l)<8&&Math.abs(c)<8)){a=!0;var d=Math.max(0,Math.min(n+l,window.innerWidth-60)),u=Math.max(0,Math.min(i+c,window.innerHeight-60));r.style.left=d+"px",r.style.top=u+"px",r.style.bottom="auto",r.style.right="auto"}}}),document.addEventListener("mouseup",function(t){if(e){if(e=!1,r&&(r.style.transition=""),a&&r){var o=r.getBoundingClientRect(),n=Math.max(0,Math.min(Math.round(o.left),window.innerWidth-60)),i=Math.max(0,Math.min(Math.round(o.top),window.innerHeight-60));r.style.left=n+"px",r.style.top=i+"px",localStorage.setItem("btc_nacho_position",JSON.stringify({left:n,top:i})),setTimeout(c,50)}r=null}});var d=window.showNacho;window.showNacho=function(){d.apply(this,arguments),l(),setTimeout(c,200)},setTimeout(c,1e3),document.addEventListener("dblclick",function(e){var t=document.getElementById("nacho-avatar");if(t&&t.contains(e.target)){localStorage.removeItem("btc_nacho_position");var o=s();o&&(o.style.left="",o.style.top="",o.style.bottom="",o.style.right=""),"function"==typeof showToast&&showToast("🦌 Nacho reset to default position!"),setTimeout(c,100)}})}(),window.hideBubble=function(e){var t=document.getElementById("nacho-bubble");if(e||!t||"true"!==t.getAttribute("data-interactive")){window._nachoBusy=!1,localStorage.setItem("btc_nacho_clicked","true"),setTimeout(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},2e3);var o=document.getElementById("nacho-avatar");t&&t.classList.remove("show"),clearTimeout(g),setTimeout(function(){k("default"),o&&o.classList.add("anim-tap")},500)}};let C=0,A=[],E=0;function z(){if(!m||y>=12)return;if(Math.random()>.3)return;if("function"==typeof nachoCheckMilestone){var e=nachoCheckMilestone();if(e)return S(e.text,e.pose),void setTimeout(nachoFly,500)}if("function"==typeof nachoLiveMessage&&Math.random()<.2){var t=nachoLiveMessage();if(t)return void B(t.text,t.pose)}if("function"==typeof checkNachoNewItems){var o=checkNachoNewItems();if(o)return S(o.text,o.pose),void("function"==typeof nachoPlaySound&&nachoPlaySound("coin"))}var n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var l=Math.random(),c=("new"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&l<.15?NACHO_CLOSET_TIPS:l<.6?a:l<.8?r:s:"regular"===i?"undefined"!=typeof NACHO_CLOSET_TIPS&&l<.1?NACHO_CLOSET_TIPS:l<.4?s:l<.7?a:r:"undefined"!=typeof NACHO_CLOSET_TIPS&&l<.15?NACHO_CLOSET_TIPS:l<.65?s:l<.9?r:a).filter(e=>!b.has(e.text));if(0===c.length&&0===(c=[...s,...r].filter(e=>!b.has(e.text))).length)return;const d=U(c);B(d.text,d.pose)}window.nachoClick=function(){if(window._nachoActionClicked)return void(window._nachoActionClicked=!1);const e=Date.now();if(A.push(e),A.length>3&&A.shift(),3===A.length&&A[2]-A[0]<600&&e-E>5e3)return A=[],E=e,v=e,"function"==typeof nachoFly&&nachoFly(),void S(personalize("Wheeeee! ⚡🦌⚡"));if(A.length>=2&&A[A.length-1]-A[A.length-2]<400&&A.length<3)return A=[],v=e,"function"==typeof hideNacho&&hideNacho(),void("function"==typeof showToast&&showToast("🦌 Nacho hidden — tap the 🦌 button to bring him back!"));if(e-v<1500)return;v=e,localStorage.setItem("btc_nacho_clicked","true"),"function"==typeof checkHiddenBadges&&checkHiddenBadges(),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoPlaySound&&nachoPlaySound("click");const t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show"))return void hideBubble();if(C++,C%3==0&&"function"==typeof showNachoInput)return void showNachoInput();var o,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i="new";n>=31?i="veteran":n>=10&&(i="regular");var l=(o="new"===i?[...a,...a,...r,...s]:"regular"===i?[...a,...s,...s,...r]:[...s,...s,...s,...r]).filter(e=>!b.has(e.text));const c=U(l.length>3?l:o);f=0,k(c.pose),S(c.text,c.pose)},window.showNacho=function(){m=!0,localStorage.removeItem("btc_nacho_hidden"),document.getElementById("nacho-container").classList.remove("hidden"),document.getElementById("nacho-toggle").style.display="none",f=0;var e,t=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,o=void 0!==currentUser&¤tUser&¤tUser.channelsVisited||0;if(t<=2&&o<3&&!localStorage.getItem("btc_nacho_tour_shown"))return[{text:"Welcome to the Bitcoin Education Archive, {name}! I'm Nacho, your deer guide! 🦌",pose:"wave",delay:0},{text:"Click the grid icons to explore Bitcoin topics. Start with the orange ones — they're beginner-friendly! 📚",pose:"point",delay:4e3},{text:"See the 🔥 number? That's your streak! Come back daily to keep it growing. ⚡",pose:"fire",delay:8e3},{text:"Tap me anytime to chat, or double-tap to enter Nacho Mode for deep conversations! 💬",pose:"cheese",delay:12e3}].forEach(function(e,t){setTimeout(function(){t>0&&k(e.pose),S(personalize(e.text))},e.delay)}),void localStorage.setItem("btc_nacho_tour_shown","true");if(t>2&&t<=10&&o<10){var n=["Pro tip {name}: Use the ⚡ tab to check the Bitcoin price anytime! 📈","Did you know? Completing a Quest earns you bonus Orange Tickets! 🎟️","Try tapping the Menu (☰) to see your progress on the Exploration Map! 🗺️","You can customize my outfit in Settings → Stats/Nacho → Closet! 👔"];e=n[Math.floor(Math.random()*n.length)],k("cool")}else if(t>20){var i=["Tick tock, next block! Ready for some high-signal learning, {name}? 🧱","Welcome back, master HODLer! I've been keeping the Archive warm for you. 🦌🔥","I noticed you've visited many channels. Want to test your knowledge with a Quest today? ⚡","Back for your daily dose of decentralization? Let's dive in! 📘"];e=i[Math.floor(Math.random()*i.length)],k("brain")}else if(t>5){var a=["Hey {name}, great to see you again! ✨","Welcome back! Ready to stack some more knowledge? 📚","I missed you! Check out my closet if you've earned new items! 👔","You're making great progress on your Exploration Map! 🗺️"];e=a[Math.floor(Math.random()*a.length)],k("wave")}else e="I'm back, {name}! Miss me? 🦌",k("wave");S(personalize(e))},window.hideNacho=function(){m=!1,localStorage.setItem("btc_nacho_hidden","user"),document.getElementById("nacho-container").classList.add("hidden"),document.getElementById("nacho-toggle").style.display="flex"},window.nachoOnPage=function(e){var t;if(m&&("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoNickname&&nachoNickname(),"forum"===e?t=[{pose:"wave",text:personalize("Welcome to PlebTalk, {name}! 🗣️ This is where Bitcoiners discuss ideas. Jump in!")},{pose:"point",text:"💡 Post a new topic to earn +10 points, or reply to an existing one for +5. Quality content gets upvoted!"},{pose:"brain",text:"Remember — this is a Bitcoin-only space. Stay respectful, stay on topic, and attack ideas, not people! 🤝"},{pose:"cheese",text:personalize("Psst {name}... earn the 📣 Town Crier badge by posting in PlebTalk! Your first post counts!")},{pose:"fire",text:"🔥 Pro tip: Upvote posts you find valuable with ⚡ — it helps the best content rise to the top!"}]:"marketplace"===e&&(t=[{pose:"wave",text:personalize("Welcome to LightningMart, {name}! ⚡ Buy and sell with Bitcoin — the way it should be!")},{pose:"point",text:"💡 All prices are in sats. Sellers set their own prices. Payments happen directly between buyer and seller."},{pose:"cheese",text:"🛒 List your first item to earn the 🏪 Merchant badge! Books, hardware, merch — whatever you've got!"},{pose:"brain",text:"🛡️ Safety first! Meet in public for local trades, use Lightning for instant payments, and report suspicious listings."},{pose:"fire",text:personalize("Pro tip {name}: add a Lightning address to your listing so buyers can pay you instantly! ⚡")}]),t)){var o=t[Math.floor(Math.random()*t.length)];S(o.text,o.pose)}},window.nachoOnChannel=function(e){if(m){if("function"==typeof trackNachoInteraction&&trackNachoInteraction(),"function"==typeof nachoChannelIntro){var t=nachoChannelIntro(e);if(t)return void S(t.text,t.pose)}if("function"==typeof nachoCategoryCheck){var o=nachoCategoryCheck(e);if(o)return S(o.text,o.pose),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),void setTimeout(nachoFly,500)}if(i[e]&&Math.random()<.6){const t=i[e];return void B(t.text,t.pose)}if(parseInt(sessionStorage.getItem("btc_channel_read_seconds")||"0")>=30+Math.floor(90*Math.random())&&Math.random()<.3&&"undefined"!=typeof QUEST_QUESTIONS&&QUEST_QUESTIONS.length>0){var n=void 0!==CHANNELS?CHANNELS[e]:null,a=n?n.cat:"",r=QUEST_QUESTIONS.filter(function(e){return e.category&&a&&-1!==e.category.toLowerCase().indexOf(a.toLowerCase().split(" ")[0])});0===r.length&&(r=QUEST_QUESTIONS);for(var s=r[Math.floor(Math.random()*r.length)],l='
    🎮 Quick Quiz!
    '+s.question+"
    ",d=s.options||[],u=0;u'+d[u]+"";return S(l,"brain"),void sessionStorage.setItem("btc_channel_read_seconds","0")}if(Math.random()<.25){const e=U(c);B(e.text,e.pose)}}},window.nachoBubbleQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n=e.parentElement,i=n.querySelectorAll("button");if(i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1";var a=document.createElement("div");a.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#22c55e;",a.textContent="✅ Correct! +5 pts",n.appendChild(a),"function"==typeof awardPoints&&awardPoints(5,"🎮 Quiz correct!"),"function"==typeof haptic&&haptic("success")}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("true")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var r=document.createElement("div");r.style.cssText="margin-top:6px;font-size:0.8rem;font-weight:700;color:#ef4444;",r.textContent="❌ Not quite! The correct answer is highlighted.",n.appendChild(r)}clearTimeout(g);var s=document.getElementById("nacho-bubble");s&&s.setAttribute("data-interactive","true")},window.nachoOnPoints=function(e){if(!m)return;if(e>=250)return void setTimeout(nachoFly,500);if(Math.random()>.2)return;const t=U(d);B(t.text,t.pose)},window.nachoFly=function(){var e=document.getElementById("nacho-avatar");if(e&&!e.classList.contains("flying")){["anim-tap","anim-lean","anim-wiggle","anim-bounce","anim-stretch","anim-look","anim-wave","anim-sleepy"].forEach(function(t){e.classList.remove(t)}),e.classList.add("flying");var t="false"!==localStorage.getItem("btc_nacho_sound"),o=[1200,1800,1400,2200,1600,2800];[0,400,800,1200,1600,2e3].forEach(function(n,i){setTimeout(function(){t&&e.classList.contains("flying")&&function(e){if("function"!=typeof canPlaySound||canPlaySound())try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();o.connect(n),n.connect(t.destination),o.frequency.value=e,o.type="sawtooth",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.12),o.start(t.currentTime),o.stop(t.currentTime+.12)}catch(e){}}(o[i])},n)});var n=["⚡","✨","🔥","⚡","💫","⚡"],i=setInterval(function(){if(e.classList.contains("flying")){var t=e.getBoundingClientRect(),o=document.createElement("div");o.className="nacho-trail",o.textContent=n[Math.floor(Math.random()*n.length)],o.style.left=t.left+t.width/2+(20*Math.random()-10)+"px",o.style.top=t.top+t.height/2+(20*Math.random()-10)+"px",document.body.appendChild(o),setTimeout(function(){o.parentNode&&o.remove()},600)}else clearInterval(i)},40);e.addEventListener("animationend",function o(){if(e.classList.remove("flying"),e.classList.add("anim-bounce"),e.removeEventListener("animationend",o),clearInterval(i),t&&("function"!=typeof canPlaySound||canPlaySound()))try{var n=new(window.AudioContext||window.webkitAudioContext),a=n.createOscillator(),r=n.createGain();a.connect(r),r.connect(n.destination),a.frequency.value=300,a.type="sine",r.gain.setValueAtTime(.08,n.currentTime),r.gain.exponentialRampToValueAtTime(.001,n.currentTime+.2),a.start(n.currentTime),a.stop(n.currentTime+.2)}catch(e){}})}},window.nachoOnQuest=function(e){m&&(f=0,e?(k("celebrate"),S(personalize("{name}, you CRUSHED that quest! This buck is VERY impressed! 🦌🎉🔥")),setTimeout(nachoFly,500)):(k("love"),S(personalize("Hey {name}, some questions are hard! Read up and try again — Nacho believes in you! 🦌💪"))))},window.nachoOnSearch=function(){!m||Math.random()>.3||B("Looking for something? I'd help search but I don't have thumbs. Good luck! 🔍🦌","think")},window.nachoOnFinishChannel=function(){if(!m||Math.random()>.3)return;const e=U([{pose:"celebrate",text:"You read the whole thing! Dedicated. I respect that. 🦌👏"},{pose:"point",text:"All done? Hit the 🎲 to find your next channel!"},{pose:"fire",text:"Knowledge: stacked. You're a machine! 💪"}]);B(e.text,e.pose)},window.nachoUserName=function(){return void 0!==currentUser&¤tUser&¤tUser.username?String(currentUser.username).replace(//g,">").replace(/"/g,"""):""};let L=0,M=0,P=!1;function U(e){return e[Math.floor(Math.random()*e.length)]}window.DeviceMotionEvent&&window.addEventListener("devicemotion",function(e){if(m&&!P){var t=e.accelerationIncludingGravity;if(t&&Math.sqrt(t.x*t.x+t.y*t.y+t.z*t.z)>28){var o=Date.now();o-L>1e3&&(M=0),L=o,M++,M>=2&&(P=!0,M=0,"function"==typeof haptic&&haptic("heavy"),"function"==typeof nachoFly&&nachoFly(),S(personalize("Whoa, {name}! Too much coffee? ⚡🦌🌪️")),setTimeout(function(){P=!1},3e3))}}},!0),window.personalize=function(e){var t=nachoUserName();if(e=t?e.replace(/\{name\}/g,t):e.replace(/,?\s*\{name\}\s*,?\s*/g,function(e){return 0===e.indexOf(",")&&e.lastIndexOf(",")>0?", ":","===e.charAt(0)?" ":""}),window._btcData){var o=window._btcData.price;if(!o)try{o=parseFloat(localStorage.getItem("btc_last_price"))}catch(e){}const t=o?"$"+Math.round(o).toLocaleString():"over $60,000",n=window._btcData.height?window._btcData.height.toLocaleString():"over 840,000",i=window._btcData.halvingBlocks?window._btcData.halvingBlocks.toLocaleString():"less than 150,000";e=(e=(e=e.replace(/\{price\}/g,t)).replace(/\{height\}/g,n)).replace(/\{halving\}/g,i)}return e.replace(/ +/g," ").replace(/^ ,/,"").replace(/, ,/g,",").trim()};let q=null;document.addEventListener("DOMContentLoaded",function(){setTimeout(function(){const e=document.getElementById("nacho-avatar");function t(e){"touchstart"===e.type&&e.preventDefault(),q=setTimeout(function(){hideNacho(),"function"==typeof showToast&&showToast("🦌 Nacho is hiding. Click the small 🦌 to bring him back!")},800)}function o(){clearTimeout(q)}e&&(e.addEventListener("mousedown",t),e.addEventListener("mouseup",o),e.addEventListener("mouseleave",o),e.addEventListener("touchstart",t,{passive:!1}),e.addEventListener("touchend",o),e.addEventListener("touchmove",o))},1e3)}),document.addEventListener("click",function(e){var t=document.getElementById("nacho-bubble");if(t&&t.classList.contains("show")){var o=document.getElementById("nacho-container");o&&o.contains(e.target)||hideBubble(!0)}}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",x):x(),function(){var e="btc_nacho_position",t=null,o=null,n=!1,i=0,a=0,r=0,s=0,l=!1;function c(){return t||(t=document.getElementById("nacho-container")),t}function d(){return o||(o=document.getElementById("nachoDragHandle")),o}function u(){try{var t=JSON.parse(localStorage.getItem(e));if(t&&"number"==typeof t.left&&"number"==typeof t.bottom){var o=c();if(o){var n=window.innerWidth-80,i=window.innerHeight-80,a=Math.max(0,Math.min(t.left,n)),r=Math.max(0,Math.min(t.bottom,i));o.style.left=a+"px",o.style.bottom=r+"px",o.style.right="auto",o.style.top="auto",o.style.position="fixed"}}}catch(e){}}function p(t,o){try{localStorage.setItem(e,JSON.stringify({left:t,bottom:o}))}catch(e){}}function h(e,t){var o=c();if(o){n=!0,l=!1,i=e,a=t;var u=o.getBoundingClientRect();r=u.left,s=window.innerHeight-u.bottom,o.style.transition="none",o.style.cursor="grabbing";var p=d();p&&(p.style.cursor="grabbing")}}function m(e,t){if(n){var o=e-i,d=t-a;if(l||!(Math.abs(o)+Math.abs(d)<8)){l=!0;var u=c();if(u){var p=r+o,h=s-d;p=Math.max(0,Math.min(p,window.innerWidth-80)),h=Math.max(0,Math.min(h,window.innerHeight-80)),u.style.left=p+"px",u.style.bottom=h+"px",u.style.right="auto",u.style.top="auto",u.style.position="fixed"}}}}function g(){if(n){n=!1;var e=c();if(e&&(e.style.transition="",e.style.cursor="",l)){var t=e.getBoundingClientRect();p(t.left,window.innerHeight-t.bottom)}var o=d();o&&(o.style.cursor="grab")}}function f(){var e=d();if(e){if(!e._dragInit){e._dragInit=!0,e.addEventListener("mousedown",function(e){e.preventDefault(),e.stopPropagation(),h(e.clientX,e.clientY)}),document.addEventListener("mousemove",function(e){n&&(e.preventDefault(),m(e.clientX,e.clientY))}),document.addEventListener("mouseup",g),e.addEventListener("touchstart",function(e){1===e.touches.length&&(e.stopPropagation(),h(e.touches[0].clientX,e.touches[0].clientY))},{passive:!0}),document.addEventListener("touchmove",function(e){n&&1===e.touches.length&&m(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("touchend",function(){n&&g()});var t=document.getElementById("nacho-avatar");t&&t.addEventListener("click",function(e){l&&(e.stopPropagation(),e.preventDefault(),l=!1)},!0),u(),function(){var e=document.getElementById("nacho-toggle");if(e&&!e._dragInit){e._dragInit=!0;var t=!1,o=0,n=0,i=0,a=0,r=!1;e.addEventListener("mousedown",function(s){t=!0,r=!1,o=s.clientX,n=s.clientY;var l=e.getBoundingClientRect();i=l.left,a=window.innerHeight-l.bottom,e.style.transition="none"}),e.addEventListener("touchstart",function(s){if(1===s.touches.length){t=!0,r=!1,o=s.touches[0].clientX,n=s.touches[0].clientY;var l=e.getBoundingClientRect();i=l.left,a=window.innerHeight-l.bottom,e.style.transition="none"}},{passive:!0}),document.addEventListener("mousemove",function(e){s(e.clientX,e.clientY)}),document.addEventListener("touchmove",function(e){t&&1===e.touches.length&&s(e.touches[0].clientX,e.touches[0].clientY)},{passive:!0}),document.addEventListener("mouseup",l),document.addEventListener("touchend",l),e.addEventListener("click",function(e){r&&(e.stopPropagation(),e.preventDefault(),r=!1)},!0)}function s(s,l){if(t){var c=s-o,d=l-n;if(r||!(Math.abs(c)+Math.abs(d)<8)){r=!0;var u=Math.max(0,Math.min(i+c,window.innerWidth-50)),p=Math.max(0,Math.min(a-d,window.innerHeight-50));e.style.left=u+"px",e.style.bottom=p+"px",e.style.right="auto",e.style.top="auto"}}}function l(){if(t&&(t=!1,e.style.transition="",r)){var o=e.getBoundingClientRect();p(o.left,window.innerHeight-o.bottom)}}}(),window.addEventListener("resize",function(){u()})}}else setTimeout(f,1e3)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(f,500)}):setTimeout(f,500)}(),setInterval(function(){document.querySelectorAll(".nacho-trail").forEach(function(e){e.remove()})},3e3),window.updateNachoAvatarForPage=function(){var n=document.getElementById("nacho-avatar");if(n){var i=o();if(i!==("1"===n.getAttribute("data-tctv"))){n.setAttribute("data-tctv",i?"1":"0"),i?(n.style.width="120px",n.style.height="100px",n.innerHTML=t+'Nacho
    click to ask!
    👔📖
    '):(n.style.width="",n.style.height="",n.innerHTML=e+'Nacho
    click to ask!
    👔📖
    ');var a=document.getElementById("nachoClosetBtn");if(a){var r=!1;a.addEventListener("mousedown",function(e){e.stopPropagation(),e.stopImmediatePropagation()},!1),a.addEventListener("touchstart",function(e){e.stopPropagation(),e.stopImmediatePropagation(),r=!0},{passive:!1}),a.addEventListener("touchend",function(e){e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),r&&(r=!1,window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},200),"function"==typeof nachoClosetNotifClear&&nachoClosetNotifClear())},{passive:!1})}}}};var N=window.go;N&&(window.go=function(){var e=N.apply(this,arguments);return setTimeout(window.updateNachoAvatarForPage,100),e})}(),function(){window.nachoTimeGreeting=function(){var e=(new Date).getHours(),t=((new Date).getDay(),"function"==typeof nachoUserName?nachoUserName():""),o=t?", "+t:"";return e>=5&&e<12?{pose:"wave",text:"Good morning"+o+"! ☀️ Ready to learn some Bitcoin today?"}:e>=12&&e<17?{pose:"wave",text:"Good afternoon"+o+"! 🌤️ Let's stack some knowledge!"}:e>=17&&e<21?{pose:"wave",text:"Good evening"+o+"! 🌅 Great time to dive into some Bitcoin education!"}:e>=21||e<2?{pose:"cool",text:"Late night study session"+o+"? 🌙 Respect! The night owl and the night deer, learning together. 🦉🦌"}:{pose:"sleep",text:"Whoa"+o+", it's the middle of the night! 😴 Your dedication is legendary. Most deer would be asleep right now!"}},window.nachoStreakMessage=function(){if(void 0===currentUser||!currentUser)return null;var e=currentUser.streak||0,t="function"==typeof nachoUserName?nachoUserName():"",o=t?", "+t:"";return e>=30?{pose:"fire",text:e+"-day streak"+o+"! You're absolutely unstoppable! 🔥🦌👑"}:e>=14?{pose:"fire",text:e+"-day streak"+o+"! Two weeks straight! You're a machine! 🔥💪"}:e>=7?{pose:"celebrate",text:e+"-day streak"+o+"! A whole week! Nacho is very impressed! 🎉🔥"}:e>=3?{pose:"love",text:e+"-day streak"+o+"! Keep it going! 🔥"}:null};const e=[100,250,500,1e3,2100,5e3,1e4,21e3];window.nachoCheckMilestone=function(){if(void 0===currentUser||!currentUser)return null;for(var t=currentUser.points||0,o=JSON.parse(localStorage.getItem("btc_nacho_milestones")||"[]"),n="function"==typeof nachoUserName?nachoUserName():"",i=n?", "+n:"",a=[],r=0;r=s&&!o.includes(s)&&(a.push(s),o.push(s))}if(0===a.length)return null;localStorage.setItem("btc_nacho_milestones",JSON.stringify(o)),"function"==typeof syncCelebratedState&&syncCelebratedState();var l=a[0],c="function"==typeof getLevel?getLevel(t):null,d=c?" You're now rank: "+c.emoji+" "+c.name+"!":"";if(a.length>1&&"function"==typeof forceShowBubble)for(var u=1;u=3){var s=r.wrong.slice(0,3),l=Math.floor(4*Math.random());s.splice(l,0,r.a),e.push({q:r.q,options:s,correct:l,pts:10,_fromBank:!0})}}}var c=JSON.parse(localStorage.getItem("btc_nacho_trivia_asked")||"[]");c.length>.8*e.length&&(c=[],localStorage.removeItem("btc_nacho_trivia_asked"));var d=e.filter(function(e,t){return!c.includes(e._fromBank?"qb_"+e.q.substring(0,30):t)});if(0===d.length)return null;var u=d[Math.floor(Math.random()*d.length)],p=u._fromBank?"qb_"+u.q.substring(0,30):e.indexOf(u);return c.push(p),localStorage.setItem("btc_nacho_trivia_asked",JSON.stringify(c)),{trivia:u,index:idx}},window.showNachoTrivia=function(){if(window._nachoBusy)return!1;var e=nachoTrivia();if(!e)return!1;var t=e.trivia,o=document.getElementById("nacho-bubble"),n=document.getElementById("nacho-text");if(!o||!n)return!1;"function"==typeof setPose&&setPose("think"),o.setAttribute("data-interactive","true"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout();for(var i='
    🧠 Quick Trivia! (+'+t.pts+' pts)
    '+t.q+"
    ",a=0;a'+String.fromCharCode(65+a)+". "+t.options[a]+"";return n.innerHTML=i,o.classList.add("show"),"function"==typeof clearNachoBubbleTimeout&&clearNachoBubbleTimeout(),!0},window.nachoTriviaAnswer=function(e,t,o,n){for(var i=n.parentElement.querySelectorAll("button"),a=0;a","function"==typeof setPose&&setPose("celebrate");else{var d=Math.max(2,Math.floor(o/3));"function"==typeof awardPoints&&awardPoints(d,"🧠 Nice try!"),s.innerHTML+='
    ❌ Not quite'+c+"! The answer was "+String.fromCharCode(65+t)+". +"+d+" pts for trying! 📚
    ","function"==typeof setPose&&setPose("love")}s.innerHTML+='',s.innerHTML+=''},window.getNachoFriendship=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?{level:5,name:"Best Buds",emoji:"💛"}:e>=350?{level:4,name:"Close Friends",emoji:"🧡"}:e>=100?{level:3,name:"Good Friends",emoji:"😊"}:e>=10?{level:2,name:"Getting Acquainted",emoji:"👋"}:e>=1?{level:1,name:"Just Met",emoji:"🦌"}:{level:0,name:"Strangers",emoji:"❓"}},window.trackNachoInteraction=function(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0")+1;if(localStorage.setItem("btc_nacho_interactions",e.toString()),window._nachoLastInteraction=Date.now(),void 0!==db&&void 0!==auth&&auth.currentUser){var t=parseInt(localStorage.getItem("btc_nacho_questions")||"0");try{db.collection("users").doc(auth.currentUser.uid).update({nachoInteractions:e,nachoQuestions:t})}catch(e){}}"function"==typeof renderProgressRings&&renderProgressRings()};const i={mining:["How does the difficulty adjustment work?","What is a halving?","Is mining bad for the environment?","What is a nonce?","Can I mine at home?","What is an ASIC?"],wallet:["What is a seed phrase?","What is self-custody?","What is a hardware wallet?","How do I back up my wallet?","What is multisig?","Which wallet is best for beginners?"],lightning:["How fast is Lightning?","What are sats?","How do I get a Lightning Address?","What is a payment channel?","What is LNURL?","Can I tip people with Lightning?"],halving:["What is the block reward?","When is the next halving?","Why does the price go up after halving?","How many halvings are left?","What happens when all Bitcoin are mined?"],price:["Is it too late to buy?","What is DCA?","Why is Bitcoin volatile?","How high can Bitcoin go?","What is stock-to-flow?"],"self-custody":["What is a seed phrase?","What wallets do you recommend?","What does HODL mean?","What is cold storage?","What is a passphrase?"],privacy:["What is CoinJoin?","What is non-KYC Bitcoin?","Is Bitcoin anonymous?","What are silent payments?","What is Nostr?"],basics:["How does mining work?","What is the Lightning Network?","Who created Bitcoin?","What is a sat?","Why is there only 21 million?"],fud:["Is Bitcoin bad for the environment?","Can Bitcoin be hacked?","Will governments ban Bitcoin?","What about quantum computers?","Is Bitcoin a Ponzi scheme?"],node:["Why should I run a node?","What is a full node?","How does consensus work?","What is Nakamoto Consensus?"],taproot:["What is Schnorr?","What are covenants?","What is MuSig2?","What is OP_CAT?"],security:["What is a 51% attack?","How secure is Bitcoin?","What is proof of work?","Can Bitcoin be hacked?"],scarcity:["Why only 21 million?","What makes Bitcoin scarce?","What is inflation?","Bitcoin vs gold?"],layer:["What is Lightning Network?","What are sidechains?","What is the Liquid Network?","What are channel factories?"],economics:["What is sound money?","What is the Cantillon Effect?","What is time preference?","Why is fiat bad?"],satoshi:["Why did Satoshi disappear?","Who is Hal Finney?","What is the Genesis Block?","Is Craig Wright Satoshi?"],nostr:["What is Nostr?","How do I use Nostr?","What are Nostr relays?","Can I sign in with Nostr?"],regulation:["Can Bitcoin be banned?","What happened when China banned Bitcoin?","Is Bitcoin legal?","What about the SEC?"],altcoin:["Why is Bitcoin different from altcoins?","What about Ethereum?","Are meme coins worth it?","Why Bitcoin only?"],invest:["What is DCA?","How much should I invest?","Is now a good time to buy?","What is HODL?"],history:["What is Pizza Day?","What are the blocksize wars?","When was the first transaction?","What is the Genesis Block?"],energy:["Does Bitcoin waste energy?","How much energy does mining use?","Is Bitcoin green?","What is stranded energy?"]};var a=[];window.nachoFollowUps=function(e){if(!e)return[];var t=e.toLowerCase(),o=[];for(var n in i)t.includes(n)&&(o=o.concat(i[n]));0===o.length&&(o=["What is Bitcoin?","How do I get started?","What is the Lightning Network?","Who created Bitcoin?","Why is there only 21 million?","What is self-custody?"]);var r=window._nachoAskedQuestions||[],s=o.filter(function(e){return-1===a.indexOf(e)&&-1===r.indexOf(e.toLowerCase())});s.length<3&&(a=[],s=o.filter(function(e){return-1===r.indexOf(e.toLowerCase())})),0===s.length&&(s=o),s.sort(function(){return Math.random()-.5});var l=Math.min(Math.max(3,s.length),5),c=s.slice(0,l);return(a=a.concat(c)).length>30&&(a=a.slice(-15)),c},window.trackNachoQuestion=function(e,t){try{var o=JSON.parse(localStorage.getItem("btc_nacho_analytics")||"[]");o.push({q:e.substring(0,100),matched:t,t:Date.now()}),o.length>100&&(o=o.slice(-100)),localStorage.setItem("btc_nacho_analytics",JSON.stringify(o))}catch(e){}};let r="false"!==localStorage.getItem("btc_nacho_sound");window.nachoPlaySound=function(e){if(("function"!=typeof canPlaySound||canPlaySound())&&r)try{var t=new(window.AudioContext||window.webkitAudioContext),o=t.createOscillator(),n=t.createGain();if(o.connect(n),n.connect(t.destination),n.gain.value=.08,"pop"===e)o.frequency.value=800,o.type="sine",n.gain.setValueAtTime(.08,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.15),o.start(t.currentTime),o.stop(t.currentTime+.15);else if("coin"===e){o.frequency.value=1200,o.type="sine",n.gain.setValueAtTime(.06,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.3),o.start(t.currentTime),o.stop(t.currentTime+.3);var i=t.createOscillator();i.connect(n),i.frequency.value=1600,i.type="sine",i.start(t.currentTime+.1),i.stop(t.currentTime+.3)}else"click"===e?(o.frequency.value=600,o.type="triangle",n.gain.setValueAtTime(.05,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.08),o.start(t.currentTime),o.stop(t.currentTime+.08)):"tctv-beep"===e&&(o.frequency.value=2400,o.type="square",n.gain.setValueAtTime(.03,t.currentTime),n.gain.exponentialRampToValueAtTime(.001,t.currentTime+.06),o.start(t.currentTime),o.stop(t.currentTime+.06))}catch(e){}},window.toggleNachoSound=function(){return r=!r,localStorage.setItem("btc_nacho_sound",r.toString()),r};let s=[];window.nachoAddContext=function(e){s.push(e),s.length>5&&s.shift()},window.nachoGetContext=function(){return s},setTimeout(function(){if("1"!==localStorage.getItem("btc_ln_prompt_dismissed")){var e=void 0!==currentUser?currentUser:null;if(e&&e.username&&!e.lightning&&!e.lightningAddress){var t=[];try{t=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}t.length<5||"function"==typeof forceShowBubble&&(forceShowBubble("⚡ Hey "+(e.username||"friend")+"! Connect a Lightning wallet to tip other users and receive tips! Tap me to learn how. 🦌",function(){go("lightning")}),localStorage.setItem("btc_ln_prompt_dismissed","1"))}}},3e4),function(){var e="btc_smart_nudges";function t(){try{return JSON.parse(localStorage.getItem(e)||"{}")}catch(e){return{}}}function o(e){var o=t();return!o[e]||Date.now()-o[e]>864e5}function n(){if("function"==typeof forceShowBubble&&!(Date.now()-(window._sessionStart||Date.now())<3e4)){var n=document.getElementById("nacho-bubble");if(!(n&&n.classList.contains("show")||window._nachoBusy)){var i,a,r=[];if(void 0!==BADGE_DEFS&&void 0!==earnedBadges){var s=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]").length;!earnedBadges.has("explorer_10")&&s>=7&&o("near_explorer_10")&&r.push({id:"near_explorer_10",text:"You've visited "+s+" topics — just "+(10-s)+" more to earn the Explorer badge! 🧭 Keep exploring!"}),!earnedBadges.has("explorer_25")&&s>=20&&s<25&&o("near_explorer_25")&&r.push({id:"near_explorer_25",text:"Only "+(25-s)+" more topics to unlock Trailblazer! 🗺️ You're so close!"});var l=void 0!==currentUser&¤tUser&¤tUser.streak||0;!earnedBadges.has("streak_7")&&l>=5&&l<7&&o("near_streak_7")&&r.push({id:"near_streak_7",text:l+"-day streak! 🔥 Just "+(7-l)+" more days for the Week Warrior badge! Don't break it!"}),!earnedBadges.has("streak_30")&&l>=25&&l<30&&o("near_streak_30")&&r.push({id:"near_streak_30",text:l+"-day streak! 💪 "+(30-l)+" more days to Monthly Maxi! That's legendary dedication!"}),!earnedBadges.has("streak_100")&&l>=90&&l<100&&o("near_streak_100")&&r.push({id:"near_streak_100",text:l+"-day streak! 💎 "+(100-l)+" days from Diamond Hands! You're in the top tier!"});var c=parseInt(localStorage.getItem("btc_chat_msgs")||"0");!earnedBadges.has("chat_50")&&c>=40&&c<50&&o("near_chat_50")&&r.push({id:"near_chat_50",text:c+" chat messages! Just "+(50-c)+" more to become a Conversationalist! 🎤 Head to Global Chat!"});var d=parseInt(localStorage.getItem("btc_pvp_wins")||"0");!earnedBadges.has("pvp_5")&&d>=3&&d<5&&o("near_pvp_5")&&r.push({id:"near_pvp_5",text:d+" PVP wins! ⚔️ "+(5-d)+" more to unlock Contender! Ready for a battle?"});var u=void 0!==completedQuests&&completedQuests.size||0;!earnedBadges.has("quest_3")&&u>=2&&u<3&&o("near_quest_3")&&r.push({id:"near_quest_3",text:"You've completed "+u+" quests! One more for the Quest Seeker badge! ⚔️ Try a quest after reading!"});var p=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0");!earnedBadges.has("tctv_couch_potato")&&p>=45&&p<60&&o("near_tctv_60")&&r.push({id:"near_tctv_60",text:p+" minutes of Timechain TV! 📺 Just "+(60-p)+" more for Couch Potato! Grab some popcorn! 🍿"}),localStorage.getItem("btc_last_spin_date")!==(new Date).toDateString()&&o("daily_spin")&&r.push({id:"daily_spin",text:"You haven't spun the daily wheel yet! 🎡 Free tickets and prizes await!"})}if(r.length>0){var h=r[Math.floor(Math.random()*r.length)];i=h.id,(a=t())[i]=Date.now(),localStorage.setItem(e,JSON.stringify(a)),forceShowBubble(h.text)}}}}setTimeout(function(){n(),setInterval(n,3e5)},12e4),window.checkSmartNudges=n}()}(),window.nachoNickname=function(){return localStorage.getItem("btc_nacho_nickname")||"Nacho"},function(){const e=[{id:"orange_scarf",category:"shirt",name:"Bitcoin Scarf",emoji:"🧣",desc:"A cozy orange scarf with the ₿ symbol.",level:1,overlay:{top:"68%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"sunglasses",category:"glasses",name:"Cool Shades",emoji:"🕶️",desc:"Sunglasses so cool, even the blockchain can't see through them.",level:1,overlay:{top:"43%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"bowtie",category:"shirt",name:"Fancy Bowtie",emoji:"🎀",desc:"A dapper bowtie for a distinguished buck. Class and sats.",level:1,overlay:{top:"64%",left:"50%",transform:"translateX(-50%)",fontSize:"1.3em"},hidden:!1,colorable:!0},{id:"mining_helmet",category:"hat",name:"Mining Helmet",emoji:"⛑️",desc:"A safety helmet for a hardworking miner. Ready to find the next block!",level:2,overlay:{top:"5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"lightning_chain",category:"glasses",name:"Lightning Chain",emoji:"⚡",desc:"A chain necklace with a Lightning bolt pendant.",level:2,overlay:{top:"65%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em"},hidden:!1},{id:"party_hat",category:"hat",name:"Party Hat",emoji:"🎉",desc:"Every day is a party when you're stacking sats!",level:2,overlay:{top:"2%",left:"58%",transform:"translateX(-50%) rotate(15deg)",fontSize:"1.8em"},hidden:!1,colorable:!0},{id:"hodl_hoodie",category:"shirt",name:"HODL Hoodie",emoji:"🧥",desc:"A hoodie that says HODL on the back. For diamond-handed deer.",level:3,overlay:{top:"72%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1,colorable:!0},{id:"laser_eyes",category:"glasses",name:"Laser Eyes",emoji:"🔴",desc:"The legendary Bitcoin laser eyes. Number go up!",level:3,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"0.9em",custom:"🔴 🔴"},hidden:!1,colorable:!0},{id:"wizard_hat",category:"hat",name:"Wizard Hat",emoji:"🪄",desc:"A mystical wizard hat. Nacho casts spells of financial sovereignty!",level:3,overlay:{top:"-5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!1,colorable:!0},{id:"crown",category:"hat",name:"Royal Crown",emoji:"👑",desc:"Fit for the king of cryptocurrency. There is no second best!",level:3,overlay:{top:"3%",left:"50%",transform:"translateX(-50%)",fontSize:"2.2em"},hidden:!1},{id:"steak",category:"glasses",name:"Proof of Steak",emoji:"🥩",desc:"A juicy steak for a hardworking buck. Proof of Steak > Proof of Stake!",level:4,overlay:{top:"58%",right:"-18%",fontSize:"1.8em",transform:"rotate(20deg)"},hidden:!1},{id:"diamond_hooves",category:"glasses",name:"Diamond Hooves",emoji:"💎",desc:"Diamond hooves for a deer with diamond hands. Never selling!",level:4,overlay:{bottom:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"1.4em",custom:"💎💎"},hidden:!1},{id:"astronaut",category:"hat",name:"Moon Helmet",emoji:"🪖",desc:"To the moon! A space helmet for the ultimate HODLer.",level:4,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1},{id:"cape_permanent",category:"shirt",name:"Hero Cape",emoji:"🦸",desc:"A permanent cape for a Bitcoin hero. Earned, not given!",level:4,overlay:{top:"55%",right:"-15%",fontSize:"2.4em",transform:"rotate(-12deg)"},hidden:!1,colorable:!0},{id:"golden_antlers",category:"hat",name:"???",emoji:"✨",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"0.5%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Golden Antlers",revealEmoji:"✨",revealDesc:"Antlers plated in pure gold. Only the closest friends get to see these shine!"},{id:"satoshi_cloak",category:"shirt",name:"???",emoji:"🧥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"68%",left:"50%",transform:"translateX(-50%)",fontSize:"2.4em"},hidden:!0,revealName:"Satoshi's Cloak",revealEmoji:"🧥",revealDesc:"A mysterious cloak worn by Satoshi himself. Legend says it grants anonymity to any deer who wears it."},{id:"flame_aura",category:"glasses",name:"???",emoji:"🔥",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"25%",left:"50%",transform:"translateX(-50%)",fontSize:"3.5em"},hidden:!0,revealName:"Flame Aura",revealEmoji:"🔥",revealDesc:"A blazing aura of pure Bitcoin energy. The ultimate flex for Nacho's best friend!"},{id:"rainbow_antlers",category:"hat",name:"???",emoji:"🌈",desc:"Reach Best Buds friendship to reveal this item!",level:5,overlay:{top:"2%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!0,revealName:"Rainbow Antlers",revealEmoji:"🌈",revealDesc:"Prismatic rainbow antlers that shimmer in every color. Legendary!"},{id:"bitcoin_eyes",category:"glasses",name:"???",emoji:"₿",desc:"How do you find this one?",level:1,overlay:{top:"43%",left:"50.5%",transform:"translateX(-50%)",fontSize:"1.2em",custom:"₿ ₿"},hidden:!0,revealName:"Bitcoin Eyes",revealEmoji:"₿",revealDesc:"Eyes made of pure Bitcoin. You found the secret! Nacho sees everything in sats now."},{id:"santa_hat",category:"hat",name:"Santa Hat",emoji:"🎅",desc:"Ho ho HODL! A festive Santa hat for the holiday season.",level:1,overlay:{top:"1%",left:"54%",transform:"translateX(-50%) rotate(15deg)",fontSize:"2.2em"},hidden:!1,seasonal:"december"},{id:"pumpkin",category:"hat",name:"Pumpkin Head",emoji:"🎃",desc:"Spooky season! A jack-o-lantern for Halloween.",level:1,overlay:{top:"8%",left:"50%",transform:"translateX(-50%)",fontSize:"2.8em"},hidden:!1,seasonal:"october"},{id:"halving_pickaxe",category:"glasses",name:"Golden Pickaxe",emoji:"⛏️",desc:"A golden pickaxe to celebrate the halving! Limited edition.",level:1,overlay:{top:"22%",right:"-15%",fontSize:"2.2em",transform:"rotate(30deg)"},hidden:!1,seasonal:"april"}];var t=document.createElement("style");function o(){var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");return e>=750?5:e>=350?4:e>=100?3:e>=10?2:e>=1?1:0}t.textContent="\n @keyframes nachoEquipPop {\n 0% { transform: scale(0) rotate(-45deg); opacity: 0; }\n 50% { transform: scale(1.5) rotate(10deg); opacity: 1; }\n 70% { transform: scale(0.9) rotate(-5deg); }\n 100% { transform: scale(1) rotate(0deg); opacity: 1; }\n }\n @keyframes nachoEquipGlow {\n 0% { filter: drop-shadow(0 0 0px transparent); }\n 30% { filter: drop-shadow(0 0 12px rgba(247,147,26,0.8)); }\n 100% { filter: drop-shadow(0 0 4px rgba(247,147,26,0.3)); }\n }\n @keyframes nachoUnequip {\n 0% { transform: scale(1); opacity: 1; }\n 40% { transform: scale(1.3) rotate(15deg); opacity: 0.8; }\n 100% { transform: scale(0) rotate(-30deg); opacity: 0; }\n }\n @keyframes nachoItemFloat {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-3px); }\n }\n @keyframes nachoLaserPulse {\n 0%, 100% { opacity: 0.8; filter: drop-shadow(0 0 4px #ff0000); }\n 50% { opacity: 1; filter: drop-shadow(0 0 10px #ff0000) drop-shadow(0 0 20px #ff3300); }\n }\n @keyframes nachoSparkle {\n 0%, 100% { filter: drop-shadow(0 0 4px rgba(255,215,0,0.3)); }\n 50% { filter: drop-shadow(0 0 10px rgba(255,215,0,0.8)) drop-shadow(0 0 20px rgba(255,215,0,0.4)); }\n }\n @keyframes nachoCloakWave {\n 0%, 100% { transform: translateX(-50%) rotate(-2deg); }\n 50% { transform: translateX(-50%) rotate(2deg); }\n }\n .nacho-overlay-item {\n position: absolute;\n pointer-events: none;\n z-index: 3;\n }\n .nacho-overlay-item.equipping {\n animation: nachoEquipPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards,\n nachoEquipGlow 0.8s ease-out forwards;\n }\n .nacho-overlay-item.unequipping {\n animation: nachoUnequip 0.35s ease-in forwards;\n }\n .nacho-overlay-item.idle-float {\n animation: nachoItemFloat 3s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-laser {\n animation: nachoLaserPulse 1.5s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-sparkle {\n animation: nachoSparkle 2s ease-in-out infinite;\n }\n .nacho-overlay-item.idle-wave {\n animation: nachoCloakWave 4s ease-in-out infinite;\n }\n",document.head.appendChild(t),window.equipNachoItem=function(t){if(!t)return localStorage.removeItem("btc_nacho_equipped_multi"),void renderNachoOverlay();var n=o(),i=e.find(function(e){return e.id===t}),a=JSON.parse(localStorage.getItem("btc_spin_closet_items")||"[]");if(i&&i.level>n&&-1===a.indexOf(t))showToast("🔒 Need a higher friendship level to wear this!");else{var r=getEquippedItems(),s=i&&i.category||"misc";r[s]===t?(delete r[s],"function"==typeof forceShowBubble&&forceShowBubble("Back to natural in the "+s+" department! 🦌")):(r[s]=t,"function"==typeof forceShowBubble&&forceShowBubble({orange_scarf:"Looking cozy! This scarf really brings out my orange. 🧣🦌",mining_helmet:"Safety first! Time to mine some blocks! ⛑️⛏️",lightning_chain:"Bling bling! Fast as Lightning! ⚡🦌",hodl_hoodie:"HODL gang! This hoodie makes me feel unstoppable! 🧥💎",laser_eyes:"LASER EYES ACTIVATED! Number go up! 🔴🔴🚀",steak:"Mmm, Proof of Steak! Way better than Proof of Stake! 🥩😋",golden_antlers:"These golden antlers are MAGNIFICENT! Only for my best friends! 👑✨",satoshi_cloak:"Who am I? Nobody knows... I am Satoshi Nachoamoto! 🧙🦌"}[t]||"Looking fresh with my "+(i.hidden?i.revealName:i.name)+"! 🦌")),localStorage.setItem("btc_nacho_equipped_multi",JSON.stringify(r)),renderNachoOverlay(!0),"function"==typeof nachoPlaySound&&nachoPlaySound("coin"),document.getElementById("nachoClosetGrid")&&renderNachoClosetUI(document.getElementById("nachoClosetGrid").parentElement)}},window.renderNachoOverlay=function(t){document.querySelectorAll(".nacho-overlay-item").forEach(e=>e.remove());var o=getEquippedItems(),n=document.getElementById("nacho-avatar");n&&(Object.values(o).forEach(function(o){var i=e.find(function(e){return e.id===o});if(i){var a=i.hidden?i.revealEmoji:i.emoji,r=function(e){switch(e){case"laser_eyes":return"idle-laser";case"golden_antlers":case"diamond_hooves":return"idle-sparkle";case"satoshi_cloak":return"idle-wave";default:return"idle-float"}}(i.id),s=document.createElement("span");for(var l in s.className="nacho-overlay-item"+(t?" equipping":" "+r),s.id="nacho-overlay-"+i.id,s.textContent=i.overlay.custom||a,i.overlay.custom&&(s.style.letterSpacing="-0.1em",s.style.whiteSpace="nowrap"),i.overlay)"filter"!==l&&"custom"!==l&&(s.style[l]=i.overlay[l]);if(i.colorable){var c=localStorage.getItem("btc_closet_color_"+i.id);c&&"0deg"!==c&&(s.style.filter="hue-rotate("+c+")")}t&&s.addEventListener("animationend",function e(){s.classList.remove("equipping"),s.classList.add(r),s.removeEventListener("animationend",e)},{once:!0}),n.appendChild(s)}}),t&&function(e){for(var t=e.getBoundingClientRect(),o=["✨","⭐","💫","🌟"],n=0;n<6;n++)(function(e){setTimeout(function(){var n=document.createElement("div");n.className="nacho-trail",n.textContent=o[e%o.length],n.style.left=t.left+Math.random()*t.width+"px",n.style.top=t.top+Math.random()*t.height+"px",n.style.fontSize=.8+.8*Math.random()+"rem",document.body.appendChild(n),setTimeout(function(){n.parentNode&&n.remove()},800)},80*e)})(n)}(n))},window.getNachoFriendship=function(){const e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[{name:"Stranger",emoji:"🦌",min:0},{name:"Acquaintance",emoji:"🤝",min:10},{name:"Pleb Friend",emoji:"🧡",min:50},{name:"HODL Buddy",emoji:"💎",min:150},{name:"Maxi Mentor",emoji:"👑",min:500}];let o=t[0];for(const n of t)e>=n.min&&(o=n);return o},window.renderNachoClosetUI=function(t){for(var n=o(),i=getEquippedItems(),a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r="function"==typeof getNachoFriendship?getNachoFriendship():{level:0,name:"Strangers",emoji:"❓"},s=[1,10,100,350,750],l="",c=0;cNext level in '+(s[c]-a)+" more interactions";break}var d="",u=[];Object.values(i).forEach(function(t){var o=e.find(function(e){return e.id===t});if(o){var n=o.hidden?o.revealEmoji:o.emoji;o.overlay.custom&&(n=o.overlay.custom);var i="position:absolute;font-size:"+(o.overlay.fontSize||"1.5rem")+";";if(o.overlay.top&&(i+="top:"+o.overlay.top+";"),o.overlay.bottom&&(i+="bottom:"+o.overlay.bottom+";"),o.overlay.left&&(i+="left:"+o.overlay.left+";"),o.overlay.right&&(i+="right:"+o.overlay.right+";"),o.overlay.transform&&(i+="transform:"+o.overlay.transform+";"),i+="z-index:5;pointer-events:none;",o.colorable){var a=localStorage.getItem("btc_closet_color_"+o.id);a&&"0deg"!==a&&(i+="filter:hue-rotate("+a+");")}d+=''+n+"",u.push(o.hidden?o.revealName:o.name)}});var p="function"==typeof nachoNickname?nachoNickname():"Nacho",h='
    🦌 '+escapeHtml(p)+"'s Closet
    ";h+='
    Nacho'+d+'
    '+(u.length>0?'✨ Wearing: '+u.join(", ")+"":"No item equipped — tap one below!")+"
    ",h+='
    Friendship: '+r.emoji+" "+r.name+''+a+" interactions
    "+l,h+='
    ',h+='
    ';for(var m=(new Date).toLocaleString("en",{month:"long"}).toLowerCase(),g=0;g
    '+x+'
    '+w+"
    "+(b?'
    ✓ EQUIPPED
    ':"")+(b&&f.colorable?"
    🎨 Color
    ':"")+(y||v?"":'
    Lvl '+f.level+"
    ")+(v?'
    🔒
    ':"")+(f.seasonal?'
    🗓️ '+f.seasonal+"
    ":"")+"
    "}}h+="",h+='
    '+(Object.keys(i).length>0?function(){var t=e.find(function(e){return e.id===Object.values(i)[0]});if(!t)return"Tap an item to equip it on "+escapeHtml(p)+"!";var o=t.hidden?t.revealDesc:t.desc;return''+(t.hidden?t.revealName:t.name)+": "+o}():"Tap an unlocked item to equip it on "+escapeHtml(p)+"!
    Tap again to unequip.")+"
    ",t.innerHTML=h};var n="function"==typeof nachoNickname?nachoNickname():"Nacho";window.NACHO_CLOSET_TIPS=[{pose:"cool",text:"Did you know I have a whole closet of outfits, {name}? Check Settings → Stats → "+escapeHtml(n)+"'s Closet to dress me up! 👔🦌"},{pose:"celebrate",text:"The more we interact, the more items you unlock for me to wear! Check my closet in Settings! 🧣⚡"},{pose:"eyes",text:"I heard there are some mystery items in my closet that only my closest friends get to see... 👀🔒"},{pose:"fire",text:"Proof of Steak > Proof of Stake. Ask me about it... or better yet, unlock it in my closet! 🥩🦌"},{pose:"cheese",text:"Fashion tip from a deer: orange goes with everything. Especially Bitcoin orange. Check my closet in Settings! 🟠"}],window.checkNachoNewItems=function(){var t=o(),n=JSON.parse(localStorage.getItem("btc_nacho_items_notified")||"[]"),i=e.filter(function(e){return e.level<=t&&!n.includes(e.id)});if(i.length>0){for(var a=0;a
    '+(a?a.name:"Item")+'
    Choose a color
    ';[{name:"Default",hue:"0deg",color:"#f7931a"},{name:"Bitcoin Orange",hue:"25deg",color:"#ff8c00"},{name:"Crimson",hue:"340deg",color:"#dc2626"},{name:"Royal Purple",hue:"270deg",color:"#7c3aed"},{name:"Ocean Blue",hue:"200deg",color:"#0ea5e9"},{name:"Forest Green",hue:"120deg",color:"#16a34a"},{name:"Gold",hue:"45deg",color:"#eab308"},{name:"Hot Pink",hue:"310deg",color:"#ec4899"},{name:"Cyan",hue:"175deg",color:"#06b6d4"},{name:"Lime",hue:"90deg",color:"#84cc16"}].forEach(function(t){var n=o===t.hue;r+=""}),r+='
    ',i.innerHTML=r,n.appendChild(i),document.body.appendChild(n)},window._applyClosetColor=function(e,t){localStorage.setItem("btc_closet_color_"+e,t);var o=document.querySelector("#nacho-overlay");if(o&&(o.style.filter="0deg"===t?"none":"hue-rotate("+t+")"),"function"==typeof showColorPicker&&showColorPicker(e),"function"==typeof renderNachoClosetUI){var n=document.getElementById("nachoClosetContainer");n&&renderNachoClosetUI(n)}};const QUESTION_BANK={whitepaper:[{q:"When was the Bitcoin Whitepaper published?",a:"October 31, 2008",wrong:["January 3, 2009","March 15, 2007","December 25, 2010"]},{q:"How many pages of text is the Bitcoin Whitepaper?",a:"8 pages",wrong:["20 pages","50 pages","2 pages"]},{q:"The Whitepaper was published on:",a:"A cryptography mailing list",wrong:["A Bitcoin development forum","A computer science journal","A private university server"]},{q:"What is the title of the Bitcoin Whitepaper?",a:"Bitcoin: A Peer-to-Peer Electronic Cash System",wrong:["Digital Gold: A New Decentralized Monetary System","Cryptocurrency: The Future of Digital Finance","Blockchain: A Technology for Electronic Commerce"]},{q:"The Whitepaper proposed a solution to:",a:"The double-spending problem",wrong:["The network latency problem","The identity theft problem","The data corruption problem"]},{q:"Who is credited as the author of the Whitepaper?",a:"Satoshi Nakamoto",wrong:["Vitalik Buterin","Craig S. Wright","Gavin Andresen"]},{q:"The Whitepaper describes Bitcoin as:",a:"A peer-to-peer electronic cash system",wrong:["A digital payment network run by banks","A decentralized global stock exchange","A decentralized social payment platform"]},{q:"What concept does the Whitepaper use to timestamp transactions?",a:"A chain of hashed blocks",wrong:["A trusted notary system","A central server clock","A public key directory"]},{q:"The Bitcoin whitepaper solved what previously unsolvable problem?",a:"Digital scarcity without a trusted third party",wrong:["Instant payments without any processing delays","Quantum-proof encryption for all financial data","Free global transfers without any intermediary"]},{q:"What did Satoshi embed in the Genesis Block's coinbase transaction?",a:"A newspaper headline about bank bailouts",wrong:["A cryptographic puzzle for early miners","A private note to the early Bitcoin team","A list of early Bitcoin wallet addresses"]}],decentralized:[{q:'How many people are "in charge" of Bitcoin?',a:"No one",wrong:["Satoshi Nakamoto","A board of directors","The Bitcoin Foundation"]},{q:"What is needed for code updates to Bitcoin?",a:"Deep consensus from the network",wrong:["Miner approval alone suffices","Developer committee approval","Permission from founding nodes"]},{q:"Bitcoin is described as:",a:"A protocol, not a company",wrong:["A company based in Japan","A government-run project","A private bank consortium"]},{q:"Bitcoin nodes are run by:",a:"Anyone who wants to, worldwide",wrong:["Only licensed miners worldwide","Only certified node operators","Only nodes inside the EU region"]},{q:"If one country shuts down all Bitcoin mining:",a:"The network continues in other countries",wrong:["Bitcoin stops working in all countries","All remaining coins become inaccessible","The chain halts until operations resume"]},{q:"Bitcoin has no:",a:"Central point of failure",wrong:["Mining reward mechanism","Fixed total supply limit","Public transaction record"]},{q:"Decentralization means:",a:"No single entity controls the network",wrong:["One organization controls its rules","Developers approve all code changes","A central committee controls supply"]},{q:"What happens to Bitcoin if one country bans it?",a:"The network continues operating globally since no single country controls it",wrong:["Bitcoin stops working in that country but keeps running in all other places","All nodes globally shut down temporarily while other nations handle the ban","Mining pools worldwide pause until regulators in other countries approve it"]},{q:"How many Bitcoin full nodes are estimated to run worldwide?",a:"Tens of thousands across dozens of countries",wrong:["Fewer than a thousand across North America","One per major city in the developed world","Only certified mining companies run nodes"]},{q:"Why is geographic distribution of nodes important?",a:"It prevents any single jurisdiction from shutting down the network",wrong:["It ensures Bitcoin transactions can be processed more efficiently","It allows miners to reduce their overall electricity consumption","It automatically increases the block size when network demand rises"]}],scarce:[{q:"What is the maximum supply of Bitcoin?",a:"21 million",wrong:["100 million","1 billion","Unlimited"]},{q:"How many Bitcoin are estimated to be lost forever?",a:"2-3 million",wrong:["4-5 million","10 million","Over 500,000"]},{q:"Bitcoin's code is:",a:"Open source and auditable by anyone",wrong:["Proprietary and closed to the public","Only visible to licensed developers","Controlled by the core developer team"]},{q:"What event cuts Bitcoin's new supply in half?",a:"The halving",wrong:["The rebase","The rollback","The snapback"]},{q:"How often does the halving occur?",a:"Approximately every 4 years",wrong:["Every two to three years","Roughly once per decade as defined by Bitcoin consensus rules enforced by all full nodes","Once every three months as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"Bitcoin is often compared to which precious metal?",a:"Gold",wrong:["Silver","Platinum","Copper"]},{q:"The last Bitcoin will be mined around the year:",a:"2140",wrong:["2030","2050","2025"]},{q:"Bitcoin scarcity is enforced by:",a:"Math and code",wrong:["Government regulations","A central bank","Mining companies"]},{q:"What is the smallest unit of Bitcoin called?",a:"A satoshi (0.00000001 BTC)",wrong:["A millibit (0.001 BTC) as defined by Bitcoin consensus rules enforced by all full nodes","A nanobit (0.0000001 BTC)","A microbit (0.000001 BTC)"]},{q:"How does Bitcoin's stock-to-flow ratio compare to gold after the 2024 halving?",a:"Bitcoin's stock-to-flow surpassed gold's",wrong:["Gold's stock-to-flow still exceeds Bitcoin's","Both gold and Bitcoin share the same ratio","The model only applies to mined commodities"]}],secure:[{q:"Bitcoin has been under attack since gaining significant value around:",a:"2013",wrong:["2020","2009","2017"]},{q:"How many potential Bitcoin wallets exist?",a:"2^160",wrong:["21 million","A few billion","2^16"]},{q:"Bitcoin's monetary policy is:",a:"Set in stone and immutable",wrong:["Changed annually by miners","Voted on by mining pools","Adjusted for market demand"]},{q:"A 51% attack would require:",a:"More computing power than the rest of the network combined",wrong:["A signed approval from the core Bitcoin development team","Hacking one of the computers that keeps the Bitcoin ledger","A valid government authorization and legal court approval"]},{q:"Bitcoin has experienced how many hours of downtime since 2013?",a:"Zero",wrong:["Hundreds","A few days each year","One week"]},{q:"Bitcoin uses which hashing algorithm?",a:"SHA-256",wrong:["SHA-512","Scrypt","BLAKE2"]},{q:"The cost to attack Bitcoin's network is:",a:"Billions of dollars",wrong:["A few hundred dollars","Free as defined by Bitcoin consensus rules enforced by all full nodes","A few thousand dollars"]},{q:"What is Bitcoin's uptime percentage since launch in 2009?",a:"Over 99.98% - virtually no downtime",wrong:["About 95% uptime since its launch","Around 80% due to repeated attacks","Exactly 100% with no downtime at all"]},{q:"Why does higher hashrate make Bitcoin more secure?",a:"More computational power means an attacker needs proportionally more resources to overpower the network",wrong:["More hashing power enables any miner with enough resources to generate Bitcoin beyond the supply limit","Greater hashrate automatically reduces the time between blocks so transactions settle in under a minute","Higher hashrate means the network can process more transactions and miners earn significantly more fees"]},{q:"What makes a 51% attack on Bitcoin impractical?",a:"The enormous cost of acquiring more mining power than all honest miners combined",wrong:["Satoshi Nakamoto holds a private master key that allows reversal of any attack","Governments actively monitor mining pools and prosecute suspicious attacks","A built-in cryptographic firewall automatically rejects suspicious transactions"]}],money:[{q:"How many satoshis are in one Bitcoin?",a:"100,000,000",wrong:["1,000,000","10,000,000","50,000,000"]},{q:"Bitcoin payments are compared to:",a:"Email - anyone with your address can send",wrong:["Phone call - both parties must be online at the same time","Postal mail - delivery requires a verified physical address","Fax machine - both sender and receiver need compatible hardware"]},{q:"Bitcoin's distribution was fair because:",a:"There was no premine",wrong:["A company sold coins early","The government distributed it","Only miners got coins"]},{q:"A satoshi is named after:",a:"Bitcoin's creator, Satoshi Nakamoto",wrong:["A famous Japanese cryptography professor","The creator of an early digital cash system","A senior engineer at the Bank of Japan"]},{q:"Bitcoin is divisible to how many decimal places?",a:"8",wrong:["2","4","16"]},{q:"Bitcoin can function as:",a:"A store of value, medium of exchange, and unit of account",wrong:["A payment rail only, not designed for long-term storage or savings","A speculative asset only, lacking any formal monetary properties","A store of value only, not usable as a medium of daily exchange"]},{q:'What makes Bitcoin "sound money"?',a:"Fixed supply and predictable issuance",wrong:["Government mandate and legal tender status","Central bank oversight with regulated supply limits","Corporate backing and independent third-party reserve audits"]},{q:"Which property of money does Bitcoin's 21 million cap satisfy?",a:"Scarcity - it cannot be inflated or debased",wrong:["Acceptability - it must be accepted by all merchants worldwide","Portability - it weighs nothing and requires no physical storage","Fungibility - each coin carries a unique traceable history on-chain"]},{q:"Why are satoshis important for Bitcoin as money?",a:"They allow micropayments and make Bitcoin divisible enough for everyday transactions",wrong:["They were created to let Bitcoin expand its total supply beyond 21 million coins","They represent a separate altcoin that operates alongside the main Bitcoin network","They are only valid on Layer 2 networks and cannot be spent in on-chain transactions"]},{q:"What gives Bitcoin its monetary value according to Austrian economics?",a:"Subjective value from its useful properties: scarcity, portability, divisibility, and censorship resistance",wrong:["Objective intrinsic worth assigned by states through legal tender laws, taxation, and central bank monetary decrees","Its backing in gold and commodity reserves held by central banks, giving each token a tangible collateral floor","The total electrical energy consumed in mining, which provides each coin a measurable cost-of-production baseline"]}],peaceful:[{q:"When China banned Bitcoin:",a:"Bitcoin just moved and kept going",wrong:["Bitcoin immediately shut down across all mining pools worldwide","Bitcoin's price collapsed all the way to zero permanently","All miners erased the source code and abandoned the network"]},{q:"What happened to Bitcoin transactions during the 2021 China mining ban?",a:"The network kept running - hash rate dipped then recovered within months",wrong:["Transactions slowed severely as hash rate took over a year to fully recover","The difficulty adjustment failed and blocks stopped confirming for several weeks","The network split into two chains — one with and one without Chinese nodes"]},{q:"Bitcoin enables protest by:",a:"Allowing people to transact without government permission",wrong:["Enabling activists to flood government payment portals with traffic","Letting dissidents publish untraceable encrypted messages to the state","Allowing programmers to hack and expose corrupt central bank systems"]},{q:'Bitcoin is called "peaceful" because:',a:"It opts out of the existing system without force",wrong:["It forces corrupt central banks to reform by draining their reserves","It distributes wealth equally among all participants over time","It prevents all violence by monitoring every global transaction"]},{q:"Bitcoin helps people in authoritarian regimes by:",a:"Providing censorship-resistant money",wrong:["Helping insurgent groups to seize state banking institutions","Allowing authoritarian governments to track dissidents online","Letting citizens mint and spend unlimited local digital coins"]},{q:"Bitcoin adoption is described as:",a:"Voluntary and organic",wrong:["Mandatory and forced","Government-mandated","Corporate-controlled"]},{q:"How does Bitcoin function as a peaceful protest tool?",a:"It allows people to opt out of inflationary monetary systems without violence",wrong:["It provides anonymous funding to protest and activist organizations worldwide","It disables government financial websites by routing encrypted protest traffic","It replaces traditional voting systems with a cryptographically secured ballot"]},{q:'Why is Bitcoin described as "opt-in" money?',a:"Nobody is forced to use it - participation is entirely voluntary",wrong:["You must register with a licensed exchange before you can hold any Bitcoin","Governments automatically assign a starting Bitcoin wallet to every new citizen","You are required to run a full mining node before being allowed to spend coins"]},{q:"How did Bitcoin help protestors in authoritarian regimes?",a:"It allowed them to receive donations that could not be frozen by the government",wrong:["It gave activists free and unrestricted access to the public internet worldwide","It created anonymous digital identity documents that could replace national passports","It provided a fully encrypted messaging service immune to government wiretapping"]},{q:'What makes Bitcoin "permissionless"?',a:"Anyone can send, receive, or hold Bitcoin without needing approval from any authority",wrong:["You must first obtain a government-issued license before you are permitted to own Bitcoin","Only wallets that have been explicitly approved by a licensed exchange are allowed to transact","Each transaction must receive manual approval from the mining pool nearest to the sender"]}],dominant:[{q:"∞/21M means:",a:"All world wealth funneling into 21 million coins",wrong:["Bitcoin has no supply cap and new coins can be issued indefinitely","There are infinite users all competing for an equal share of coins","Each of the 21 million coins exists on its own independent blockchain"]},{q:"Bitcoin's growth pattern resembles:",a:"A J-shaped curve",wrong:["A straight trend line","A symmetric bell curve","A long flat plateau"]},{q:"Bitcoin is said to change you by:",a:"Lowering your time preference",wrong:["Making you overnight very wealthy","Increasing your urge to spend today","Having no real effect on behavior"]},{q:"Bitcoin's market dominance refers to:",a:"Its share of total cryptocurrency market cap",wrong:["The total number of active users across all its wallets","The average speed at which it confirms new transactions","The maximum data size allowed in each individual block"]},{q:"Bitcoin's ∞/21M meme represents:",a:"All the world's wealth eventually stored in a 21M coin supply",wrong:["Bitcoin has no hard supply cap and new coins are issued indefinitely","An unlimited number of users each receive equal daily block rewards","There are countless competing blockchains all processing the same payments"]},{q:"Bitcoin is considered dominant because:",a:"It has the strongest network effect and security",wrong:["It launched first and was available at the very lowest price","A coalition of central banks officially selected it as a reserve","It has more programmable smart contract features than competitors"]},{q:'What is the "Lindy effect" as applied to Bitcoin\'s dominance?',a:"The longer Bitcoin survives and grows, the more likely it is to continue dominating",wrong:["Old legacy technology always fails eventually as newer and faster alternatives emerge to replace it","Bitcoin's market dominance naturally decreases each year as newer competing chains attract more users","The Lindy effect only applies to physical goods with a tangible form factor, not to digital protocols"]},{q:"Why do network effects favor Bitcoin over altcoins?",a:"More users, miners, developers, and infrastructure create a self-reinforcing cycle that's hard for competitors to match",wrong:["Bitcoin simply had the largest early marketing budget, backed by venture capital and high-profile celebrity endorsements","Altcoins are prohibited in most jurisdictions, which prevents them from attracting developers and institutional capital","Network effects apply only to social media platforms and cannot meaningfully transfer to monetary networks like Bitcoin"]},{q:'What does Bitcoin\'s "dominance" metric measure?',a:"Bitcoin's share of total cryptocurrency market capitalization",wrong:["The total number of Bitcoin full nodes relative to all altcoin nodes combined","Bitcoin's fraction of all global cryptocurrency mining hash rate output","The percentage of worldwide merchants and retailers currently accepting Bitcoin"]},{q:"Why has no altcoin overtaken Bitcoin despite thousands of attempts?",a:"Bitcoin's first-mover advantage, network effects, decentralization, and brand recognition create an insurmountable moat",wrong:["Governments around the world have enacted laws specifically designed to protect Bitcoin and block altcoin competition","All alternative cryptocurrencies are deliberate scams built on copied code with no genuine utility or use case","Satoshi Nakamoto retains secret admin access and uses it to prevent any competing hard fork from gaining traction"]}],"use-cases":[{q:"Bitcoin is described as better than gold because:",a:"It can be sent across the planet instantly",wrong:["It weighs more than gold making it much harder to transport safely","It looks shinier than silver coins and is far more visually appealing","Its price is fully backed by physical gold reserves held in a vault"]},{q:"How do Bitcoin remittance fees compare to Western Union?",a:"Much cheaper, nearly free",wrong:["About the same as a wire fee","Slightly more expensive overall","Nearly double the standard fee"]},{q:"Credit card merchants pay about what fee?",a:"3%",wrong:["0%","10%","25%"]},{q:"Bitcoin can help the unbanked because:",a:"You only need a phone and internet to use it",wrong:["Local banks distribute it to customers who pass basic identity checks","The government issues it for free to citizens who hold a valid national ID","Users must pass a credit check and hold a valid bank account to access it"]},{q:"Bitcoin as a hedge against inflation means:",a:"Its fixed supply protects purchasing power",wrong:["Its price only ever rises and can never fall below its prior value","The government legally guarantees its minimum exchange rate in dollars","It pays a fixed annual interest rate like a government savings bond"]},{q:"Micropayments on Bitcoin are possible through:",a:"The Lightning Network",wrong:["The Visa payment network","PayPal instant transfers","Bank wire transfer rails"]},{q:"Bitcoin enables financial sovereignty by:",a:"Letting you be your own bank",wrong:["Requiring a licensed bank account","Needing government-issued identification","Using a third-party credit system"]},{q:"Why is Bitcoin especially valuable for international remittances?",a:"It settles in minutes with low fees compared to days and high fees with traditional wire transfers",wrong:["It automatically converts to the recipient's local currency using real-time exchange rate data","Banks around the world process Bitcoin-based remittances instantly with no service or transfer fees","It works completely offline using encrypted Bluetooth so transfers complete without needing internet"]},{q:'How does Bitcoin serve as a "savings technology"?',a:"Its fixed supply and deflationary nature preserve purchasing power over time",wrong:["It pays variable interest rates, just like high-yield bank savings accounts do","Government-backed deposit insurance guarantees the value of all Bitcoin holdings","Bitcoin is programmed to automatically increase in value by exactly 10% every year"]},{q:"What makes Bitcoin useful for micropayments via Lightning?",a:"Sub-penny transaction fees and instant settlement enable payments too small for traditional systems",wrong:["The Lightning Network fully replaces Bitcoin on-chain and operates as a completely separate chain","All micropayments regardless of size must still be processed directly on the main blockchain ledger","Lightning channels only process payments that exceed one US dollar, filtering out tiny transactions"]}],mining:[{q:"What do miners do?",a:"Secure the network and process transactions",wrong:["Create Bitcoin by approving and validating new transactions","Print digital money for the broader payment network","Erase old or outdated transactions to maintain the ledger"]},{q:"Miners are paid in:",a:"New Bitcoin and transaction fees",wrong:["US dollars and government bonds","Ethereum and other altcoin tokens","Company stock and equity options"]},{q:"Mining difficulty adjusts approximately every:",a:"2 weeks (2016 blocks)",wrong:["Every day (144 blocks)","Each hour (6 new blocks)","Each month (4,320 blocks)"]},{q:"A mining pool is:",a:"A group of miners combining computing power",wrong:["A shared server for pooling and distributing rewards","A single powerful dedicated mining computer","A government-regulated mining operation facility"]},{q:"The mining reward after the 2024 halving is:",a:"3.125 BTC per block",wrong:["6.25 BTC per block","50.0 BTC per block","12.5 BTC per block"]},{q:"ASIC miners are:",a:"Specialized hardware designed only for mining",wrong:["Standard laptops with mining software installed","Gaming computers adapted for mining operations","Smartphones modified with extra processing power"]},{q:"What prevents miners from cheating?",a:"Other nodes verify their work",wrong:["An honor system among all miners","Government oversight prevents it","Nothing prevents cheating miners"]},{q:"What milestone did Bitcoin hash rate reach in September 2025?",a:"1 Zettahash per second",wrong:["500 Exahash per second","10 Petahash per second","100 Terahash per second"]},{q:"Pleb Pool and Atlas Pool are examples of:",a:"Solo Bitcoin mining pools",wrong:["Bitcoin Lightning wallets","Centralized Bitcoin exchanges","Hardware-based cold wallets"]},{q:"D-Central Technologies specializes in:",a:"Home mining equipment and support",wrong:["Bitcoin day trading and arbitrage","Lightning routing and channel management","Hardware cold storage and backup"]},{q:"Constellation Heating combines mining with:",a:"Heating swimming pools",wrong:["Cooling server data centers","Generating wind power","Installing solar panels"]},{q:'What is a "nonce" in Bitcoin mining?',a:'A "number used once" that miners change to find a valid hash',wrong:["A specialized type of ASIC mining hardware chip used in rigs","A small transaction fee paid by miners directly to network nodes","The total fixed number of Bitcoins that will ever be mined"]},{q:"Mining pools allow small miners to:",a:"Receive more frequent, smaller payouts",wrong:["Gain more control over the network","Mine Bitcoin with no electricity use","Vote to change the Bitcoin supply cap"]},{q:"Bitcoin difficulty adjusts every how many blocks?",a:"2,016 blocks (roughly 2 weeks)",wrong:["210,000 blocks (roughly 4 years)","Only when a halving event occurs","After every individual block mined"]},{q:"Bitcoin mining is best described as:",a:"A brute-force lottery of guessing nonces until a valid hash is found",wrong:["Solving complex cryptographic equations using advanced mathematical formulas","Running an algorithm that successfully factors large semi-prime numbers quickly","Decrypting encoded transaction data in each block using a private key"]},{q:"What happens when a miner finds a valid block hash?",a:"They broadcast the block to the network, collect the block reward and transaction fees",wrong:["They must submit the block to a government regulator for review before it can be added","The newly found block gets sent to Satoshi's node for final cryptographic verification","All other competing miners must immediately cease operations and restart their hardware"]},{q:"Why does Bitcoin mining use so much energy?",a:"Energy expenditure is what gives Bitcoin its security - it makes attacks prohibitively expensive",wrong:["Bitcoin's original source code was never fully optimized, resulting in unnecessary energy waste","All commercial miners are legally required by regulators to operate hardware continuously nonstop","Each individual Bitcoin transaction requires a dedicated mining operation to confirm and finalize"]},{q:'What is "hash rate" in Bitcoin mining?',a:"The total computational power being used to process transactions and secure the network",wrong:["The speed at which brand new Bitcoins are printed and added to the circulating supply","The rate at which old or invalid transactions are removed from the blockchain ledger","The precise real-time number of all active Bitcoin miners running equipment at once"]},{q:'What is "stranded energy" and why do Bitcoin miners seek it?',a:"Energy produced in remote locations with no local demand - miners can monetize it at low cost",wrong:["Energy pre-stored in large industrial battery banks for use during peak demand periods","Solar energy that goes unused because panels generate far more than the local grid absorbs","Power sourced exclusively from decommissioned plants that have been permanently shut down"]},{q:'What is a mining "share" in a pool?',a:"Proof that a miner contributed valid work toward finding a block, used to split rewards proportionally",wrong:["An ownership stake in the mining company entitling the holder to dividends and future profit sharing","A fractional Bitcoin automatically sent to the miner's wallet after each successful hash attempt","A governance vote granting miners the right to decide which pending transactions get added to blocks"]},{q:"What does Stratum V2 allow individual miners to do that Stratum V1 does not?",a:"Choose their own transactions for block templates",wrong:["Mine without needing any internet connection","Bypass the network difficulty adjustment algorithm","Mine multiple different coins at the same time"]},{q:"What is a block template in Bitcoin mining?",a:"A candidate block with selected transactions awaiting a valid hash",wrong:["A technical design blueprint for building specialized ASIC hardware chips","A complete offline backup copy of the entire Bitcoin blockchain ledger","A configuration template for setting up new mining pool infrastructure"]},{q:"What is a selfish mining attack?",a:"Withholding discovered blocks to gain an unfair chain advantage",wrong:["Refusing to share all earned mining rewards with fellow pool members","Mining only low-fee transactions for the miner's personal gain","Using stolen electricity to illegally power Bitcoin mining rigs"]},{q:"What is ASICBoost?",a:"A technique that optimizes SHA-256 to reduce energy per hash",wrong:["A specific brand of mining hardware manufactured by Bitmain","A firmware update that automatically doubles any miner's hashrate","A method to cool ASIC miners using advanced liquid nitrogen"]},{q:"What is the difference between overt and covert ASICBoost?",a:"Overt is visible in block headers; covert is hidden from view",wrong:["Overt is legal in all jurisdictions while covert is illegal","Overt uses significantly more energy per hash than covert does","Overt works on any ASIC while covert is Bitmain hardware only"]},{q:'What is "hash price" in Bitcoin mining economics?',a:"Revenue earned per unit of hash rate per day",wrong:["The cost to purchase a single ASIC mining unit","Bitcoin's spot price divided by the global hash rate","Electricity price charged per unit of hash rate"]},{q:"What typically happens to less efficient miners shortly after a Bitcoin halving?",a:"They become unprofitable and may shut down",wrong:["They automatically receive double the reward","Their hash rate doubles to compensate","They permanently switch to mining altcoins"]},{q:"What is the typical operational lifespan of an ASIC miner before it becomes obsolete?",a:"Approximately 3 to 5 years",wrong:["About 6 months on average","Over 20 years with maintenance","Exactly one halving cycle"]},{q:"What is the breakeven electricity cost for Bitcoin mining?",a:"The kWh price where revenue equals costs",wrong:["A fixed rate set by Bitcoin core developers","The average global electricity cost across regions","The minimum wattage needed to run one ASIC miner"]},{q:"As block subsidies decrease over time, what must replace them to incentivize miners?",a:"Transaction fees paid by users",wrong:["Government subsidies for miners","Increased mining difficulty","New coins from hard forks as defined by Bitcoin consensus rules enforced by all full nodes"]}],nodes:[{q:"Running a node lets you:",a:"Verify transactions independently",wrong:["Mine new Bitcoin from the network","Print digital money from your node","Control the entire Bitcoin network"]},{q:'What does it mean to say Bitcoin has "no leader"?',a:"No single person or organization controls the protocol rules",wrong:["Satoshi still controls it anonymously from an undisclosed location","The Bitcoin Foundation oversees and enforces all protocol changes","Core developers vote on all protocol upgrades using a majority system"]},{q:"A full node stores:",a:"The entire blockchain history",wrong:["Only your own wallet transactions","Only the most recent block headers","Only the current UTXO set data"]},{q:"How many Bitcoin nodes exist approximately?",a:"Tens of thousands worldwide",wrong:["Only a few hundred globally","Exactly 21 million in total","One official node per country"]},{q:"Running a node requires:",a:"A regular computer with enough storage",wrong:["A dedicated server-grade machine with special specs","Official government approval and a registered license","A specialized mining rig equipped with ASIC hardware"]},{q:"Nodes enforce:",a:"The consensus rules of Bitcoin",wrong:["National financial laws and regulations","Corporate terms of service and policies","Community-voted social governance rules"]},{q:"Clark Moody dashboard is useful for tracking:",a:"Bitcoin network stats and Knots adoption",wrong:["Altcoin market prices and trading volumes","Social media follower counts and engagement","Email subscriber growth and newsletter stats"]},{q:"Matt Hill is the founder and CEO of:",a:"Start9 (node-in-a-box solution)",wrong:["The Bitcoin Magazine publication","Coinbase, the largest US exchange","Blockstream, a major Bitcoin company"]},{q:"The Bitcoin Commons governance model proposes:",a:"Coordination without authority for Bitcoin implementations",wrong:["Centralized planning and scheduling for all Bitcoin protocol upgrades","A formal voting mechanism for Bitcoin block size and fee decisions","Mandatory government oversight and compliance for Bitcoin node operators"]},{q:"A pruned node saves space by:",a:"Deleting old block data after validating it",wrong:["Only downloading block headers from network peers","Offloading stored blocks onto neighboring nodes for free","Slowing down the rate at which new blocks are accepted"]},{q:"A full node is different from a miner because:",a:"It enforces all rules but doesn't create new blocks",wrong:["It processes transactions significantly faster than a miner does","It consumes considerably more electricity than a mining node","It is designed exclusively for experienced developers to operate"]},{q:"How does your node know if a transaction is valid?",a:"It checks the signatures and inputs against the consensus rules",wrong:["It queries a trusted central server for a validation confirmation","It polls other nodes and uses a majority vote to confirm validity","It relies on a trusted third-party oracle service to verify inputs"]},{q:"What is the main benefit of running your own Bitcoin node?",a:"You verify all transactions and blocks yourself without trusting any third party",wrong:["You earn small Bitcoin rewards every time your node relays a valid transaction","You can mine Bitcoin significantly more efficiently using dedicated node software","You receive faster transaction confirmations by connecting directly to the network"]},{q:'What does "initial block download" (IBD) mean?',a:"The process of downloading and validating the entire blockchain when first setting up a node",wrong:["The amount of time required to mine and confirm the very first block on a fresh chain","The process of downloading the Bitcoin Core software installer and configuring a wallet","The procedure for synchronizing your personal wallet balance with a trusted exchange server"]},{q:"How does a Bitcoin node protect you from accepting fake transactions?",a:"It independently validates every transaction against consensus rules before accepting it",wrong:["It sends each transaction to Satoshi's known address for manual verification approval","It queries three randomly selected nodes and requires a majority vote to confirm validity","It applies machine learning models trained on historical fraud patterns to detect errors"]},{q:"What is the key difference between a pruned node and an archival (full) node?",a:"A pruned node deletes old block data after verifying it",wrong:["A pruned node skips signature verification entirely to reduce load","An archival node only retains the active UTXO set in fast memory","A pruned node is unable to validate or relay any newly arriving blocks"]},{q:"What does BIP 152 (Compact Block Relay) do?",a:"Sends short transaction IDs instead of full transactions",wrong:["Compresses entire blockchain history into smaller gzip archive files","Lets nodes skip certain redundant blocks during the initial sync phase","Encrypts all block data to ensure privacy between directly peered nodes"]},{q:"What is the Erlay protocol designed to improve?",a:"Transaction relay efficiency between nodes",wrong:["Block mining throughput via nonce optimization techniques","Lightning Network payment channel balancing and routing","Wallet synchronization speed for mobile and lightweight devices"]},{q:"What is the UTXO set and why does its size matter for nodes?",a:"All unspent outputs nodes must keep in memory for validation",wrong:["A complete index of every transaction ever confirmed on the blockchain","A ledger recording every mining reward ever paid out to all miners","A distributed backup of all wallet private keys held across nodes"]},{q:"What is a major concern about running a Bitcoin full node related to bandwidth?",a:"Relaying transactions and blocks uses significant upload bandwidth",wrong:["Nodes must pay per-megabyte data fees to peers on the network","Network bandwidth usage drops to near zero after initial block sync","Only active mining nodes are responsible for consuming upload bandwidth"]},{q:"What programming language is Bitcoin Core primarily written in?",a:"C++",wrong:["Rust","Python","Java"]},{q:"What is btcd?",a:"An alternative Bitcoin full node written in Go",wrong:["A Bitcoin desktop wallet application for storing and sending funds","A command-line mining tool for optimizing Bitcoin hash rate output","A developer testing and simulation framework built for Bitcoin Core"]},{q:"What are reproducible builds in the context of Bitcoin Core?",a:"Anyone can compile source and get an identical binary",wrong:["A feature that lets Bitcoin Core silently update itself automatically","A method to quickly restore a node's data from an encrypted backup","A technique to compile Bitcoin Core faster on recently released CPUs"]},{q:"What is Guix used for in Bitcoin Core development?",a:"A build system for reproducible, verifiable builds",wrong:["A graphical dashboard for running and monitoring a Bitcoin node","A security auditing tool for scanning code for vulnerabilities","A package manager for downloading and installing Bitcoin wallets"]},{q:"Why is it important to be able to build Bitcoin Core from source?",a:"To verify the code and ensure your binary matches it",wrong:["Because official pre-built binary releases are not publicly available","To unlock access to hidden or beta developer-only features in the code","Because compiling from source produces a more optimized and faster node"]}],"pow-vs-pos":[{q:"Bitcoin uses which consensus mechanism?",a:"Proof of Work",wrong:["Proof of Stake","Proof of Authority","Proof of Space"]},{q:"In Proof of Work, security comes from:",a:"Computational work and electricity",wrong:["Staking and locking up coins as collateral","Weighted voting among registered validators","Government-issued authorization and oversight"]},{q:"Proof of Stake has been criticized for:",a:"Favoring wealthy holders (the rich get richer)",wrong:["Consuming far too much energy and wasting global resources","Being excessively decentralized and lacking any clear governance","Being far too slow to handle real-world transaction throughput"]},{q:"Proof of Work connects Bitcoin to:",a:"The physical world through energy expenditure",wrong:["The global stock market through asset price correlation","Social media networks via community-driven consensus signals","National government databases and legal financial records"]},{q:"In PoW, you can't fake:",a:"The energy spent to mine a block",wrong:["Your miner's registered identity or username","Your node's publicly visible IP address","The exact timestamp recorded in a block"]},{q:"Proof of Work was chosen because:",a:"It provides unforgeable costliness",wrong:["It was the cheapest and simplest option available","Satoshi had no viable alternatives to consider","A government mandate specifically required its use"]},{q:"What real-world resource does Proof of Work consume that Proof of Stake does not?",a:"Energy (electricity used for computation)",wrong:["Hard drive storage space and disk capacity","Internet bandwidth and network data transfer","RAM memory and active processor compute cycles"]},{q:'What is the "nothing at stake" problem in Proof of Stake?',a:"Validators can sign multiple competing chain forks at no cost, weakening consensus",wrong:["Validators immediately lose all their staked tokens each time they try to validate a block","There is absolutely no block reward ever offered to validators in any Proof of Stake system","Validators are required to purchase and maintain expensive specialized mining hardware rigs"]},{q:"Why do PoW proponents argue it provides stronger security guarantees?",a:"Attacking PoW requires massive ongoing real-world energy expenditure that can't be faked",wrong:["PoW is more secure because the developer ecosystem is larger and more diversely distributed globally","PoW confirms transactions much faster, making it harder for attackers to reorganize recent chain history","PoW has accumulated more battle-testing over its longer history, making its security assumptions well-verified"]},{q:"How does Proof of Stake differ from Proof of Work in block producer selection?",a:"PoS selects validators based on the amount of coins they lock up, while PoW requires solving computational puzzles",wrong:["PoS uses a lottery where validators purchase entry tickets with fiat money to win block production rights","PoW always awards blocks to whichever miner owns the most hardware, making both systems functionally equivalent","Both systems rely on the same underlying random selection process; only the energy cost of participation differs"]},{q:"Why do Bitcoin advocates argue Proof-of-Work is a stronger security foundation than Proof-of-Stake?",a:"PoW links digital security to real-world energy expenditure — you cannot fake or virtualize the physical cost of mining blocks",wrong:["PoW uses more electricity, which signals that all participants are financially committed to the network's long-term success","PoW produces a public record of miner identities so the community can penalize dishonest participants after any attack occurs","PoW requires specialized hardware purchases that effectively deanonymize miners, creating legal accountability for any attack"]},{q:"How are validators selected to produce blocks in a Proof-of-Stake system?",a:"Validators are chosen based on the size of their token stake; those with more tokens staked gain proportionally more block rights",wrong:["Validators are elected by token-holder votes each epoch and then share block rewards equally with their supporting voters","Validators are selected by a verifiable random function with absolutely no weighting by stake size or prior token holdings","Validators are chosen by a committee of existing validators who review each candidate's historical performance and uptime record"]},{q:'What is the "nothing at stake" problem that affects naive Proof-of-Stake designs?',a:"Validators can vote on multiple competing chain forks simultaneously at zero cost because no real resource is being consumed",wrong:["Validators can pledge the same tokens to multiple chains at once because there is no on-chain registry of all staked assets","Validators have no incentive to stay online because the penalty for downtime costs less than the reward for staying connected","New participants can't accumulate stake because established validators monopolize block production without expending any resources"]},{q:"When did Ethereum complete its switch from Proof-of-Work to Proof-of-Stake consensus?",a:'September 2022, in an event called "The Merge" that replaced Ethereum\'s PoW mining with a Proof-of-Stake validator set',wrong:["March 2021, when the Ethereum Foundation completed deployment of the Beacon Chain mainnet consensus upgrade on schedule","December 2023, when Ethereum's final sharding upgrade replaced the remaining PoW elements with Proof-of-Stake validation","June 2020, when Ethereum 2.0 Phase 0 launched and the Proof-of-Work chain was simultaneously deprecated in the upgrade"]},{q:"How do the thresholds for a successful attack differ between Bitcoin's PoW and a typical PoS network?",a:"A Bitcoin 51% attack requires over half of total global hashrate; a typical PoS attack requires acquiring over 33% of staked tokens",wrong:["A PoW attack requires 67% of mining power while PoS needs only 10% of staked capital, making PoS actually more attack-resistant","Both systems require exactly 51% of their respective resources; the cost difference depends solely on the current token price","PoW is attacked by controlling 25% of ASIC manufacturers; PoS requires 51% of staked tokens for an equivalent disruption"]},{q:"What did Saifedean Ammous write about Proof-of-Work's uniquely fair property in The Bitcoin Standard?",a:'"PoW is the only mechanism that does not confer explicit power on any subset of participants" — Saifedean Ammous, The Bitcoin Standard',wrong:['"PoW guarantees equal returns on investment for all miners regardless of pool size or geographic cost of electricity access"','"PoW creates a perfectly merit-based network where each participant\'s contribution is measured objectively by work performed"','"PoW eliminates all insider advantages by requiring every participant to solve the same cryptographic puzzle each block epoch"']},{q:"Does Proof-of-Stake slashing fully resolve the security weaknesses inherent in stake-based consensus?",a:"No — slashing punishes detectable misbehavior but cannot prevent long-range attacks where an attacker rewrites old chain history",wrong:["Yes — slashing penalizes all forms of validator dishonesty and provides demonstrably stronger security guarantees than PoW mining","Yes — slashing combined with finality gadgets eliminates all known attack vectors including long-range history rewriting attacks","No — slashing creates severe centralization pressure by making it prohibitively risky for small validators to run nodes at all"]},{q:"What was Bitcoin's approximate network hashrate in the 2024–2025 timeframe?",a:"Over 700 exahashes per second (EH/s), making a successful 51% attack require more hardware than currently exists on Earth",wrong:["Over 100 exahashes per second (EH/s), a figure comparable to Ethereum's peak PoW hashrate just before The Merge in 2022","Approximately 200 terahashes per second (TH/s), reflecting the dominance of next-generation 7nm ASIC mining hardware farms","Around 500 petahashes per second (PH/s), representing roughly 40% annual growth sustained since the May 2020 halving event"]},{q:"How does access to Bitcoin mining compare to participation in Proof-of-Stake validation?",a:"Anyone with hardware and cheap electricity can mine Bitcoin; PoS compounds advantages for those who already hold large wealth",wrong:["Bitcoin mining requires a license from the Bitcoin Foundation; PoS is fully open to anyone willing to make a small token deposit","Both systems offer equivalent access barriers; entry cost is roughly comparable between mining rigs and major PoS token deposits","PoS is far more accessible because anyone can stake tiny amounts; Bitcoin mining requires millions of dollars minimum investment"]},{q:"What is the fundamental difference in the nature of costs between PoW and PoS security models?",a:"PoW requires external real-world energy cost to attack; PoS only requires internal tokens the attacker may already own and hold",wrong:["PoW security comes from miner coordination costs; PoS security relies on smart contract audits and formal verification proofs","PoW security depends on hardware scarcity; PoS security relies entirely on the irreversibility of slashing penalties post-attack","PoW costs are paid by miners and passed to users through fees; PoS costs are socialized across all token holders proportionally"]}],"layer-2-lightning":[{q:"Lightning is which layer of Bitcoin?",a:"Layer 2",wrong:["Layer 1","Layer 3","Layer 0"]},{q:"Lightning uses what for privacy?",a:"Onion routing",wrong:["GPS tracking","Public ledger","Email verification"]},{q:"Opening a Lightning channel is like:",a:"Opening a bar tab",wrong:["Buying a car as defined by Bitcoin consensus rules enforced by all full nodes","Getting a loan","Opening a bank account"]},{q:"Lightning transactions are:",a:"Nearly instant and very cheap",wrong:["Slow and costly like on-chain transactions","Free to use but take many hours to settle","Only available for large-value transfers"]},{q:"Lightning channels are settled on:",a:"The Bitcoin base layer",wrong:["The Ethereum mainnet","A parallel sidechain","A centralized bank ledger"]},{q:"Lightning enables:",a:"Micropayments as small as 1 satoshi",wrong:["Only large transactions above 0.01 BTC","Only fiat-backed stablecoin payments","Only cross-border international payments"]},{q:"Lightning capacity refers to:",a:"The total Bitcoin locked in payment channels",wrong:["The available bandwidth across all network nodes","The total mining power contributed by active nodes","The number of active routing nodes on the network"]},{q:"Satogram allows you to:",a:"Send messages across the Lightning network",wrong:["Mine Bitcoin directly using your mobile device","Create and sell NFTs on the Lightning network","Swap altcoins using Lightning-backed atomic swaps"]},{q:"Lightning Cats and Lightning Goats let you:",a:"Feed real animals using Lightning payments",wrong:["Trade collectible animal-themed NFTs for sats","Use animal activity to generate Bitcoin mining power","Buy and adopt real pets with on-chain Bitcoin payments"]},{q:"Pay With Flash is a service for:",a:"Businesses to accept Bitcoin payments",wrong:["Miners to earn Bitcoin using solar energy","Users to securely store Bitcoin offline","Users to mix coins for enhanced privacy"]},{q:"LNgigs is a Bitcoin-powered:",a:"Freelance marketplace",wrong:["Bitcoin mining pool","Cryptocurrency exchange","Hardware wallet vendor"]},{q:"The Lightning Network whitepaper was written by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto and Hal Finney","Vitalik Buterin and Gavin Wood","Adam Back and Gregory Maxwell"]},{q:"Lightning Network payment channels work by:",a:"Opening a channel with an on-chain transaction, then transacting off-chain instantly",wrong:["Creating a dedicated sidechain for each payment pair that merges back into Bitcoin after closure","Sending Bitcoin through encrypted relay servers that batch-broadcast transactions to the main chain","Using staked collateral to validate Lightning payments without changing Bitcoin's core consensus rules"]},{q:"Why is Lightning considered a Layer 2 solution?",a:"It builds on top of Bitcoin's base layer without changing the protocol",wrong:["It was the second payment network to launch, built directly after Bitcoin itself","It requires two on-chain confirmations for every Lightning payment to settle","Only two participants can share any single payment channel at the same time"]},{q:"A Lightning invoice is:",a:"A payment request containing the amount, destination, and expiry time",wrong:["A monthly subscription bill sent to users who operate Lightning routing nodes","An itemized receipt issued to miners after each successful block reward payment","A required tax document that Lightning node operators must submit to authorities"]},{q:"What does Lightning Labs' Loop service do?",a:"It moves funds between on-chain and Lightning using submarine swaps",wrong:["It mines Bitcoin directly from a Lightning node by aggregating routing fees","It converts Bitcoin to altcoins through Lightning-powered atomic swaps","It keeps the Lightning channel graph in sync with every new confirmed Bitcoin block"]},{q:"What is Multi-Path Payments (MPP) on Lightning?",a:"Splitting a payment across multiple routes to exceed single-channel limits",wrong:["Making multiple separate payments to different recipients simultaneously in one request","A fallback payment method that only activates when direct Lightning channels are offline","Sending the same payment through multiple channels concurrently to guarantee delivery"]},{q:"What privacy advantage does AMP have over basic MPP on Lightning?",a:"Each shard has a different payment hash, making it harder for routing nodes to link shards",wrong:["AMP wraps each shard in an extra onion layer completely invisible to intermediate nodes","AMP routes every shard through Tor by default, concealing the sender's network identity","AMP uses zero-knowledge proofs so routing nodes cannot observe any payment metadata"]},{q:"What is trampoline routing on the Lightning Network?",a:"Delegating route calculation to intermediate nodes for lighter clients",wrong:["Bouncing payments off satellites for wider global coverage area","A routing method that always prioritizes the fastest available path","A security protocol that encrypts all payment amounts in transit"]},{q:"What are channel factories in the Lightning Network?",a:"Opening many channels among multiple parties in one on-chain transaction",wrong:["Physical facilities where Lightning network nodes are manufactured","Automated systems that create channels based on user demand levels","Software that converts on-chain wallets into Lightning-ready wallets"]},{q:"What is liquidity management on the Lightning Network?",a:"Balancing inbound and outbound capacity to reliably route payments",wrong:["Converting Lightning Bitcoin back to regular on-chain Bitcoin","Managing the total circulating supply of Bitcoin on Lightning","Keeping Lightning nodes continuously connected to the internet"]},{q:"What is channel rebalancing on Lightning?",a:"Moving funds between your own channels to redistribute liquidity",wrong:["Closing and reopening channels with updated funding parameters","Resetting all channel state back to the initial funding amount","Transferring full channel ownership to a different Lightning node"]},{q:"What is a Lightning Service Provider (LSP)?",a:"A service offering liquidity and channel management for easy onboarding",wrong:["An internet service provider that specializes in Bitcoin traffic","A government-licensed operator required to run Lightning nodes as defined by Bitcoin consensus rules enforced by all full nodes","A cloud service that mines Bitcoin using collected Lightning fees"]},{q:"What are zero-conf channels on Lightning?",a:"Channels usable immediately without waiting for on-chain confirmation",wrong:["Channels that require zero Bitcoin as a deposit to open them as defined by Bitcoin consensus rules enforced by all full nodes","Channels that provide completely zero-fee routing for payments","Channels that are permanent and cannot be closed once opened as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"How do Lightning routing nodes earn revenue?",a:"By charging small fees for forwarding payments through their channels",wrong:["By mining new Bitcoin blocks on the Lightning Network's second-layer chain","By collecting a fixed percentage of all Lightning transactions worldwide","By selling their channel topology and routing data to network analytics firms"]},{q:"What is the fundamental on-chain mechanism that makes Lightning Network payment channels possible?",a:"Two parties lock funds in a 2-of-2 multisig UTXO on-chain, then exchange signed balance updates off-chain without broadcasting",wrong:["Two parties create a shared custodial wallet hosted by a Lightning Service Provider who settles batches periodically on-chain","Two parties send micropayments through a trusted routing hub that accumulates them and settles on-chain once per day","Two parties lock funds with a single-signature escrow contract and route payments outward through Lightning Service Providers"]},{q:"What cryptographic primitive enables trustless multi-hop routing through intermediate Lightning Network nodes?",a:"HTLCs (Hash Time-Locked Contracts): payment releases when the recipient reveals a preimage, or refunds after a timeout expires",wrong:["Schnorr threshold signatures: three-of-five quorums authorize each hop and prevent intermediate nodes from stealing funds","Zero-knowledge proofs: each routing node proves it forwarded funds without learning the source or destination of the payment","Pedersen commitments: each hop commits to the forwarded amount and reveals it only after the full route successfully completes"]},{q:"What information does a standard Lightning Network BOLT11 invoice contain?",a:"Payment amount, payment hash, expiry time, and destination public key — all encoded in a compact BOLT11 string format",wrong:["Sender's node ID, payment amount, full routing path, and a cryptographic commitment to the sender's current channel balance","Recipient's Bitcoin address, invoice amount, expiry time, and an ordered list of acceptable intermediate routing node IDs","Payment hash, a UTXO reference, expiry time, and the maximum routing fee the payer will accept per hop along the route"]},{q:'What is "inbound liquidity" on the Lightning Network and why is it required to receive payments?',a:"It's capacity to receive funds; someone else must open and fund a channel directed toward your node before you can receive",wrong:["It's the total BTC you have locked across all outgoing channels; more inbound capacity increases your maximum outgoing send limit","It's a routing score assigned by the network based on how reliably your node has historically forwarded other people's payments","It's the reserved on-chain balance your Lightning wallet holds as collateral before you can open any new payment channel"]},{q:"How are routing fees structured on the Lightning Network?",a:"A flat base fee in satoshis per payment plus a proportional fee rate charged in parts per million of the payment amount",wrong:["A uniform percentage fee set globally by the Bitcoin protocol and charged identically by every node along every payment route","Fees equal the hop count multiplied by the node operator's published hourly rate, capped at 0.5% of total payment value","Routing fees are negotiated bilaterally between each pair of nodes before every payment using a real-time fee auction system"]},{q:'What key advantage do BOLT12 "offers" provide over standard BOLT11 Lightning invoices?',a:"Offers are static reusable payment codes; unlike BOLT11 single-use invoices, the same offer can be paid repeatedly by anyone",wrong:["Offers include mandatory KYC fields that make Lightning payments compliant with financial regulations in regulated jurisdictions","Offers embed a complete routing path to the recipient, eliminating pathfinding work in the sender's wallet software entirely","Offers encode pre-negotiated channel paths that bypass normal routing, making payments confirm faster than standard BOLT11 invoices"]},{q:"What is LNURL and what categories of interaction does it enable in Lightning wallets?",a:"LNURL is a set of HTTP-based protocols enabling QR-driven Lightning interactions: pay-to-link, withdraw, and auth flows",wrong:["LNURL is a Bitcoin Improvement Proposal defining a universal address format for cross-chain Lightning payment routing globally","LNURL is a routing protocol that enables Lightning nodes to discover the lowest-fee multi-hop path to any global destination","LNURL is a Lightning wallet sync standard that replicates channel states across multiple devices belonging to one user"]},{q:'What is a Lightning Network "force-close" and what protection exists against fraud after one is broadcast?',a:"A unilateral broadcast of the last signed channel state; a CSV timelock gives the counterparty time to contest any cheating attempt",wrong:["A force-close is a cooperative mutual settlement where both parties co-sign an on-chain transaction dividing the balance evenly","A force-close triggers automatic reimbursement to both parties from the Lightning Service Provider's dedicated insurance fund","A force-close broadcasts a penalty transaction that burns the cheating party's funds and credits the honest party in full"]},{q:"How does Lightning Network improve payment privacy compared to base-layer Bitcoin transactions?",a:"Lightning payments are not recorded on-chain at all; only channel open and close transactions appear in the public ledger",wrong:["Lightning uses stealth addresses so each payment routes to a freshly generated one-time destination hiding the recipient identity","Lightning payments are logged on a private sidechain visible only to the two channel partners and their direct routing nodes","Lightning improves privacy because routing nodes are legally required to delete all payment records within 24 hours of routing"]},{q:"How does Lightning Network's theoretical transaction throughput compare to Bitcoin's base layer?",a:"Lightning can theoretically handle millions of transactions per second at near-zero cost; base layer manages only about 7 TPS",wrong:["Lightning handles up to 1,000 TPS with current node software; the base layer handles ~7 TPS but provides stronger settlement finality","Lightning doubles effective base-layer capacity to about 14 TPS; the primary advantage is lower fees rather than raw throughput","Lightning processes up to 100,000 TPS in ideal conditions with capacity bounded by the weakest routing node's available bandwidth"]}],"self-custody":[{q:'"Not your keys, not your..."',a:"Bitcoin",wrong:["Wallet","Password","Account"]},{q:"The most secure long-term storage is:",a:"Hardware wallet",wrong:["Exchange account","Phone app as defined by Bitcoin consensus rules enforced by all full nodes","Email attachment"]},{q:"A seed phrase is typically:",a:"12 or 24 words that recover your wallet",wrong:["A 6-digit PIN code used to log into your exchange","A QR code generated by your wallet application","A long alphanumeric code tied to your online account"]},{q:"You should store your seed phrase:",a:"On paper or metal in a secure location",wrong:["Encrypted and saved to a secure cloud storage service","Inside a password manager app installed on your device","Memorized and never physically recorded anywhere at all"]},{q:"Multi-sig means:",a:"Multiple keys required to authorize a transaction",wrong:["Multiple Bitcoin addresses combined into one shared wallet","Multiple approval requests issued from a single private key","Multiple separate blockchains cooperating to confirm a payment"]},{q:"When an exchange holds your Bitcoin:",a:"You have an IOU, not actual Bitcoin",wrong:["Your coins are fully insured by the exchange platform","You own the Bitcoin directly on the blockchain","Government regulation protects your exchange balance"]},{q:"Cold storage means:",a:"Keeping keys offline, disconnected from the internet",wrong:["Keeping your wallet on a computer that rarely goes online","Storing Bitcoin on a secure exchange with two-factor authentication","Using an encrypted wallet app that disables all internet browsing"]},{q:"A hardware wallet provides security by:",a:"Keeping private keys on a dedicated device that never exposes them to the internet",wrong:["Storing your Bitcoin balance inside the secure encrypted chip of the physical device","Encrypting your local blockchain copy so only your device can verify and read transactions","Requiring a PIN and bank approval code before any Bitcoin transaction can be authorized"]},{q:"If you lose your hardware wallet but have your seed phrase, you can:",a:"Recover all your Bitcoin on a new wallet using the seed phrase",wrong:["Purchase a new hardware wallet and wait for your funds to resync automatically","Contact the manufacturer with your registration details to restore access remotely","File a recovery claim with the exchange that sold you the device for reimbursement"]},{q:"Multisig (multi-signature) wallets require:",a:"Multiple keys to authorize a transaction (e.g., 2-of-3)",wrong:["Multiple Bitcoin addresses linked together to pool their shared balances","Multiple confirmation steps from the same single key before sending is allowed","Multiple separate mining pools all verifying and confirming the transaction"]},{q:"What is Sparrow Wallet known for in multisig coordination?",a:"Deep UTXO management and easy multisig setup with hardware signers",wrong:["A mobile-only wallet with cloud-based multisig and automatic portfolio rebalancing","A hardware signing device that stores multiple seed phrases in its secure element","A browser extension designed primarily for Lightning Network channel management"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction)?",a:"A standard format letting a transaction be built and signed by multiple parties",wrong:["A special transaction type used to send Bitcoin in multiple smaller partial installments","A privacy protocol that conceals the sender's identity using stealth address schemes","A transaction format created exclusively for mining pools to broadcast block rewards"]},{q:"What are output descriptors in Bitcoin?",a:"A standard way to describe how a wallet derives addresses for reliable recovery",wrong:["Custom labels attached to individual transaction outputs to help users track their spending","A complete on-chain index listing every unspent output recorded on the Bitcoin blockchain","Metadata that miners embed into blocks to identify which pool included each transaction"]},{q:"Why is multisig generally preferred over Shamir Secret Sharing (SSS) for Bitcoin custody?",a:"Multisig never reconstructs the full private key in one place; SSS does when signing",wrong:["Multisig transactions always cost significantly less in network fees than comparable SSS schemes","SSS setups always require more hardware devices to operate safely than an equivalent multisig","Multisig predates SSS by many years and has far wider support across Bitcoin wallets and tools"]},{q:"What is Nunchuk known for in the Bitcoin wallet space?",a:"Easy collaborative multisig setup and built-in inheritance planning",wrong:["Being the first wallet to natively support Lightning Network payments on mobile devices","A hardware wallet designed exclusively for air-gapped Bitcoin cold storage use","A privacy wallet that automatically applies CoinJoin mixing to every transaction sent"]},{q:"Why is titanium preferred over stainless steel for seed phrase backup plates?",a:"Higher melting point and better corrosion resistance in extreme conditions",wrong:["Titanium is significantly cheaper and far more widely sourced than stainless steel globally","Titanium backup plates are thicker and can engrave more seed words per unit of surface area","Titanium is the only commonly used metal that remains fully undetectable by metal detectors"]},{q:"What is a passphrase (25th word) in Bitcoin seed phrase security?",a:"An extra user-chosen word that generates an entirely different wallet",wrong:["The numeric PIN you enter to unlock and access your hardware wallet device","A backup phrase your wallet manufacturer generates and assigns when you register the device","An encryption key that your wallet software uses to protect its locally stored transaction data"]},{q:"Why is geographic distribution important for Bitcoin seed phrase storage?",a:"It protects against localized disasters destroying all backup copies at once",wrong:["It speeds up wallet sync by routing connections through the nearest available Bitcoin nodes","It is required by law as a financial compliance measure in most major regulatory jurisdictions","It mathematically strengthens the entropy and randomness of your generated seed phrase"]},{q:"What is a dead man's switch in Bitcoin inheritance planning?",a:"A mechanism that triggers key release if the owner fails to check in",wrong:["A physical switch on hardware wallets that wipes them if tampered","A transaction that auto-sends all Bitcoin to a burn address on a timer","A self-destruct feature built directly into the Bitcoin Core software"]},{q:"What is the biggest risk of not having a Bitcoin inheritance plan?",a:"Your Bitcoin could be permanently lost since no one else has the keys",wrong:["The government will automatically seize all of your Bitcoin holdings","Your Bitcoin gets redistributed among other active network participants","Your Bitcoin will steadily lose value without an actively managed wallet"]}],"privacy-nonkyc":[{q:"KYC stands for:",a:"Know Your Customer",wrong:["Keep Your Coins","Keys You Control","Knowledge Yields Crypto"]},{q:"CoinJoin is used for:",a:"Mixing transactions for privacy",wrong:["Combining outputs to reduce on-chain fees","Merging separate wallet balances into one","Batching payments to speed up confirmations"]},{q:"Non-KYC Bitcoin means:",a:"Bitcoin acquired without identity verification",wrong:["Bitcoin purchased using anonymous prepaid or gift cards","Bitcoin held in wallets with no recorded exchange history","Bitcoin flagged by compliance tools as potentially high risk"]},{q:"Bitcoin's blockchain is:",a:"Public - anyone can see transactions",wrong:["Private and securely encrypted on the chain","Visible only to miners and full node operators","Hidden and accessible only to direct participants"]},{q:"Why do some people prefer non-KYC Bitcoin?",a:"To maintain financial privacy",wrong:["To avoid paying taxes on gains","To access lower-priced Bitcoin deals","To bypass spending limits on exchanges"]},{q:"A Bitcoin address should ideally be:",a:"Used only once for privacy",wrong:["Reused freely for all transactions","Shared with all trading counterparties","Saved and reused permanently in your wallet"]},{q:"The first recorded address poisoning attack on Bitcoin happened in:",a:"2025",wrong:["2021","2013","2009"]},{q:"Shielded CSV on Bitcoin promises:",a:"Better than Zcash-level privacy as an L1.5",wrong:["Faster block times than the Bitcoin base layer allows","Higher throughput and far lower fees than the mainchain","Full native compatibility with all major altcoin networks"]},{q:"Briar messenger is engineered for:",a:"Privacy in hostile environments using Tor",wrong:["High-quality encrypted video and voice calling","Social media sharing with end-to-end encryption","Seamless cloud backup for messages and contacts"]},{q:'What is a "Dust Attack"?',a:"Tiny amounts of BTC sent to addresses to track the owner's movement",wrong:["A spam attack used to flood the mempool with thousands of unspendable small transactions","A hardware failure that causes miners to repeatedly broadcast corrupted block data to peers","Accidentally wiping your wallet's private keys during a routine software update process"]},{q:'"WabiSabi" and "Whirlpool" are types of:',a:"CoinJoin coordination protocols",wrong:["Layer 2 Bitcoin payment routing solutions","Standardized Bitcoin address generation formats","Open-source hardware wallet firmware projects"]},{q:"KYC (Know Your Customer) in Bitcoin refers to:",a:"Identity verification required by regulated exchanges",wrong:["A cryptographic method used to sign and verify Bitcoin transactions","A consensus mechanism adopted by proof-of-stake blockchain networks","A popular open-source Bitcoin wallet available on mobile and desktop"]},{q:"Why do some Bitcoiners prefer non-KYC acquisition?",a:"To protect financial privacy and avoid linking identity to Bitcoin holdings",wrong:["Because peer-to-peer trades typically have lower fees and faster settlement than exchanges","Because KYC-linked Bitcoin can be frozen or seized by financial regulators at any time","Because mining your own Bitcoin is always more profitable than buying it on any exchange"]},{q:'What is "address reuse" and why is it a privacy concern?',a:"Using the same Bitcoin address multiple times lets observers link all those transactions to one entity",wrong:["Repeatedly reusing the same address causes automated compliance systems to flag your wallet for review","Reusing a Bitcoin address forces the wallet to charge increased miner fees on every subsequent transaction","Bitcoin addresses are programmed to expire after a single use and will reject all future incoming payments"]},{q:'What does "non-KYC Bitcoin" mean?',a:"Bitcoin acquired without providing identity documents, such as through peer-to-peer trades or mining",wrong:["Bitcoin purchased from exchanges before mandatory government identity verification requirements existed","Bitcoin mined at home on consumer-grade hardware before large industrial mining farms took over the network","Bitcoin held in a self-custodied hardware wallet that has never interacted with any registered exchange platform"]},{q:"What is a PayJoin (P2EP) transaction?",a:"Both sender and receiver contribute inputs, obscuring who paid whom",wrong:["A payment where both parties contribute equal amounts and split the total transaction cost evenly","A transaction format that requires two sequential block confirmations before it is fully settled","A collaborative mining payout where two pools split the block reward proportionally by hash rate"]},{q:"What are Silent Payments (BIP 352)?",a:"One static address generates a unique on-chain address per payment",wrong:["Transactions that are hidden from the public mempool entirely","Payments delayed until network activity drops to low levels","A method to send Bitcoin without paying any transaction fees"]},{q:"What is the Boltzmann entropy score used for in Bitcoin privacy?",a:"Measuring ambiguity of a transaction's input-output linkages",wrong:["Calculating the thermodynamic energy cost of a transaction","Rating the randomness quality of a wallet's seed phrase","Scoring how quickly a transaction will get confirmed as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What does Whirlpool do for Bitcoin privacy?",a:"Mixes UTXOs via CoinJoin to break transaction history links",wrong:["Provides a VPN service designed specifically for Bitcoin nodes","Encrypts Bitcoin transactions end-to-end before broadcast","Runs a privacy coin layer on top of the Bitcoin blockchain"]},{q:"What is CoinSwap and how does it differ from CoinJoin?",a:"Uses atomic swaps so mixing is invisible on-chain, unlike CoinJoin",wrong:["Converts Bitcoin to privacy coins and back for mixing purposes","Is faster but provides less privacy protection than CoinJoin","Requires a trusted third party while CoinJoin does not need one"]}],"problems-of-money":[{q:'Why is inflation described as a "hidden tax"?',a:"It silently erodes the purchasing power of savings without a formal vote",wrong:["It is an unofficial surcharge added by central banks on top of existing income taxes","Banks secretly deposit hidden service fees into government accounts disguised as price rises","Only people in the highest tax bracket are actually subject to the effects of inflation"]},{q:"Fractional reserve banking means:",a:"Banks hold only a fraction of deposits",wrong:["Banks must hold all deposits as full cash reserves","Banks lend only from their own shareholder equity","Banks are barred from investing any customer deposits"]},{q:"Inflation is often called:",a:"A hidden tax on savings",wrong:["A government bonus for savers","A stimulus for wage growth","A tool to strengthen currency"]},{q:"Fiat currency is backed by:",a:"Government decree and trust",wrong:["Gold held in reserve vaults","Federal deposit insurance funds","Commodity reserves and bonds"]},{q:"The US dollar has lost what percentage of purchasing power since 1913?",a:"Over 96%",wrong:["About 10%","None as defined by Bitcoin consensus rules enforced by all full nodes","About 50%"]},{q:"Money printing causes:",a:"Devaluation of existing currency",wrong:["Increased purchasing power for citizens","Higher savings yields for depositors","Economic growth and a stronger currency"]},{q:"Sound money historically meant:",a:"Money that couldn't be easily debased",wrong:["Money backed by government commodity reserves","Currency issued only by state-chartered institutions","Money that held value only through centrally set law"]},{q:"The Cantillon Effect describes how:",a:"Those closest to new money benefit most from inflation",wrong:["Early Bitcoin adopters profit most from each halving cycle","Commercial banks absorb the losses from excess money creation","Gold prices automatically rise in response to money printing"]},{q:"ShadowStats.com tracks:",a:"Real inflation rates vs official government numbers",wrong:["Alternative consumer price metrics compared to CPI baselines","Housing price trends versus central bank interest rate changes","Unemployment statistics as reported by competing data agencies"]},{q:'"The Four Horsemen" documentary (2013) exposes:',a:"The fiat monetary system scam",wrong:["The collapse of pension funds and retirement savings","How governments manipulate economic data and statistics","The risks of corporate monopolies and unchecked market power"]},{q:'"Nixon Shock" in 1971 refers to:',a:"The US ending the dollar's convertibility into gold",wrong:["The launch of the first government-issued digital currency","The collapse of major US stock markets and widespread bank failures","The founding of the Federal Reserve as the central banking authority"]},{q:"Gresham's Law states that:",a:'"Bad money drives out good money"',wrong:['"Bitcoin will replace fiat" as defined by Bitcoin consensus rules enforced by all full nodes','"Gold is always better than silver"','"Taxes are voluntary" as defined by Bitcoin consensus rules enforced by all full nodes']},{q:"What happened in 1971?",a:"Nixon ended the gold standard, allowing unlimited fiat money printing",wrong:["Satoshi Nakamoto published the Bitcoin whitepaper under a pseudonym","The first commercial digital computer was demonstrated at a US university","The European Economic Community introduced a shared continental currency"]},{q:'Inflation is often called a "hidden tax" because:',a:"It silently erodes the purchasing power of your savings",wrong:["The IRS taxes Bitcoin capital gains at an undisclosed rate","Banks charge account maintenance fees that are never disclosed","Governments secretly deduct inflation levies from wage payments"]},{q:"What is seigniorage?",a:"The profit a government makes by issuing currency that costs less to produce than its face value",wrong:["A special tax levied on gold and silver mining operations by the state treasury as defined by Bitcoin consensus rules enforced by all full nodes","The interest income a central government earns by lending funds to commercial banks as defined by Bitcoin consensus rules enforced by all full nodes","The administrative fee that central banks charge for processing all interbank transfers"]},{q:"The Cantillon Effect describes how newly printed money benefits those closest to its creation. Who benefits MOST from money printing?",a:"Banks and the politically connected who receive new money first",wrong:["Average workers who receive higher wages from inflation as defined by Bitcoin consensus rules enforced by all full nodes","Retirees on fixed incomes who get cost-of-living adjustments","Small business owners who can raise their prices immediately"]},{q:"What is Quantitative Easing (QE)?",a:"A central bank creating new money to buy bonds, expanding supply",wrong:["A method of reducing government debt by printing less money","A technique for making international trade easier between nations","A system where banks lend to each other at zero percent interest"]},{q:'What is the "repo market" and why does it matter for understanding fiat fragility?',a:"Overnight lending market using bonds as collateral - its 2019 crisis exposed systemic fragility",wrong:["A marketplace where banks sell repossessed properties and vehicles directly to investors","A government repository that audits and stores physical gold and foreign currency reserves","A database system where central banks track and reconcile all cross-border financial transfers"]},{q:'What is the "Eurodollar system"?',a:"US dollars held and created by banks outside the US, forming a shadow system",wrong:["The official exchange mechanism that converts Euros into Dollars at European bank desks","A European Central Bank program designed to eventually replace the Dollar with the Euro","A cryptocurrency stablecoin project backed equally by Euros and US Dollars in reserve"]},{q:'What does the decline of the "petrodollar" system mean for global finance?',a:"Oil nations moving away from dollar pricing weakens its reserve status",wrong:["Major oil companies are converting their energy infrastructure to Bitcoin mining operations","The decline of petrodollar demand means crude oil is rapidly losing its economic value","European nations are now contractually forced to purchase all imported oil using gold"]}],"investment-strategy":[{q:"DCA stands for:",a:"Dollar Cost Averaging",wrong:["Digital Currency Account","Decentralized Crypto Asset","Direct Coin Access"]},{q:"A common Bitcoin investment strategy is:",a:"Buy regularly and hold long-term",wrong:["Trade actively based on daily price signals","Sell your holdings on a fixed weekly schedule","Only purchase Bitcoin when it hits all-time highs"]},{q:"HODL originated from:",a:'A misspelled forum post saying "I AM HODLING"',wrong:["A strategy term coined in a financial textbook on investing","An acronym introduced in a government savings policy document","A banking industry term for long-term certificate deposit accounts"]},{q:"Bitcoin's 4-year cycle is often tied to:",a:"The halving events",wrong:["US elections as defined by Bitcoin consensus rules enforced by all full nodes","Solar cycles as defined by Bitcoin consensus rules enforced by all full nodes","Stock market seasons"]},{q:"The best time to buy Bitcoin according to Bitcoiners is:",a:"Always - time in the market beats timing the market",wrong:["Only when the price dips below its 200-day moving average","During January to benefit from known seasonal price patterns","Only after major corrections of at least 30% from recent highs"]},{q:"Stacking sats means:",a:"Accumulating small amounts of Bitcoin over time",wrong:["Holding Bitcoin across multiple custodial exchange accounts","Building a collection of hardware wallets for extra redundancy","Running Lightning nodes to earn small routing fee payments"]},{q:"The biggest drawdown in Bitcoin history was:",a:"94% decline from $32 to $2 in July 2011",wrong:["85% drop from $19,700 down to $3,100 across late 2018","80% decline from $69,000 to $13,800 during calendar year 2022","73% crash from $65,000 to $17,500 between June and December 2022"]},{q:"MNAV.com tracks:",a:"Bitcoin treasury companies and their metrics",wrong:["Lightning Network routing nodes and their channel statistics","Bitcoin mining pool hash rates and block reward earnings","Altcoin market capitalizations and daily trading volumes"]},{q:"Lump-sum investing means:",a:"Buying a large amount of Bitcoin all at once",wrong:["Buying a set amount of Bitcoin on a regular schedule","Liquidating your entire Bitcoin position in one trade","Trading Bitcoin only during low-volume off-peak hours"]},{q:"Dollar Cost Averaging (DCA) means:",a:"Buying a fixed amount of Bitcoin at regular intervals regardless of price",wrong:["Only purchasing Bitcoin when the price falls below a predetermined target level","Converting your entire savings into Bitcoin in a single immediate lump-sum transaction","Automatically selling a fixed portion of Bitcoin each time the price rises by 10 percent"]},{q:'The Bitcoin phrase "zoom out" means:',a:"Look at the long-term price trend instead of daily volatility",wrong:["Reduce your overall Bitcoin allocation when market conditions feel uncertain","Withdraw funds from trading platforms during periods of unusually high volatility","Rebalance your entire portfolio away from Bitcoin during any significant downturn"]},{q:'What does "stacking sats" mean in Bitcoin culture?',a:"Regularly accumulating small amounts of Bitcoin (satoshis) over time",wrong:["Collecting a physical stack of commemorative Bitcoin medallions and coins","Distributing your Bitcoin holdings evenly across multiple custodial exchanges","Running multiple Bitcoin mining rigs simultaneously to accumulate block rewards"]},{q:'Why do Bitcoiners say "time in the market beats timing the market"?',a:"Long-term holders historically outperform those trying to buy dips and sell tops",wrong:["Because Bitcoin's price has never experienced a prolonged or significant multi-year decline","Because cryptocurrency exchanges charge substantially higher fees for precisely timed trades","Because Bitcoin mining block rewards automatically increase in size over long holding periods"]},{q:'What is the "HODL" strategy?',a:"Buying Bitcoin and holding it long-term regardless of short-term price volatility",wrong:["Actively trading Bitcoin to profit from short-term price fluctuations each day","Using automated trading bots to execute buy and sell orders based on market signals","Keeping a fixed portfolio allocation of exactly one whole Bitcoin at all times"]},{q:"Why is cold storage recommended for long-term Bitcoin holdings?",a:"Keeping private keys offline eliminates the risk of remote hacking or exchange failure",wrong:["Cold storage wallets generate yield by staking Bitcoin through a delegated proof-of-stake system","Storing coins offline enables faster confirmation because miners prioritize cold wallet transactions","Cold wallets automatically sync encrypted private key copies to a cloud server for easy recovery"]},{q:"What is UTXO management for tax optimization?",a:"Choosing specific UTXOs with known cost bases to minimize capital gains taxes",wrong:["Automatically hiding UTXO transaction history to avoid IRS capital gains reporting","Converting all UTXOs into stablecoins before tax season to defer all reporting obligations","Splitting Bitcoin into sub-$600 transfers to stay under IRS transaction reporting thresholds"]},{q:'What does "step-up in cost basis" mean for inherited Bitcoin?',a:"Cost basis resets to market price at owner's death, erasing prior gains",wrong:["Inherited Bitcoin retains its original purchase price as the permanent taxable cost basis","Bitcoin inheritance is fully tax-exempt in every jurisdiction regardless of the gain size","The cost basis of inherited Bitcoin automatically doubles each year following the inheritance"]},{q:"What is a Bitcoin IRA?",a:"A self-directed retirement account holding Bitcoin with tax advantages",wrong:["A federal program that pays out Bitcoin monthly to eligible American retirees","An insurance policy that compensates Bitcoin holders for losses from theft or hacks","A bank savings account offering a fixed interest rate paid out in Bitcoin"]},{q:"Why do experienced Bitcoiners warn against lending out your Bitcoin?",a:"Lending platforms like Celsius and BlockFi collapsed, losing depositor funds",wrong:["The Bitcoin codebase explicitly forbids any form of lending or borrowing of coins","Lending out Bitcoin causes measurable network congestion and slower confirmation times","Bitcoin lending always yields negative real returns because platform fees erode all gains"]},{q:"Why is cost basis tracking important for Bitcoin investors?",a:"Each purchase creates a separate tax lot needed for capital gains calculations",wrong:["Cost basis is only required for Bitcoin custodied at licensed exchange platforms","The IRS uses a flat tax rate on all Bitcoin regardless of what you paid for it","Cost basis is irrelevant since Bitcoin is officially treated as foreign currency"]}],cryptography:[{q:"Why did Satoshi choose the secp256k1 elliptic curve for Bitcoin instead of the more widely used NIST P-256?",a:"secp256k1's parameters have no known backdoor; NIST P-256's constants were generated through an opaque process lacking transparency",wrong:["secp256k1 produces shorter 48-byte signatures versus NIST P-256's 72-byte signatures, saving meaningful space per transaction","secp256k1 was the only elliptic curve with an existing open-source implementation available when Bitcoin was being actively developed","secp256k1 enables faster signature verification on commodity CPUs, which was critical for Satoshi's constrained 2009 launch timeline"]},{q:"Which digital signature algorithm did Bitcoin use to authorize transactions before the Taproot upgrade activated?",a:"ECDSA (Elliptic Curve Digital Signature Algorithm) was used to sign and authorize all Bitcoin transactions before Taproot activated",wrong:["EdDSA (Edwards-curve Digital Signature Algorithm), a Schnorr-based variant used widely across modern cryptography since the 1990s","RSA-2048, which was replaced by ECDSA in a 2012 BIP update to reduce transaction signature size and improve overall verification speed","DSA (Digital Signature Algorithm), the original NIST standard adapted for Bitcoin's secp256k1 elliptic curve in the genesis block"]},{q:"What is the key mathematical property of Schnorr signatures that makes them especially valuable for Bitcoin?",a:"Schnorr signatures are linear and additive — multiple parties' signatures can be aggregated into one compact signature via MuSig",wrong:["Schnorr signatures are 256 bytes shorter than equivalent ECDSA signatures, significantly reducing the on-chain footprint of all transactions","Schnorr signatures operate on a different elliptic curve that is provably harder to attack than the secp256k1 curve used by ECDSA","Schnorr signatures are non-deterministic by design, which prevents the timing-based side-channel attacks that can affect ECDSA"]},{q:"What are the key security properties of the SHA-256 hash function as used in Bitcoin?",a:"256-bit fixed output, deterministic, pre-image resistant, and avalanche effect: one changed input bit completely alters the output",wrong:["128-bit variable output, probabilistic, collision-resistant only, designed for high speed on the hardware-accelerated Bitcoin ASICs","512-bit fixed output, deterministic, fully reversible using the corresponding private key, and exhibits a strong avalanche effect","256-bit fixed output, non-deterministic due to an internal random salt, collision-resistant only, and tied to the secp256k1 curve"]},{q:"What is the step-by-step process for deriving a Bitcoin address from a public key?",a:"SHA-256 the public key, then RIPEMD-160 to get a 20-byte hash, then apply Base58Check encoding to produce the final address",wrong:["RIPEMD-160 the private key directly, then SHA-256 it twice, producing a 32-byte output encoded in hexadecimal as the address","SHA-512 the public key then truncate to 20 bytes, then apply Base64 encoding with a 4-byte checksum appended to the result","SHA-256 the compressed public key twice, take the final 20 bytes, then encode using standard Base64 plus a 4-byte checksum"]},{q:'Why are cryptographic hash functions described as "one-way" functions?',a:"Given hash output H(x), finding the original input x is computationally infeasible — you can compute forward but never reverse it",wrong:["Hash functions are one-way because they discard excess information via bitwise truncation performed during the internal hashing rounds","Hash functions are one-way by law only; reversing them without authorization qualifies as a federal computer intrusion crime globally","Hash functions are one-way in hardware only; software implementations of SHA-256 can theoretically be reversed with sufficient RAM"]},{q:"Why does Bitcoin's Base58Check encoding omit certain characters from its alphabet?",a:"It removes visually ambiguous characters — 0, O, I, and l — to prevent costly transcription errors when addresses are copied manually",wrong:["It removes alphabetically late characters x, y, and z to keep all encoded strings short enough to fit on a single paper backup","It excludes special symbols and all uppercase letters to ensure compatibility with every Unicode keyboard and QR code scanner","It removes vowels entirely to prevent encoded addresses from accidentally spelling dictionary words that users might confuse with keys"]},{q:"What is the discrete logarithm problem and how does it protect Bitcoin private keys?",a:"Given a public key (a curve point), deriving the private key (scalar multiplier) is computationally infeasible on the secp256k1 curve",wrong:["Given a private key expressed as a large prime, factoring it into two component primes is computationally infeasible on modern hardware","Given a hash of the public key, reversing SHA-256 to recover the original elliptic curve point is computationally infeasible always","Given an AES-encrypted wallet file, brute-forcing the decryption key is computationally infeasible without the user's original passphrase"]},{q:"How are cryptographic commitment schemes used within Lightning Network HTLCs?",a:"A hash of a secret preimage is shared first; the preimage is revealed upon payment, atomically unlocking funds across all hops",wrong:["A time-locked commitment to a routing fee is published on-chain first; revealing it later proves the payment was properly delivered","Each routing node commits to holding forwarded funds for a fixed timelock period and reveals its commitment to prevent double-spend","A cryptographic commitment to the exact payment amount is shared with all hops; revealing it triggers simultaneous on-chain settlement"]},{q:"What is P2PKH and what security advantage does it offer over the earlier Pay-to-Public-Key output type?",a:"P2PKH (Pay-to-Public-Key-Hash) hashes the public key before use, providing protection if ECDSA is ever weakened or compromised",wrong:["P2PKH locks outputs behind a 2-of-2 multisig requirement, making theft completely impossible without access to both signing keys","P2PKH encrypts the output script with the sender's public key so only the intended recipient can decode the locking conditions","P2PKH uses RIPEMD-256 instead of RIPEMD-160, producing a longer hash that offers significantly stronger collision-resistance guarantees"]},{q:"Elliptic curve cryptography is used for:",a:"Generating Bitcoin key pairs",wrong:["Hashing new Bitcoin blocks","Encrypting transaction data","Verifying peer connections"]},{q:"What type of cryptography does Bitcoin use for digital signatures?",a:"Elliptic Curve Digital Signature Algorithm (ECDSA) on the secp256k1 curve",wrong:["RSA-2048 with standard padding, used as the primary Bitcoin signature algorithm","AES-256 symmetric block cipher used to generate and protect Bitcoin private keys","Triple DES in EDE mode, a legacy block cipher used for Bitcoin digital signatures"]},{q:"What is a hash function's role in Bitcoin?",a:"It creates a fixed-size, unique digital fingerprint of any input data, used for block headers, addresses, and mining",wrong:["It encrypts all Bitcoin transactions end-to-end so that only the sender and receiver can access the payment amounts","It compresses the full blockchain into smaller data segments so nodes require less disk space and can sync faster","It converts Bitcoin values into standardized forms used by other blockchains, making cross-chain swaps possible"]},{q:"Why can't you derive a private key from a public key?",a:"Elliptic curve math is a one-way function - easy to compute forward, computationally infeasible to reverse",wrong:["Private keys have more bits than public keys, making it impossible to derive the longer value from the shorter one","The Bitcoin network automatically purges private key data after a transaction is signed and confirmed on-chain","Satoshi Nakamoto encrypted all key pairs using a proprietary cipher that requires a secret master key to reverse"]},{q:"What does SHA-256 stand for and where is it used in Bitcoin?",a:"Secure Hash Algorithm 256-bit - used in mining (proof of work) and creating transaction IDs",wrong:["Super Hash Accelerator 256 - used only for wallet file encryption by software client applications","Satoshi Hash Algorithm 256 - applied during signature verification to authenticate transaction signers","Shared Hash Array 256 - used in peer-to-peer message routing to propagate transactions across nodes"]},{q:"What advantage do Schnorr signatures provide over ECDSA in Bitcoin?",a:"Key aggregation for efficient multi-signature transactions",wrong:["Quantum resistance that the older ECDSA algorithm intrinsically cannot provide","Uniformly smaller signature bytes in every case no matter how many signers","Backward compatibility with all legacy scripts, active from the Bitcoin genesis block"]},{q:"What is MuSig2 in Bitcoin?",a:"A Schnorr-based multi-sig scheme producing one standard-looking signature",wrong:["A second version of Bitcoin's block-streaming protocol used between all full nodes","A next-generation mining algorithm designed to replace SHA-256 in a future protocol fork","A Lightning Network routing protocol optimized for two-hop payment channel paths"]},{q:"What are adaptor signatures used for in Bitcoin?",a:"Conditional payments where signing reveals a secret value",wrong:["Upgrading old Script paths to be compatible with Taproot transaction outputs","Allowing multiple parties to jointly co-sign a single Bitcoin transaction","Adding Turing-complete logic to Bitcoin Script through extended opcodes"]},{q:"What is a Pedersen commitment?",a:"A commitment that hides a value while allowing math verification",wrong:["A legal pledge between Bitcoin developers to preserve protocol backward compatibility","A specific fee amount committed and locked inside each block's transactions","A formal promise from miners to always enforce current network consensus rules"]},{q:"What is the current status of zero-knowledge proofs on Bitcoin?",a:"Being explored via projects like BitVM and validity rollups",wrong:["Fully implemented in Bitcoin Core since the Taproot upgrade","Impossible on Bitcoin due to fundamental Script limitations","Removed from Bitcoin in 2015 due to critical security risks"]}],regulation:[{q:"Bitcoin's response to bans has been:",a:"Moving to friendlier jurisdictions",wrong:["Shutting down all operations worldwide","Complying with every new law passed","Becoming illegal in all countries forever"]},{q:"El Salvador made Bitcoin:",a:"Legal tender in 2021",wrong:["Illegal to hold in 2020","A classified state asset","Available only to tourists"]},{q:"Bitcoin regulation varies by:",a:"Country - each has different rules",wrong:["No country has any Bitcoin rules at all","One universal global law governs it","The Bitcoin code sets its own rules"]},{q:"A Bitcoin ETF allows:",a:"Traditional investors to get Bitcoin exposure through stock markets",wrong:["Any person to receive free Bitcoin as a government-issued daily dividend","Government agencies to operate and directly control Bitcoin mining facilities","Central banks to print and issue new Bitcoin in response to investor demand"]},{q:"The SEC has classified Bitcoin as:",a:"A commodity, not a security",wrong:["A security similar to stocks","A foreign currency like euros","An illegal financial instrument"]},{q:'What is a "Self-Custody" regulation attempt?',a:"Rules that try to force users to use custodial services",wrong:["Laws guaranteeing free Bitcoin payouts to all registered citizens","Safety regulations covering electricity use by Bitcoin mining operations","Maximum price controls on how much Bitcoin can legally be worth"]},{q:"Can a government effectively ban Bitcoin?",a:"They can restrict fiat on-ramps but cannot stop peer-to-peer transactions",wrong:["Yes - a country that cuts all internet access can permanently shut down Bitcoin","Yes - every node operator can be identified by IP address and then shut down","No country has ever proposed or enacted any formal restriction on Bitcoin"]},{q:"China has banned Bitcoin mining multiple times, yet:",a:"Miners relocated and the network hash rate recovered within months",wrong:["Bitcoin permanently lost over 50% of its value and never recovered","All Chinese-held Bitcoin was confiscated by government authorities","The Bitcoin network went entirely offline for several weeks afterward"]},{q:"How is Bitcoin classified for tax purposes in most jurisdictions?",a:"As property or a capital asset, meaning gains are subject to capital gains tax",wrong:["As a foreign currency, which exempts gains from standard capital gains taxation rules","As a commodity with only voluntary reporting obligations and no formal tax requirement","As digital pocket cash, making it exempt from any tax under existing currency statutes"]},{q:'What does the "Travel Rule" require for crypto transactions?',a:"Regulated exchanges must share sender and receiver identity information for transfers above a threshold",wrong:["Users must physically appear at a licensed exchange office to authorize any outgoing Bitcoin transfer","Bitcoin is legally restricted to being transferred only to recipients within your home country boundaries","Bitcoin miners must verify the passport number of every user before including their transaction in a block"]},{q:"In the US, what is the key difference between SEC and CFTC jurisdiction over digital assets?",a:"SEC regulates securities (most altcoins); CFTC regulates Bitcoin as a commodity",wrong:["The SEC handles Bitcoin while the CFTC regulates all other digital assets as securities","Both the SEC and CFTC hold identical overlapping jurisdiction over all digital asset classes","The CFTC only regulates physical commodities and has no authority over any digital asset"]},{q:"What is the Howey Test and how does it apply to Bitcoin?",a:"A legal test for securities - Bitcoin fails to qualify since it has no central enterprise",wrong:["A technical test blockchain researchers use to measure a network's degree of decentralization","Bitcoin passes the Howey Test, which is why the SEC classifies it as a regulated security","An IRS formula used to determine the applicable capital gains tax rate on crypto disposals"]},{q:'What is the "Travel Rule" in cryptocurrency regulation?',a:"A FATF rule requiring institutions to share sender/receiver identity above a threshold",wrong:["A rule restricting Bitcoin transfers to recipients within the sender's own home country","A requirement that Bitcoin miners register the physical location of all their mining hardware","A law prohibiting people from carrying hardware wallets across any international border crossing"]},{q:"What is the FATF and why is it significant for Bitcoin privacy?",a:"An international body pushing KYC/AML standards that threaten self-custodial privacy",wrong:["A global mining consortium that coordinates hash rate and difficulty adjustment standards","A nonprofit promoting Bitcoin adoption and financial inclusion in the developing world","A technology standards body focused on improving Bitcoin transaction processing speed"]},{q:"How have US states approached Bitcoin regulation differently from the federal government?",a:"Several states passed pro-Bitcoin laws like reserve bills and transmitter exemptions",wrong:["All 50 states enforce identical cryptocurrency regulations matching federal law","States are constitutionally prohibited from creating crypto-related legislation","Most states have banned Bitcoin mining operations due to energy concerns as defined by Bitcoin consensus rules enforced by all full nodes"]}],energy:[{q:"Bitcoin mining and energy:",a:"Promotes renewable energy and uses wasted energy",wrong:["Relies entirely on coal and fossil fuel energy sources","Consumes all input energy without producing any useful output","Runs on no electricity and generates its own internal power"]},{q:"Stranded energy refers to:",a:"Energy produced in remote locations with no buyers",wrong:["Power lost during grid transmission and electrical line failures","Solar energy that cannot be captured when panels go offline at night","Wind turbine output during periods of insufficient wind speed"]},{q:"Bitcoin miners often locate near:",a:"Cheap renewable energy sources",wrong:["Major urban population and city centers","Existing coal and natural gas power plants","Government-designated industrial manufacturing zones"]},{q:"Bitcoin mining can help stabilize:",a:"Electrical grids by acting as a flexible load",wrong:["Financial markets by absorbing excess liquidity costs","Global internet speeds by distributing network traffic","National economies by generating significant tax revenue"]},{q:"Compared to traditional banking, Bitcoin's energy use is:",a:"Debatable but often comparable or less",wrong:["Far higher, consuming roughly 100 times more power","Essentially zero, as nodes share idle renewable capacity","Precisely equal by international regulatory requirement"]},{q:"Methane flaring and Bitcoin mining:",a:"Miners can capture and use flared gas productively",wrong:["Flaring and Bitcoin mining are completely unrelated industries","Bitcoin mining operations significantly increase local methane flaring","All Bitcoin mining is powered entirely by captured flared gas"]},{q:"Bitcoin mining primarily uses which type of energy?",a:"Over 50% renewable - often stranded or wasted energy",wrong:["Primarily coal and natural gas, making it highly polluting","Entirely nuclear energy sourced from dedicated power plants","Solar panels mounted directly onto the physical mining hardware"]},{q:"Bitcoin mining can actually help the environment by:",a:"Monetizing flared methane that would otherwise be released into the atmosphere",wrong:["Reducing total global electricity demand through more efficient transaction processing","Generating new renewable energy as a byproduct of the computational hashing process","Cooling local environments through large-scale heat exchange and water evaporation systems"]},{q:"How do Bitcoin miners contribute to grid stability?",a:"They can instantly power down during peak demand, acting as flexible load that balances the grid",wrong:["They generate surplus electricity by recovering heat from mining hardware and exporting it back to the grid","They replace traditional power plants by acting as distributed energy generation nodes across local grids","They are legally required to operate only during low-demand off-peak hours under formal grid usage agreements"]},{q:"What percentage of Bitcoin mining uses renewable energy sources according to recent estimates?",a:"Over 50% and growing, driven by miners seeking the cheapest energy",wrong:["Less than 5%, with the vast majority still coming from coal and natural gas","Exactly 100%, as all mining facilities are now required by law to use renewables","Around 10%, mostly from dedicated nuclear power plants located near data centers"]}],"core-source-code":[{q:"Changes to Bitcoin Core require:",a:"Careful testing and peer review",wrong:["Approval from a single trusted lead developer","A majority vote from participating corporations","Official regulatory permission from a government body"]},{q:"What is a Bitcoin Improvement Proposal (BIP)?",a:"A formal document proposing changes or standards for the Bitcoin protocol",wrong:["A mandatory software update all Bitcoin nodes must immediately install","A formal funding request submitted by miners to the Bitcoin Foundation","A signed petition from major exchanges required before protocol changes occur"]},{q:"Anyone can:",a:"Read, review, and propose changes to Bitcoin's code",wrong:["Freely modify Bitcoin's consensus rules without peer review","Delete recorded blockchain history to correct discovered errors","Issue new coins or increase the fixed 21 million supply cap"]},{q:"A BIP is:",a:"A Bitcoin Improvement Proposal",wrong:["A Bitcoin Investment Plan as defined by Bitcoin consensus rules enforced by all full nodes","A Block Information Protocol","A Banking Integration Process"]},{q:"Bitcoin's code repository is hosted on:",a:"GitHub",wrong:["Facebook","A secret server","The dark web"]}],"blockchain-timechain":[{q:"A new Bitcoin block is produced approximately every:",a:"10 minutes",wrong:["1 second","1 hour as defined by Bitcoin consensus rules enforced by all full nodes","1 day as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"Each block contains:",a:"A list of transactions and a reference to the previous block",wrong:["A single transaction along with the miner's identification details","Compressed image files that visually represent each coin transfer","Encrypted email addresses linked to each registered wallet holder"]},{q:"The blockchain is often called:",a:"An immutable ledger",wrong:["A cloud server as defined by Bitcoin consensus rules enforced by all full nodes","A website as defined by Bitcoin consensus rules enforced by all full nodes","A database that can be edited"]},{q:"Satoshi originally called it:",a:"A timechain",wrong:["A blockchain","A datachain","A coinchain"]},{q:"The Genesis Block contains a message about:",a:"A newspaper headline about bank bailouts",wrong:["A step-by-step recipe embedded as a tribute to early cypherpunks","A love letter written by Satoshi addressed to future generations","A coded stock market tip referencing a major technology company IPO"]},{q:"Block height refers to:",a:"The sequential number of a block in the chain",wrong:["The physical height of the server rack that stores the block","The total storage size of a block measured in kilobytes","The current difficulty level required to mine a valid block"]},{q:"Satoshi originally called the blockchain the:",a:"Timechain",wrong:["Hashchain","Blockweb","Cryptoledger"]},{q:"Each Bitcoin block contains a reference to:",a:"The hash of the previous block, creating an unbreakable chain",wrong:["The predicted hash of the next block that miners are currently solving","A cryptographic commitment to all future transactions not yet confirmed","A compressed encrypted backup of the entire blockchain up to that block"]},{q:"The mempool is:",a:"A waiting area where unconfirmed transactions sit until miners include them in a block",wrong:["A secure hardware wallet format specifically designed to store private Bitcoin keys offline","The total aggregate RAM consumed by all connected Bitcoin full nodes running on the network","A distributed memory pool shared between ASIC mining rigs to coordinate their hashing workload"]},{q:'Why did Satoshi originally call it a "timechain" rather than "blockchain"?',a:"Because each block timestamps transactions in chronological order, creating a chain of time-stamped records",wrong:["Because Bitcoin blocks are mined at fixed intervals tied to a global atomic clock standard for synchronization","Because each transaction record includes a precise timestamp reflecting the time zone of the initiating wallet node","Because the name 'blockchain' was already trademarked by an existing financial services firm at the time of release"]},{q:'Why do some Bitcoiners prefer the term "timechain" over "blockchain"?',a:"It emphasizes chronological ordering — each block is permanently anchored in time, not merely linked by shared data hashes",wrong:['It was Satoshi\'s original preferred name in the whitepaper before "blockchain" became the mainstream term later',"It highlights that Bitcoin blocks have timestamps while most other blockchains completely omit block time information","It refers to the fixed 10-minute block interval creating a reliable and predictable sequence of time-indexed records"]},{q:"What date was the Bitcoin genesis block mined, and what was embedded in it as proof-of-time?",a:'January 3, 2009; the Times headline "Chancellor on brink of second bailout for banks" proving no coins predate that block',wrong:['October 31, 2008; the text "Bitcoin: A Peer-to-Peer Electronic Cash System" matching the title of the whitepaper exactly','January 9, 2009; the headline "US Federal Reserve cuts interest rates to near zero" referencing the ongoing financial crisis','November 1, 2008; the phrase "The Times 01/Nov/2008 Global markets near total collapse" embedded as political commentary']},{q:"How does Bitcoin track ownership differently from a traditional bank account?",a:"Bitcoin uses UTXOs (Unspent Transaction Outputs) — discrete coin-like objects — rather than maintaining a running account balance",wrong:["Bitcoin maintains a shared ledger of named accounts with balances updated atomically by each confirmed transaction on the chain","Bitcoin stores ownership in a global identity table where each public key maps to a single cumulative spendable balance amount","Bitcoin assigns each wallet address a unique balance field that miners update when new blocks are added to the chain"]},{q:"What role do Merkle trees play in Bitcoin's design?",a:"They allow SPV wallets to verify a transaction exists in a block without downloading the entire blockchain at all",wrong:["They compress raw transaction bytes so each block can store more transactions within the standard 1 MB block size limit","They link blocks together unforgeable by hashing all transactions directly into the previous block's header field","They prevent double-spending by organizing transactions into a sorted tree that all miners must validate on confirmation"]},{q:"What happens when two miners simultaneously find valid blocks at the same block height?",a:"Both are briefly valid; this is called an orphan or stale block situation — only one survives once the chain extends further",wrong:["Both blocks are merged by the network into a combined super-block containing all transactions from each competing version","The network pauses for 10 minutes and nodes vote on which block to accept based on total transaction fees included","Both miners split the block reward equally and every node permanently accepts whichever block it received first"]},{q:"Which six fields appear in a standard Bitcoin block header?",a:"Version, previous block hash, Merkle root, timestamp, nBits difficulty target, and nonce — the six canonical header fields",wrong:["Version, miner address, transaction count, Merkle root, timestamp, and block height as specified in the protocol spec","Previous block hash, coinbase reward amount, timestamp, nBits target, nonce, and the winning miner's signature field","Block height, previous hash, Merkle root, transaction list hash, nonce, and the miner's public key identifier field"]},{q:'How does Bitcoin settlement compare to the "instant" transfers promoted by retail banking?',a:"Bank transfers are IOUs between institutions; Bitcoin achieves irreversible on-chain settlement in roughly 10 minutes",wrong:["Both achieve true final settlement instantly; the only difference is Bitcoin's settlement is public while bank transfers are private","Bitcoin settlement takes 3–5 business days like wire transfers; the 10-minute block time is only for initial confirmation","Fiat transfers settle on delivery while Bitcoin requires a 72-hour grace period for large transactions over 1 BTC value"]},{q:"What is the Bitcoin mempool and how do miners interact with it?",a:"It's the waiting room for unconfirmed transactions; miners select from it and prioritize higher-fee transactions for inclusion",wrong:["It's a permanent archive of all confirmed transactions that nodes must query to validate each new incoming spending attempt","It's a shared pool where miners deposit newly minted coins before distributing them back to senders as transaction change","It's a registry of known peer node addresses used to discover and connect to other participants on the Bitcoin network"]},{q:"How does Bitcoin's transaction finality compare to SWIFT international bank transfers?",a:"Bitcoin reaches practical finality in about 1 hour (6 confirmations); SWIFT international transfers take 1–5 business days",wrong:["Bitcoin finality takes 24 hours for large transactions; SWIFT now settles in under 2 hours for standard bank-to-bank wires","Both systems achieve finality in roughly the same timeframe; the meaningful difference is in cost rather than settlement speed","Bitcoin reaches finality in under 1 minute with Taproot active; SWIFT settles same-day under the ISO 20022 standard"]},{q:"Why is altering a historical Bitcoin block effectively impossible once buried under sufficient work?",a:"Changing any block invalidates every subsequent block's hash, forcing an attacker to redo all downstream proof-of-work",wrong:["Changing a block triggers a cryptographic alarm that immediately alerts all nodes causing automatic rejection of the edit","Each block is countersigned by a quorum of miners who must all re-sign any proposed modifications to historical records","Historical blocks are stored in read-only memory on every Bitcoin node, making any write operation physically impossible"]}],analogies:[{q:"In the airport analogy, Lightning is like:",a:"A bicycle courier in the terminal",wrong:["The main runway used for all departing flights","A large cargo aircraft transporting bulk shipments","The central air traffic control tower overhead"]},{q:"Bitcoin is often compared to:",a:"Digital gold",wrong:["Digital silver","Digital stocks","Digital bonds"]},{q:"The Bitcoin network is sometimes compared to:",a:"The internet protocol (TCP/IP)",wrong:["A single popular website on the internet","A private encrypted telephone voice call","A cable television broadcasting channel"]},{q:"Holding Bitcoin is compared to:",a:"Holding property in cyberspace",wrong:["Renting a digital movie through a streaming app","Subscribing to a recurring monthly online service","Opening a savings account at a traditional bank"]},{q:"Nick Szabo's pre-Bitcoin proposal for digital scarce money was called:",a:"Bit Gold",wrong:["Digital Cash","E-Gold","Digi-Buck"]}],byzantine_generals__problem:[{q:"The Byzantine Generals Problem is about:",a:"Reaching agreement when some participants may be dishonest",wrong:["Coordinating siege tactics across multiple castle walls with limited messengers","Tracking the value and secure movement of physical gold bullion between allies","Delivering encrypted military messages securely across hostile enemy territory"]},{q:"Bitcoin solved the Byzantine Generals Problem using:",a:"Proof of Work consensus",wrong:["Delegated voting by peers","A trusted coordinator node","Public key encryption alone"]},{q:"In the analogy, the generals need to:",a:"Coordinate an attack without a trusted messenger",wrong:["Build a defensive wall around the city without sharing blueprints","Trade supplies with each other without meeting in person","Sign a peace treaty by sending letters through enemy territory"]},{q:"Before Bitcoin, the Byzantine Generals Problem was considered:",a:"Unsolvable in a trustless digital environment",wrong:["A trivial problem solved by any standard encryption library","An outdated concept that modern networking had made obsolete","Fully resolved by existing public key infrastructure systems"]},{q:"The Byzantine Generals Problem asks how dispersed parties can reach consensus without trusting each other. What mechanism did Bitcoin invent to solve this?",a:"Nakamoto Consensus (proof-of-work + longest chain)",wrong:["Delegated voting by a supermajority of elected validator nodes","A centralized coordinator server that timestamps all messages","Proof of stake with randomized leader selection each round"]}],game_theory:[{q:"Bitcoin's incentive structure uses:",a:"Game theory to align participants",wrong:["Legal penalties and fines to deter cheaters","Signed contracts enforceable in court","Social trust among known community members"]},{q:"Miners are incentivized to be honest because:",a:"Cheating costs more than playing by the rules",wrong:["They are required to sign legal agreements before mining","Government regulators audit and monitor their operations","The protocol distributes rewards equally regardless of effort"]},{q:"Nash Equilibrium in Bitcoin means:",a:"No participant benefits from changing their strategy alone",wrong:["Every miner must contribute exactly equal computational power","Bitcoin's exchange rate stays stable regardless of supply changes","All nodes in the network must run identical hardware and software"]},{q:"The prisoner's dilemma relates to Bitcoin because:",a:"Cooperation is more profitable than defection",wrong:["Miners who break the rules get permanently banned by the network","Bitcoin transactions require approval from a central authority","All participants are legally bound to follow the open protocol"]},{q:"What game theory concept explains why Bitcoin miners are incentivized to stay honest rather than attack the network?",a:"Nash equilibrium - attacking costs more than honest mining",wrong:["Prisoner's dilemma - miners always defect when reward is higher","Zero-sum dynamics - every hash one miner gains another miner loses","Pareto efficiency - all miners simultaneously maximize their profits"]}],elevator_pitches:[{q:"A good Bitcoin elevator pitch should be:",a:"Simple and compelling in under a minute",wrong:["A thorough two-hour technical deep-dive seminar","Focused entirely on recent price chart performance","As jargon-heavy and technically complex as possible"]},{q:"When explaining Bitcoin to beginners, start with:",a:"The problem it solves (broken money)",wrong:["How mining hardware and hashing algorithms work","Cryptographic signatures and merkle tree structures","Exchange fees and how to pick the right trading pair"]},{q:"The simplest Bitcoin pitch is often:",a:"Digital money that no one can print or confiscate",wrong:["A get-rich-quick asset designed for speculative investors","A rewards point system for making internet purchases","A new digital bank for borderless online payments"]},{q:"How would you explain Bitcoin to a complete newcomer in one sentence?",a:"A digital form of money that no government or company can print, freeze, or control",wrong:["A speculative digital asset whose price rises whenever institutional investors decide to buy in","A digital payment card for online purchases that bypasses banks but still relies on card networks","An interest-bearing savings account that uses blockchain technology to offer returns above banks"]},{q:"What is the most important feature for Bitcoin newcomers to understand first?",a:"Nobody can confiscate or freeze your bitcoin if you hold your own keys",wrong:["The price tends to appreciate over time, making it a superior long-term investment strategy","It functions like anonymous cash and leaves absolutely no traceable record on any public ledger","Sending bitcoin anywhere in the world is always instant and completely free of any transaction fees"]}],taproot:[{q:"Taproot is a Bitcoin:",a:"Upgrade that improves privacy and smart contracts",wrong:["A new altcoin forked from the main Bitcoin network","A faster proof-of-work mining algorithm for Bitcoin","A regulated exchange platform built on Bitcoin rails"]},{q:"Taproot was activated in:",a:"November 2021",wrong:["August 2017","March 2019","April 2024"]},{q:"Taproot uses Schnorr signatures which:",a:"Make multi-sig transactions look like regular ones",wrong:["Speed up block validation by parallelizing hash computations","Generate new coins by merging multiple block reward outputs","Delete old unspent outputs to reduce total blockchain storage"]},{q:"Taproot improves:",a:"Privacy, efficiency, and smart contract capabilities",wrong:["Mining speed, network latency, and hardware throughput only","Block size limits, hash rate targets, and fee market dynamics","Transaction fees, confirmation times, and dust output thresholds"]},{q:"What type of signature scheme did Taproot introduce to Bitcoin?",a:"Schnorr signatures",wrong:["RSA digital signatures","ECDSA ring signatures","BLS aggregate signatures"]},{q:"Taproot improves Bitcoin by:",a:"Enhancing privacy, efficiency, and smart contract capabilities using Schnorr signatures",wrong:["Increasing the maximum coin supply beyond 21 million by unlocking additional miner reward multipliers","Eliminating the need for proof-of-work mining by switching to a validator-based staking consensus model","Making every Bitcoin transaction fully anonymous and untraceable by permanently obscuring all addresses"]},{q:"When was the Taproot upgrade activated on Bitcoin?",a:"November 2021 at block 709,632",wrong:["August 2017 at block 481,824","January 2009 at block 0 as defined by Bitcoin consensus rules enforced by all full nodes","April 2024 at block 840,000"]},{q:"What is MAST (Merkelized Abstract Syntax Trees) in Taproot?",a:"A structure that reveals only the executed spending condition, hiding unused conditions for privacy",wrong:["A replacement mining algorithm for SHA-256 that speeds up proof-of-work block production on Bitcoin","A Lightning channel variant that uses hashed time-lock contracts to route payments across multiple hops","An off-chain database system that caches smart contract execution state between on-chain settlements"]},{q:"How does Taproot improve multi-signature transactions?",a:"Schnorr signatures allow multiple signers to produce a single compact signature indistinguishable from a regular one",wrong:["Taproot fully removes the requirement for multiple signatures by automatically converting all multi-sig scripts to single-key spends","Each participant's signature is stored in a separate dedicated block on-chain so validators can independently verify each signer later","All signing parties are required to be simultaneously online so the coordinator node can collect and aggregate approval keys in real time"]},{q:"What is Tapscript?",a:"An updated version of Bitcoin Script that enables new opcodes and improved scripting with Taproot",wrong:["A standalone programming language for writing and deploying new altcoin smart contracts on external sidechains","A developer command-line utility for submitting and reviewing proposed consensus patches to the Bitcoin Core client","The dedicated scripting engine used exclusively by the Lightning Network to enforce payment channel closing conditions"]}],scalability:[{q:"Bitcoin base layer processes roughly:",a:"7 transactions per second",wrong:["Around 7 million per second","About one every 10 minutes","Roughly 100,000 per second"]},{q:"Bitcoin scales primarily through:",a:"Layer 2 solutions like Lightning",wrong:["Larger base-chain block sizes","Removing the block size limit","Faster hardware on full nodes"]},{q:"The block size limit exists to:",a:"Keep node requirements low and maintain decentralization",wrong:["Artificially cap network growth so that adoption stays small","Allow miners to collect higher fees on every completely full block","Restrict daily throughput so that only high-value users get priority"]},{q:"The Blocksize Wars were about:",a:"Whether to increase block size or use Layer 2",wrong:["Whether Bitcoin mining rewards were economically sustainable","Who holds the legal rights to the Bitcoin name and trademark","Which cryptocurrency exchange should be the official BTC venue"]},{q:"Bitcoin's block size is limited to approximately:",a:"1-4 MB (with SegWit)",wrong:["100 MB as defined by Bitcoin consensus rules enforced by all full nodes","Unlimited - it grows with demand","1 KB as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What did SegWit (Segregated Witness) do for Bitcoin scalability?",a:"Separated signature data from transaction data, effectively increasing block capacity to ~2 MB equivalent",wrong:["Raised the raw block size limit from 1 MB to 2 MB by modifying the block header format in the base protocol","Removed all block size restrictions so that miners could freely include as many transactions as they desired","Migrated all transaction validation to a parallel sidechain that batch-settles its state back to mainchain regularly"]},{q:"What is transaction batching?",a:"Combining multiple payments into a single on-chain transaction to save block space and fees",wrong:["Sending the same transaction repeatedly to different nodes to guarantee reliable and confirmed network delivery","Organizing all pending mempool transactions by the sender's country before miners include them in a block","Holding all pending payments in a queue and submitting them only after the current block has reached full capacity"]},{q:"Why did the Bitcoin community reject simply raising the block size limit?",a:"Larger blocks increase node operating costs, risking centralization and reducing censorship resistance",wrong:["Larger blocks would make Bitcoin easier for governments to track and censor transactions globally","Satoshi deliberately designed the 1 MB cap as permanent and warned against ever raising it","Larger blocks would speed transactions so much that the mining difficulty algorithm would break"]},{q:"How does the Lightning Network improve Bitcoin's throughput?",a:"By processing millions of transactions off-chain and only settling final balances on the Bitcoin blockchain",wrong:["By replacing Bitcoin's slow blockchain with a faster parallel ledger that periodically merges back into the main chain","By increasing the block size limit to 100 MB so thousands of additional transactions can fit into every block","By reducing the time between Bitcoin blocks to one second, dramatically increasing total on-chain throughput"]},{q:"What is payment channel batching on Lightning?",a:"Opening or closing multiple channels in a single on-chain transaction to save fees and block space",wrong:["Sending a single Lightning payment simultaneously to multiple recipients using one shared payment hash","Mining several blocks in rapid succession so more channel open and close transactions can be confirmed","Compressing multiple Lightning transaction signatures together to reduce byte size and speed up routing"]}],utxos:[{q:"UTXO stands for:",a:"Unspent Transaction Output",wrong:["Universal Token Exchange Order","Unified Transaction eXecution Object","Ultra-fast Transfer of eXchange Operations"]},{q:"A UTXO is like:",a:"A specific bill in your wallet that you spend whole",wrong:["A running total of all your Bitcoin deposits and withdrawals","A credit line assigned to your Bitcoin address by the network","A numbered entry in your wallet's shared account balance ledger"]},{q:"When you spend a UTXO:",a:"It's consumed entirely and change is returned as a new UTXO",wrong:["Only the amount you spend is deducted while the remainder stays in the same output","It stays locked in your wallet until the recipient confirms they received the funds","It temporarily freezes on the blockchain and is unlocked after miner confirmation"]},{q:"UTXO management matters for:",a:"Privacy and minimizing future transaction fees",wrong:["Maximizing mining rewards and block confirmation speed","Speeding up network sync and reducing total block creation time","Lowering full node hardware requirements and long-term storage"]},{q:"What is a UTXO in Bitcoin?",a:"Unspent Transaction Output - the amount of bitcoin remaining after a transaction",wrong:["A Unified Transaction Order — a queue of pending transactions awaiting block inclusion","A mining reward token given to validators each time they confirm a new Bitcoin block","A Unique Transaction Origin — the digital address marker attached to each outgoing payment"]}],dust:[{q:'Bitcoin "dust" is:',a:"An amount too small to spend because the fee exceeds the value",wrong:["Bitcoin permanently deleted from supply when a private key is irreversibly lost","Leftover chain data that full nodes must periodically clear to stay synchronized","A regulatory label for bitcoin amounts below minimum legal reporting thresholds"]},{q:"Dust attacks are used to:",a:"Track and deanonymize wallet owners",wrong:["Steal bitcoin directly from targeted wallets","Flood the mempool and slow down mining confirmations","Create fake addresses to inflate the UTXO set artificially"]},{q:"To avoid dust issues:",a:"Consolidate small UTXOs when fees are low",wrong:["Delete all UTXOs that fall below the current dust limit","Stop accepting any incoming Bitcoin payments entirely","Move all Bitcoin to an exchange custodial wallet instead"]},{q:'What is a "dust attack" in Bitcoin?',a:"Sending tiny amounts of bitcoin to wallets to track and de-anonymize users",wrong:["Flooding the network with oversized transactions to delay block confirmations for everyone","Static electricity buildup that physically damages Bitcoin ASIC mining hardware over time","A software bug in Bitcoin Core that lets malicious miners insert unauthorized fake outputs"]},{q:"Why should users consolidate small UTXOs when fees are low?",a:"To reduce future transaction costs, as each UTXO adds to transaction size",wrong:["To increase bitcoin's market value by permanently reducing the circulating supply","To improve wallet privacy by merging all addresses into a single combined identifier","To qualify for mining rewards that are only paid to wallets holding fewer UTXOs"]}],rbf:[{q:"RBF stands for:",a:"Replace-By-Fee",wrong:["Really Big Fee","Rapid Block Finality","Return Bitcoin Fast"]},{q:"RBF allows you to:",a:"Bump a stuck transaction's fee to speed confirmation",wrong:["Cancel any unconfirmed transaction and reclaim the full amount sent","Send Bitcoin without paying fees during low-traffic mempool periods","Mine your own blocks to confirm your transactions ahead of the queue"]},{q:"RBF is useful when:",a:"Your transaction is stuck because the fee was too low",wrong:["You want to speed up your node's sync with the broader Bitcoin network","Your wallet software version is outdated and needs a full security update","You want to swap your Bitcoin for a lower-fee altcoin at a better rate"]},{q:"What does RBF (Replace-by-Fee) allow users to do?",a:"Replace an unconfirmed transaction with a higher-fee version",wrong:["Reverse a confirmed transaction by broadcasting a corrected replacement","Increase their bitcoin balance by reclaiming fees from prior failed transactions","Prevent double-spending by locking a transaction the moment it hits the mempool"]},{q:"What is CPFP (Child Pays for Parent) used for?",a:"Accelerating confirmation by spending an unconfirmed output with a high-fee transaction",wrong:["Splitting a parent transaction's bitcoin equally across multiple child receiving addresses","Creating a new child wallet that inherits all pending unconfirmed outputs from the parent","Shrinking the byte size of a parent transaction by compressing it with a child signature"]}],time_preference:[{q:"Low time preference means:",a:"Saving for the future instead of spending now",wrong:["Spending all your money as quickly as you earn it","Not worrying about money or future financial needs at all","Day trading assets constantly to maximize short-term returns"]},{q:"Bitcoin encourages low time preference because:",a:"Its value tends to increase over time due to scarcity",wrong:["Its price tends to decline steadily, making it costly to hold long-term","It pays annual interest rewards directly to long-term wallet holders","Governments mandate Bitcoin savings requirements for all citizens by law"]},{q:"High time preference leads to:",a:"Overconsumption and debt",wrong:["Long-term wealth accumulation","Increased savings and capital","Personal financial security"]},{q:"Fiat currency encourages:",a:"Spending now because money loses value over time",wrong:["Long-term saving since fiat money reliably retains purchasing power","Low time preference by rewarding those who patiently defer spending","Financial discipline by linking the money supply to gold reserves"]},{q:'What is "low time preference" in Bitcoin culture?',a:"Prioritizing long-term saving over short-term spending",wrong:["Trading Bitcoin frequently to capture short-term gains","Spending Bitcoin before each halving to avoid potential value loss","Watching price charts closely and acting on every short-term market swing"]},{q:"A Bitcoin standard encourages low time preference because:",a:"Saving is rewarded since the money appreciates over time",wrong:["Bitcoin's slow transaction speeds make frequent daily spending impractical","Government regulations require minimum Bitcoin holding periods for all users","Bitcoin protocol rules restrict each address to selling only once per calendar year"]},{q:'What does "low time preference" mean in the context of Bitcoin?',a:"Prioritizing long-term value and future rewards over immediate gratification",wrong:["Preferring to spend Bitcoin quickly before volatility causes its value to drop","Setting a firm deadline on how long to hold Bitcoin before converting to cash","Trading Bitcoin on short timeframes to maximize returns ahead of each halving"]},{q:"How does fiat money encourage high time preference?",a:"Inflation erodes purchasing power, incentivizing spending now rather than saving for later",wrong:["Fiat currency expires after a government-set date, forcing people to spend it before it becomes void","Banks charge escalating fees on idle cash balances, making holding money costlier than spending it","Governments levy heavy taxes on savings accounts while fully exempting everyday consumer spending"]},{q:'Why do Bitcoiners say Bitcoin "fixes" time preference?',a:"A deflationary hard money incentivizes saving and long-term thinking since purchasing power increases over time",wrong:["Bitcoin automatically stakes your savings in yield protocols, rewarding holders for their extended patience","Bitcoin transactions are deliberately slower than traditional banking, which naturally trains users toward patience","Bitcoin wallet software enforces a one-year minimum hold period, preventing impulsive short-term spending decisions"]},{q:"How does time preference relate to civilization building?",a:"Lower time preference leads to more capital accumulation, investment, and long-term infrastructure development",wrong:["Higher time preference actually builds civilizations faster because immediate consumption drives stronger economic growth","Time preference has no proven relationship to economic development according to mainstream economic theory today","Only governments and central banks have the power to effectively lower the collective time preference of entire societies"]},{q:'According to Saifedean Ammous in "The Bitcoin Standard," what is the relationship between sound money and time preference?',a:"Sound money lowers time preference, encouraging saving and long-term investment",wrong:["Sound money raises time preference because people rush to spend appreciating currency","There is no meaningful relationship between money type and individual time preference","Sound money eliminates time preference entirely, making people fully indifferent to timing"]},{q:"How does Ammous argue that low time preference connects to civilization building?",a:"People invest in long-term projects when money reliably holds its value",wrong:["Civilizations advance fastest when people spend money as quickly as possible","Low time preference leads to stagnation because nobody takes any risks","Civilization building is completely unrelated to the monetary system"]},{q:"What behavioral effect does fiat money have on time preference according to the Austrian economics perspective?",a:"Fiat raises time preference - inflation punishes savers and rewards debtors",wrong:["Fiat lowers time preference because stable inflation aids long-term planning","Fiat has no effect on time preference, which is determined by culture","Fiat encourages saving because interest rates compensate for inflation"]},{q:"How does the concept of delayed gratification relate to Bitcoin and sound money?",a:"Sound money rewards patience by preserving purchasing power over time",wrong:["Delayed gratification is irrelevant to any monetary system design","Bitcoin punishes patience because its price is far too volatile","Sound money discourages waiting by making everything too expensive"]},{q:"What is the key difference between how fiat and Bitcoin influence personal financial behavior?",a:"Fiat incentivizes consumption and debt; Bitcoin incentivizes saving",wrong:["Both systems produce identical behavior - spending stays the same","Bitcoin makes people spend more as they feel wealthy from gains","Fiat encourages saving; Bitcoin encourages spending due to deflation"]}],soft_vs_hard_forks:[{q:"A soft fork is:",a:"Backward-compatible upgrade",wrong:["A complete network shutdown","A deletion of all old rules","A new altcoin token launch"]},{q:"A hard fork creates:",a:"A permanent chain split if not everyone upgrades",wrong:["A temporary network pause until all nodes resync to the new rules","A free distribution of newly generated Bitcoin to all existing holders","A permanently faster network with shorter block times and higher throughput"]},{q:"Bitcoin Cash was created by:",a:"A hard fork of Bitcoin in 2017",wrong:["A soft fork of Bitcoin in 2015","A proposal rejected by Bitcoin miners in 2016","A merger between Bitcoin and Litecoin developers"]},{q:"SegWit was activated as:",a:"A soft fork",wrong:["A hard fork","A new blockchain","An altcoin"]},{q:"The key difference between a soft fork and a hard fork is:",a:"Soft forks are backwards-compatible; hard forks are not",wrong:["Soft forks are optional upgrades; hard forks are forced on all nodes","Soft forks affect only miners; hard forks require every wallet to upgrade","Soft forks are reversible changes; hard forks permanently alter the chain"]},{q:"The Blocksize Wars resulted in:",a:"Bitcoin Cash splitting off as a hard fork while Bitcoin kept small blocks + SegWit",wrong:["Bitcoin permanently increasing its block size to 2MB after a global miner referendum in 2017","A compromise upgrade merging SegWit with 4MB blocks that satisfied both the big-block and small-block camps","The entire Bitcoin mining network temporarily migrating to Bitcoin Cash before returning to Bitcoin"]},{q:"What is a soft fork in Bitcoin?",a:"A backward-compatible protocol upgrade where old nodes still accept new blocks",wrong:["A protocol change that temporarily halts the blockchain while all nodes download new software","A network split that divides the chain into two equal parts before eventually reconnecting","A mining rule change that requires all node operators to manually approve before it activates"]},{q:"What is a hard fork?",a:"A non-backward-compatible change that requires all nodes to upgrade or they'll follow a different chain",wrong:["A scheduled software maintenance that pauses the network while all nodes synchronize to the new rules","A minor protocol refinement automatically accepted by 51% of miners without requiring any node upgrades","A security patch that nodes can optionally apply to improve performance without changing any consensus rules"]},{q:"What was the Bitcoin Cash (BCH) hard fork about?",a:"A disagreement over scaling - BCH proponents wanted larger blocks while Bitcoin kept the 1 MB base limit with SegWit",wrong:["A conflict over who owned the Bitcoin trademark and had the legal right to use the name for their competing network","A dispute over replacing proof-of-work with a faster consensus mechanism that BCH developers wanted to adopt first","A disagreement about mandatory privacy features that BCH proposed adding while Bitcoin Core developers firmly rejected"]},{q:"Why are soft forks generally preferred over hard forks for Bitcoin upgrades?",a:"They maintain backward compatibility, don't force upgrades, and don't risk splitting the network",wrong:["They require unanimous approval from all miners and are significantly faster to deploy than any hard fork alternative","They permanently lower transaction fees and improve block propagation speed for every participant on the network","They have never caused disruption and must be formally endorsed by the Bitcoin Foundation before activation"]}],fedimints:[{q:"Fedimint helps with:",a:"Community custody with privacy",wrong:["Peer-to-peer exchange with fees","Pooled mining with shared rewards","On-chain transaction batching"]},{q:"A Fedimint uses:",a:"Federated guardians who jointly custody Bitcoin",wrong:["A single appointed trustee who manages all user deposits","A regulated bank that holds and insures all user funds","An automated smart contract that controls all withdrawals"]},{q:"Fedimint provides privacy through:",a:"Chaumian eCash tokens",wrong:["Zero-knowledge proofs","Ring signature schemes","Stealth address mixing"]},{q:"Fedimints are designed for:",a:"Communities that trust each other but want privacy",wrong:["Individuals who prefer to keep all their Bitcoin on exchanges","Businesses that need government-compliant custodial accounts","Miners who want to pool rewards and share custody with partners"]},{q:"A Fedimint (Federated Mint) provides:",a:"Community-custodial privacy through Chaumian ecash on Bitcoin",wrong:["A decentralized exchange for swapping Bitcoin without any KYC process","A pooled mining protocol where communities share block rewards equally","A layer-2 scaling solution that increases Bitcoin's transactions per second"]},{q:"Fedimints improve Bitcoin privacy by:",a:"Using blinded signatures so the mint cannot link deposits to withdrawals",wrong:["Storing all transaction records on a private sidechain only the guardians can read","Requiring every user to generate a fresh address for each new deposit into the mint","Routing all payments through multiple Lightning hops in order to obscure the sender's origin"]},{q:"What is a Fedimint?",a:"A federated Chaumian eCash mint where a group of guardians custody Bitcoin and issue private eCash tokens",wrong:["A decentralized exchange run by a committee of validators who approve every trade before it settles","A layer-2 protocol where elected miners vote on valid transactions before they are confirmed on-chain","A multi-signature wallet where all community members share equal signing authority over the pooled funds"]},{q:"How do Fedimints provide privacy?",a:"Using blind signatures so the mint cannot link who deposited Bitcoin with who redeems eCash tokens",wrong:["By routing every deposit through a series of on-chain mixer contracts before issuing any eCash token","By keeping all user balances in an encrypted database that only the lead guardian is permitted to access","By requiring a zero-knowledge proof from each user confirming fund ownership before any withdrawal is processed"]},{q:"What is the trust model of a Fedimint?",a:"Users trust a federation of guardians (e.g., 3-of-5 multisig) rather than a single custodian",wrong:["Users trust an automated smart contract that enforces all withdrawal rules without any human involvement","All funds are protected by a government deposit insurance program that replaces individual custodians","Users trust the open-source code alone with no custodians since funds are locked by on-chain proofs"]},{q:"How do Fedimints interact with the Lightning Network?",a:"They can send and receive Lightning payments, allowing private transactions with the broader Bitcoin network",wrong:["They operate as dedicated Lightning routing nodes that earn fees forwarding payments on behalf of users","They issue Bitcoin-backed stablecoins that can be transferred across the broader Lightning payment network","They bypass Lightning entirely and settle all payments directly on the Bitcoin base layer via batch transactions"]}],books:[{q:"The Bitcoin Standard is a popular book about:",a:"Sound money and Bitcoin economics",wrong:["Gold standard history and fiat money policy","Bitcoin mining hardware and pool management","Day trading strategies and chart analysis"]},{q:"Mastering Bitcoin by Andreas Antonopoulos is:",a:"A technical deep-dive into how Bitcoin works",wrong:["A beginner's guide to buying and holding Bitcoin safely","A legal handbook for reporting cryptocurrency taxes correctly","A financial guide to building generational wealth through crypto"]},{q:"The Sovereign Individual predicted:",a:"Digital money and the decline of nation-states",wrong:["The rise of social media and the collapse of individual privacy","Digital currencies issued and controlled exclusively by central banks","The collapse of global free trade and the return of local economies"]},{q:"21 Lessons by Gigi explores:",a:"Philosophical lessons learned from going down the Bitcoin rabbit hole",wrong:["A beginner's practical guide to mining Bitcoin profitably from a home setup","Twenty-one step-by-step tutorials for building Lightning Network payment channels","The personal stories of early Bitcoin adopters who became millionaires before 2020"]},{q:'"The Bitcoin Standard" by Saifedean Ammous primarily argues:',a:"Bitcoin is the hardest money ever invented and will replace fiat",wrong:["Bitcoin is innovative but remains too volatile to ever function as reliable money","Bitcoin is useful as an asset class but was never designed to replace government fiat","Governments will regulate Bitcoin into irrelevance before it can seriously threaten fiat"]},{q:'Gigi\'s "21 Lessons" is structured around:',a:"21 philosophical, economic, and technical lessons learned from Bitcoin",wrong:["A 21-day step-by-step plan for complete beginners to start investing in Bitcoin","Profiles of the 21 wealthiest early Bitcoin adopters and their investing strategies","An analysis of 21 altcoin failures and what they reveal about the cryptocurrency market"]},{q:'Who wrote "The Bitcoin Standard"?',a:"Saifedean Ammous",wrong:["Andreas Antonopoulos","Satoshi Nakamoto","Michael Saylor"]},{q:"What book by Jimmy Song teaches Bitcoin programming and development?",a:"Programming Bitcoin",wrong:["The Bitcoin Standard","Digital Gold as defined by Bitcoin consensus rules enforced by all full nodes","Cryptoassets as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What book by Lyn Alden provides a broad investment perspective including Bitcoin?",a:"Broken Money",wrong:["The Bitcoin Standard","Digital Gold","The Internet of Money"]},{q:'What is "The Blocksize War" by Jonathan Bier about?',a:"The history of Bitcoin's scaling debate, SegWit activation, and the BCH fork",wrong:["A technical guide to optimizing block size parameters and improving Bitcoin mining efficiency","A historical account of the Ethereum versus Bitcoin rivalry and the subsequent rise of DeFi","A fictional thriller about competing mining cartels fighting for control of the global blockchain"]}],"misconceptions-fud":[{q:"FUD stands for:",a:"Fear, Uncertainty, and Doubt",wrong:["Fundamental Upgrade Directive","Financial Utility and Demand","Fork, Upgrade, and Deploy"]},{q:'"Bitcoin is used by criminals" ignores that:',a:"Cash is used far more for crime and Bitcoin is traceable",wrong:["Bitcoin is fully anonymous and law enforcement cannot trace any transactions","Most global illicit activity today is exclusively financed using Bitcoin","No government agency has ever successfully traced a Bitcoin transaction to a criminal"]},{q:'"Bitcoin has no intrinsic value" ignores:',a:"Its network security, scarcity, and utility",wrong:["Its government backing and central bank reserve status","The value assigned to it by global commodity futures exchanges","Its ability to be redeemed for physical precious metals on demand"]},{q:'"Bitcoin is too volatile" ignores:',a:"Its long-term upward trend and decreasing volatility over time",wrong:["That traditional equities have historically shown far higher volatility than Bitcoin","That gold experienced equivalent price swings before becoming a widely accepted store of value","Historical data showing major fiat currencies fluctuate more than Bitcoin across multi-year periods"]},{q:'"Bitcoin wastes energy" ignores:',a:"Its use of stranded/renewable energy and the value it secures",wrong:["That conventional banking infrastructure consumes far more total energy than all Bitcoin miners combined","Studies showing that Bitcoin mining energy use is fully offset by purchased renewable energy certificates","That all proof-of-work mining is legally required to run on certified excess renewable power from grids"]},{q:'How do Bitcoiners respond to "Bitcoin is too volatile to be money"?',a:"Every 4-year period has been profitable and volatility decreases over time",wrong:["They concede that Bitcoin's price swings make it unsuitable as a reliable medium of daily exchange","They argue volatility only appears because of speculative trading and fully disappears with mass adoption","They claim Bitcoin miners actively stabilize the price by adjusting the block reward at key price levels"]},{q:'Why is the claim "quantum computers will break Bitcoin" misleading?',a:"Such computers don't exist yet and Bitcoin can upgrade before they do",wrong:["Bitcoin already uses quantum-resistant encryption algorithms by default","Quantum computers are proven to actually strengthen Bitcoin's network security","Satoshi specifically designed Bitcoin to be immune to all future computing advances"]},{q:'What is the rebuttal to "Tether (USDT) props up Bitcoin\'s price"?',a:"Bitcoin grew for years before Tether and kept rising through its controversies",wrong:["Tether holds 100% of its cash reserves in Bitcoin and annual audits confirm this","Bitcoin's price is determined solely by the energy cost required to mine each coin","Tether was created alongside Bitcoin by Satoshi as an integrated stable reserve layer"]},{q:'Why is "Bitcoin is a pyramid scheme" factually wrong?',a:"It has no company, no CEO, no return promises, and no recruitment profits",wrong:["Because early adopters are guaranteed investment returns directly by the protocol","Because Satoshi Nakamoto still privately operates the foundation behind Bitcoin","Because the Bitcoin protocol automatically pays dividends to all long-term holders"]},{q:'What is the strongest argument against "governments will ban Bitcoin"?',a:"China banned it multiple times yet it kept growing, and the US approved ETFs",wrong:["Governments lack reliable tools to actually monitor or intercept Bitcoin activity","International law explicitly prevents any nation from restricting digital currencies","Bitcoin's protocol automatically disables itself in any country that formally bans it"]}],"satoshi-nakamoto":[{q:"Satoshi Nakamoto:",a:"Stepped down and disappeared",wrong:["Is currently the CEO of Bitcoin","Was arrested as defined by Bitcoin consensus rules enforced by all full nodes","Sold all Bitcoin as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"Satoshi's last known communication was around:",a:"2011",wrong:["2020","2015","2009"]},{q:"Satoshi's Bitcoin holdings are estimated at:",a:"About 1 million BTC that have never moved",wrong:["None at all - Satoshi deliberately never mined any Bitcoin","Roughly 100 BTC earned only from the very first blocks","The entire 21 million BTC supply was pre-mined by Satoshi"]},{q:"Satoshi's disappearance is seen as:",a:"A feature - it made Bitcoin truly decentralized",wrong:["A critical bug that severely weakened Bitcoin's ongoing development","A deliberate crime committed to avoid paying taxes on Bitcoin profits","A planned marketing strategy designed to generate media attention and hype"]},{q:"Satoshi's true identity is:",a:"Unknown - it could be one person or a group",wrong:["Confirmed to be Elon Musk based on an FBI forensic investigation","Identified as a retired CIA analyst operating under a government alias","Revealed to be a sitting US President who acted under strict secrecy"]},{q:"Why is it important that Satoshi Nakamoto disappeared?",a:"Bitcoin has no leader who can be arrested, corrupted, or pressured",wrong:["Because Satoshi was actively being sought by law enforcement for financial crimes","So they could secretly continue accumulating Bitcoin without drawing public scrutiny","Because the entire codebase was considered complete and required absolutely no further work"]},{q:"What evidence suggests Satoshi Nakamoto was likely one person rather than a team?",a:"Consistent writing style, coding patterns, and posting times across years of activity",wrong:["A signed public confession that was posted and later quietly deleted from the Bitcoin Talk forum","DNA and fingerprint evidence discovered on hardware used to run the original Bitcoin node","A classified government investigation that officially confirmed Satoshi was a single known individual"]},{q:"When did Satoshi Nakamoto stop posting publicly?",a:"Around December 2010, with a final known post in April 2011",wrong:["In January 2009, just a few days after the Bitcoin network first went live","They never fully stopped and are widely believed to still post anonymously today","Around mid-2015 during the peak of the heated block size scaling debate"]},{q:"How many Bitcoin did Satoshi Nakamoto reportedly mine?",a:"Approximately 1 million BTC based on analysis of early mining patterns",wrong:["Exactly 21 million BTC, since Satoshi pre-mined the entire fixed total supply","Zero BTC in total, as Satoshi deliberately chose never to mine any coins at all","Roughly 100 BTC earned exclusively by mining only the original genesis block"]},{q:"What famous message did Satoshi embed in the Bitcoin genesis block?",a:'"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"',wrong:['"Hello World - the Bitcoin network is now live and open to the entire world"','"In cryptography we trust - a peer to peer electronic cash system begins today"','"The revolution will not be centralized - the age of digital cash is now upon us"']}],history:[{q:"The Bitcoin Genesis Block was mined in:",a:"January 2009",wrong:["October 2008","June 2010","December 2007"]},{q:"The first real-world Bitcoin transaction was:",a:"10,000 BTC for two pizzas",wrong:["5,000 BTC traded for a used car","1,000 BTC paid for a small house","50 BTC spent on a single cup of coffee"]},{q:"Bitcoin Pizza Day is celebrated on:",a:"May 22",wrong:["January 3","October 31","December 25"]},{q:"Mt. Gox was:",a:"An early Bitcoin exchange that was hacked and collapsed",wrong:["A Bitcoin mining pool that collapsed after a prolonged drop in hash rates","A widely used Bitcoin hardware wallet that was later discovered to have a critical flaw","A regulatory agency established in Japan to oversee early cryptocurrency exchanges"]},{q:"The first Bitcoin block is called:",a:"The Genesis Block (Block 0)",wrong:["The Alpha Block (Block 1)","The Satoshi Block (Block 1)","The Origin Block (Block 0)"]},{q:"Hal Finney received:",a:"The first Bitcoin transaction from Satoshi",wrong:["The very last Bitcoin that will ever be mined around 2140","An official government commendation for contributions to digital currency","The exclusive worldwide rights to the Bitcoin name and trademark"]},{q:"Laszlo's famous pizza order was called from:",a:"London (Laszlo was in Florida)",wrong:["New York City (Laszlo was based there at the time)","San Francisco (the call was placed by a local volunteer)","Tokyo (Laszlo was living in Japan at the time)"]},{q:"The Bitcoin Wiki has been online since:",a:"2010",wrong:["2015","2009","2013"]},{q:"Tim Draper is known in Bitcoin for:",a:"Buying seized Silk Road Bitcoin at US Marshals auction",wrong:["Founding and developing the Lightning Network off-chain payment protocol","Writing and publishing the original Bitcoin whitepaper anonymously in 2008","Mining and signing Bitcoin's original genesis block alongside Satoshi Nakamoto"]},{q:'The "Lightning Torch" was:',a:"A Lightning payment passed between notable Bitcoiners",wrong:["A competitive global Bitcoin mining event offering prizes to the fastest miners","A popular open-source hardware wallet for storing Bitcoin securely offline","A well-known documentary film about Bitcoin's early rise and key pioneers"]},{q:"Approximately how many BTC did Mt. Gox lose in its collapse?",a:"850,000 BTC",wrong:["100,000 BTC","2 million BTC","50,000 BTC"]},{q:"What year did the Silk Road marketplace get seized?",a:"2013",wrong:["2011","2015","2017"]},{q:"How many Bitcoins were exchanged for two pizzas on Bitcoin Pizza Day?",a:"10,000 BTC",wrong:["1,000 BTC","100,000 BTC","1,000,000 BTC"]},{q:"What was the main conflict of the Blocksize War?",a:"Whether to increase block size limit",wrong:["Whether to switch Bitcoin to proof of stake","Whether to add mandatory privacy features to Bitcoin","Whether to change Bitcoin's fixed halving schedule"]},{q:"What was SegWit2x?",a:"Failed agreement to double block size after SegWit",wrong:["A completed upgrade that raised the block size limit to 2MB permanently","A brand new proof-of-work mining algorithm proposed to replace SHA-256","An independent second layer payment network designed to scale Bitcoin"]}],_general:[{q:"One Bitcoin equals how many satoshis?",a:"100,000,000 (one hundred million)",wrong:["1,000,000 (exactly one million)","10,000,000 (exactly ten million)","1,000,000,000 (exactly one billion)"]},{q:"Bitcoin was launched in which year?",a:"2009",wrong:["2008","2010","2012"]},{q:"Bitcoin transactions are recorded on:",a:"A public distributed ledger",wrong:["A private encrypted server","A shared central bank database","A secure chain of verified email receipts"]},{q:"Who can send you Bitcoin?",a:"Anyone who knows your address",wrong:["Only your linked bank or licensed exchange","Only users who have completed KYC verification","Only people located in your same country"]},{q:"Bitcoin operates on:",a:"24/7, 365 days a year",wrong:["Banking hours only","Weekdays only as defined by Bitcoin consensus rules enforced by all full nodes","It shuts down for maintenance"]},{q:"The total number of Bitcoins that will ever exist is:",a:"Exactly 21 million",wrong:["Unlimited supply","Exactly 100 million","It changes every year"]},{q:"Bitcoin is often abbreviated as:",a:"BTC",wrong:["BTN","BCN","BIT"]},{q:"A Bitcoin wallet stores:",a:"Private keys, not actual Bitcoin",wrong:["Physical coins minted per transaction","Actual digital Bitcoin file tokens","Visual QR code images of your Bitcoin"]},{q:"To receive Bitcoin you need:",a:"A Bitcoin address",wrong:["A bank account","A social security number","A credit card as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"The Bitcoin network is maintained by:",a:"Thousands of volunteers running nodes worldwide",wrong:["A nonprofit foundation based in California with a global paid staff","The United Nations through its digital finance regulatory oversight body","A single powerful supercomputer managed by the core development team"]},{q:"Bitcoin confirmation time depends on:",a:"Network congestion and fee paid",wrong:["The time of day the transaction is sent","Your local internet or WiFi connection speed","The specific country or jurisdiction you are in"]},{q:"A mempool is:",a:"Where unconfirmed transactions wait to be included in a block",wrong:["A shared pool where miners combine resources to find new blocks faster","A type of hardware wallet used to store Bitcoin and keys securely offline","A centralized exchange platform where users buy and trade digital assets"]},{q:"Bitcoin difficulty adjustment ensures:",a:"Blocks are found roughly every 10 minutes regardless of hash power",wrong:["Bitcoin prices remain stable and predictable within a controlled trading range","Every miner earns an identical block reward regardless of their hash rate contributed","All Bitcoin transactions automatically become free once the network reaches full size"]},{q:"SegWit stands for:",a:"Segregated Witness",wrong:["Secure Widget as defined by Bitcoin consensus rules enforced by all full nodes","Sequential Witness","Segment Width as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"A Bitcoin address starts with:",a:"1, 3, or bc1",wrong:["0x, as specified in the original Bitcoin whitepaper released in 2008","BTC, as specified in the original Bitcoin whitepaper released in 2008","Any letter"]},{q:"The Lightning Network whitepaper was published by:",a:"Joseph Poon and Thaddeus Dryja",wrong:["Satoshi Nakamoto, as specified in the original Bitcoin whitepaper released in 2008","Vitalik Buterin, as specified in the original Bitcoin whitepaper released in 2008","Elon Musk, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Bitcoin hash rate measures:",a:"The total computing power securing the network",wrong:["Transaction speed, as specified in the original Bitcoin whitepaper released in 2008","Number of users, as specified in the original Bitcoin whitepaper released in 2008","Price changes, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"A nonce in mining is:",a:"A number miners change to find a valid block hash",wrong:["A type of fee, as specified in the original Bitcoin whitepaper released in 2008","A wallet address, as specified in the original Bitcoin whitepaper released in 2008","A block reward, as specified in the original Bitcoin whitepaper released in 2008"]},{q:'The term "NGMI" in Bitcoin culture means:',a:"Not Gonna Make It",wrong:["New Global Money Index","Next Generation Mining Interface","Network Growth Metric Indicator"]},{q:"Hyperbitcoinization refers to:",a:"Mass voluntary adoption of Bitcoin as money",wrong:["A Bitcoin price crash, as specified in the original Bitcoin whitepaper released in 2008","A mining difficulty spike, as specified in the original Bitcoin whitepaper released in 2008","A new altcoin launch, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Strike, Cash App, and River are all:",a:"Apps that let you buy Bitcoin",wrong:["Mining pools, as specified in the original Bitcoin whitepaper released in 2008","Altcoins, as specified in the original Bitcoin whitepaper released in 2008","Bitcoin forks, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Nostr is:",a:"A decentralized social protocol popular in the Bitcoin community",wrong:["A mining algorithm, as specified in the original Bitcoin whitepaper released in 2008","A Bitcoin fork, as specified in the original Bitcoin whitepaper released in 2008","An exchange, as specified in the original Bitcoin whitepaper released in 2008"]},{q:'The phrase "fix the money, fix the world" means:',a:"Sound money leads to better societal outcomes",wrong:["Print more money, as specified in the original Bitcoin whitepaper released in 2008","Ban all currencies, as specified in the original Bitcoin whitepaper released in 2008","Use only credit cards, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"A timelock in Bitcoin allows:",a:"Locking funds until a specific block height or time",wrong:["Freezing the blockchain, as specified in the original Bitcoin whitepaper released in 2008","Stopping mining, as specified in the original Bitcoin whitepaper released in 2008","Deleting transactions, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Block reward plus transaction fees equals:",a:"The total miner revenue per block",wrong:["The Bitcoin price, as specified in the original Bitcoin whitepaper released in 2008","The network speed, as specified in the original Bitcoin whitepaper released in 2008","The difficulty level, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Ordinals on Bitcoin are:",a:"A way to inscribe data on individual satoshis",wrong:["A ranking system for miners, as specified in the original Bitcoin whitepaper released in 2008","A type of wallet, as specified in the original Bitcoin whitepaper released in 2008","A government regulation, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"A paper wallet is:",a:"A printed private key for cold storage",wrong:["A paper receipt from an ATM as defined by Bitcoin consensus rules enforced by all full nodes","A bank statement, as specified in the original Bitcoin whitepaper released in 2008","A type of fiat currency, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"The Lightning Network can theoretically handle:",a:"Millions of transactions per second",wrong:["7 per second, as specified in the original Bitcoin whitepaper released in 2008","100 per second, as specified in the original Bitcoin whitepaper released in 2008","1 per minute, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"A watch-only wallet lets you:",a:"Monitor a balance without being able to spend",wrong:["Mine Bitcoin, as specified in the original Bitcoin whitepaper released in 2008","Create new coins, as specified in the original Bitcoin whitepaper released in 2008","Edit the blockchain, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Pleb is a term of endearment in Bitcoin meaning:",a:"An everyday Bitcoiner, not wealthy but committed",wrong:["A professional trader, as specified in the original Bitcoin whitepaper released in 2008","A mining executive, as specified in the original Bitcoin whitepaper released in 2008","A government official, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"What is the total number of satoshis that will ever exist?",a:"2.1 quadrillion (2,100,000,000,000,000)",wrong:["21 million, as specified in the original Bitcoin whitepaper released in 2008","100 billion, as specified in the original Bitcoin whitepaper released in 2008","21 quadrillion, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Bitcoin's first confirmed exchange rate (in 2010) was roughly:",a:"1,309 BTC per US dollar",wrong:["1 BTC per US dollar as defined by Bitcoin consensus rules enforced by all full nodes","100 BTC per US dollar","0.01 BTC per US dollar"]},{q:"The first Bitcoin exchange rate was established at approximately:",a:"$0.00099 per BTC (less than one penny)",wrong:["$1.00 per BTC, as specified in the original Bitcoin whitepaper released in 2008","$0.10 per BTC, as specified in the original Bitcoin whitepaper released in 2008","$100 per BTC, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Dollar-cost averaging (DCA) into Bitcoin means:",a:"Buying a fixed amount regularly regardless of price",wrong:["Borrowing dollars to buy Bitcoin all at once as defined by Bitcoin consensus rules enforced by all full nodes","Selling Bitcoin when the dollar strengthens as defined by Bitcoin consensus rules enforced by all full nodes","Converting Bitcoin profits back into dollars as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:'The phrase "Not your keys, not your coins" warns against:',a:"Keeping Bitcoin on exchanges where you don't control the private keys",wrong:["Using physical Bitcoin coins instead of digital, as specified in the original Bitcoin whitepaper released in 2008","Sharing your public key with other people, as specified in the original Bitcoin whitepaper released in 2008","Using hardware wallets instead of software, as specified in the original Bitcoin whitepaper released in 2008"]}],risks__threats__attack_vectors__weaknes:[{q:"Which Bitcoin address type is better for quantum resistance?",a:"SegWit (bc1q) because Taproot exposes the public key",wrong:["Taproot (bc1p), as specified in the original Bitcoin whitepaper released in 2008","Legacy (1...), as specified in the original Bitcoin whitepaper released in 2008","All are equally vulnerable, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"BIP 360 proposes:",a:"Pay to Quantum Resistant Hash",wrong:["Bigger blocks, as specified in the original Bitcoin whitepaper released in 2008","Faster mining, as specified in the original Bitcoin whitepaper released in 2008","New altcoin support, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Why is a 51% attack economically irrational against Bitcoin?",a:"The cost of acquiring that hash rate would far exceed any attainable reward",wrong:["Because Bitcoin's code blocks it automatically, as specified in the original Bitcoin whitepaper released in 2008","Because Satoshi holds 51% of hash rate as a safeguard as defined by Bitcoin consensus rules enforced by all full nodes","Because 51% of miners have agreed never to attack, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"What can a successful 51% attacker actually do to Bitcoin?",a:"Double-spend their own recent transactions and block some new transactions",wrong:["Create new Bitcoin out of thin air beyond the 21M cap as defined by Bitcoin consensus rules enforced by all full nodes","Steal coins from other users' wallets, as specified in the original Bitcoin whitepaper released in 2008","Delete the entire blockchain history, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Quantum computing threatens Bitcoin by potentially:",a:"Breaking ECDSA signatures used to authorize spending",wrong:["Mining all remaining Bitcoin in seconds as defined by Bitcoin consensus rules enforced by all full nodes","Deleting the entire blockchain, as specified in the original Bitcoin whitepaper released in 2008","Creating unlimited new Bitcoin addresses as defined by Bitcoin consensus rules enforced by all full nodes"]}],"evidence-against-alts":[{q:"Ethereum's original sale page reveals that ETH was:",a:"Pre-sold as a security to fund development",wrong:["Mined fairly like Bitcoin, as specified in the original Bitcoin whitepaper released in 2008","Distributed equally, as specified in the original Bitcoin whitepaper released in 2008","Created by Satoshi, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"What fundamental difference exists between Bitcoin and altcoins regarding decentralization?",a:"Altcoin founders often hold large pre-mines or centralized control",wrong:["Altcoins are too cheap, as specified in the original Bitcoin whitepaper released in 2008","Bitcoin has better marketing, as specified in the original Bitcoin whitepaper released in 2008","Altcoins use different blockchains, as specified in the original Bitcoin whitepaper released in 2008"]},{q:'Why do Bitcoiners say "there is no second best"?',a:"No other crypto achieves Bitcoin's decentralization, security, and immutability",wrong:["Bitcoin was the first, so it automatically wins, as specified in the original Bitcoin whitepaper released in 2008","The SEC has declared all other cryptos illegal, as specified in the original Bitcoin whitepaper released in 2008","Satoshi patented the blockchain concept, as specified in the original Bitcoin whitepaper released in 2008"]},{q:'What is a "pre-mine" and why is it concerning?',a:"Founders allocate coins to themselves before public launch - unfair distribution",wrong:["A technique to speed up transaction processing, as specified in the original Bitcoin whitepaper released in 2008","A security measure that protects the network, as specified in the original Bitcoin whitepaper released in 2008","A method of testing the blockchain before launch, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Most altcoins are considered securities because:",a:"They have identifiable teams profiting from token sales with promises of returns",wrong:["They use proof-of-stake consensus, which regulators treat as interest paid by an enterprise","The SEC automatically registers any digital asset listed on a US-based trading platform","They are listed and traded on traditional stock exchange platforms alongside conventional equities"]},{q:'What is a "premine" and why is it a red flag for altcoins?',a:"Founders create and keep tokens before public launch, giving insiders an unfair edge",wrong:["A premine is a security scanning process that protects new blockchains from early 51% hashrate attacks","A premine means the full codebase was professionally audited before release, a widely accepted practice","A premine is when validators confirm the genesis block transactions without receiving any block reward"]},{q:"Why are many altcoin tokens considered securities under US law?",a:"They pass the Howey Test - buyers expect profits from a centralized team's efforts",wrong:["The SEC automatically classifies every digital token asset as a regulated investment security","Any token actively traded on a licensed cryptocurrency exchange is legally classified as a security","Only tokens with market caps exceeding one billion dollars are large enough to formally qualify as securities"]},{q:'What is "VC token dumping" in the altcoin market?',a:"VCs invest early at a discount, then sell their tokens on retail investors at launch",wrong:["VCs donate their early-discounted token allocations to nonprofit charitable organizations after launch","VCs permanently lock their allocated tokens inside smart contracts to demonstrate long-term commitment","VCs convert their discounted token positions into grants that fund open-source protocol development"]},{q:'Why do Bitcoiners argue that "decentralized governance tokens" are an oxymoron?',a:"Token voting concentrates power with whales and VCs, recreating inequality",wrong:["Governance tokens are far too technically complex to implement secure on-chain voting","Bitcoin already uses internal governance tokens to coordinate votes on protocol upgrades","Governance tokens have been declared illegal financial instruments in most global jurisdictions"]},{q:"What key evidence do Bitcoiners cite about Ethereum's centralization?",a:"A massive premine to insiders, repeated monetary policy changes, and known leadership",wrong:["Ethereum runs on a centralized server cluster secretly managed by Vitalik Buterin and his core team","Ethereum transactions require explicit approval from government financial regulators before confirming","Ethereum currently has far fewer active global nodes than a typical mid-sized enterprise cloud database"]},{q:"How was Ethereum's initial token supply structured at its 2014 crowdsale?",a:"About 72 million ETH were pre-mined; roughly 70% of the initial supply was allocated to founders and early insiders",wrong:["All 72 million ETH were sold in a fully public fair launch with zero allocation reserved for the founding team or investors","Roughly 20 million ETH were pre-mined with the remainder distributed through a public sale open to any retail investor globally","100 million ETH were created and divided equally: one third to founders, one third to an R&D reserve, one third to the public"]},{q:"What does research reveal about the infrastructure running Ethereum's validator nodes?",a:"About 61% of Ethereum nodes run in cloud data centers; AWS alone hosts roughly 25% making centralization a severe concern",wrong:["Only about 15% of Ethereum nodes run in the cloud; the vast majority are home validators run by individual stakers globally","Nearly 95% of Ethereum nodes run on dedicated bare-metal servers; cloud hosting is actively discouraged by the foundation","Roughly 40% of nodes are cloud-hosted, a level considered acceptable within Ethereum's published decentralization targets"]},{q:"What action did Ethereum take after the DAO hack in 2016, and what principle did it violate?",a:'Ethereum rolled back its blockchain to reverse the hack, proving its "code is law" and immutability claims were overrideable',wrong:["Ethereum implemented a smart contract patch to freeze hacker funds without altering any already-confirmed on-chain state","Ethereum hard forked to add new security rules but preserved all historical transactions, maintaining full ledger immutability","Ethereum's core developers sued the attacker in Swiss court and recovered the funds without touching or altering the chain"]},{q:"What are the key concerns about XRP's token distribution and Ripple's legal status?",a:"Ripple pre-created ~100 billion XRP, controls its scheduled release, and was sued by the SEC for an unregistered securities offering",wrong:["XRP has a capped supply of 21 million tokens like Bitcoin, but Ripple Labs retains permanent veto power over all protocol upgrades","Ripple distributed XRP through open mining but faces legal challenges because its founders hold United States banking licenses","XRP has no maximum supply cap and Ripple can mint new tokens freely; the SEC sued over undisclosed token minting activities"]},{q:"What is notable about Solana's track record of network availability since its mainnet launch?",a:"Solana has suffered over 10 major network outages since launch, including a single outage lasting approximately 17 hours",wrong:["Solana has maintained a perfect uptime record since launch thanks to its Proof-of-History consensus and strong validator incentives","Solana experienced one brief 2-hour outage in 2021 that was rapidly resolved via a coordinated validator restart procedure","Solana's network undergoes scheduled maintenance windows twice per year, which critics sometimes mischaracterize as full outages"]},{q:"Why can't a competing cryptocurrency simply copy Bitcoin's open-source code and achieve equivalent security and value?",a:"Code is easily copied but network effects are not: Bitcoin's liquidity, hashrate security, deep trust, and developer talent are irreplaceable",wrong:["Bitcoin's source code is proprietary and legally protected under copyright law, making direct copying a violation of intellectual property","Bitcoin's cryptographic algorithms are patented by the Satoshi Nakamoto estate, preventing any fork from using SHA-256 legitimately","Bitcoin's code can be copied but all resulting forks must share the original UTXO set, preventing any fork from bootstrapping independently"]},{q:"What has happened to nearly all altcoins throughout Bitcoin's history when evaluated in BTC-denominated terms?",a:"Over 99% of altcoins ever launched have declined toward zero when priced against Bitcoin, regardless of their initial hype cycles",wrong:["About 50% of altcoins outperform Bitcoin over five-year windows; the rest decline, making broad diversification a rational strategy","Altcoins have collectively outperformed Bitcoin since 2017 on a volume-weighted basis when adjusted for total market capitalization","Roughly 30% of altcoins launched before 2018 still trade above their original ICO price when measured in BTC-denominated terms"]},{q:'What happened to major corporate "blockchain not Bitcoin" initiatives at firms like JPMorgan, IBM, and Maersk?',a:"JPMorgan, IBM, and Maersk all launched enterprise blockchain projects with great fanfare and then quietly abandoned each of them",wrong:["JPMorgan's blockchain now processes $10 trillion daily and IBM's Food Trust actively tracks 25 billion food supply chain records","The corporate blockchain era succeeded in creating interoperable networks that now settle cross-border payments in real time","IBM and JPMorgan merged their blockchain platforms into a single enterprise network now operating across 500 Fortune 500 companies"]},{q:"What makes Bitcoin's origin uniquely different from every other major cryptocurrency ever launched?",a:'Bitcoin has an "immaculate conception": no founder enrichment, no premine, no ICO, and an anonymous creator who then disappeared',wrong:["Bitcoin is unique because its consensus rules have never changed since genesis; no other network has achieved this full stability","Bitcoin's origin is unique because it was launched by a publicly known academic team who donated all profits back to a foundation","Bitcoin is the only cryptocurrency launched before 2015 that still runs its original completely unmodified consensus algorithm"]},{q:"Why does launching a new Proof-of-Work coin present a fundamental and unavoidable security problem?",a:"Any new PoW chain starts with near-zero hashrate, meaning an attacker with modest hardware could 51% attack it from day one",wrong:["New PoW coins are insecure because ASIC manufacturers refuse to supply hardware to chains below the 1 EH/s threshold hashrate","New PoW chains are vulnerable because they must use Bitcoin's SHA-256 algorithm, enabling cheap merged mining attack exploits","Launching a new PoW coin requires regulatory approval in most countries, creating legal barriers that deter legitimate honest miners"]}],"smart-contracts":[{q:"Bitcoin's scripting language has supported smart contracts:",a:"Since the beginning - Bitcoin always had them",wrong:["Only after the Taproot soft fork was activated on the network in late 2021","Only after SegWit was activated and deployed on the main Bitcoin network in 2017","Never - Bitcoin's intentional design explicitly prohibits all smart contract logic"]},{q:"OP_RETURN is used in Bitcoin to:",a:"Embed small amounts of data in transactions",wrong:["Automatically return unspent Bitcoin change back to the original sending address","Cancel or reverse pending unconfirmed transactions waiting in the mempool queue","Accelerate block confirmation times for high-fee-rate priority Bitcoin transactions"]},{q:"What is Bitcoin\\'s native scripting language called?",a:"Bitcoin Script",wrong:["Solidity Script","Python Script","EVM Bytecode"]},{q:"What does OP_RETURN allow users to do on Bitcoin?",a:"Embed up to 80 bytes of arbitrary data in a transaction",wrong:["Execute Ethereum-style Turing-complete smart contract logic directly on-chain","Alter or update a Bitcoin transaction's output amounts after it was broadcast","Issue and distribute new Bitcoin-backed tokens or colored coin asset classes"]},{q:"What are DLCs (Discreet Log Contracts) on Bitcoin?",a:"Smart contracts that settle based on external oracle data without revealing details",wrong:["Encrypted private key backups distributed across transaction log files for disaster recovery","Special developer debugging tools that trace and profile contract execution steps on testnet","Decentralized peer-to-peer lending agreements that execute natively on the Ethereum blockchain"]}],"chaumian-mints":[{q:"Cashu is an implementation of:",a:"Chaumian ecash on Bitcoin/Lightning",wrong:["An independent proof-of-work blockchain","An Ethereum-based altcoin token protocol","A memory-hard Bitcoin mining algorithm"]},{q:"Who invented the blind signature technology used in Chaumian eCash?",a:"David Chaum in 1982",wrong:["Satoshi Nakamoto in 2008","Adam Back in 1997","Hal Finney in 2004"]},{q:"What modern Bitcoin layer implements Chaumian eCash for minting privacy-preserving tokens?",a:"Cashu and Fedimint protocols",wrong:["The Lightning Network layer","The Liquid sidechain network","Ethereum's ERC-20 token system"]},{q:"Cashu is:",a:"An ecash protocol built on Bitcoin using Chaumian blind signatures",wrong:["A competing proof-of-stake cryptocurrency designed to challenge Bitcoin's role in payments","A hardware wallet manufacturer that specializes in cold-storage security for Bitcoin holders","A type of open-source Bitcoin mining pool software used to coordinate distributed hashrate"]},{q:'What are "blind signatures" in ecash?',a:"The mint signs tokens without knowing which user they belong to",wrong:["Signatures that automatically expire and become cryptographically invalid after exactly 24 hours","A technique for signing blockchain transactions without needing the user's own private key","Cryptographic proofs that can only be verified and validated by government-approved authorities"]}],"swag-merch":[{q:"BTCAccepted.org helps you find:",a:"Businesses that accept Bitcoin payments",wrong:["Bitcoin mining pools and hashrate marketplaces","Lightning node operators and payment routing hubs","Altcoin and stablecoin spot exchange platforms"]},{q:"Sats.host offers:",a:"Bitcoin-powered static website hosting",wrong:["Bitcoin cloud mining-as-a-service rentals","Hardware cold-storage wallet distribution","Identity-based KYC verification services"]},{q:'What annual Bitcoin conference is often called "the Super Bowl of Bitcoin"?',a:"Bitcoin Conference (formerly Miami/Bitcoin 2021)",wrong:["Consensus (the annual CoinDesk crypto industry conference)","DevCon (the Ethereum Foundation's annual developer summit)","ETHDenver (the largest Ethereum-focused hackathon and festival)"]},{q:"What is the significance of wearing an orange pill at Bitcoin conferences?",a:'Signifies being "orange pilled" - awakened to Bitcoin\\\'s importance',wrong:["It promotes a popular vitamin supplement brand that sponsors the Bitcoin conference","It identifies official conference staff members and volunteers on the event floor","It serves as a VIP lanyard granting holders priority access to all mainstage panels"]},{q:"What popular Bitcoin merchandise item satirizes central banking?",a:'"End the Fed" t-shirts and posters',wrong:["Bitcoin-branded ergonomic gaming chairs","Satoshi Nakamoto collectible action figures","ASIC miner miniature keychain replicas"]}],"apps-tools":[{q:"PPQ.ai lets you use AI models and pay with:",a:"Bitcoin per prompt - no subscription needed",wrong:["Monthly recurring credit card subscription billing","Ethereum gas fees via a MetaMask browser extension","Free access to models supported by targeted display ads"]},{q:"Angor is a platform for:",a:"Non-custodial Bitcoin crowdfunding",wrong:["Hosted cloud Bitcoin mining pool services","On-chain coin mixing for transaction privacy","Consumer-grade cold-storage hardware wallet sales"]},{q:"What website provides real-time visualization of the Bitcoin mempool?",a:"mempool.space",wrong:["blockchain.com","coinmarketcap.com","bitcoincharts.com"]},{q:"What popular hardware wallet supports both Bitcoin and Lightning?",a:"Coldcard and BitBox02",wrong:["Ledger Nano and Trezor","KeepKey and Passport","Foundation and SeedSigner"]},{q:"What full node implementation is the most widely used for running Bitcoin?",a:"Bitcoin Core",wrong:["Bitcoin Cash","Ethereum Classic","Ripple Node"]}],games:[{q:"Timechain Arcade offers:",a:"Free Bitcoin-themed video games",wrong:["Bitcoin cloud mining rental services","Automated crypto portfolio trading tools","Plug-and-play Bitcoin hardware wallet devices"]},{q:"CanYouBeatBitcoin.com is:",a:"An investing simulator comparing your picks to Bitcoin",wrong:["A live mining difficulty recalculation tool for professional Bitcoin miners","A self-custodial Bitcoin and Lightning Network mobile wallet application","An automated algorithmic trading bot for Bitcoin and altcoin spot markets"]},{q:"What type of Bitcoin games reward players with satoshis?",a:"Play-to-earn Lightning games",wrong:["Casino-style Bitcoin gambling sites","Console role-playing video games","Free mobile games monetized by banner ads"]},{q:"What popular Bitcoin trivia app lets users earn sats for answering questions?",a:"THNDR Games (like Bitcoin Bounce, Bitcoin Bay)",wrong:["Fortnite (which added sats reward drops in a 2022 seasonal battle pass)","Candy Crush Saga (which partnered with Lightning Network to pay out winners)","Minecraft (which features a Lightning sats plugin for Bitcoin-paying servers)"]},{q:"What is Zebedee known for in the Bitcoin gaming space?",a:"A platform enabling Lightning payments in games",wrong:["A producer of specialized ASIC Bitcoin mining hardware rigs","A centralized altcoin and stablecoin spot exchange platform","An Ethereum NFT marketplace for trading in-game digital collectibles"]}],"difficulty-adjustment":[{q:"How often does Bitcoin's difficulty adjustment occur?",a:"Every 2,016 blocks (approximately 2 weeks)",wrong:["Every 1,008 blocks (approximately 1 week)","Every 4,032 blocks (approximately 1 month)","Every 144 blocks (approximately 1 day)"]},{q:"What does the difficulty adjustment ensure?",a:"Blocks are found roughly every 10 minutes regardless of hash power changes",wrong:["Transaction fees stay constant regardless of how many transactions fill each block","Mining rewards automatically increase whenever total network hash rate grows","Block size scales automatically in response to changes in total hash power"]},{q:"Bitcoin's difficulty adjusts every:",a:"2,016 blocks (roughly every 2 weeks)",wrong:["Every single block as defined by Bitcoin consensus rules enforced by all full nodes","Once per year as defined by Bitcoin consensus rules enforced by all full nodes","Every 210,000 blocks (at each halving)"]},{q:"If miners leave the network, difficulty adjustment:",a:"Lowers the difficulty so blocks are found at the target rate",wrong:["Increases difficulty so remaining miners must work harder to find blocks","Has no effect, as blocks simply take longer to find each time","Automatically doubles the block subsidy to lure miners back"]},{q:"The target time between Bitcoin blocks is approximately:",a:"10 minutes",wrong:["5 minutes","60 minutes","30 seconds"]},{q:"What algorithm does Bitcoin use for difficulty adjustment?",a:"Direct calculation based on actual vs target time",wrong:["PID controller algorithm with feedback loops","Neural network prediction of future hash rate","Moving average of recent hash rate samples as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"How many blocks is the difficulty retarget period?",a:"2,016 blocks",wrong:["1,008 blocks","4,032 blocks","10,080 blocks"]},{q:"What causes hash rate oscillation between mining pools?",a:"Miners chasing short-term luck variance",wrong:["Scheduled Bitcoin Core software update cycles","Daily difficulty adjustment recalculations","Network communication delays between nodes"]},{q:"What variance measure describes pool mining luck?",a:"Statistical variance around expected block discovery",wrong:["Fixed reward percentage distributed to miners as defined by Bitcoin consensus rules enforced by all full nodes","Difficulty share ratio across pool participants","Network propagation delay between peer nodes as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"How long does a difficulty epoch typically last?",a:"Approximately 2 weeks",wrong:["Exactly seven days long","Approximately one month","Approximately four days"]}],nostr:[{q:"What does the Nostr acronym stand for?",a:"Notes and Other Stuff Transmitted by Relays",wrong:["Network of Secured Transactions and Relays","New Open Standard for Trustless Relay Networks","Node-Operated Social Transmission Registry"]},{q:"What makes Nostr unique from typical social media?",a:"Your identity is uncensorable and no single entity controls the platform",wrong:["It automatically pays users in Bitcoin proportional to the engagement they receive","It functions exclusively on mobile devices with no desktop interface available","It requires government-issued identity verification before any content can be published"]},{q:"What is a NIP in the Nostr ecosystem?",a:"A Nostr Implementation Possibility - a protocol specification for how clients and relays behave",wrong:["A Nostr Identity Protocol mapping public keys to verified human-readable display names","A standardised end-to-end encryption layer that secures private messages between Nostr users","A subscription fee structure charged by premium relay operators for publishing user events"]},{q:"Nostr uses cryptographic keys to:",a:"Allow users to own their identity without a central authority",wrong:["Earn new coins by mining blocks on the Nostr blockchain ledger","Encrypt all relay messages so that only the sender can read them","Create verifiable smart contracts between any two Nostr users"]},{q:"How is Nostr connected to Bitcoin?",a:"Many clients integrate Lightning for tips and payments",wrong:["Nostr events are written directly into Bitcoin blocks","You must own some Bitcoin to create a Nostr account","Nostr relays help verify Bitcoin transactions as well"]}],network_effects:[{q:"Bitcoin's network effect means:",a:"Each new user increases the value and utility for all existing users",wrong:["The internet gets faster and more resilient as each new node joins","Mining gets easier and cheaper for all participants as the network expands","Transaction fees trend toward zero as competition between miners increases"]},{q:"Why is Bitcoin's network effect considered a strong moat?",a:"It creates a self-reinforcing cycle of liquidity, security, and adoption that competitors cannot easily replicate",wrong:["Because international patents protect Bitcoin, preventing competitors from replicating its fundamental structure","Because government policy explicitly protects Bitcoin's market position against all competing cryptocurrency networks","Because Bitcoin uses proprietary encryption that makes it impossible for any competitor to successfully fork its code"]},{q:"What economic principle explains Bitcoin\\'s value increasing as more people use it?",a:"Metcalfe\\'s Law - network value proportional to connected users squared",wrong:["Moore\\'s Law, as specified in the original Bitcoin whitepaper released in 2008","Murphy\\'s Law, as specified in the original Bitcoin whitepaper released in 2008","Pareto Principle, as specified in the original Bitcoin whitepaper released in 2008"]},{q:"Metcalfe's Law applied to Bitcoin suggests:",a:"Its value grows proportionally to the square of its users",wrong:["The price will always increase linearly with total users","Only the first users receive any real financial benefit","Network effects only apply to social media platforms"]},{q:"What is the flywheel effect in Bitcoin adoption?",a:"More users attract more developers, merchants, and infrastructure, which attracts even more users",wrong:["Mining becomes progressively easier as each additional user contributes hash power to the network","Transaction fees steadily fall toward zero as more miners and users compete within the growing network","Bitcoin's price always rises directly whenever more users create wallets and start transacting"]}],governance:[{q:"Bitcoin governance is best described as:",a:"Rough consensus among users, developers, miners, and node operators",wrong:["A chief executive officer at the Bitcoin Foundation makes all key decisions","Miners vote on all proposed protocol changes and their votes are binding","A central Bitcoin Foundation sets and enforces all protocol-level rules"]},{q:"The Blocksize Wars demonstrated that:",a:"Users and node operators ultimately control Bitcoin's rules, not miners alone",wrong:["Miners hold absolute power and can unilaterally enforce any protocol rule change","Core developers can force any protocol change by releasing a new Bitcoin Core version","Bitcoin's protocol is immutably fixed and cannot be upgraded or changed in any way"]},{q:"What is the BIP process in Bitcoin?",a:"Bitcoin Improvement Proposals for suggesting protocol changes",wrong:["Bitcoin Investment Plan for funding protocol development initiatives","Blockchain Intellectual Property registration for Bitcoin core code","Banking Integration Protocol for financial network compliance"]},{q:"How is Bitcoin governed?",a:"Through rough consensus among users, developers, miners, and node operators",wrong:["By a board of directors at the official Bitcoin Foundation headquarters","Through proxy shareholder voting, similar to how a public corporation operates","By whoever owns the most Bitcoin, as majority ownership grants protocol rights"]},{q:"A BIP (Bitcoin Improvement Proposal) is:",a:"A formal document proposing changes to Bitcoin's protocol or processes",wrong:["A mandatory update which all full nodes must install to remain in consensus","A formal financial investment in Bitcoin's ongoing core protocol development","A bug report submitted to the Bitcoin Core support team for urgent review"]},{q:"Who can submit a Bitcoin Improvement Proposal (BIP)?",a:"Anyone in the Bitcoin community",wrong:["Only Bitcoin Core maintainers","Only miners with enough hash rate","Only officially registered developers"]},{q:"What activation method does BIP 9 use?",a:"Miner signaling with version bits during a defined window",wrong:["Node operators vote directly without miner input as defined by Bitcoin consensus rules enforced by all full nodes","Core developers set a flag day with no miner input as defined by Bitcoin consensus rules enforced by all full nodes","Miners and the SEC jointly approve the activation as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"BIP 8 improves on BIP 9 by adding what option?",a:'A "lock-in on timeout" (LOT=true) that forces activation even without miner majority',wrong:["A mandatory 95% node upgrade threshold that must be met before version bit signaling","An emergency pause mechanism letting any single mining pool block the activation","A two-thirds supermajority developer vote required before version bit signaling begins"]},{q:"What does UASF stand for?",a:"User-Activated Soft Fork",wrong:["Unified Active Soft Fork","Universal Auto Soft Fork","User Approval Soft Fork"]},{q:"What was Speedy Trial used for in Bitcoin?",a:"Taproot activation with a shortened signaling period",wrong:["SegWit activation with extended miner coordination","Lightning Network deployment across mainnet nodes","Difficulty adjustment algorithm changes and updates"]}],human_rights__social_justice_and_freedo:[{q:"Bitcoin supports human rights by:",a:"Providing censorship-resistant money that cannot be confiscated by authoritarian regimes",wrong:["Replacing all fiat currency-issuing governments with a decentralized digital monetary system","Eliminating global poverty immediately by providing everyone with a free Bitcoin wallet","Being administered by the United Nations as a neutral global reserve currency held in trust"]},{q:"Alex Gladstein advocates for Bitcoin because:",a:"It empowers people living under authoritarian regimes with financial freedom",wrong:["It makes buying stocks much easier for everyday investors in wealthy nations","It replaces the need for traditional banks for all citizens in wealthy countries","It was specifically designed as a protest instrument against monetary systems"]},{q:"How has Bitcoin helped activists in authoritarian regimes?",a:"By enabling uncensorable fundraising and protecting wealth from seizure",wrong:["By hiding their identity completely and anonymizing all transactions","By earning guaranteed interest through Bitcoin-integrated savings accounts","By creating new digital currencies that circumvent government monetary controls"]},{q:"How does Bitcoin help people under authoritarian regimes?",a:"It provides censorship-resistant money that governments cannot freeze",wrong:["It automatically reports suspicious transactions to financial authorities","It requires government-issued identity verification before any transaction","It only functions correctly in stable democratic countries worldwide"]},{q:"Alex Gladstein of the Human Rights Foundation argues that:",a:"Bitcoin is the most important tool for financial freedom globally",wrong:["Only wealthy developed nations can meaningfully benefit from Bitcoin","Bitcoin should be controlled by established human rights organizations","Proof of Stake is better for human rights than Proof of Work"]}],market_cap:[{q:"Bitcoin's market cap is calculated by:",a:"Current price multiplied by total coins in circulation",wrong:["Total daily transaction volume across all global exchanges","Number of active wallets times their average Bitcoin balance","Total mining revenue multiplied by the current block height"]},{q:"Why can Bitcoin's market cap potentially exceed gold's?",a:"Bitcoin is more portable, divisible, verifiable, and scarce than gold",wrong:["Bitcoin transactions are faster and carry lower fees than physical gold trading","Bitcoin is backed by a global reserve fund that guarantees its long-term value","Bitcoin's mining process ensures a steady new supply making it superior to gold"]},{q:"What metric compares Bitcoin\\'s market value to all other cryptocurrencies combined?",a:"Bitcoin Dominance Index",wrong:["Crypto Dominance Score","Digital Asset Share Index","Total Market Value Ratio"]},{q:"Bitcoin's market capitalization represents:",a:"The total value of all existing Bitcoin at the current price",wrong:["The maximum number of Bitcoin coins that will ever be created by mining","The total amount of money spent on Bitcoin mining hardware globally","The sum of all Bitcoin transactions recorded on the blockchain annually"]},{q:"If Bitcoin captured gold's market cap, each coin would be worth approximately:",a:"Over $500,000",wrong:["Around $100,000","Close to $200,000","Up to $50,000"]}],the_future:[{q:'What hypothetical event do Bitcoiners call "hyperbitcoinization"?',a:"A voluntary tipping point where Bitcoin displaces fiat as the world's dominant money",wrong:["A coordinated government transition where nations simultaneously adopt a Bitcoin standard","A planned protocol upgrade that makes Bitcoin the only globally compatible payment rail","A forced redenomination where central banks exchange fiat reserves for Bitcoin at par"]},{q:"Bitcoin is described as 'generational wealth' because:",a:"Its fixed supply and growing adoption may increase its value over decades",wrong:["Only family members can legally inherit and access a deceased holder's Bitcoin wallet","Bitcoin wallets automatically expire and reset to zero after 25 years of inactivity","Central banks officially guarantee Bitcoin's face value for 100 years as a reserve asset"]},{q:'What is the "digital scarcity" argument for Bitcoin\'s long-term value?',a:"Unlike any prior asset, Bitcoin's supply cap is enforced by math rather than human institutions",wrong:["Unlike gold, Bitcoin's scarcity is irrelevant because its supply can be subdivided without any limit","Bitcoin's value derives from a government-backed reserve fund, similar to how gold underpins fiat money","Since digital files can always be perfectly copied, Bitcoin cannot achieve true or lasting economic scarcity"]},{q:"What happens when the last Bitcoin is mined (~2140)?",a:"Miners will be compensated solely through transaction fees",wrong:["The Bitcoin network will gradually shut down due to the complete absence of block rewards","A governance vote will unlock and release an additional 21 million coins for continued mining","Mining rigs will continue to process transactions but miners will receive absolutely no compensation"]},{q:'Who coined the term "hyperbitcoinization"?',a:"Daniel Krawisz in a 2014 Nakamoto Institute essay",wrong:["Satoshi Nakamoto in the original 2008 Bitcoin whitepaper published online","Michael Saylor during a widely viewed 2020 MicroStrategy investor presentation","Andreas Antonopoulos in his widely read book Mastering Bitcoin second edition"]}],"orange-pilling":[{q:"'Orange-pilling' someone means:",a:"Convincing them to understand and adopt Bitcoin",wrong:["Selling them a diversified portfolio of altcoin investments","Sending them a small amount of free Bitcoin directly to their wallet","Registering them for an account on a centralized cryptocurrency exchange"]},{q:"The most effective way to orange-pill someone is often:",a:"Starting with the problem Bitcoin solves (broken money) rather than technical details",wrong:["Showing them historical Bitcoin price charts to demonstrate its impressive investment returns","Explaining the SHA-256 hashing algorithm and how it cryptographically secures the blockchain","Telling them to invest immediately before the next halving event inevitably drives prices upward"]},{q:'What does "orange pilling" someone mean?',a:"Educating them about Bitcoin until they understand its importance",wrong:["Literally giving them orange-colored vitamin supplement pills as an introductory gesture","Selling them Bitcoin mining hardware so they can independently earn their own coins","Setting up a Bitcoin wallet on their phone and depositing a small starter amount"]},{q:"What is the best approach when orange-pilling a skeptic?",a:"Start with their specific pain point (inflation, remittances, censorship) rather than technical details",wrong:["Show them historical price charts and assure them that Bitcoin investment always provides guaranteed returns","Pressure them into purchasing Bitcoin immediately before the next halving event drives up prices significantly","Begin by explaining the full UTXO model, Merkle trees, and proof-of-work consensus mechanism in complete detail"]},{q:"The most effective orange-pilling strategy is:",a:"Meeting people where they are and addressing their specific concerns",wrong:["Regularly posting Bitcoin price predictions and market analysis on social media platforms","Telling people they are making a serious financial mistake by not purchasing Bitcoin right now","Assuring friends and family that they will receive guaranteed returns on their Bitcoin investment"]},{q:'What is the "Socratic method" approach to orange-pilling someone about Bitcoin?',a:"Asking questions that lead them to discover Bitcoin's value themselves",wrong:["Citing ancient Greek philosophers like Aristotle who supposedly anticipated sound digital money","Requiring the person to read the entire Bitcoin whitepaper aloud before any discussion can begin","Engaging in aggressive economic debate with them until they finally concede that Bitcoin has value"]},{q:'What is "progressive disclosure" when introducing someone to Bitcoin?',a:"Starting with simple concepts they care about, then going deeper",wrong:["Showing them Bitcoin's full transaction history from genesis","Revealing your entire Bitcoin portfolio to build their trust","Disclosing all of Bitcoin's technical flaws upfront to seem honest"]},{q:"When orange-pilling family members, what is generally the most effective approach?",a:"Focus on what they care about - savings, retirement, their future",wrong:["Send them a lengthy three-hour technical podcast covering Bitcoin mining and cryptographic hashing","Purchase Bitcoin on their behalf without asking first and present it as a surprise financial gift","Bring the topic up at every family gathering until they eventually agree with your position on Bitcoin"]},{q:"What is one of the biggest mistakes people make when trying to orange-pill someone?",a:"Information overload - dumping too much detail at once",wrong:["Being too patient and waiting for them to ask questions","Starting with how Bitcoin helps people in other countries","Recommending they read a book about the history of money"]},{q:"Which book is widely considered the best starting point for orange-pilling someone interested in economics and sound money?",a:"The Bitcoin Standard by Saifedean Ammous",wrong:["Mastering Bitcoin by Andreas Antonopoulos","Programming Bitcoin by Jimmy Song as defined by Bitcoin consensus rules enforced by all full nodes","The Blocksize War by Jonathan Bier as defined by Bitcoin consensus rules enforced by all full nodes"]}],maximalism:[{q:"Bitcoin maximalism is the belief that:",a:"Bitcoin is the only cryptocurrency that truly matters as sound money",wrong:["You should invest your entire net worth in Bitcoin at every available opportunity","Bitcoin's technology should completely replace the entire global financial infrastructure","Bitcoin was specifically designed to be used exclusively by professional software developers"]},{q:"Maximalists argue altcoins are unnecessary because:",a:"Bitcoin's base layer plus additional protocol layers can serve all use cases",wrong:["Governments have legally classified most altcoins as unregistered securities requiring enforcement","Satoshi Nakamoto explicitly stated in early writings that all other cryptocurrencies were invalid","The global peer-to-peer network infrastructure can only support one active blockchain at any time"]},{q:"What is Bitcoin maximalism?",a:"The belief that Bitcoin will be the only cryptocurrency to achieve long-term dominance",wrong:["An investment strategy focused exclusively on altcoins in order to maximize portfolio gains","The practice of acquiring as much Bitcoin as possible regardless of any personal financial cost","A technical discipline requiring users to run multiple full Bitcoin nodes to support the network"]},{q:"Why do deep Bitcoin researchers tend to become maximalists?",a:"They realize no other project achieves true decentralization and immutability",wrong:["They receive financial compensation from Bitcoin-focused companies to publicly advocate for the protocol","Their limited exposure to alternative technologies prevents them from recognizing other viable options","Active participation in the Bitcoin developer forums technically requires holding and expressing maximalist views"]},{q:"What is the core argument of Bitcoin maximalists?",a:"Only Bitcoin achieves true decentralization and sound money; altcoins compromise on critical aspects",wrong:["Bitcoin should be formally declared the only legal tender globally, fully replacing all national fiat currencies","Any technology or platform that is not directly and exclusively related to Bitcoin is fundamentally worthless","True Bitcoin maximalists actively refuse to use internet services or any new technology created after 2009"]},{q:'What do Bitcoiners mean when they call "toxic maximalism" an immune response?',a:"Aggressive pushback against scams protects newcomers like an immune system",wrong:["Maximalists spread computer viruses to attack competing altcoin networks","Toxic maximalism is a disease Bitcoin developers are actively trying to cure","It means Bitcoin's code automatically rejects transactions from altcoins"]},{q:'What is the "altcoin opportunity cost" argument made by Bitcoin maximalists?',a:"Money spent on altcoins could have gone to Bitcoin, which outperforms long-term",wrong:["Altcoins are free to create so there is no real opportunity cost involved in holding them","Bitcoin maximalists believe that active altcoin trading actually increases Bitcoin's overall value","Opportunity cost is a fiat-era economic concept that simply does not apply to any digital assets"]},{q:"Why do Bitcoin-only companies (like Swan, River, and Unchained) choose not to support altcoins?",a:"They see promoting altcoins as ethically wrong since most will fail and harm users",wrong:["They currently lack the technical engineering capability needed to support other cryptocurrency tokens","Existing government regulations formally prohibit financial companies from offering multiple crypto assets","Supporting altcoins would significantly degrade the performance of their exchange and wallet software"]},{q:'What is the "ethical case" for Bitcoin maximalism?',a:"Promoting risky altcoins to unsophisticated investors causes real financial harm",wrong:["Bitcoin maximalists believe they hold a moral and even near-religious duty to spread global adoption","Ethics fundamentally require that all financial technologies be treated equally and without discrimination","The ethical argument holds that Bitcoin miners alone deserve to receive all cryptocurrency-related profits"]},{q:'How does Gresham\'s Law ("bad money drives out good") apply to the Bitcoin maximalism argument?',a:"People spend weak fiat and altcoins while hoarding Bitcoin as the hardest money",wrong:["Gresham's Law demonstrates that cheaper and more abundant altcoins will ultimately displace Bitcoin","It implies that world governments will eventually be forced to compel citizens to transact using Bitcoin","Gresham's Law is a principle that applies strictly to physical metal coinage and not to any digital currency"]}],developers:[{q:"Bitcoin Core is primarily written in:",a:"C++",wrong:["Python","JavaScript","Rust"]},{q:"Contributing to Bitcoin open source requires:",a:"Anyone can propose changes - no permission needed",wrong:["A formal computer science degree from an accredited and recognized university","Official written approval submitted to and granted by the Bitcoin Foundation","A paid annual developer license issued by the Bitcoin Core organization"]},{q:"Who is considered Bitcoin\\'s lead maintainer as of recent years?",a:"There is no formal leader; Bitcoin Core has multiple maintainers",wrong:["Satoshi Nakamoto, who continues to guide development quietly under an anonymous pseudonym","Vitalik Buterin, who oversees several major blockchain codebases including Bitcoin Core","Elon Musk, whose vocal public support grants him widely recognized informal authority over Bitcoin"]},{q:"What organization has historically funded Bitcoin Core development?",a:"MIT Digital Currency Initiative, Chaincode Labs, Brink, Spiral",wrong:["World Bank and United Nations joint digital finance development division","Federal Reserve's fintech research and digital payment systems innovation unit","Goldman Sachs and JPMorgan's jointly managed cryptocurrency development fund"]},{q:"Which version control system hosts Bitcoin Core's source code?",a:"Git",wrong:["SVN","Mercurial","Bazaar"]}],ham_radio:[{q:"Bitcoin transactions can be sent via ham radio, which means:",a:"Bitcoin can work without an internet connection",wrong:["Bitcoin nodes require a dedicated satellite dish to receive block data","Only licensed Bitcoin miners are permitted to broadcast transactions by radio","Transactions sent over radio waves are processed entirely without any network fee"]},{q:"How can Bitcoin transactions be sent without internet?",a:"Via ham radio operators broadcasting signed transactions",wrong:["Via physical mail containing paper-printed encrypted transaction codes","Via standard telephone voice calls encoded with audio signal sequences","Via satellite television broadcasts restricted to licensed subscriber dishes"]},{q:"What mesh network protocol has been used to broadcast Bitcoin transactions?",a:"Blockstream Satellite and goTenna mesh networks",wrong:["Standard Bluetooth Classic radio frequency mesh protocol","Near-field NFC contactless payment relay broadcast system","Zigbee low-power home automation wireless mesh network"]},{q:"What is the benefit of Bitcoin over ham radio?",a:"Censorship resistance even when governments shut down internet",wrong:["Significantly faster data transmission speeds than standard fiber optic connections","Much lower Bitcoin transaction fees compared to routing through normal internet relays","Superior performance when transferring large data files over very long geographic distances"]},{q:"Who demonstrated sending Bitcoin via ham radio in 2019?",a:"Rodolfo Novak co-founder of Coinkite",wrong:["Andreas Antonopoulos Bitcoin educator","Nick Szabo creator of the Bit Gold idea","Adam Back CEO of Blockstream company"]}],lightning_node:[{q:"Running a Lightning node allows you to:",a:"Route payments and earn fees while supporting the network",wrong:["Increase your hashrate and earn larger Bitcoin block rewards","Generate new Bitcoin directly without needing proof-of-work","Send anonymous transactions bypassing any network payment routing"]},{q:"What is a Lightning node?",a:"Software that routes payments on the Lightning Network using payment channels",wrong:["A dedicated hardware device that plugs directly into the Bitcoin mainchain","A specialized mining rig that processes Lightning Network computational tasks","A centralized server that exchanges run to settle off-chain Bitcoin balances"]},{q:"What do node operators lock up to open payment channels?",a:"Bitcoin as liquidity for routing payments",wrong:["Wrapped Ether tokens as collateral for channel liquidity","Fiat currency held in a custodial bank account","Proof-of-work computing power via mining hardware"]},{q:"What fee do Lightning routing nodes typically charge?",a:"Routing fees measured in milli-satoshis (very small fraction of a cent)",wrong:["A flat percentage of one percent applied to each full transaction amount","A fixed five dollar charge assessed on every individual Lightning payment","No fees are allowed since all routing is provided as a free community service"]},{q:"What is inbound liquidity for a Lightning node?",a:"The ability to receive payments based on funds others have locked with you",wrong:["Funds transferred directly from your bank account into a Lightning channel","Block rewards earned by miners that flow automatically into payment channels","Profits generated from automated trading on a centralized exchange platform"]}],stablecoins:[{q:"Stablecoins in the Bitcoin ecosystem are typically:",a:"Tokens pegged to fiat currency values, sometimes built on Bitcoin layers",wrong:["A special block subsidy paid to miners who meet the current difficulty target","Bitcoin units whose price is locked by the protocol so it cannot fluctuate","Central bank digital currencies issued by governments as a cash replacement"]},{q:"What backs the majority of USDT (Tether)?",a:"Commercial paper, cash equivalents, and other reserves (historically controversial)",wrong:["One hundred percent US Treasury bonds held in a fully audited government escrow","Physical gold bullion stored in Swiss vaults providing full one-to-one backing","Bitcoin held in cold storage wallets providing direct crypto-native collateral"]},{q:"What major risk do centralized stablecoins pose?",a:"Issuer can freeze funds or fail to maintain peg",wrong:["Mining them requires excessive computational power","Transaction fees make small payments impractical","Private key loss leaves users with no recourse"]},{q:"What caused USDC to depeg temporarily in March 2023?",a:"Exposure to failed Silicon Valley Bank",wrong:["A Bitcoin price drop below key support levels","A Lightning Network critical bug was discovered","Reports of Satoshi Nakamoto selling his coins"]},{q:"Stablecoins are NOT a threat to Bitcoin because:",a:"They are centralized IOUs that can be frozen, while Bitcoin is permissionless",wrong:["Stablecoins use the same decentralized proof-of-work technology that Bitcoin uses","Bitcoin automatically converts into stablecoins during market crashes to protect value","Stablecoins already have a larger total market capitalization than all Bitcoin"]}],consensus:[{q:"Bitcoin consensus means:",a:"All nodes agree on the state of the blockchain without a central authority",wrong:["All Bitcoin holders vote on transactions and the majority outcome is accepted","Miners single-handedly decide which transactions are valid without node verification","Government regulators review and approve each block before it joins the chain"]},{q:"What is Nakamoto Consensus?",a:"The combination of proof-of-work, longest chain rule, and economic incentives",wrong:["A proportional voting system where holders vote based on their Bitcoin holdings","A formal governance process managed by the Bitcoin Foundation's elected board","A consensus mechanism requiring all major exchanges to agree on the valid chain"]},{q:"Why does Bitcoin use the longest chain as the valid chain?",a:"Most proof-of-work indicates most energy/computational investment",wrong:["The chain is selected at random from all competing valid available chains","Shorter competing chains are discarded regardless of their computational work","Network users submit formal votes to determine which chain is accepted"]},{q:"Nakamoto Consensus achieves agreement by:",a:"Having nodes follow the longest valid proof-of-work chain",wrong:["Requiring all nodes to approve each transaction by peer majority vote","Letting the wealthiest network node unilaterally decide which blocks are valid","Using a central server to broadcast the correct chain to all network nodes"]},{q:"What happens if two miners find a valid block at nearly the same time?",a:"A temporary fork occurs and resolves when the next block is found",wrong:["Both competing blocks are permanently accepted and merged into the blockchain","The entire network automatically pauses until all nodes vote to resolve it","The block from the longest-running mining node always takes priority"]},{q:"What does finality mean in Nakamoto Consensus?",a:"Reversals become exponentially harder with each confirmation",wrong:["Transactions are instantly irreversible once broadcast to the first node","Miners periodically vote to confirm finality for each individual transaction","The longest chain is guaranteed to be correct and can never be altered"]},{q:"What are orphan blocks in Bitcoin?",a:"Valid blocks not included in the main chain",wrong:["Invalid blocks rejected by network nodes","Blocks that contain zero transactions inside","Alternative variants of the genesis block"]},{q:"What is selfish mining in Bitcoin?",a:"Withholding found blocks to gain unfair advantage",wrong:["Mining solo without joining any mining pool as defined by Bitcoin consensus rules enforced by all full nodes","Using only renewable energy sources for mining","Deliberately refusing to validate any transactions"]},{q:"What is the typical Bitcoin block propagation time?",a:"1-10 seconds globally",wrong:["About 60 seconds on average","Nearly instantaneous at all times","Approximately 10 full minutes"]},{q:"What was the FIBRE network designed to improve?",a:"Block propagation speed between miners",wrong:["Lightning Network payment routing as defined by Bitcoin consensus rules enforced by all full nodes","Wallet synchronization with nodes as defined by Bitcoin consensus rules enforced by all full nodes","Mining difficulty adjustment calculations"]}],open_source:[{q:"Bitcoin being open source means:",a:"Anyone can read, audit, and propose changes to the code",wrong:["The source code is private but free to download and run by anyone","Only developers pre-approved by the core team can view the source code","It simply means mining Bitcoin costs nothing in electricity or hardware"]},{q:"What license is Bitcoin Core released under?",a:"MIT License (open source)",wrong:["Proprietary commercial license","GPL v3 only as defined by Bitcoin consensus rules enforced by all full nodes","Patent-encumbered license"]},{q:"How can anyone contribute to Bitcoin Core?",a:"Submit pull requests on GitHub after code review",wrong:["Pay a required developer fee to the Bitcoin Foundation for access","Get a job at a bank that operates Bitcoin infrastructure nodes","Apply for an official open source contributor license from the team"]},{q:"What is the purpose of code review in Bitcoin development?",a:"To catch bugs and security issues before deployment",wrong:["To slow down the development process and ensure additional caution","To charge developers a submission fee for contributing their patches","To restrict source code visibility and keep it hidden from attackers"]},{q:"Why is peer review critical in Bitcoin Core development?",a:"It catches bugs and vulnerabilities before they reach production, since changes affect billions in value",wrong:["It is simply a legal formality mandated by the MIT open source license with no real security benefit","Only a single reviewer is required to approve even minor patches that touch critical consensus code","Peer review is unnecessary overhead that slows development without adding any meaningful security value"]}],coin_mixing_coinjoin_coin_control_utxo:[{q:"CoinJoin improves privacy by:",a:"Combining multiple users' transactions so individual spending is hard to trace",wrong:["Encrypting all blockchain transactions so their details are hidden from viewers","Permanently deleting transaction history from the public blockchain record","Inserting decoy transactions into blocks to confuse blockchain surveillance tools"]},{q:"What is CoinJoin?",a:"A privacy technique combining multiple users\\' transactions to break heuristics",wrong:["A digital token specifically designed to enable anonymous coin mixing services","A proprietary hardware wallet feature that encrypts transactions before broadcast","A standard exchange withdrawal option that obscures the origin of transaction funds"]},{q:"What does coin control allow Bitcoin users to do?",a:"Manually select which UTXOs to spend in a transaction",wrong:["Adjust the Bitcoin exchange rate displayed within your wallet software","Set the mining difficulty to reduce your node's energy consumption","Set the transaction confirmation speed across the whole network"]},{q:"What privacy benefit does proper UTXO management provide?",a:"Preventing address clustering and transaction graph analysis",wrong:["Increasing block rewards paid to miners for processing each new block","Reducing the transaction fees you pay to miners per network transfer","Speeding up how quickly your transactions receive their confirmations"]},{q:'What is "coin control" in a Bitcoin wallet?',a:"The ability to manually select which UTXOs to spend in a transaction for better privacy",wrong:["A government-mandated compliance program that monitors all Bitcoin spending for regulation","An exchange software setting that limits how much Bitcoin a user can purchase per day","A mining protocol feature that controls how frequently new blocks can be produced"]}],environment___energy:[{q:"Bitcoin mining's relationship with renewable energy is:",a:"Miners actively seek cheap renewable and stranded energy, incentivizing green energy development",wrong:["Miners are forced by government regulation to exclusively use coal-powered electricity","Renewable sources lack sufficient power density and reliability to support mining operations","Bitcoin mining has no connection to the broader global energy market whatsoever as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What percentage of Bitcoin mining comes from renewable energy (estimates)?",a:"Estimates range from 50-60% using renewable or stranded energy",wrong:["Zero percent, since all mining relies entirely on coal-fired power plants","One hundred percent clean energy, as all miners have fully committed to green power","Under ten percent because fossil fuels remain far cheaper than any renewable source"]},{q:'What is "stranded energy" in Bitcoin mining?',a:"Energy that would otherwise go to waste due to lack of transmission infrastructure",wrong:["Excess electricity from broken or malfunctioning solar panels at remote farm sites","Power left unused in large lithium battery banks that can no longer be discharged","Natural gas burned in industrial heating systems that is then converted to electricity"]},{q:"How does Bitcoin mining help stabilize electrical grids?",a:"Miners can rapidly reduce load during peak demand (demand response)",wrong:["By storing surplus electricity in large on-site battery arrays for future reuse","By donating a portion of their mining profits to local electrical utility companies","By funding construction of additional coal-fired baseload power plants in nearby areas"]},{q:"What common criticism about Bitcoin energy use is often misrepresented?",a:"Per-transaction energy cost (Bitcoin uses same energy regardless of transaction count)",wrong:["Carbon emissions per kilowatt-hour (most Bitcoin miners exclusively rely on fossil fuel grids)","Total annual electricity compared to countries (mining consumes more than some European nations)","Heat waste per mining farm (miners deliberately produce useless heat as a fundamental design flaw)"]}],austrian_school_of_economics:[{q:"The Austrian School of Economics relates to Bitcoin because:",a:"It advocates for sound money with limited supply, which Bitcoin embodies",wrong:["It was founded in Vienna to support government-managed monetary and central banking systems","It promotes central bank intervention and price controls to stabilize the broader economy","It predicts that private assets like Bitcoin will collapse without sovereign price support"]},{q:"Which Austrian economist emphasized the importance of sound money and criticized fiat?",a:"Ludwig von Mises and Friedrich Hayek",wrong:["John Maynard Keynes and Paul Samuelson","Milton Friedman and Anna Jacobson Schwartz","Karl Marx and Friedrich Engels as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"The Austrian School of Economics emphasizes:",a:"Sound money, free markets, and the dangers of central banking",wrong:["Government control of money supply and all centralized economic planning","The view that managed inflation is necessary and beneficial for long-run growth","The idea that central banks should print money freely to stimulate aggregate demand"]},{q:'Who wrote "The Theory of Money and Credit"?',a:"Ludwig von Mises",wrong:["John Maynard Keynes","Paul Krugman as defined by Bitcoin consensus rules enforced by all full nodes","Adam Smith as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:'Saifedean Ammous\' book "The Bitcoin Standard" argues that Bitcoin is the best form of money because:',a:"It is the hardest money ever created — no authority can inflate its supply",wrong:["It provides higher investment returns than gold over any comparable 10-year period","It is the only payment network capable of achieving true instant global settlement","A global coalition of central banks has adopted it as their primary reserve asset"]}],lindy_effect:[{q:'The term "Lindy Effect" was coined and popularized in its modern form by:',a:"Nassim Nicholas Taleb in his 2012 book Antifragile",wrong:["Satoshi Nakamoto in the Bitcoin whitepaper as defined by Bitcoin consensus rules enforced by all full nodes","Albert Goldman originally in 1964 as defined by Bitcoin consensus rules enforced by all full nodes","Benoît Mandelbrot in The Fractal Geometry of Nature"]},{q:"What is the Lindy Effect?",a:"The longer something survives, the longer its remaining life expectancy",wrong:["A statistical model measuring how quickly Bitcoin mining difficulty adjusts to hash rate","A type of cryptographic hash function used to verify Bitcoin block headers on-chain","An industry certification that labels hardware wallet firmware as officially secure"]},{q:"The Lindy Effect applies to non-perishable things. Which of these would it NOT apply to?",a:"A human being - biological organisms have decreasing life expectancy with age",wrong:["Bitcoin, which has survived and strengthened over 15+ years of relentless stress-testing","The concept of sound money, which has persisted across thousands of years of civilisation","The C++ programming language, widely used on critical systems since the early 1980s"]},{q:"What concept is closely related to Lindy Effect in Bitcoin?",a:"Antifragility - stress makes the system stronger",wrong:["Network effects - more adopters exponentially raise a coin's value","Reflexivity - rising prices reinforce further adoption and belief","Mean reversion - assets always drift back to their long-run average"]},{q:"Why is Bitcoin's 15+ year survival significant for the Lindy Effect?",a:"Demonstrates resilience to attacks, bugs, and regulatory pressure",wrong:["Proves the codebase is now too rigid and entrenched to accept meaningful future upgrades","Makes it technically obsolete compared to newer blockchain protocols built after 2018","Shows that its energy consumption has compounded past any level that society can sustain"]}],softwar:[{q:"Jason Lowery's Softwar thesis argues that:",a:"Proof-of-work is a form of digital power projection analogous to military power in the physical world",wrong:["Bitcoin mining hardware can be weaponized to disable foreign financial networks and enemy critical infrastructure","Software-defined systems will eventually replace all conventional military hardware, rendering standing armies obsolete","Bitcoin was secretly developed by the US Department of Defense as a covert mechanism to fund classified cyber operations"]},{q:'Who authored the "Softwar" thesis about Bitcoin?',a:"Major Jason Lowery of the US Space Force",wrong:["Lieutenant Colonel Michael Saylor, US Army","Commander Nick Szabo of the Naval Cyber Division","Professor Hal Finney of the West Point Academy"]},{q:"What is the core argument of the Softwar thesis?",a:"Proof-of-work is a form of kinetic power projection for cyberspace",wrong:["Bitcoin should be classified as regulated military-grade defense technology","Proof of stake provides superior deterrence for national security than proof-of-work","Bitcoin was designed by classified US intelligence agencies as an offensive cyberweapon"]},{q:"What does Softwar compare Bitcoin\\'s hash rate to?",a:"Physical military power projection and deterrence",wrong:["Social media influence and online narrative dominance","Stock market capitalization and daily trading volume","Aggregate banking reserves and credit market issuance"]},{q:"How does the Softwar thesis view Bitcoin mining in terms of national security?",a:"As a strategic asset that projects power in cyberspace, similar to how militaries project power in physical space",wrong:["As a dangerous liability exposing power grids to attack, and a threat that nations should ban to protect critical infrastructure","As a profit-seeking commercial activity with zero geopolitical significance, no different from operating commercial cloud servers","As a direct computational replacement for nuclear deterrence, where hash rate substitutes for megatons as the deterrence measure"]},{q:"What military rank is Jason Lowery?",a:"Major",wrong:["Colonel","Lieutenant","Captain"]},{q:"What university did Jason Lowery work with on his thesis?",a:"MIT",wrong:["Harvard","Stanford","Caltech"]},{q:"According to Softwar, what does proof of work project?",a:"Physical power through cyberspace",wrong:["Financial return on invested capital","Social consensus through majority voting","Network bandwidth and transaction throughput"]},{q:"How does Softwar view Bitcoin for nation-states?",a:"A strategic defense technology",wrong:["A replacement for fiat currency","A consumer payment system as defined by Bitcoin consensus rules enforced by all full nodes","An unregulated security asset"]},{q:"What energy concept is central to the Softwar thesis?",a:"Using energy to secure cyberspace property",wrong:["Lowering energy costs to maximize mining profitability margins","Shifting all global mining operations toward renewable energy sources","Profiting from arbitrage across regional electricity price differentials"]}],sidechains:[{q:"A Bitcoin sidechain is:",a:"A separate blockchain that is pegged to Bitcoin, enabling additional features while settling back to the main chain",wrong:["A parallel database that mirrors Bitcoin's full transaction history as a redundant off-site backup for disaster recovery purposes","An optimized fork of Bitcoin Core with larger blocks and faster confirmations designed for high-volume payment processing","An independent blockchain that permanently split from Bitcoin to pursue different governance, rules, and monetary policy goals"]},{q:"What is the Liquid Network?",a:"A federated sidechain enabling faster confidential Bitcoin transactions",wrong:["An Ethereum layer-2 scaling solution enabling fast and private ERC-20 token swaps","A cooperative mining pool where participants combine hash rate for smoother block rewards","An air-gapped hardware device that signs Bitcoin transactions offline using secure enclaves"]},{q:"What is RSK (Rootstock)?",a:"A Bitcoin sidechain supporting smart contracts with merged mining",wrong:["A major centralized cryptocurrency exchange and custody platform based in Russia","A tamper-resistant hardware device for securely storing Bitcoin and crypto private keys","A custodial Lightning wallet application designed for easy mobile Bitcoin payments"]},{q:"How are assets secured when moving to a sidechain?",a:"Through a federated peg locking bitcoin on mainchain",wrong:["By permanently destroying bitcoin in a verifiable on-chain burn transaction","By delegating full custody to a single centralized bridge institution","No formal security exists since sidechains operate entirely independently"]},{q:"What is a downside of federated sidechains compared to Bitcoin mainchain?",a:"Less decentralization due to reliance on federation members",wrong:["Higher transaction fees due to additional cross-chain bridging overhead costs","Slower block confirmation times than the Bitcoin mainchain baseline speed","No support for scripting languages or any programmable smart contract logic"]}],submarine_swap:[{q:"A submarine swap allows you to:",a:"Exchange on-chain Bitcoin for Lightning Bitcoin (or vice versa) trustlessly",wrong:["Mine Bitcoin using specialised deep-sea cooling rigs for better thermal efficiency","Send Bitcoin transactions without the internet using a mesh radio relay network","Convert Bitcoin into Ethereum through a cross-chain atomic bridge smart contract"]},{q:'Why is it called a "submarine" swap?',a:'On-chain is "above water" and Lightning off-chain is "below water" - you swap between the two',wrong:["The swap conceals funds below the blockchain visible layer before resurfacing on-chain","On-chain funds are submerged in a time-locked escrow vault beneath the mempool layer","The name comes from the HTLC diving beneath regular channel capacity during the swap"]},{q:"What enables submarine swaps to be trustless?",a:"HTLCs (Hash Time Locked Contracts)",wrong:["Centralized exchange custodial holding services","Bank wire settlement and confirmation process","Social media identity verification systems"]},{q:"What problem do submarine swaps solve?",a:"Moving funds between on-chain and Lightning without closing channels",wrong:["Automatically rebalancing mining pool difficulty when large hash rate enters or exits","Stabilising the exchange rate between on-chain BTC and Lightning-denominated sats","Recovering wallet access when a user loses their hardware device or written seed phrase"]},{q:"Alex Bosworth and Olaoluwa Osuntokun created submarine swaps while at which company?",a:"Lightning Labs",wrong:["Blockstream","Chaincode Labs","River Financial"]},{q:"What is a Loop Out in Lightning?",a:"Moving funds from Lightning back to on-chain",wrong:["Opening a new outbound Lightning payment channel","Receiving additional inbound Lightning payment capacity","Closing all existing active payment channels at once"]},{q:"What is Boltz Exchange known for?",a:"Trustless on-chain and Lightning swaps",wrong:["Running a proof-of-work Bitcoin mining pool","Operating a custodial centralized exchange","Selling proprietary Bitcoin hardware wallets"]},{q:"What makes submarine swaps trustless?",a:"Atomic hash time-locked contracts",wrong:["Multi-signature federated escrow wallets","Trusted third-party intermediary verification","Proof of stake validator consensus rules"]},{q:"How do submarine swaps differ from atomic swaps?",a:"They move between layers of the same chain",wrong:["Submarine swaps always require a trusted third party","Atomic swaps confirm significantly faster and cheaper","Submarine swaps always exchange between different coins"]},{q:"What enables cross-chain atomic swaps without intermediaries?",a:"HTLCs combining hashlock and timelock",wrong:["Trusted custodial escrow bridge services","Centralized exchange matching order books","Smart contract bytecode execution platforms"]}],supranational:[{q:'What does "supranational" mean in the context of Bitcoin?',a:"It transcends national borders and governments",wrong:["It is officially backed by the United Nations reserve fund","It requires international regulatory approval before use","It can only be used in certified cross-border transactions"]},{q:'What does it mean that Bitcoin is "supranational" money?',a:"It operates beyond any single nation's jurisdiction or control",wrong:["It is jointly governed by a coalition of United Nations member states","Only licensed financial institutions and governments are permitted to use it","It requires international banking licenses from the BIS to legally operate"]},{q:"Bitcoin settlement finality means:",a:"Once confirmed, transactions cannot be reversed",wrong:["Transactions can be disputed within 30 days","A central authority must approve each transaction","Only miners can verify if a transaction is final"]},{q:"Which of these best demonstrates Bitcoin's supranational nature?",a:"A citizen of any country can hold Bitcoin without a bank or government permission",wrong:["The United Nations officially declared Bitcoin legal tender for all member nations in 2021","All Bitcoin miners are legally required to register with their national financial regulators","Cross-border Bitcoin transfers require a valid SWIFT banking code to be processed successfully"]},{q:"What makes Bitcoin different from national currencies like the dollar or euro?",a:"No central bank can print more or manipulate its supply",wrong:["It is backed by physical gold reserves held in US Treasury vaults","It requires explicit government authorization for every transaction","It can only function within licensed and regulated online platforms"]}],organic:[{q:"Bitcoin grew organically because:",a:"It had no pre-mine, no ICO, and no marketing budget",wrong:["A major corporation funded its development as defined by Bitcoin consensus rules enforced by all full nodes","Governments agreed to adopt it simultaneously","Social media algorithms promoted it automatically"]},{q:"What makes Bitcoin's distribution unique among cryptocurrencies?",a:"Fair launch - no coins were pre-allocated to founders",wrong:["Satoshi kept 50% of all coins before launch as defined by Bitcoin consensus rules enforced by all full nodes","Venture capitalists funded the initial distribution","Coins were distributed based on national GDP as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"How has Bitcoin grown without traditional marketing?",a:"Through grassroots adoption and word-of-mouth from users",wrong:["Through massive multi-million dollar advertising campaigns across media","Through celebrity endorsements and paid influencer marketing deals","Through government subsidies and partnerships with central banks"]},{q:"What drives Bitcoin\\'s organic adoption in developing countries?",a:"Real need for inflation protection and remittance savings",wrong:["Central bank mandates requiring citizens to hold Bitcoin reserves","Corporate marketing campaigns funded by Silicon Valley venture firms","Mandatory school curriculum programs teaching Bitcoin to all students"]},{q:"What is the role of Bitcoin\\'s open source community?",a:"Volunteer developers contribute code without corporate hierarchy",wrong:["Paid employees of the Bitcoin Foundation who control all protocol decisions","They receive government salaries and grants to maintain the network","They own a large reserve of bitcoins used to fund development work"]}],programmable:[{q:"Bitcoin Script is intentionally limited because:",a:"Simplicity reduces attack surface and increases security",wrong:["Satoshi lacked the programming skills needed to build a more complex system","The blockchain physically cannot store or process complex instructions","It was designed as a temporary placeholder intended to be fully upgraded"]},{q:'What does "Turing-incomplete" mean for Bitcoin Script?',a:"It cannot run arbitrary programs or infinite loops",wrong:["It cannot process any transactions at all without external validation","It requires a separate computer to verify and execute each script","It can only handle one transaction per block due to stack memory limits"]},{q:"What makes Bitcoin programmable money?",a:"Bitcoin Script enables conditional spending and smart contracts",wrong:["Only licensed banks and financial institutions can write Bitcoin scripts","It executes Python code directly on nodes using a built-in interpreter","A central team of approved programmers controls all transaction logic"]},{q:"What are timelocks in Bitcoin?",a:"Conditions preventing spending until a specific time or block height",wrong:["Physical locks built into hardware wallets that prevent unauthorized access","Password requirements set by exchanges to restrict withdrawal timing","Banking hours restrictions preventing Bitcoin transfers outside business hours"]},{q:"What is a multisig (multi-signature) transaction?",a:"Requires multiple private keys to authorize spending",wrong:["Multiple separate transactions that are combined into a single payment","Multiple miners required to confirm and validate a single transaction","Multiple exchanges that must approve and relay the transaction together"]}],ordinals:[{q:"Bitcoin Ordinals allow:",a:"Inscribing data (images, text) directly on individual satoshis",wrong:["Creating new programmable tokens on top of the Bitcoin base layer","Speeding up transaction confirmation times by batching multiple payments","Reducing the total circulating supply of Bitcoin through burn mechanisms"]},{q:"Why are Ordinals controversial in the Bitcoin community?",a:"They increase block space demand and fees for financial transactions",wrong:["They permanently alter the 21 million supply cap by creating new satoshis","They require a contentious hard fork to implement, risking a chain split","They give miners exclusive control over which transactions get confirmed"]},{q:"What are Bitcoin Ordinals?",a:"A numbering system for satoshis enabling inscription of arbitrary data",wrong:["A type of altcoin token built on a separate sidechain alongside Bitcoin","A new mining algorithm designed to replace the proof-of-work consensus system","A specialized Lightning Network channel type used for streaming micropayments"]},{q:"What controversial use case emerged from Ordinals?",a:"BRC-20 tokens creating fungible tokens on Bitcoin",wrong:["Instant payment settlement bypassing the mempool fee market entirely","Hardware wallet security features using Ordinal-tracked satoshi keys","Private key encryption schemes using data inscribed on satoshis"]},{q:"What is the debate around Ordinals inscriptions?",a:"They use block space, potentially raising fees for regular transactions",wrong:["They exploit Bitcoin Script vulnerabilities to transfer funds from wallets","They embed malicious executable code that can compromise full nodes","They prevent mining from working by overloading nodes with inscription data"]}],geopolitics___macroeconomics:[{q:"Why is Bitcoin relevant to geopolitics?",a:"It provides a neutral monetary system outside any nation's control",wrong:["Major governments collectively control Bitcoin's code through an international treaty","Bitcoin mining is only legal in a small handful of G20-member countries","The United Nations actively regulates and monitors Bitcoin's international transfers"]},{q:'What is the "petrodollar" system?',a:"Oil is priced in US dollars, forcing global demand for the dollar",wrong:["A type of digital currency that is fully backed by physical oil reserves","A Bitcoin mining technique that relies exclusively on petroleum-powered generation","A special tax imposed on all Bitcoin transactions by major oil-producing nations"]},{q:"Which country was the first to adopt Bitcoin as legal tender?",a:"El Salvador in September 2021",wrong:["The United States in early 2022","Japan in November 2020 as defined by Bitcoin consensus rules enforced by all full nodes","Germany in December 2019 as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"How do sanctions-evading nations view Bitcoin?",a:"As a way to circumvent SWIFT restrictions and frozen reserves",wrong:["As a serious threat to local currency stability and existing capital controls","As a covert US surveillance tool designed to track all foreign transactions","As illegal under international law and actively banned by all sanctioned regimes"]},{q:"What macro trend drives Bitcoin adoption during inflation?",a:"Currency debasement making bitcoin\\'s fixed supply attractive",wrong:["Lower interest rates on Bitcoin savings accounts offered by regulated exchanges","Government subsidies distributed to citizens who hold verified Bitcoin savings","Strict bank account requirements that push unbanked users toward digital assets"]},{q:"What is the BRICS de-dollarization movement and how does it relate to Bitcoin?",a:"BRICS nations are reducing dollar dependence, creating demand for neutral reserves like Bitcoin",wrong:["BRICS nations jointly launched a Bitcoin mining pool to dominate block production and earn seigniorage","BRICS nations have collectively banned Bitcoin to shield their central bank digital currencies from competition","BRICS de-dollarization is complete because all five member nations have officially adopted Bitcoin as legal tender"]},{q:'What is the "strategic Bitcoin reserve" concept that multiple nations are exploring?',a:"Nations accumulating Bitcoin as a reserve asset alongside gold for its scarcity and hedge value",wrong:["A legal requirement for all nations to back their fiat currency reserves with a fixed proportion of Bitcoin","A binding UN mandate requiring every member country to hold at least one thousand Bitcoin in sovereign reserves","A coordinated IMF program where central banks systematically replace all existing gold reserves with Bitcoin"]},{q:'What is the "nation-state game theory" argument for Bitcoin adoption?',a:"Early adopter nations gain a massive strategic edge, pressuring others to follow or fall behind",wrong:["Nations that ban Bitcoin grow more economically powerful because they retain full control of their money supply","Game theory conclusively proves that no sovereign nation will ever voluntarily hold Bitcoin as a reserve asset","Nation-state game theory around Bitcoin only applies to countries that already possess nuclear weapons stockpiles"]},{q:"How do proponents respond to critics who say Bitcoin is used for sanctions evasion?",a:"Bitcoin's transparent public ledger makes transactions easier to trace than physical cash",wrong:["Many Bitcoin proponents openly admit that sanctions evasion represents its primary real-world use case today","All Bitcoin transactions are completely invisible and therefore undetectable by any government or agency","International sanctions do not legally apply to any digital assets under any existing international law"]},{q:"How do institutions like the IMF and World Bank view Bitcoin?",a:"Generally hostile - they've pressured nations like El Salvador to drop Bitcoin legal tender status",wrong:["The IMF and World Bank are secretly among the largest institutional Bitcoin holders, controlling millions of BTC","Both organizations have publicly and enthusiastically endorsed Bitcoin as the clear future of global reserve finance","The IMF originally created Bitcoin as a planned technical replacement for its existing Special Drawing Rights system"]}],"op-codes":[{q:"Bitcoin OP_CODES are:",a:"Instructions in Bitcoin's scripting language that define spending conditions",wrong:["Numerical error codes automatically returned to the sender when a transaction fails validation","Standardized codes used to transmit data and coordinate operations between competing mining pools","Secret backdoor commands embedded by Bitcoin core developers for emergency network maintenance"]},{q:"OP_RETURN allows:",a:"Embedding small amounts of arbitrary data in the blockchain",wrong:["Reversing a confirmed transaction and refunding bitcoin to the original sender","Returning stolen or lost Bitcoin to its rightful owner through a scripted rollback","Dynamically increasing the block size limit when sustained network demand is high"]},{q:"What is OP_CHECKSIG in Bitcoin Script?",a:"Verifies a digital signature against a public key",wrong:["Creates new bitcoins by triggering a scheduled coinbase reward mechanism","Encrypts the full transaction data before broadcasting it to the network","Connects nodes automatically to approved mining pools for transaction validation"]},{q:"What was the OP_RETURN controversy?",a:"Its limit was reduced to prevent blockchain bloat from non-financial data",wrong:["It was exploited by attackers to secretly drain funds from major custodial exchanges","A bug in OP_RETURN was discovered that allowed malicious miners to create unlimited bitcoins","An early OP_RETURN implementation bug halted all network transactions for several days"]},{q:"What did Taproot enable for Bitcoin opcodes?",a:"More flexible scripting through Schnorr signatures and Merkle branches",wrong:["Removal of all previous legacy script types and their replacement with simpler code","Full compatibility with Ethereum-style smart contracts through a cross-chain bridge opcode","Centralized approval of all new scripts by an elected committee of Bitcoin core developers"]},{q:"What would OP_CAT enable if re-enabled?",a:"Concatenation of data values in script",wrong:["Comparison of timestamp values across multiple simultaneous script branches","Multiplication of two numeric values within a single stack script operation","Direct verification of cryptographic signatures placed anywhere on the stack"]},{q:"What does OP_CHECKSIGFROMSTACK verify?",a:"Arbitrary message signatures on the stack",wrong:["Only standard transaction signatures derived from predefined ECDSA keypairs","Block header signatures that are submitted by miners to claim their block rewards","Lightning Network commitment signatures used for off-chain channel balance updates"]},{q:"What is Simplicity designed for in Bitcoin?",a:"Formal verification of smart contracts",wrong:["Faster transaction processing speeds","Simplified user wallet address formats","Reduced on-chain footprint of block data"]},{q:"What is a major limitation of Bitcoin Script?",a:"No loops or complex control flow",wrong:["Maximum of 100 opcodes per script","Cannot handle any signatures as defined by Bitcoin consensus rules enforced by all full nodes","Requires active internet access"]},{q:"Which script type was introduced with Taproot?",a:"P2TR (Pay to Taproot)",wrong:["P2SH (Pay to Script Hash)","P2WSH (Pay to Witness Script)","P2PKH (Pay to Pub Key Hash)"]}],public_key_vs_private_key:[{q:"Your Bitcoin public key is like:",a:"Your email address - you share it so people can send you Bitcoin",wrong:["Your password - keep it private so no one can access your funds","Your bank PIN code - used only by you to authorize payments","Your social security number - it proves and confirms your identity"]},{q:"If someone has your private key, they can:",a:"Spend all the Bitcoin controlled by that key",wrong:["Only read and view your full transaction history","Reset your wallet password and lock you out","Create new Bitcoin out of thin air freely"]},{q:"What is the relationship between private and public keys?",a:"Public keys are derived from private keys via one-way cryptographic function",wrong:["Private keys are distributed publicly so any node can verify transactions","Public keys encrypt the private key using symmetric cryptographic methods","They are mathematically identical values stored in just different formats"]},{q:"What should you do with your private keys?",a:"Keep them secret and secure, never share with anyone",wrong:["Publish them openly online for community verification","Email them to exchanges for secure account recovery","Print them on merchandise to promote Bitcoin adoption"]},{q:"What is the purpose of a public key?",a:"To receive bitcoin and verify signatures without revealing the private key",wrong:["To spend and send bitcoin to others without requiring any additional keys","To mine new blocks on the network and collect the associated block reward","To generate and derive the matching private key through mathematical means"]}],transaction_fees:[{q:"Bitcoin transaction fees are determined by:",a:"The size of the transaction in bytes and current network demand",wrong:["A fixed percentage of the total amount sent in each transaction","The total number of bitcoin units being sent in the transaction","The geographic distance between the sender and recipient addresses"]},{q:"When the mempool is full:",a:"Transactions with higher fees get confirmed first",wrong:["All transactions are rejected until the mempool clears","The block size limit is automatically increased","Transaction fees are fully refunded to all senders"]},{q:"What determines Bitcoin transaction fees?",a:"Transaction size in bytes and current network demand (mempool congestion)",wrong:["The total transaction amount in bitcoin sent to the recipient address","The sender's account reputation and transaction history with miners","Government regulatory requirements and compliance fees imposed on nodes"]},{q:"What is the mempool?",a:"A waiting area for unconfirmed transactions held by nodes",wrong:["A mining hardware pool where miners jointly operate equipment","A decentralized cryptocurrency exchange for peer-to-peer trading","A type of hardware Bitcoin wallet for offline secure storage"]},{q:"Why do fees spike during network congestion?",a:"Users compete for limited block space by bidding higher fees",wrong:["Miners arbitrarily raise fee requirements during busy periods","Bitcoin exchanges charge extra fees during periods of peak usage","The Bitcoin supply shrinks due to an accelerated halving schedule"]}],philosophy:[{q:'"Don\'t trust, verify" means:',a:"Run your own node to independently verify all Bitcoin rules",wrong:["Never use Bitcoin because its security model cannot be trusted","Only trust exchanges that are licensed and government-regulated","Always verify your identity before making any Bitcoin transaction"]},{q:'The concept "Bitcoin is Time" by Gigi suggests:',a:"Bitcoin creates a decentralized clock through proof of work",wrong:["Bitcoin transactions can be rolled back using timestamp proofs","Bitcoin was invented to help people save and manage their time","Bitcoin mining depends on GPS-synchronized atomic clock networks"]},{q:"What is the cypherpunk movement that birthed Bitcoin?",a:"Advocates for privacy through cryptography and code over trust",wrong:["Bankers advocating for digitized central bank money and payments","Game developers creating virtual in-game currencies and economies","Government officials promoting digital tracking of all transactions"]},{q:'What does it mean that Bitcoin had a "fair launch"?',a:"No pre-mine, no ICO - anyone could mine from day one on equal terms",wrong:["The government approved it as legal tender before any public launch","Satoshi pre-distributed coins equally to all early registered users","A public committee reviewed and officially certified the genesis block"]},{q:'What does Bitcoin\\\'s "monetary policy" refer to?',a:"Fixed supply schedule with predictable issuance rate until 21 million",wrong:["Central bank interest rate policies that control inflation and growth","Government fiscal spending policies that regulate how money is issued","Investment fund allocation strategies used by major asset managers"]},{q:"Who wrote the Cypherpunk Manifesto?",a:"Eric Hughes",wrong:["Timothy May","Julian Assange","Nick Szabo"]},{q:"What concept did Timothy May advocate for in the Crypto-Anarchist Manifesto?",a:"Using cryptography to protect individual privacy",wrong:["Building centralized digital currency systems","Government regulation of all encryption tools","Corporate ownership of communication networks"]},{q:"What was Nick Szabo's Bit Gold concept?",a:"A digital collectible using proof of work",wrong:["A stablecoin fully backed by physical gold","A centralized government digital currency","A Lightning-style payment channel design"]},{q:"What did Wei Dai propose with b-money?",a:"Anonymous digital cash with decentralized minting",wrong:["A blockchain system with standard mining reward schedules","A central bank platform to control digital currency issuance","A gold-certificate system for tracking physical gold ownership"]},{q:"What was Hal Finney's famous contribution to Bitcoin?",a:"Received the first Bitcoin transaction from Satoshi",wrong:["Co-authored the original Bitcoin whitepaper with Satoshi","Invented the SHA-256 hashing algorithm for Bitcoin mining","Launched the very first Bitcoin exchange for public trading"]}],halving:[{q:"The Bitcoin halving occurs every:",a:"210,000 blocks (approximately every 4 years)",wrong:["Once every calendar year, on or around January 3rd","Every 100,000 blocks mined on the network","Whenever the market price of Bitcoin doubles in value"]},{q:"After the 2024 halving, the block reward is:",a:"3.125 BTC per block",wrong:["6.25 BTC per block","1.5625 BTC per block","50 BTC per block"]},{q:"The halving is significant because it:",a:"Mathematically enforces Bitcoin's decreasing supply issuance",wrong:["Doubles the total circulating supply of Bitcoin in the market","Reduces the number of active miners by half temporarily","Changes Bitcoin's proof-of-work consensus mechanism entirely"]},{q:"What happens during a Bitcoin halving?",a:"Block reward paid to miners is cut in half",wrong:["Transaction fees are automatically doubled for users","The total circulating supply of Bitcoin doubles","The Bitcoin mining difficulty level also halves"]},{q:"When will the final bitcoin be mined?",a:"Around year 2140 when all 21 million are issued",wrong:["Around year 2025 when the block subsidy drops to zero","Around year 2040 at the current pace of new block mining","Mining never ends because rewards continue indefinitely"]}],bitcoin_vs_real_estate:[{q:"What are the inflation-adjusted annual returns of US real estate over a full century?",a:"Approximately 0–2% real annual returns after accounting for inflation, far below the impressive nominal figures typically advertised by the industry",wrong:["Approximately 6–8% real annual returns after inflation, making residential property the most reliable long-term wealth preservation asset available","Approximately 4–5% real annual returns after inflation, driven primarily by land scarcity in growing metropolitan and coastal urban areas","Approximately 3–4% real annual returns after inflation, compounding consistently across all US regional markets over every significant historical period"]},{q:"What ongoing costs does real estate ownership typically impose on investors?",a:"1–4% of property value annually in maintenance costs alone, plus additional property taxes, insurance premiums, and management fees on top of that",wrong:["Less than 0.5% of property value annually, making residential real estate the most cost-efficient long-term store of value among all asset classes","Exactly 2% of property value annually, standardized by industry actuarial formulas and applied uniformly across all residential property types","5–10% of property value annually for commercial properties only; well-maintained residential homes carry negligible operating costs once fully paid off"]},{q:"How does Bitcoin's liquidity compare to real estate when investors need to exit a position?",a:"Bitcoin trades 24/7 globally with settlement in minutes; real estate typically requires 30–90 days to sell and incurs 5–10% in transaction costs",wrong:["Real estate sells faster than Bitcoin in most markets because institutional buyers routinely complete off-market transactions within 48 business hours","Both assets have similar liquidity profiles since Bitcoin's extreme volatility makes it practically impossible to exit large positions at fair market value","Bitcoin and real estate carry comparable transaction costs since major crypto exchanges charge 5–7% fees on high-value liquidation orders"]},{q:"How does real estate use leverage, and what risk does that introduce?",a:"Real estate commonly uses mortgage leverage to amplify gains, but this equally amplifies losses during price downturns and can wipe out equity entirely",wrong:["Real estate leverage is capped by regulation at 20% of property value, making catastrophic leveraged losses virtually impossible under normal conditions","Real estate leverage always benefits owners long-term because national property values have never declined over any rolling 10-year historical period","Leverage risk applies only to commercial real estate; owner-occupied residential mortgages are federally insured against any significant loss of principal"]},{q:"Can Bitcoin be transferred internationally as easily as real estate can be conveyed between parties?",a:"Bitcoin settles globally across borders in minutes with no intermediaries required; real estate is geographically immovable and cannot cross borders at all",wrong:["Both assets are equally difficult to transfer internationally due to strict capital controls and harmonized anti-money-laundering regulations worldwide","Real estate transfers more easily across some international jurisdictions because standardized legal frameworks exist under international property law treaties","Bitcoin international transfers face the same title verification and escrow delays as real estate due to mandatory blockchain finality confirmation periods"]},{q:"How does Bitcoin differ from real estate when it comes to government seizure risk?",a:"Property can be seized through eminent domain, tax liens, or civil forfeiture by governments; properly secured self-custodied Bitcoin cannot be confiscated",wrong:["Both assets are equally vulnerable to government seizure since courts can subpoena Bitcoin private keys the same way they can seize titled property","Real estate is better protected from seizure than Bitcoin because constitutional property rights provide stronger legal safeguards against government confiscation","Bitcoin is more vulnerable to seizure than real estate since regulated exchanges are required to freeze accounts and comply with government asset orders"]},{q:"How does Bitcoin's divisibility compare to real estate for investors with limited capital?",a:"Bitcoin is divisible down to 1 satoshi (0.00000001 BTC), allowing fractional purchases at any size; you cannot sell 0.01% of a house to raise cash",wrong:["Real estate through REITs is more divisible than Bitcoin, which enforces a minimum practical transaction size of 0.001 BTC on most networks","Both assets are equally accessible to small investors since modern fractional ownership platforms let people buy proportional shares of any property","Real estate is more accessible to capital-constrained investors because government programs allow property acquisition with as little as 1% down payment"]},{q:"How does Bitcoin's geographic risk profile differ from that of real estate?",a:"Real estate values depend entirely on local economies and geography; Bitcoin is a global asset uncorrelated with any specific regional market or jurisdiction",wrong:["Bitcoin and real estate are highly correlated hard assets that both respond identically to global CPI data, Federal Reserve rate changes, and currency debasement cycles","Bitcoin actually carries more geographic concentration risk than real estate because the majority of all mining activity is located in just two or three countries","Major global-city real estate markets are largely uncorrelated with local economic conditions and behave identically to fully global assets like commodity futures"]},{q:"How has Bitcoin performed relative to real estate over any 4-year or longer holding period?",a:"Bitcoin has outperformed real estate by an enormous margin over every 4-year or longer holding period across its entire existence as an asset class",wrong:["Real estate has consistently outperformed Bitcoin on a risk-adjusted basis over 4-year holding periods due to its substantially lower price volatility","Bitcoin and real estate have delivered nearly identical total returns over 4-year periods once leverage, tax benefits, and rental income are properly included","Bitcoin has outperformed real estate only in exceptional bull market cycles; most 4-year holding period comparisons show highly mixed and inconclusive results"]},{q:"What happened to real estate values during hyperinflation in countries like Venezuela, Zimbabwe, and Lebanon?",a:"Real estate also lost value in hard money terms during hyperinflation across Venezuela, Zimbabwe, and Lebanon; Bitcoin preserved purchasing power for those who held it",wrong:["Real estate proved to be the most reliable inflation hedge in Venezuela and Zimbabwe, consistently outperforming gold, foreign currency, and every other measured asset class","Real estate fully retained its value in all documented hyperinflationary environments, since physical property cannot be devalued by money printing or currency collapse","Real estate outperformed Bitcoin in hyperinflationary countries because local governments banned cryptocurrency exchanges and blocked all digital asset transactions"]}],bitvm:[{q:"What does BitVM enable on Bitcoin without requiring a protocol change?",a:"Arbitrary computation verification through fraud proofs",wrong:["Turing-complete smart contracts executed by miners","On-chain virtual machine execution like the EVM as defined by Bitcoin consensus rules enforced by all full nodes","Zero-knowledge proof generation inside Bitcoin Script"]},{q:"BitVM uses which computational model to verify off-chain computation?",a:"An optimistic model with prover claims and verifier challenges",wrong:["A zero-knowledge model where proofs are posted each block","A consensus model where all nodes re-execute computation","A federated model where trusted signers attest to results"]},{q:"In BitVM, what is the fundamental logic gate used to represent any computable function?",a:"NAND gates",wrong:["AND gates","XOR gates","NOR gates"]},{q:"Who proposed the original BitVM whitepaper?",a:"Robin Linus",wrong:["Peter Todd","Jeremy Rubin","Andrew Poelstra"]},{q:"How does BitVM2 improve upon the original BitVM design?",a:"It reduces on-chain transactions needed for dispute resolution",wrong:["It adds Turing-complete execution directly on the base layer","It eliminates the need for any verifier role in the protocol","It requires a Bitcoin soft fork to enable several needed opcodes"]}],"block_time-block-size":[{q:"Why did Satoshi choose approximately 10 minutes for Bitcoin's target block time?",a:"It balances throughput with time needed for global block propagation",wrong:["It was arbitrary with no real technical justification behind it","Faster blocks would make mining unprofitable due to power costs","It matches the average time needed for international wire transfers"]},{q:"What is the difference between block weight and block size in Bitcoin?",a:"Weight counts witness bytes at a discount versus non-witness bytes",wrong:["Block weight and block size are identical with different names","Block weight measures computational effort to validate a block","Block weight only applies to Lightning Network transactions"]},{q:"What is the maximum block weight allowed by Bitcoin's consensus rules?",a:"4 million weight units (4 MWU)",wrong:["1 megabyte of raw data","8 million weight units (8 MWU)","2 million weight units (2 MWU)"]},{q:"Why does SegWit give witness data a discount in the block weight calculation?",a:"Witness data costs less for nodes to process, incentivizing adoption",wrong:["Witness data is encrypted and takes up less physical storage","The discount was a political compromise with no technical basis","Witness data is stored temporarily then deleted after 100 blocks"]},{q:'What is "blockspace economics" in Bitcoin?',a:"The fee market where users bid for limited space in each block",wrong:["A government program subsidizing mining in renewable energy zones","The cost of running a full node in electricity and bandwidth","A pricing model used for Lightning Network channel capacity"]}],burn_bitcoin:[{q:"What is the maximum amount of data that can be stored in an OP_RETURN output?",a:"80 bytes",wrong:["40 bytes","160 bytes","1000 bytes"]},{q:"What does it mean for Bitcoin to be provably unspendable through OP_RETURN?",a:"The output has no valid script path to spend it",wrong:["It requires a special private key to spend","It can only be spent after 100 confirmations","It is temporarily locked until a timelock expires"]},{q:"Roughly how many Bitcoin are estimated to be permanently lost or burned?",a:"Between 3-4 million BTC",wrong:["Less than 1 million BTC","Over 10 million BTC","Exactly 1 million BTC"]},{q:"What type of Bitcoin address output is provably unspendable with no script?",a:"Bare multisig with invalid pubkeys",wrong:["Standard P2PKH legacy address output scripts","Wrapped P2SH redeem script hash outputs","Native segwit P2WPKH address formats"]},{q:"What is proof of burn in the context of cryptocurrency?",a:"Demonstrating coins were sent to an unspendable address",wrong:["Mining blocks without ever receiving any block rewards","Permanently deleting the private keys associated with a wallet","Sending coins to a wallet address belonging to a person who has died"]}],"ctv-covenants":[{q:"What does BIP-119 (CheckTemplateVerify) allow a Bitcoin output to do?",a:"Commit to a specific future transaction template for spending",wrong:["Execute arbitrary smart contract code when it is spent","Lock funds until a specific block height has been reached","Require multiple signatures from different keys to spend"]},{q:'What is a "covenant" in the context of Bitcoin?',a:"A restriction on how a UTXO can be spent in the future",wrong:["A multisig arrangement between federation member nodes","A legal agreement between Lightning channel counterparties","A time-locked contract that expires after a set period"]},{q:'What Bitcoin use case does CTV enable through "congestion control"?',a:"Batching many payments into one transaction claimable later",wrong:["Auto-adjusting fees based on current mempool congestion","Throttling transactions a wallet can send within a block","Limiting block size during periods of high network load"]},{q:"What is OP_VAULT designed to provide using covenants?",a:"Time-delayed withdrawals with an emergency clawback option",wrong:["A decentralized exchange built for trustless atomic swaps","Cold storage that auto-moves funds to hardware wallets","Multi-party escrow designed for marketplace transactions"]},{q:"Why are covenants considered controversial by some Bitcoiners?",a:"They could enable coin censorship or spending blacklists",wrong:["They require a hard fork that would split the network","They make all transactions public and remove user privacy","They increase block size beyond what nodes can handle"]}],cycles:[{q:"What drives Bitcoin's historically observed ~4-year market cycle?",a:"The halving, which cuts new supply in half every ~4 years",wrong:["The theory that each mining difficulty cycle gets shorter as ASIC hardware improves each year","A proposal from core developers to extend the halving interval from four years to eight years","The idea that Bitcoin transaction confirmation times increase significantly with each passing year"]},{q:"How does the Gartner Hype Cycle apply to each Bitcoin halving era?",a:"Each cycle shows trigger, peak hype, disillusionment, then recovery to a plateau",wrong:["Bitcoin skips disillusionment because the price only goes up long-term","The Gartner Hype Cycle only applies to new tech products, not currencies","Each Bitcoin cycle follows the exact same price pattern as the last one"]},{q:'What is the "lengthening cycles" debate in Bitcoin?',a:"The theory that each bull run takes longer to peak with smaller percentage gains",wrong:["The theory that mining cycles get shorter as new hardware generations get faster","A proposal to extend the block halving period from four years to eight years","The idea that Bitcoin transaction confirmation times increase noticeably every year"]},{q:"Which on-chain metrics are commonly used to analyze Bitcoin market cycles?",a:"MVRV, NUPL, and the Pi Cycle Top indicator",wrong:["GDP growth, unemployment, and consumer price index","Twitter followers, Google Trends, and Reddit subs","Block size, node count, and developer commit stats"]},{q:'What is the "diminishing returns" theory in Bitcoin cycles?',a:"Each cycle's percentage gain shrinks, though absolute highs keep rising",wrong:["Returns are accelerating each cycle with larger percentage gains","Bitcoin will eventually produce negative returns in every cycle","It refers to decreasing energy efficiency of mining each cycle"]}],derivation_path:[{q:"What does a BIP-32 HD (Hierarchical Deterministic) wallet allow you to do?",a:"Generate unlimited key pairs from a single master seed",wrong:["Store multiple cryptocurrencies in one single private key","Recover funds without a seed phrase using only email","Connect directly to the network without running a node"]},{q:"In the derivation path m/84'/0'/0'/0/0, what does the \"84\" represent?",a:"BIP-84, the Native SegWit (bech32) address standard",wrong:["The year 1984 when public key crypto was standardized","The 84th account stored inside this particular wallet","The total number of addresses that can be derived"]},{q:"Which BIP defines the derivation path standard for Taproot (bc1p) addresses?",a:"BIP-86",wrong:["BIP-84","BIP-49","BIP-44"]},{q:"Why is sharing an xpub (extended public key) a privacy concern?",a:"It lets anyone see all addresses and balances from that account",wrong:["It allows someone to spend your Bitcoin without the private key","It broadcasts your seed phrase to every node on the network","It reveals your real-world name and identity on the blockchain"]},{q:'What is the "gap limit" in HD wallet address discovery?',a:"How many consecutive unused addresses are checked before stopping",wrong:["The maximum number of addresses a wallet can generate total","The required time delay between each new address generation in a wallet","The minimum allowed gap between two UTXOs when building a transaction"]}],dlcs:[{q:"In a Discreet Log Contract (DLC), what role does an oracle play?",a:"It signs a real-world outcome that determines how the contract pays out",wrong:["It holds the funds in escrow until both parties agree on the result","It executes smart contract code on a sidechain to settle the bet","It mines the specific transaction that settles the contract on-chain"]},{q:'What cryptographic technique makes DLCs "discreet" - invisible to the oracle?',a:"Adaptor signatures that use the oracle's attestation privately",wrong:["Zero-knowledge proofs that hide the contract from participants","Ring signatures that mix the contract with unrelated transactions","Homomorphic encryption that processes data without decrypting it"]},{q:"What is a common real-world use case for Discreet Log Contracts?",a:"Financial derivatives and betting settled by price or event data",wrong:["Decentralized file storage using the Bitcoin network as a backend","Privacy-preserving identity verification on the Bitcoin blockchain","Automated market making for Lightning Network liquidity pools"]},{q:"Why is the oracle in a DLC considered more trustworthy than traditional smart contract oracles?",a:"The oracle doesn't know the contract exists or what depends on it",wrong:["The oracle stakes Bitcoin collateral that is slashed if it lies","Multiple oracles must all agree before any payout can occur","The oracle runs inside a trusted execution environment on-chain"]},{q:"DLC.Link enables Discreet Log Contracts to be used primarily for what purpose?",a:"Bridging Bitcoin as collateral into DeFi without giving up custody",wrong:["Mining pool payout distribution based on individual hash rate","Decentralized name registration powered by the Bitcoin base layer","Cross-chain atomic swaps between Bitcoin and Ethereum directly"]}],"dollar-bitcoin_milkshake_theory":[{q:'Who originated the "Dollar Milkshake Theory"?',a:"Brent Johnson of Santiago Capital",wrong:["All fiat currencies collapse simultaneously and get replaced by Bitcoin as the global reserve asset overnight","The dollar weakens progressively as other major currencies collectively strengthen against it over decades","Central banks secretly coordinate to create and adopt a single supranational global digital currency"]},{q:"What is the core thesis of the Dollar Milkshake Theory?",a:"The dollar strengthens by sucking up global liquidity while other fiat currencies weaken",wrong:["Every major fiat currency collapses simultaneously while Bitcoin absorbs the resulting capital","The dollar steadily weakens as other currencies collectively gain strength against it globally","Major central banks coordinate in secret to jointly create and adopt a single global currency"]},{q:'What is the "dollar strength paradox" in the Milkshake Theory?',a:"The dollar gets stronger vs other currencies while losing purchasing power vs hard assets",wrong:["A strong dollar always reliably causes the Bitcoin price to fall proportionally in tandem","Dollar strength is a reliable indicator that the US economy is genuinely healthy and growing","Nobody genuinely wants to hold dollars but every country still needs them to service debts"]},{q:"How does Bitcoin fit into the Dollar Milkshake Theory's endgame?",a:"After the dollar absorbs global liquidity, Bitcoin becomes the ultimate fiat exit",wrong:["Bitcoin is irrelevant to the Milkshake Theory because it isn't classified as a fiat currency","Bitcoin collapses alongside weaker currencies as the dollar absorbs all global liquidity first","The theory explicitly predicts that Bitcoin gets banned and eventually replaced by CBDCs"]},{q:"Why does global dollar demand play a central role in the Milkshake Theory?",a:"Trillions in dollar-denominated debt forces nations to buy dollars, strengthening it",wrong:["Global dollar demand is declining rapidly as nations actively de-dollarize","Dollar demand is only relevant to US domestic economic transactions and bilateral trade","The theory argues that global dollar demand is irrelevant and only total money supply matters"]}],"el-salvador":[{q:"What was the Chivo wallet in El Salvador's Bitcoin adoption?",a:"A government-issued Lightning wallet that gave citizens $30 in Bitcoin",wrong:["A private hardware wallet manufactured locally in El Salvador","An exchange platform where Salvadorans could trade altcoins","A banking app that only supported US dollar-based transactions"]},{q:'What is "Bitcoin Beach" and why is it significant to El Salvador\'s Bitcoin story?',a:"El Zonte - a village that built a grassroots Bitcoin economy before the national law",wrong:["A luxury resort in San Salvador that exclusively accepts Bitcoin payments","A government-built tourist attraction designed to promote Bitcoin adoption","A cryptocurrency exchange headquartered on the Salvadoran coastal region"]},{q:"What was President Bukele's core strategy behind making Bitcoin legal tender?",a:"Financial inclusion for the unbanked, foreign investment, and cheaper remittances",wrong:["Replacing the US dollar entirely with Bitcoin as El Salvador's sole legal currency","Mining Bitcoin at industrial scale using El Salvador's largely untapped natural oil reserves","Creating a government-controlled national cryptocurrency designed to replace Bitcoin"]},{q:"How did the World Bank and IMF respond to El Salvador's Bitcoin law?",a:"They pushed back - the World Bank refused help and the IMF warned of risks",wrong:["Both organizations fully endorsed and helped fund the entire initiative","The IMF designed and helped build the Chivo wallet infrastructure","The World Bank provided a $500 million loan specifically for adoption"]},{q:"How did Lightning Network adoption benefit El Salvador's economy?",a:"It enabled fast, near-free payments and remittances, cutting out costly services",wrong:["Lightning was not used - only on-chain Bitcoin transactions were supported","Lightning made transactions faster but significantly more expensive overall","El Salvador banned Lightning in favor of on-chain-only Bitcoin payments"]}],"extension-blocks":[{q:"What are extension blocks in Bitcoin?",a:"Additional block space running alongside the main chain without changing it",wrong:["Larger blocks created by increasing the block size limit via a hard fork","Blocks reserved exclusively for Lightning Network channel operations","Compressed blocks that store only transaction hashes to save space"]},{q:"How do extension blocks differ from a traditional soft fork upgrade?",a:'Old nodes see extension transactions as "anyone-can-spend" outputs',wrong:["Extension blocks require all nodes to upgrade or be forked off the network","Extension blocks reduce the block size to improve network decentralization","Extension blocks are identical to soft forks but use a different label"]},{q:'What is the "space chain" concept related to extension blocks?',a:"A separate chain whose block space is auctioned via the main chain",wrong:["A satellite network that broadcasts Bitcoin blocks from orbit","A virtual reality environment where Bitcoin nodes operate in 3D","A specialized blockchain optimized for storing files over 4MB"]},{q:"What is a key trade-off of extension blocks?",a:"Non-upgraded nodes cannot fully validate extension block transactions",wrong:["All miners must upgrade their hardware simultaneously to participate","The main block size permanently increases for all future blocks","Lightning Network channels become incompatible with the base layer"]},{q:"Why have extension block proposals historically been controversial in Bitcoin development?",a:"They risk creating a second-class zone that weakens full node security",wrong:["They were proposed by altcoin developers trying to undermine Bitcoin","They would eliminate the need for the Lightning Network entirely","They require replacing SHA-256 with a completely different hash algorithm"]}],feedback_loops:[{q:"What is the price-hashrate-security feedback loop in Bitcoin?",a:"Higher price attracts miners, boosting hashrate, security, and confidence in a rising cycle",wrong:["Higher price causes miners to shut down equipment due to overheating, reducing hashrate and network stability","Hashrate and Bitcoin price are completely independent variables with no meaningful statistical connection","Security drops sharply as price rises because more sophisticated hackers are financially motivated to attack"]},{q:"How does the adoption-liquidity-utility feedback loop work in Bitcoin?",a:"More users deepen liquidity, making Bitcoin more useful, which attracts even more users",wrong:["The Lindy Effect means Bitcoin becomes progressively less reliable as its codebase ages and technical debt grows","Older technology always gets replaced by newer innovations eventually, so the Lindy Effect actually hurts Bitcoin","The Lindy Effect only applies to physical objects and printed books, not digital protocols or software systems"]},{q:"How does the Lindy Effect create a reinforcing feedback loop for Bitcoin?",a:"Each day Bitcoin survives boosts confidence in its longevity, drawing more adoption",wrong:["Reflexivity means Bitcoin's price always reflects its true fundamental value without emotional distortion","It describes the tendency of Bitcoin to always revert to a fixed long-run equilibrium price over time","Reflexivity is a mining optimization technique that increases block production speed during difficulty periods"]},{q:"What is reflexivity in the context of Bitcoin market cycles?",a:"Perceptions influence fundamentals, which reinforce perceptions, creating self-amplifying cycles",wrong:["Bitcoin has only one feedback loop but that single loop happens to be extremely strong during bull markets","Bitcoin's feedback loops are actually weaker than traditional markets because they lack institutional backstops","Feedback loops only function during bull markets and reverse direction completely and instantly during bear phases"]},{q:"Why are Bitcoin's feedback loops considered among the most powerful in economics?",a:"Multiple self-reinforcing loops in price, hashrate, adoption, and security amplify together",wrong:["Bitcoin has only one feedback loop but it happens to be extremely strong as defined by Bitcoin consensus rules enforced by all full nodes","Bitcoin's feedback loops are actually weak compared to traditional market loops as defined by Bitcoin consensus rules enforced by all full nodes","Feedback loops only work in bull markets and reverse completely in bear runs as defined by Bitcoin consensus rules enforced by all full nodes"]}],first_principles:[{q:'What does "first principles thinking" mean when applied to Bitcoin?',a:"Breaking money down to fundamental properties and reasoning up from there",wrong:["Bitcoin was simply the first cryptocurrency launched, so it wins by historical default over all later altcoins","Altcoins are effectively illegal in most jurisdictions, so Bitcoin is the only legally compliant option available","Bitcoin has the best-funded marketing team and strongest global brand recognition beating all cryptocurrency rivals"]},{q:"Which philosopher is most associated with the first principles method of reasoning from fundamental truths?",a:"Aristotle",wrong:["Plato, as specified in the original Bitcoin whitepaper released in 2008","Socrates","Descartes"]},{q:"When reasoning from first principles about what makes good money, which set of properties matters most?",a:"Scarcity, portability, durability, divisibility, and fungibility",wrong:["Government backing, legal enforcement, and central bank control","Physical weight, aesthetic beauty, and historical tradition","Ease of printing, widespread banking, and inflation targeting"]},{q:"First principles thinking reveals what fundamental connection between energy and money?",a:"Money should represent stored energy - unforgeable costliness gives it value",wrong:["Money has no relationship to energy since it is purely a social construct","Only physical commodities can serve as money because they contain atoms","Energy is irrelevant to money if a government declares it legal tender"]},{q:"Why does first principles reasoning tend to lead people toward Bitcoin rather than altcoins?",a:"Bitcoin best satisfies the fundamental properties of sound money from first principles",wrong:["Bitcoin was the first cryptocurrency so it wins by default over altcoins as defined by Bitcoin consensus rules enforced by all full nodes","Altcoins are illegal in most countries so Bitcoin is the only legal option as defined by Bitcoin consensus rules enforced by all full nodes","Bitcoin has the best marketing team and strongest brand awareness overall as defined by Bitcoin consensus rules enforced by all full nodes"]}],foss:[{q:"What type of software license does Bitcoin Core use?",a:"MIT License",wrong:["GPL v3 as defined by Bitcoin consensus rules enforced by all full nodes","Apache License 2.0","Creative Commons"]},{q:"Why is it important that Bitcoin Core is free and open-source software (FOSS)?",a:"Anyone can audit the code to verify no backdoors or hidden rules exist",wrong:["It makes Bitcoin free to use with zero transaction fees for users","It allows developers to create unlimited Bitcoin through the code","It means no one actually needs to run the Bitcoin software as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What is the Guix build system used for in Bitcoin Core?",a:"Producing reproducible, auditable binaries so anyone can verify the software",wrong:["Automatically deploying Bitcoin Core updates to all nodes across the network","Managing the peer-review and merge workflow for Bitcoin Core pull requests","Cross-compiling Bitcoin Core binaries optimised for different CPU architectures"]},{q:'"Linus\'s Law" states that "given enough eyeballs, all bugs are shallow." How does this apply to Bitcoin?',a:"Thousands of developers review Bitcoin's code, so vulnerabilities get found and fixed faster",wrong:["Linux servers are the only machines capable of running Bitcoin full nodes properly","Linus Torvalds personally reviews and audits every Bitcoin Core release himself as defined by Bitcoin consensus rules enforced by all full nodes","Bitcoin can only run on open-source operating systems like Linux and FreeBSD as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"Why does open-source matter specifically for money/monetary software like Bitcoin?",a:"Users must verify the rules of their money - no hidden inflation or secret changes",wrong:["Open-source software is always faster and more efficient than proprietary code","It allows banks to freely copy Bitcoin and make their own branded version","It makes Bitcoin significantly easier for governments to regulate and control"]}],hardware:[{q:"What makes the Coldcard hardware wallet stand out among Bitcoin hardware wallets?",a:"It's air-gapped, Bitcoin-only, and supports NFC signing",wrong:["It supports thousands of altcoins and NFTs as defined by Bitcoin consensus rules enforced by all full nodes","It connects directly to the internet for speed as defined by Bitcoin consensus rules enforced by all full nodes","It's the cheapest hardware wallet available as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What is a PSBT (Partially Signed Bitcoin Transaction) and why is it important for hardware wallets?",a:"A format for building transactions on one device and signing on another",wrong:["A tamper-resistant chip that secures the Wi-Fi connection between the hardware wallet and the signing app","A specialized processing component that accelerates cryptographic signing and transaction speed on the device","An embedded GPS module that tracks the physical location of the hardware wallet for remote recovery purposes"]},{q:"What is SeedSigner?",a:"A DIY, open-source, air-gapped wallet built on a Raspberry Pi",wrong:["The wallet is hermetically sealed inside a vacuum chamber to prevent physical tampering by sophisticated attackers","The wallet uses low-earth-orbit satellite uplinks instead of Wi-Fi to broadcast transactions anonymously","The hardware wallet can only be safely operated outdoors away from electronics that could intercept its signals"]},{q:'What is a "secure element" chip in hardware wallets?',a:"A tamper-resistant chip that stores keys and blocks extraction",wrong:["A chip that connects the wallet to Wi-Fi securely as defined by Bitcoin consensus rules enforced by all full nodes","A component that speeds up transaction processing as defined by Bitcoin consensus rules enforced by all full nodes","A GPS module that tracks the wallet for recovery as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:'What does "air-gapped" mean when describing a hardware wallet like Coldcard or Foundation Passport?',a:"It never connects to internet - data moves via SD card, QR, or NFC",wrong:["The wallet is sealed in a vacuum to prevent tampering as defined by Bitcoin consensus rules enforced by all full nodes","The wallet uses satellite connections instead of Wi-Fi as defined by Bitcoin consensus rules enforced by all full nodes","The wallet can only be used outdoors for security as defined by Bitcoin consensus rules enforced by all full nodes"]}],improved_incentive_structure:[{q:'How does Bitcoin "fix broken incentives" in the current monetary system?',a:"By removing money printing, it forces honest accounting and ends inflation of debt",wrong:["It gives governments better tools to manage the economy, as specified in the original Bitcoin whitepaper released in 2008","It doesn't change incentives - just moves them to digital, as specified in the original Bitcoin whitepaper released in 2008","It fixes incentives by making all transactions government-traceable as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:'What does "low time preference society" mean in the context of a Bitcoin standard?',a:"People plan long-term and save more because their money gains value over time",wrong:["Proof of work distributes equal amounts of Bitcoin automatically to every registered person on Earth","Early miners received special privileged allocation rates that new miners joining the network cannot access","Proof of work distributes Bitcoin proportionally based on geographic location and regional energy costs"]},{q:'Why is proof of work considered a "fair distribution" mechanism for new Bitcoin?',a:"Anyone can mine by spending real energy - no pre-mines or insider allocations",wrong:["Sound money discourages saving because appreciating money becomes too valuable to spend on any investments","Individual investment behavior stays statistically identical regardless of whether the monetary system inflates","Sound money causes universal hoarding behavior that starves businesses of capital and collapses the economy"]},{q:"How does sound money (like Bitcoin) change savings and investment behavior?",a:"People save more and only invest in projects with real returns above deflation",wrong:["Fiat money incentivizes excessive saving over spending because the currency retains value across decades","Fiat money contains no broken incentives and functions exactly as economists designed it to work long-term","Bitcoin creates identical borrow-over-save incentives since interest rates still exist in a Bitcoin economy"]},{q:"What broken incentive does fiat money create that Bitcoin eliminates?",a:"Fiat rewards borrowing over saving because inflation erodes purchasing power",wrong:["Fiat incentivizes too much saving, which Bitcoin fixes as defined by Bitcoin consensus rules enforced by all full nodes","Fiat money has no broken incentives - it works as designed as defined by Bitcoin consensus rules enforced by all full nodes","Bitcoin creates the same borrow incentive since rates exist as defined by Bitcoin consensus rules enforced by all full nodes"]}],laws_of_thermodynamics:[{q:"How does the First Law of Thermodynamics (conservation of energy) relate to Bitcoin mining?",a:"Miners convert electricity into computational work securing the ledger",wrong:["Bitcoin mining creates energy from nothing to power the network","The First Law means Bitcoin can only exist in cold climates as defined by Bitcoin consensus rules enforced by all full nodes","Energy is destroyed during mining, explaining the high usage as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:'What does "unforgeable costliness" mean in Bitcoin\'s thermodynamic context?',a:"Real energy must be spent to produce Bitcoin and this cost can't be faked",wrong:["Bitcoin fundamentally violates the Second Law by creating economic value and order from computationally nothing","Entropy has no meaningful connection to digital ledger systems like Bitcoin running on transistor-based hardware","The Second Law implies Bitcoin's network will inevitably reach maximum entropy and permanently stop functioning"]},{q:"How does the Second Law of Thermodynamics (entropy always increases) connect to Bitcoin?",a:"Proof of work creates order in the ledger by increasing entropy via energy use",wrong:["Maxwell's Demon is the historical codename for the first Bitcoin mining software written by Satoshi Nakamoto","It describes a theoretical advanced AI attack that could take over mining and reorganize the blockchain at will","It refers to the apparent randomness of Bitcoin price movements being analogous to Brownian particle motion"]},{q:'Why do some physicists describe proof of work as "thermodynamic security"?',a:"Reversing the chain would require re-spending all the energy that built it",wrong:["Because Bitcoin mining rigs get very hot during operation as defined by Bitcoin consensus rules enforced by all full nodes","Because proof of work requires cooling systems to function as defined by Bitcoin consensus rules enforced by all full nodes","Because thermodynamic equations are used to set transaction fees as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:'What is the "Maxwell\'s Demon" analogy sometimes applied to Bitcoin?',a:"You can't sort molecules or secure a ledger without real energy expenditure",wrong:["Maxwell's Demon is the name of the first Bitcoin mining software as defined by Bitcoin consensus rules enforced by all full nodes","It describes a theoretical AI attack that takes over the network as defined by Bitcoin consensus rules enforced by all full nodes","It refers to Bitcoin price randomness being like particle motion as defined by Bitcoin consensus rules enforced by all full nodes"]}],"layer-3-sidechains":[{q:"How does the Liquid Network secure its two-way peg to Bitcoin?",a:"Through a federation of functionaries managing the peg via multisig",wrong:["Through merge-mining where Bitcoin miners also validate Liquid","Through a trustless smart contract deployed on Bitcoin's base layer","Through proof-of-stake consensus among Liquid token holder nodes"]},{q:"How does RSK (Rootstock) secure its sidechain?",a:"Through merge-mining where Bitcoin miners also validate RSK blocks",wrong:["Through a federation of trusted companies that collectively sign","Through proof-of-stake where RSK token holders vote on blocks","Through BitVM fraud proofs posted to Bitcoin's main base layer"]},{q:"What consensus mechanism does Stacks use to connect to Bitcoin?",a:"Proof of Transfer (PoX), where miners spend BTC to produce blocks",wrong:["Proof of Work using the same SHA-256 algorithm as Bitcoin mining","Delegated Proof of Stake with community-elected block producers","Proof of Authority using a fixed and permissioned validator set"]},{q:"What are drivechains (BIP-300) designed to enable?",a:"Permissionless sidechains with miner-voted withdrawals to mainchain",wrong:["Faster block times on Bitcoin by reducing difficulty adjustment","A new Lightning channel type that skips on-chain funding steps","Decentralized mining pools that auto-distribute block rewards"]},{q:"What is the primary security concern with federated sidechains like Liquid?",a:"Users must trust federation members not to collude and steal funds",wrong:["The sidechain can reverse Bitcoin base layer transactions at will","Federated sidechains consume more energy than Bitcoin's proof-of-work","The federation has the power to change Bitcoin's 21 million cap"]}],ordinals_inscriptions:[{q:"Who proposed the Ordinal Theory for Bitcoin?",a:"Casey Rodarmor",wrong:["Adam Back as defined by Bitcoin consensus rules enforced by all full nodes","Pieter Wuille","Satoshi Nakamoto"]},{q:"How are individual satoshis numbered in Ordinal Theory?",a:"Sequentially based on mining order",wrong:["Randomly assigned by the network","By their transaction ID hash as defined by Bitcoin consensus rules enforced by all full nodes","By the receiving wallet address"]},{q:"What do inscriptions attach to specific satoshis?",a:"Arbitrary data like images or text",wrong:["Private keys for spending them","Their full transaction history","Multisig spending conditions as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What token standard emerged from Ordinals functionality?",a:"BRC-20",wrong:["ERC-20","RGB","Omni Layer"]},{q:"What was a major criticism of Ordinals regarding block space?",a:"They use limited block space for non-monetary data",wrong:["They significantly reduce mining reward amounts","They break Bitcoin's core consensus rules as defined by Bitcoin consensus rules enforced by all full nodes","They allow theft of other users' funds as defined by Bitcoin consensus rules enforced by all full nodes"]}],rollups:[{q:"What is a validity rollup on Bitcoin?",a:"A system that bundles off-chain transactions and posts a ZK proof to Bitcoin",wrong:["A sidechain that copies Bitcoin's consensus rules exactly as written","A Lightning Network channel that batches together multiple payments","A mining pool feature that combines block templates from miners as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"How do sovereign rollups differ from validity rollups?",a:"Users verify rollup state themselves rather than relying on the base layer",wrong:["Sovereign rollups use a central authority; validity rollups are decentralized","Sovereign rollups use proof-of-stake; validity rollups use proof-of-work","Sovereign rollups are limited to only seven transactions per second"]},{q:"How could BitVM enable rollups on Bitcoin?",a:"By allowing fraud proofs to verify rollup state without needing new opcodes",wrong:["By adding a Turing-complete VM directly into Bitcoin's consensus layer","By creating a dedicated sidechain specifically for validating rollup data","By replacing Bitcoin's existing Script language with Solidity contracts"]},{q:"How do Bitcoin rollups differ from sidechains?",a:"Rollups post proofs or data to Bitcoin, inheriting its security guarantees",wrong:["Rollups use a separate token for gas while sidechains use native BTC","Rollups need a federation of signers while sidechains are fully trustless","Rollups are faster than sidechains but limited to simple transfers only"]},{q:"What is the main trust assumption difference between a validity rollup and an optimistic rollup?",a:"Validity rollups prove correctness upfront; optimistic rollups assume it until challenged",wrong:["Validity rollups trust a federation of signers; optimistic rollups trust miners","Validity rollups need a soft fork to work; optimistic rollups work on Bitcoin today","Validity rollups are run centrally; optimistic rollups are always fully decentralized"]}],spv:[{q:"What does SPV (Simplified Payment Verification) allow a lightweight client to do?",a:"Verify transaction inclusion using block headers and Merkle proofs",wrong:["Mine full Bitcoin blocks competitively using only minimal and low-powered mobile computing resources","Broadcast and send transactions to the mempool without paying any required network fees to miners","Run a complete archival full node on a budget mobile phone with extremely limited storage capacity"]},{q:"What privacy problem did the original SPV bloom filters (BIP-37) have?",a:"They leaked which addresses the wallet cared about to the server",wrong:["SPV clients are receive-only and cannot initiate or sign outgoing Bitcoin transactions to any address","SPV clients are required to pay significantly higher transaction fees than users running full verification nodes","SPV clients are restricted to connecting to only a single trusted peer node at any given point in time"]},{q:"What do BIP-157 and BIP-158 (compact block filters) improve over bloom filters?",a:"Clients download pre-computed filters without revealing their addresses",wrong:["They compress the entire blockchain into a single downloadable file","They allow nodes to verify transactions without any network access","They replace Merkle proofs with zero-knowledge proofs for speed"]},{q:"What is Neutrino in the context of Bitcoin light clients?",a:"A light client protocol using BIP-157/158 compact block filters",wrong:["A privacy coin built as a Bitcoin sidechain project as defined by Bitcoin consensus rules enforced by all full nodes","A mining algorithm designed for mobile phone hardware as defined by Bitcoin consensus rules enforced by all full nodes","A wallet that runs a full node in the cloud for you as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What is the main security tradeoff of SPV compared to running a full node?",a:"SPV clients trust miners produce valid blocks without full verification",wrong:["SPV clients cannot receive Bitcoin, they can only send it as defined by Bitcoin consensus rules enforced by all full nodes","SPV clients must pay higher transaction fees than full nodes as defined by Bitcoin consensus rules enforced by all full nodes","SPV clients can only connect to one peer node at a time as defined by Bitcoin consensus rules enforced by all full nodes"]}],tail_emission:[{q:'What is "tail emission" in the context of cryptocurrency monetary policy?',a:"A small perpetual block reward ensuring miners always get some subsidy",wrong:["The final Bitcoin expected to be mined around the year 2140 as defined by Bitcoin consensus rules enforced by all full nodes","The process of burning unsold Bitcoin to reduce total supply as defined by Bitcoin consensus rules enforced by all full nodes","A mechanism that increases block rewards over time for miners as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"Which major cryptocurrency implements tail emission as part of its monetary policy?",a:"Monero, with a permanent minimum reward of 0.6 XMR per block",wrong:["Bitcoin, which added tail emission in the Taproot upgrade","Ethereum, which introduced it during the merge to proof of stake","Litecoin, which activated it after its third halving event"]},{q:"What concern about Bitcoin's long-term security does the tail emission debate address?",a:"Whether fees alone can incentivize miners after block rewards end",wrong:["Whether Bitcoin's encryption can withstand quantum computers","Whether the 21 million supply cap should be raised over time","Whether nodes will have enough storage for the growing chain"]},{q:"What is the main argument AGAINST adding tail emission to Bitcoin?",a:"It would break the 21 million cap and destroy sound money credibility",wrong:["Tail emission would make mining too profitable and attract too many","It would speed up transaction confirmation times excessively as defined by Bitcoin consensus rules enforced by all full nodes","Tail emission is technically impossible to implement on Bitcoin"]},{q:'What is the "fee market sufficiency" argument against the need for tail emission?',a:"Growing adoption and scarce block space will naturally raise fee revenue",wrong:["Miners will voluntarily work for free because they believe in Bitcoin","The government will subsidize mining to keep the network running","New Bitcoin will be discovered on the network like finding new gold"]}],vbyte:[{q:"What is a virtual byte (vbyte) in Bitcoin?",a:"A unit where 1 vbyte equals 4 weight units, used for fee calculation",wrong:["A compressed byte format that reduces transaction size by 75%","The amount of data a Bitcoin node can process per second as defined by Bitcoin consensus rules enforced by all full nodes","A unit measuring the electricity cost of validating transactions"]},{q:"How did SegWit change the way Bitcoin transaction fees are calculated?",a:"Fees use weight units or vbytes, giving witness data a discount",wrong:["SegWit made all transactions free for the first year after launch","SegWit replaced fee priority with a first-come-first-served queue","SegWit doubled the base fee rate for all transaction types"]},{q:"What is the witness discount ratio in SegWit?",a:"Witness data costs 1 weight unit per byte; non-witness costs 4",wrong:["Witness data is free; non-witness data costs 2 weight units","Both witness and non-witness data cost 2 weight units per byte","Witness data costs 3 weight units; non-witness data costs 4"]},{q:"Why is understanding vbytes important for optimizing Bitcoin transaction costs?",a:"Using SegWit addresses moves data into the discounted witness section",wrong:["Vbytes determine how many confirmations a transaction needs as defined by Bitcoin consensus rules enforced by all full nodes","Using fewer vbytes increases the mining reward for the block as defined by Bitcoin consensus rules enforced by all full nodes","Transactions with more vbytes get higher priority in mempool as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"A typical single-input, single-output SegWit transaction is approximately how many vbytes?",a:"About 110 vbytes",wrong:["About 500 vbytes","About 10 vbytes","About 1,000 vbytes"]}],austrian_economics:[{q:'What did Ludwig von Mises formalize in "Human Action" (1949)?',a:"Praxeology — the study of purposeful human action under scarcity, establishing economics as a deductive science of individual choice",wrong:["A measured preference for investments offering rapid compounding returns rather than gradual wealth accumulation as defined by Bitcoin consensus rules enforced by all full nodes","An economic condition where rising inflation expectations push consumers to purchase goods before prices climb as defined by Bitcoin consensus rules enforced by all full nodes","A deliberate investment strategy of holding only liquid assets to preserve maximum optionality and flexibility as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:'What was Hayek\'s core argument in "The Use of Knowledge in Society" (1945)?',a:"Prices are decentralized information signals encoding dispersed local knowledge that no central planner could ever collect or replicate",wrong:["Wages are collective bargaining outcomes that government intervention can optimize to achieve full employment across all economic sectors","Capital is best allocated by expert technocrats who can model aggregate market behavior using national statistical databases","Markets fail to coordinate information efficiently whenever monopolies or asymmetric information distort the natural price discovery process"]},{q:'What did Hayek propose in "Denationalization of Money" (1976)?',a:"Competitive private currencies issued and managed entirely outside government control, a concept Bitcoin made real 35 years later",wrong:["A global reserve currency jointly managed by central banks under an international treaty with binding monetary supply rules","A commodity basket standard linking currency values to weighted indices of gold, silver, and key agricultural commodity prices","Full public ownership of the money supply administered by democratically elected monetary boards with transparent policy rules"]},{q:"According to Austrian Business Cycle Theory, what causes boom-bust cycles?",a:"Artificially low central bank interest rates that encourage malinvestment and unsustainable credit expansion, inevitably followed by a painful bust",wrong:["Excessive consumer spending fueled by rising wages that outpaces underlying productivity growth in the manufacturing and services sectors","Trade imbalances caused by currency manipulation that distort the natural flow of global capital across national borders and industries","Monopolistic corporate pricing that suppresses marketplace competition and prevents efficient capital reallocation across the broader economy"]},{q:"How does sound money affect time preference across society according to Austrian theory?",a:"Sound money lowers time preference, encouraging saving and long-term investment over immediate consumption and short-term debt-fueled spending",wrong:["Sound money raises time preference by making future purchasing power uncertain, discouraging multi-year planning among investors and consumers","Sound money has no measurable effect on time preference, which is entirely determined by individual psychology and genetic disposition","Sound money temporarily lowers time preference but eventually promotes excessive hoarding that collapses demand and deflates the broader economy"]},{q:"What is the Austrian subjective theory of value, in contrast to Marxist labor theory?",a:"Value is determined solely by individual actors based on personal preferences and scarcity, not by labor hours embedded in production",wrong:["Value is determined by the collective social utility of a good as measured through democratic consensus and community price-setting processes","Value is established at market equilibrium when aggregate supply matches aggregate demand at a mutually acceptable price level","Value is a function of raw material scarcity measured objectively by the replacement cost of producing the good under current market conditions"]},{q:"What is the Cantillon Effect in monetary economics?",a:"Newly created money benefits those who receive it first — banks and government contractors — before rising prices erode everyone else's purchasing power",wrong:["Currency devaluation benefits exporters first by making their goods cheaper abroad, before domestic wage growth fully catches up to new price levels","Tax cuts benefit large corporations first because they can immediately reinvest capital gains before smaller firms or wage earners see any benefit","Interest rate reductions benefit institutional borrowers first since they can refinance cheaply before retail lending rates are fully adjusted downward"]},{q:"How did Hayek and Keynes fundamentally disagree about recessions?",a:"Keynes argued government spending cures recessions; Hayek argued forced stimulus generates malinvestment that makes the inevitable correction far worse",wrong:["Keynes supported a gold-backed currency to anchor inflation expectations; Hayek argued fiat money was essential for flexible countercyclical policy","Keynes blamed monopolistic corporations for downturns; Hayek argued recessions stemmed purely from insufficient consumer spending and weak aggregate demand","Keynes viewed free markets as naturally self-correcting over time; Hayek argued central bank intervention was essential to stabilize employment and output"]},{q:'How did Saifedean Ammous connect Austrian economics to Bitcoin in "The Bitcoin Standard"?',a:"He applied Mises and Hayek's sound money theory directly to Bitcoin, arguing it restores low time preference and the hard money properties lost under fiat",wrong:["He applied Keynesian demand-side economics to argue Bitcoin's fixed supply would prevent deflationary spirals in modern post-industrial economies","He adapted Modern Monetary Theory to show Bitcoin's decentralized issuance could replace central bank open market operations in a digital economy","He combined behavioral economics with game theory to prove Bitcoin would inevitably displace fiat through pure network adoption incentives"]},{q:'What is "high time preference" in Austrian economic terms?',a:"A strong preference for present consumption over future saving, leading to debt-fueled spending, short-term thinking, and underinvestment in capital formation",wrong:["A preference for investments with rapid compounding returns rather than patient accumulation of slower long-term capital appreciation strategies","An economic condition where rising inflation expectations cause consumers to accelerate purchases before prices increase any further as defined by Bitcoin consensus rules enforced by all full nodes","A deliberate preference for holding liquid assets to preserve maximum optionality in periods of high economic and market uncertainty as defined by Bitcoin consensus rules enforced by all full nodes"]}],gold_standard_history:[{q:"What characterized the Classical Gold Standard era from roughly 1870 to 1914?",a:"44 years of remarkable price stability, subdued long-run inflation, and a long-term investment culture that financed and enabled the Industrial Revolution",wrong:["44 years of recurring deflationary collapses and economic stagnation caused by the rigid link between currency and a slowly growing physical gold supply","Frequent currency crises triggered by large gold discoveries in California and South Africa that constantly disrupted global price stability and trade","A period of rising inflation and sovereign debt caused by British imperial expansion and surging demand for commodities in colonial territories"]},{q:"What monetary system did the Bretton Woods agreement establish in 1944?",a:"The USD was pegged to gold at $35 per ounce and all other major currencies were pegged to the dollar, making it the world reserve currency",wrong:["All G7 currencies were simultaneously pegged directly to gold at individually negotiated rates, with no single national currency designated as reserve","A post-war trade liberalization treaty that created the WTO and established a system of managed floating exchange rates among Allied nations","The British pound replaced gold as the global reserve standard at a fixed rate of £1 to $4.03, with the US and UK serving as dual anchors"]},{q:'What was the "Nixon Shock" of August 15, 1971?',a:"Nixon unilaterally suspended the dollar's gold convertibility, ending Bretton Woods entirely and launching the global era of pure unbacked fiat currency",wrong:["Nixon imposed sweeping wage and price controls to combat inflation while simultaneously proposing a formal gold revaluation to $100 per ounce","Nixon signed legislation allowing foreign central banks to convert dollars to gold at a newly negotiated rate of $70 per ounce going forward","Nixon coordinated a multilateral agreement with G10 finance ministers to collectively devalue all major currencies against gold by 10 percent simultaneously"]},{q:"What did Executive Order 6102 of 1933 do, and what penalty did it carry?",a:"FDR's order made it illegal for Americans to own gold bullion, with penalties of up to 10 years in prison and a $10,000 fine for violations",wrong:["FDR's order nationalized the Federal Reserve System and established direct Treasury Department control over all money supply decisions nationwide","A 1933 executive order creating the gold exchange standard to formally replace the classical gold standard with a centrally managed currency regime","A 1933 banking regulation requiring all gold held by private commercial banks to be audited quarterly and insured by the federal government"]},{q:'What was gold\'s "fatal flaw" as a monetary standard, according to "The Fiat Standard"?',a:"Spatial salability — gold was too heavy and risky to transport globally, driving centralization into bank vaults and enabling gradual government seizure and control",wrong:["Temporal salability — gold's slowly growing supply made it deflationary over time, consistently discouraging consumption and causing recurring economic stagnation","Divisibility — gold could not be split into units small enough for everyday retail transactions without significantly debasing its purity and market value","Verifiability — gold could not be authenticated quickly enough in ordinary commerce, creating widespread fraud through counterfeit coins and debased alloys"]},{q:"What caused the Weimar Republic's catastrophic hyperinflation between 1921 and 1923?",a:"The German government printed money to pay WWI reparations demanded by the Allies, causing prices to double every few days at the peak of the crisis",wrong:["A speculative bubble in German industrial equities collapsed, triggering simultaneous bank runs and uncontrolled monetary expansion by the Reichsbank","The Allied naval blockade of German ports cut off essential imports, creating artificial commodity shortages that drove a runaway wage-price spiral","A series of devastating agricultural droughts in 1921 and 1922 destroyed food harvests, causing scarcity-driven price spikes that spiraled into full hyperinflation"]},{q:"How did the gold standard enable the large-scale infrastructure of the Industrial Revolution?",a:"Sound money preserved the value of savings over decades, allowing investors to patiently fund long-term projects like railroads, power grids, and telephone networks",wrong:["Gold-backed currency enabled colonial resource extraction that directly funded industrial projects in Britain through forced labor and administrative taxation systems","The gold standard had minimal direct impact on industrial investment, which was primarily financed through short-term commercial bank credit and trade finance","Industrial Revolution infrastructure was financed mainly through royal patronage and long-term government bonds rather than private savings kept in hard money"]},{q:"How does gold's stock-to-flow ratio compare with Bitcoin's as halvings continue?",a:"Gold's stock-to-flow is roughly 60 years; Bitcoin's surpasses gold after each halving and approaches infinity as block rewards eventually diminish to zero",wrong:["Gold's stock-to-flow of 60 years permanently exceeds Bitcoin's because Bitcoin's supply grows faster than newly mined gold production in absolute terms","Both gold and Bitcoin effectively share equivalent stock-to-flow ratios of around 50–60 years, making them equally scarce as long-term monetary commodities","Gold's stock-to-flow is actually only 20 years due to advances in deep-sea and asteroid mining technology; this makes direct comparison with Bitcoin impossible"]},{q:"How does Bitcoin's hard supply cap compare to gold's theoretical total supply?",a:"Gold's supply is theoretically unlimited through asteroid mining and new geological discoveries; Bitcoin is mathematically capped forever at exactly 21 million coins",wrong:["Gold's accessible supply is now effectively fixed because known economically viable deposits are nearly exhausted and new mining is no longer profitable","Both gold and Bitcoin have effectively unlimited supplies since gold recycling and Bitcoin's layer-2 solutions eliminate any meaningful long-term scarcity constraint","Bitcoin's supply is also theoretically unlimited because permanently lost coins reduce effective circulation, creating protocol pressure to eventually reissue them"]},{q:"Why did the US dollar become the global reserve currency at Bretton Woods in 1944?",a:"The US held the world's largest gold reserves in 1944, making the dollar the most credible currency to serve as the global gold-backed reserve anchor",wrong:["The dollar was chosen because the US had the largest economy and most liquid bond markets regardless of the size of its gold reserve holdings","The British pound was the initial reserve currency at Bretton Woods; the dollar only replaced it after the UK defaulted on its post-war Lend-Lease debts","The IMF selected the dollar through a competitive evaluation of Allied nations' monetary policy track records and fiscal discipline over the preceding decade"]}],cypherpunks:[{q:'What did Eric Hughes declare in "A Cypherpunk\'s Manifesto" (1993)?',a:'"Privacy is necessary for an open society in the electronic age... We must defend our own privacy if we expect to have any."',wrong:['"Encryption is a weapon of the people... The state\'s monopoly on surveillance must be broken by making cryptography universally available and free."','"Anonymity is the foundation of all digital freedom... Any government that surveils its citizens without consent has permanently forfeited its legitimacy."','"Code is the new law... Those who control cryptographic infrastructure ultimately control the rights and freedoms of citizens in the digital age."']},{q:"Where did Satoshi Nakamoto first publish the Bitcoin whitepaper on October 31, 2008?",a:"The Cypherpunks mailing list, the center of digital privacy and cryptographic activism since its founding in 1992 by Eric Hughes and John Gilmore",wrong:["The Bitcoin.org website, which Satoshi registered in August 2008 specifically to host the whitepaper and distribute the initial open-source software release","The SourceForge code repository, where Satoshi posted the whitepaper alongside the initial C++ source code for broad public review and comment","The Cryptography mailing list hosted at metzdowd.com, a separate but closely overlapping community focused primarily on academic cryptographic research"]},{q:"What was Adam Back's technical contribution that directly shaped Bitcoin's design?",a:"He invented Hashcash in 1997 — a proof-of-work system directly cited in the Bitcoin whitepaper that became the foundation of Bitcoin's mining mechanism",wrong:["He created the Merkle tree data structure in 1994 that Bitcoin uses to efficiently organize and cryptographically verify transaction data inside each block","He developed the elliptic curve digital signature algorithm that Bitcoin uses to cryptographically authenticate ownership and authorize every transaction","He invented the SHA-256 hashing algorithm in 1995 that Bitcoin relies on to secure its proof-of-work calculations and generate transaction identifiers"]},{q:"Who was Hal Finney and what was his historic role in Bitcoin's earliest days?",a:"He received the first Bitcoin transaction from Satoshi (block 170), ran the second node, created RPOW in 2004, and died of ALS in 2014 with his brain cryonically preserved",wrong:["He authored the cryptographic foundations of the original Bitcoin whitepaper before Satoshi transformed them into a fully operational peer-to-peer payment system","He mined the genesis block alongside Satoshi and ran Bitcoin's first public exchange, converting BTC into USD for the earliest adopters of the network as defined by Bitcoin consensus rules enforced by all full nodes","He ran Bitcoin's first currency exchange and facilitated the landmark pizza transaction, the first documented real-world commercial use of Bitcoin as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"Why do many researchers suspect Nick Szabo is Satoshi Nakamoto?",a:'He coined the term "smart contracts" in 1994 and created bit gold in 1998 — a Bitcoin direct predecessor featuring similar proof-of-work and digital scarcity mechanics',wrong:["He registered bitcoin.org before the whitepaper's release and was the only known cypherpunk with sufficient C++ expertise to write the original client","His writing style matched the Bitcoin whitepaper with 99% confidence according to multiple independent linguistic forensic analysis studies published in 2013",'He confirmed in a 2019 podcast interview that he was "deeply involved in Bitcoin\'s conceptual design" without explicitly claiming sole authorship of the protocol']},{q:"What was Wei Dai's contribution to digital cash, and how is he honored in crypto today?",a:'He created b-money in 1998, the first proposal for anonymous distributed electronic cash directly cited by Satoshi; Ethereum\'s smallest unit, the "wei," is named after him',wrong:['He invented the zero-knowledge proof protocol in 1992 underlying Ethereum\'s privacy layer; the "gwei" denomination honors his foundational cryptographic contribution',"He designed the distributed hash table architecture in 1997 that directly inspired Bitcoin's peer-to-peer network topology and decentralized node discovery protocol",'He created e-gold in 1996, the first operational digital gold currency system, and MakerDAO\'s "dai" stablecoin was named in honor of his legacy as defined by Bitcoin consensus rules enforced by all full nodes']},{q:'What did Timothy May argue in his "Crypto-Anarchist Manifesto" written in 1988?',a:"Cryptography would make governments unable to tax or regulate digital communications, enabling untraceable anonymous transactions and entirely new free markets",wrong:["Encryption would enable investigative journalists to safely transmit whistleblower documents across borders, fundamentally reforming government accountability worldwide","Public-key cryptography would make government-issued identity documents and passports completely obsolete within two decades of widespread civilian adoption","Digital cash systems would eliminate banking fees for ordinary citizens and redistribute trillions in financial industry profits directly to technology developers"]},{q:"What is Len Sassaman's unusual and permanent connection to the Bitcoin blockchain?",a:"He was a cypherpunk cryptographer who died in July 2011 shortly after Satoshi went dark; his obituary was permanently encoded into the Bitcoin blockchain as tribute",wrong:["He merged Satoshi's final code commits before the creator went dark in 2011, making him the last developer to interact officially with the original Bitcoin client","He operated the longest-running Bitcoin full node during the first year of the network, and his node identifier was encoded in the metadata of block 21,000","He contributed the peer-to-peer networking module to the original Bitcoin client, and his PGP public key is permanently embedded inside the genesis block's coinbase script"]},{q:"What legal precedent did Phil Zimmermann establish through his battles over PGP encryption?",a:'His US prosecution for "exporting munitions" when PGP spread abroad established the critical constitutional precedent that software source code is protected free speech',wrong:["His case established that no court could compel production of cryptographic keys as self-incriminating testimony, extending Fifth Amendment protections to encryption","His legal battle with RSA Security over patent licensing established the foundational principle that mathematical algorithms cannot be privately owned as intellectual property","His prosecution established that open-source cryptographic software cannot under any circumstances be classified as a weapon under the Arms Export Control Act"]},{q:"What was Julian Assange's connection to the cypherpunk movement and to Bitcoin's early adoption?",a:"Assange was a cypherpunk mailing list subscriber when Satoshi published the whitepaper in 2008; WikiLeaks later became one of Bitcoin's first major organizational adopters",wrong:["Assange personally corresponded with Satoshi throughout 2009 to coordinate WikiLeaks's launch of a dedicated anonymous Bitcoin donation infrastructure for sources",'Assange co-authored the "Cypherpunks" book with Jacob Appelbaum in 2012, which became a widely cited foundational text within the early Bitcoin community',"Assange was a contributing Bitcoin developer before founding WikiLeaks, writing the anonymous transaction routing code that appeared in client version 0.2"]}],satoshi_nakamoto_deep:[{q:"How many posts did Satoshi Nakamoto make on the BitcoinTalk forum before going silent?",a:"Exactly 575 documented posts on the BitcoinTalk forum before Satoshi went dark in late 2010 and early 2011, handing off to Gavin Andresen",wrong:["Approximately 3,200 posts across BitcoinTalk and the Cypherpunks mailing list before formally transferring all authority and repository access to Gavin Andresen","Around 1,100 public posts on BitcoinTalk, plus hundreds of private direct messages to core developers that were later partially leaked online","Fewer than 100 public posts total, since Satoshi strongly preferred communicating through private encrypted email rather than open public forum discussions"]},{q:"What is considered significant about Satoshi's self-reported birthday of April 5, 1975?",a:"April 5 is the date of FDR's 1933 Executive Order 6102 confiscating gold, and 1975 is the year Americans regained the legal right to own gold again",wrong:["April 5 is the date Satoshi registered bitcoin.org in 2008, and 1975 is the year Whitfield Diffie and Martin Hellman published the public-key cryptography paper","April 5 is the date of the first confirmed Bitcoin transaction in 2009, and 1975 marks the founding of the first academic digital money research consortium","April 5 was chosen as a random privacy-preserving date, and 1975 simply reflects the year the cypherpunk movement's core philosophical foundations were established"]},{q:"What is notable about how Satoshi Nakamoto managed Bitcoin addresses for privacy?",a:"Satoshi maintained over 22,000 documented unique addresses and reportedly never reused a single one, demonstrating perfect on-chain privacy hygiene throughout",wrong:["Satoshi used a single master address for all early mining rewards to simplify personal accounting, then rotated to new addresses only after 2010","Satoshi reused addresses intentionally to signal authenticity to early users, maintaining fewer than 50 documented unique addresses across all activity","Satoshi's addresses followed a deterministic pattern researchers cracked in 2013, successfully mapping every early mining reward back to a single master wallet"]},{q:"What did Satoshi write in his final known email to Gavin Andresen in April 2011?",a:'"I have moved on to other things. It is in good hands with Gavin and everyone."',wrong:['"The system is working as intended. Never add features without thorough peer review, and always keep the codebase minimal and fully auditable."','"Please do not attempt to contact me again. Bitcoin must stand entirely on its own without any individual being perceived as its leader."','"Protect the 21 million supply cap above all else. Any proposal to alter total issuance must be permanently and unconditionally rejected."']},{q:"What surprising feature was hidden inside Satoshi's original Bitcoin source code?",a:"The unfinished beginnings of an online poker game were embedded within the original approximately 31,000 lines of C++ source code",wrong:["A built-in decentralized exchange for direct peer-to-peer currency swaps without intermediaries, which was deliberately stripped out before the 2009 launch","An early DNS-based identity system allowing users to cryptographically link human-readable usernames to their Bitcoin addresses across the network","A complete payment channel prototype closely resembling the Lightning Network that Satoshi implemented fully but deliberately disabled before the January 2009 launch"]},{q:"What does Satoshi's registration of netcoin.org reveal about the project's late development?",a:"Satoshi registered netcoin.org one day before bitcoin.org, strongly suggesting the project's final name was still undecided until very late in development",wrong:["Satoshi registered netcoin.org as a deliberate decoy domain to mislead corporate legal teams that were monitoring digital currency development for patent filings","Netcoin.org was registered by Hal Finney on Satoshi's behalf as a geographic mirror for distributing the whitepaper outside of US legal jurisdiction","The netcoin.org registration proves Satoshi initially envisioned a narrower online payment network before expanding the scope to a full decentralized monetary system"]},{q:"How did the pre-launch Bitcoin parameters differ from the version released in January 2009?",a:"Pre-launch Bitcoin used 15-minute block times and 30-day difficulty adjustments; these were changed to 10-minute blocks and a 2-week difficulty window before launch",wrong:["Pre-launch Bitcoin used 1-minute block times and 24-hour difficulty adjustments; these were deliberately slowed to improve stability and prevent network spam","The original technical parameters matched the final launch version exactly; no substantive changes were made between the whitepaper publication and the software release","Pre-launch Bitcoin had no automatic difficulty adjustment at all; the 2-week adjustment period was proposed by Hal Finney and added during the first year of operation"]},{q:"What is notable about the approximately 1 million Bitcoin Satoshi mined in the early days?",a:"Satoshi mined roughly 1 million BTC using a deliberately limited single-threaded miner to avoid dominating the network, and none of these coins have ever moved",wrong:["Satoshi mined approximately 1 million BTC but transferred the majority to a multi-signature escrow wallet controlled by the Bitcoin Foundation before going dark in 2011","Satoshi mined approximately 1 million BTC and quietly liquidated about half of them during the 2013 bull run to fund ongoing anonymous development work","Satoshi's early mining totaled only around 50,000 BTC; the widely cited 1 million figure is a persistent myth based on demonstrably flawed blockchain analysis methods"]},{q:"What happens to Bitcoin that fans send to the original Genesis Block address as tribute?",a:"Over 68 BTC have been sent as tribute to the Genesis Block address, but they are permanently unspendable since the output carries no valid scriptPubKey to spend from",wrong:["Bitcoin sent to the Genesis Block address is automatically destroyed by the protocol itself, permanently reducing the circulating supply below 21 million coins","Genesis Block donations remain locked and are accessible only to whoever controls Satoshi's original private keys, creating an enduring cryptographic mystery","All Bitcoin sent to the Genesis Block address accumulates in a special reserve fund governed collectively by the Bitcoin Core development team and maintainers"]},{q:"What does the fact that only 0.06% of Bitcoin Core code remains from Satoshi's original suggest?",a:'The global community has rebuilt nearly everything from scratch, embodying the spirit that "we are all Satoshi" through decades of collective open-source maintainership',wrong:["Satoshi's original code was so poorly structured and buggy that developers had to replace it entirely, raising serious questions about Satoshi's actual programming expertise","The 0.06% figure proves Satoshi contributed only the whitepaper concept while the actual software was primarily written by Hal Finney and other early collaborators","Bitcoin Core has diverged so completely from Satoshi's original design that it should be treated as an entirely different protocol incompatible with the founding vision"]}],books_deep:[{q:"Which book did Michael Saylor credit as most impactful in MicroStrategy's decision to adopt Bitcoin?",a:"The Bitcoin Standard by Saifedean Ammous",wrong:["The Fiat Standard by Saifedean Ammous","Gradually Then Suddenly by Parker Lewis","Broken Money by Lyn Alden, as specified in the original Bitcoin whitepaper released in 2008"]},{q:'In "The Bitcoin Standard," what economic concept measures the ratio of above-ground supply to annual production?',a:"Stock-to-Flow ratio",wrong:["Purchasing power parity index","Time preference discount rate","Monetary velocity multiplier"]},{q:'What is the subtitle of Saifedean Ammous\'s second book, "The Fiat Standard"?',a:"The Debt Slavery Alternative to Human Civilization",wrong:["The Hidden Tax on Every Holder of Currency as defined by Bitcoin consensus rules enforced by all full nodes","How Central Banks Destroyed the Modern World","A Monetary History of the Post-Gold Era as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"In \"21 Lessons,\" DerGigi describes Bitcoin's origin as having no founder still in control, no premine, and no ICO — he calls this Bitcoin's what?",a:"Immaculate conception",wrong:["Genesis paradox as defined by Bitcoin consensus rules enforced by all full nodes","Sovereign neutrality principle","Trustless bootstrap event"]},{q:'In "Gradually, Then Suddenly," Parker Lewis argues Bitcoin cannot be copied because of what, not because the code is proprietary?',a:"Bitcoin's network effects make a copy worthless from day one",wrong:["Bitcoin's mining hardware creates a prohibitive barrier to entry for copycats","Bitcoin's regulatory approval cannot be duplicated by any fork or altcoin","Bitcoin's cryptographic proof-of-work algorithm is patented and legally protected"]},{q:"Jason Lowery's \"Softwar\" was submitted as an MIT thesis. What novel claim does it make about Bitcoin's proof-of-work?",a:"PoW is a form of non-lethal power projection allowing nations to compete via hashrate instead of violence",wrong:["PoW is an energy accounting system that proves Bitcoin's value in physical thermodynamic terms","PoW functions as a diplomatic signaling mechanism that deters state-level cyberattacks on infrastructure","PoW creates a decentralized arms-control treaty enforced by thermodynamics rather than international law"]},{q:"According to Vijay Boyapati's \"The Bullish Case for Bitcoin,\" what is the correct order of Bitcoin's monetization stages?",a:"Collectible → store of value → medium of exchange → unit of account",wrong:["Store of value → collectible → medium of exchange → unit of account","Medium of exchange → store of value → unit of account → collectible","Collectible → medium of exchange → store of value → unit of account"]},{q:'Nik Bhatia\'s "Layered Money" argues that monetary layers built atop Bitcoin — like Lightning — are a natural evolution. What historical precedent does he trace this pattern through?',a:"The monetary hierarchy from gold to central bank notes to commercial bank deposits through history",wrong:["The progression from barter to commodity money to bills of exchange in medieval Europe as defined by Bitcoin consensus rules enforced by all full nodes","The development of the Federal Reserve system from private clearinghouses after the Panic of 1907","The transition from the classical gold standard to the Bretton Woods dollar-gold exchange system"]},{q:"Jonathan Bier's \"The Blocksize War\" documents the 2015–2017 governance battle. What broader lesson does it demonstrate about who ultimately controls Bitcoin's protocol?",a:"Economic nodes and users — not miners — hold final power over which consensus rules Bitcoin enforces",wrong:["Core developers hold final power because miners must adopt whatever client they release to the network","Miners hold final power because they can always reorganize the chain and override node-level rules","Large exchanges hold final power because they determine which version of Bitcoin earns the ticker symbol"]},{q:'Lyn Alden\'s "Broken Money" is primarily a macro case for Bitcoin. What does she identify as the core structural flaw in the current monetary system?',a:"The dollar-based reserve system built after 1971 creates persistent debt growth and destroys savings over time",wrong:["The Federal Reserve's dual mandate forces it to create inflation to meet employment targets indefinitely","Commercial banks' fractional reserve lending multiplies currency beyond any anchor to productive activity","Government deficit spending requires continuous monetization that no neutral reserve asset can currently absorb"]}],human_rights_deep:[{q:'Alex Gladstein of the Human Rights Foundation wrote "Check Your Financial Privilege." What percentage of people does he say live in liberal democracies with stable reserve currencies?',a:"Only about 13% of the global population",wrong:["Only about 28% of the global population","Roughly half — about 49% of the global population","Approximately 34% of the global population"]},{q:"When Nigeria's central bank banned banks from servicing crypto exchanges in 2021, what happened to peer-to-peer Bitcoin trading volumes?",a:"They surged to the highest levels in Africa as Nigerians routed around the ban",wrong:["They collapsed by over 80% as citizens feared criminal prosecution for trading","They remained flat because most Nigerians were unaware of hardware wallet alternatives","They shifted entirely to stablecoins, with Bitcoin trading volumes dropping to near zero"]},{q:"In Venezuela's hyperinflation crisis, what was the typical fee range that families lost when sending remittances through traditional wire and cash services?",a:"20–40% of the total transfer in fees and unfavorable exchange rates",wrong:["5–10% of the total transfer in fees and unfavorable exchange rates","50–70% of the total transfer in fees and currency conversion losses","10–15% of the total transfer in fees and exchange rate spreads"]},{q:"During the 2019–2020 Lebanese banking crisis, how did the situation differ for Bitcoin holders versus bank depositors?",a:"Banks froze depositor accounts entirely, while Bitcoin holders retained full, unobstructed access to their funds",wrong:["Bitcoin holders saw their funds seized by Lebanese authorities, while bank depositors received partial access","Both groups faced equal restrictions, as Lebanese courts extended banking freezes to crypto wallets","Bank depositors could withdraw up to $400 per week, while Bitcoin holders faced blockchain-level withdrawal limits"]},{q:"In Taliban-controlled Afghanistan, what specific financial freedom does Bitcoin on a mobile phone enable for women?",a:"Women legally barred from holding bank accounts can control their own money without requiring male permission or a bank",wrong:["Women can receive international aid disbursements that Taliban officials cannot intercept or redirect to male relatives","Women can pay for goods anonymously, preventing Taliban tracking of purchases deemed un-Islamic by local authorities","Women can earn wages in Bitcoin from foreign employers, bypassing Taliban labor laws restricting female employment"]},{q:"During the 2022 Canadian trucker convoy protests, what happened to the GoFundMe campaign, and how did the Bitcoin alternative compare in size?",a:"GoFundMe froze $10 million in donations; Bitcoin campaigns raised approximately $21 million which could not be frozen",wrong:["GoFundMe froze $3 million in donations; Bitcoin campaigns raised approximately $7 million which could not be frozen","GoFundMe froze $25 million in donations; Bitcoin campaigns raised approximately $4 million which could not be frozen","GoFundMe froze $10 million in donations; Bitcoin campaigns raised approximately $4 million which was later seized"]},{q:"In 2010, WikiLeaks was financially blockaded — Visa, Mastercard, and PayPal all cut off donations under US government pressure. What did this event demonstrate about Bitcoin?",a:"Bitcoin was completely immune to the blockade, allowing WikiLeaks to continue receiving donations without any payment processor",wrong:["Bitcoin donations to WikiLeaks were blocked by exchanges cooperating with US Treasury demands at the network layer","Bitcoin provided a brief alternative but was later traced by the NSA, leading to arrests of major WikiLeaks donors","Bitcoin exposure forced WikiLeaks to pause fundraising temporarily due to volatility making donation values unpredictable"]},{q:"How many adults worldwide are estimated to lack a bank account, and what does Bitcoin's mobile-first design offer them?",a:"About 1.4 billion unbanked adults can access Bitcoin-based financial services using only a mobile phone",wrong:["About 500 million unbanked adults can access Bitcoin-based financial services using only a mobile phone","About 3 billion unbanked adults can access Bitcoin-based financial services using only a mobile phone","About 800 million unbanked adults can access Bitcoin-based financial services using only a mobile phone"]},{q:"In Cuba, what financial problem does Bitcoin solve for diaspora families sending money home?",a:"It eliminates the 10%+ fees charged by Western Union and other remittance services for transfers to Cuba",wrong:["It bypasses the US embargo by routing transfers through Bitcoin exchanges outside Western financial networks","It prevents Cuban authorities from seizing transfers that exceed government-set remittance caps per household","It allows Cuban recipients to hold value that cannot be confiscated during government mandated currency conversions"]},{q:"Alex Gladstein argues that the global financial privilege gap is poorly understood by people in wealthy nations. What is the key stat that reframes the debate?",a:"87% of humanity lives under authoritarian or semi-authoritarian governments with weaker, less stable currencies",wrong:["65% of global GDP is produced in countries whose citizens cannot freely buy or sell foreign currencies","92% of global inflation occurs in the developing world, yet monetary reform debates are dominated by G7 economists","74% of the world's population has experienced at least one episode of government-imposed capital controls since 1970"]}],cbdc:[{q:"What does CBDC stand for, and what is its most fundamental difference from Bitcoin?",a:"Central Bank Digital Currency — it is centrally controlled by government, unlike Bitcoin which has no central issuer",wrong:["Crypto-Backed Digital Contract — it requires collateral backing unlike Bitcoin which is backed only by decentralized consensus","Cross-Border Digital Currency — it is designed for international trade unlike Bitcoin which was designed for domestic payments","Central Bank Distributed Coin — it uses distributed ledger technology unlike Bitcoin which uses a single-node blockchain"]},{q:"What is one programmability feature of CBDCs that no physical cash or Bitcoin can ever impose on a user?",a:"Expiry dates that cause the money to disappear from your account if not spent within a set time period",wrong:["Verification requirements that confirm every transaction is spent on government-approved goods and services only","Mandatory conversion into physical cash if not used for digital transactions within a quarterly spending window","Automatic tax withholding on all transactions above a threshold set by the treasury at the time of payment"]},{q:"China's digital yuan (e-CNY) is one of the most advanced CBDC deployments. How has it been distributed and monitored?",a:"It has been used in government benefit payments and all transactions are monitored in real time by Chinese authorities",wrong:["It has been distributed exclusively through commercial banks and monitored only for transactions exceeding 50,000 yuan","It runs on a private blockchain shared with approved banks, with full transaction privacy from government surveyors","It has been issued only to state employees as salary, with transaction data retained only for anti-fraud purposes"]},{q:"How could a CBDC theoretically implement negative interest rates in a way that physical cash makes impossible?",a:"The government could directly reduce account balances over time to penalize saving and force consumer spending",wrong:["The government could block transactions with foreign merchants to concentrate spending within the domestic economy","The government could require merchants to charge surcharges on CBDC payments relative to digital yuan alternatives","The government could convert idle CBDC balances into government bonds automatically after 90 days without spending"]},{q:'Privacy advocates have called CBDCs "panopticon money." What does this metaphor mean in practice?',a:"Every purchase is tracked and visible to authorities — no transaction can be anonymous like cash transactions currently are",wrong:["All financial data is visible to a network of multinational banks and corporations rather than just the government issuer","CBDC balances are displayed publicly on a blockchain explorer, removing all financial privacy from citizens as defined by Bitcoin consensus rules enforced by all full nodes","The government can see transaction patterns across all users but cannot identify specific individuals behind purchases"]},{q:"When Nigeria launched one of the world's first CBDCs — the eNaira in 2021 — what happened to public adoption?",a:"Adoption was extremely low, with citizens preferring cash and Bitcoin over the government's digital currency",wrong:["Adoption was very high in urban areas but failed in rural regions where smartphone penetration is below 20%","Adoption was forced above 60% when the government imposed penalties on businesses refusing eNaira payments","Adoption was moderate but froze after the central bank suspended the eNaira following a technical hack in 2022"]},{q:"How does a CBDC differ from ordinary digital bank money in terms of government control over individual accounts?",a:"With a CBDC the government controls the ledger directly, enabling confiscation without going through a bank as intermediary",wrong:["With a CBDC users earn interest set by the central bank directly, bypassing commercial bank interest rate decisions entirely","With a CBDC government transfers are instant and fee-free, but commercial transactions still pass through bank clearing systems","With a CBDC citizens interact with a public ledger they can audit, unlike traditional bank accounts that are privately held"]},{q:"How many central banks globally were actively researching or developing CBDC programs as of the mid-2020s?",a:"Over 130 central banks were actively exploring or developing CBDC programs",wrong:["About 40 central banks were actively exploring or developing CBDC programs","Over 200 central banks were actively exploring or developing CBDC programs","Approximately 80 central banks were actively exploring or developing CBDC programs"]},{q:"What is the key distinction between Bitcoin's permissionless access model and a CBDC's access model?",a:"Bitcoin allows anyone to participate without approval, while CBDC authorities decide who is permitted to use the system",wrong:["Bitcoin requires miners to validate identities before transactions confirm, while CBDCs use zero-knowledge proofs for privacy","Bitcoin charges higher fees than CBDCs because it lacks a central issuer to subsidize transaction processing costs","Bitcoin transactions are reversible within 24 hours, while CBDC transactions are irreversible from the moment of broadcast"]},{q:"What concern do economists raise about spending limits and category restrictions that CBDCs could technically enforce?",a:"Governments could block purchases of disfavored goods — fuel, firearms, political donations — at the payment protocol level",wrong:["Governments could restrict CBDC use to domestic merchants, effectively creating a new form of capital controls overnight","Economists worry CBDCs will displace commercial banks entirely by eliminating the need for deposit-taking institutions","Economists warn that real-time CBDC settlement will allow high-frequency traders to front-run ordinary consumer purchases"]}],block_size_wars:[{q:"What was the central technical debate in the Blocksize War of 2015–2017?",a:"Whether to increase Bitcoin's block size limit to fit more transactions per block for on-chain scaling",wrong:["Whether to replace Bitcoin's SHA-256 proof-of-work algorithm with a memory-hard alternative to reduce miner centralization","Whether to implement a second script language alongside Bitcoin Script to support smart contract functionality on-chain","Whether to increase the total Bitcoin supply cap from 21 million to accommodate growing global payment demand"]},{q:'What was the "big blocker" argument for raising the block size limit?',a:"Larger blocks would allow more on-chain transactions, keeping fees low and enabling Bitcoin to scale as a global payment system",wrong:["Larger blocks would make mining more profitable, incentivizing more miners and increasing Bitcoin's overall network security","Larger blocks would reduce orphan block rates, making the chain more stable and resistant to selfish mining attacks","Larger blocks would decrease blockchain download times by batching more data per round-trip during initial sync as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:'What was the core "small blocker" concern about raising the block size limit?',a:"Larger blocks would make running a full node too expensive, concentrating Bitcoin verification among large miners and data centers",wrong:["Larger blocks would slow transaction propagation globally, allowing well-connected miners to dominate block production","Larger blocks would require a hard fork that could be exploited by adversarial states to attack Bitcoin's consensus layer","Larger blocks would reduce the fee market needed to sustain miners after the block subsidy eventually reaches zero as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What was BIP148 (UASF) and why was it historically significant?",a:"It was a User-Activated Soft Fork where node operators threatened to reject non-SegWit blocks — users directly forced miners to comply",wrong:["It was a miner-activated upgrade proposal that required 95% hash power signaling before SegWit could activate on mainnet","It was a protocol patch that fixed the transaction malleability bug independently of SegWit, resolving the scaling debate peacefully","It was a compromise proposal combining a 2 MB block size increase with the SegWit witness discount in a single hard fork"]},{q:"What did SegWit (BIP141) actually do to Bitcoin's effective block capacity?",a:"It increased effective capacity to approximately 2–4 MB by applying a discount to signature (witness) data without a hard fork",wrong:["It increased effective capacity to exactly 8 MB by separating transaction data from signatures in a full hard fork upgrade","It doubled raw on-chain TPS by compressing transaction data with a new serialization format in a backward-compatible upgrade","It increased effective capacity to approximately 1.5 MB by removing redundant script opcodes from the transaction format"]},{q:"What was the New York Agreement (SegWit2x) and what happened to it?",a:"A 2017 deal between miners and businesses to activate SegWit then hard fork to 2 MB blocks — it was ultimately rejected and abandoned",wrong:["A 2016 deal between Core developers and exchanges to freeze block size at 1 MB permanently in exchange for Lightning funding","A 2017 proposal to move Bitcoin to a proof-of-stake system signed by major mining pools; it collapsed after a Chinese mining ban","A 2015 agreement between Blockstream and major miners to develop SegWit in exchange for their opposition to competing clients"]},{q:"Bitcoin Cash (BCH) was created on August 1, 2017. Who were the two most prominent figures leading the big-block faction that forked off?",a:'Roger Ver ("Bitcoin Jesus") and Jihan Wu of Bitmain, the dominant mining hardware manufacturer',wrong:["Gavin Andresen and Mike Hearn, the original Bitcoin Core developers who departed over the governance dispute","Charlie Lee and Craig Wright, who disagreed on block size before Craig later launched Bitcoin SV as a separate fork","Vitalik Buterin and Brian Armstrong, who favored higher-throughput chains compatible with Ethereum's transaction model"]},{q:"What did the outcome of the Blocksize War prove about the power structure in Bitcoin's governance?",a:"Miners cannot override the economic nodes — exchanges, businesses, and users running full nodes hold final authority over consensus rules",wrong:["Core developers hold veto power over any upgrade because miners must route block templates through their reference code as defined by Bitcoin consensus rules enforced by all full nodes","Large institutional holders effectively control protocol direction by threatening to sell if unfavorable forks succeed on the market","Mining pools hold governance power because they can reorganize the blockchain to reverse any soft fork that harms profitability"]},{q:"Which book is considered the definitive account of the Blocksize War and who wrote it?",a:'"The Blocksize War" by Jonathan Bier, which documents the full 2015–2017 governance battle in detail',wrong:['"Digital Gold" by Nathaniel Popper, which documents the governance battle alongside early Bitcoin adoption stories','"The Bitcoin Standard" by Saifedean Ammous, which includes a full chapter on the governance crisis and its resolution','"Cryptoassets" by Chris Burniske and Jack Tatar, which covers the fork wars across Bitcoin, Ethereum, and other protocols']},{q:"What is the broader lesson Bitcoin historians draw from the Blocksize War about contentious protocol changes?",a:"Bitcoin's governance is uniquely robust because controversial changes are extremely difficult to force through without broad consensus",wrong:["Bitcoin's governance is dangerously slow because improvements like SegWit took two years longer than technically necessary to deploy","Bitcoin's governance proves that miners always win long-term disputes because they control the hash power securing the chain","Bitcoin's governance shows that off-chain political agreements like the New York Agreement are the most effective scaling path"]}],mtgox:[{q:'What does the name "Mt. Gox" actually stand for, and what was the platform before it became a Bitcoin exchange?',a:"Magic: The Gathering Online Exchange — it was originally a card trading site repurposed for Bitcoin in 2010",wrong:["Creditors waited approximately 5 years; distributions began in 2019 and were paid entirely in fiat currency at original dollar values","Creditors waited approximately 7 years; distributions began in 2021 and were settled in USDT stablecoins rather than Bitcoin","Creditors waited approximately 10 years; distributions began in 2024 but all Bitcoin was converted to cash at bankruptcy-era prices"]},{q:"At its peak in 2013, what share of all global Bitcoin transactions passed through Mt. Gox?",a:"Over 70% of all global Bitcoin transactions were processed through Mt. Gox at its peak",wrong:["Over 90% of all global Bitcoin transactions were processed through Mt. Gox at its peak","Approximately 40% of all global Bitcoin transactions were processed through Mt. Gox at its peak","Roughly 55% of all global Bitcoin transactions were processed through Mt. Gox at its peak"]},{q:"When Mt. Gox collapsed in February 2014, how many BTC did it announce had been lost, and how many were later found internally?",a:"Mt. Gox reported ~850,000 BTC lost; approximately 200,000 BTC were later discovered in old wallets and recovered",wrong:["Mt. Gox reported ~650,000 BTC lost; approximately 150,000 BTC were later discovered in cold storage and recovered","Mt. Gox reported ~1.2 million BTC lost; approximately 350,000 BTC were later discovered during bankruptcy proceedings","Mt. Gox reported ~850,000 BTC lost; none were ever recovered as all coins were immediately laundered by the attackers"]},{q:"What were the two root causes that allowed Mt. Gox to be drained of Bitcoin over a period of years?",a:"Transaction malleability exploits combined with severe internal financial mismanagement and lack of auditing",wrong:["A private key leak on the public GitHub repository combined with a social engineering attack on the core server team","Insider theft by a rogue employee combined with a zero-day exploit in the OpenSSL library used for wallet encryption","A 51% attack on the Bitcoin network combined with poor hot wallet security that left most funds in an online server"]},{q:"What crime was Mt. Gox CEO Mark Karpeles ultimately convicted of in Japan?",a:"Data manipulation — he was convicted of falsifying electronic records, though embezzlement charges were dropped",wrong:["Theft and embezzlement — he was convicted of directly moving customer Bitcoin to personal wallets for his own enrichment","Securities fraud — he was convicted of issuing false statements about exchange reserves to prevent a bank run","Money laundering — he was convicted of funneling customer funds through shell companies registered in France and Japan"]},{q:"What phrase, now a cornerstone of Bitcoin culture, emerged directly from the lessons of the Mt. Gox collapse?",a:'"Not your keys, not your coins" — the principle that only self-custody guarantees ownership of your Bitcoin',wrong:['"Proof of reserves or proof of fraud" — the principle that exchanges must publish verifiable on-chain reserve attestations','"Run your own node, trust no one" — the principle that verifying the chain yourself is the only true form of sovereignty','"Cold storage or capitulation" — the principle that any Bitcoin left on an exchange is a loan you may never get back']},{q:"How long did Mt. Gox creditors wait for repayment, and what was notable about the form the repayment took?",a:"Creditors waited approximately 10 years; distributions began in 2024 and were paid in BTC worth far more in dollar terms than original claims",wrong:["Creditors waited approximately 5 years; distributions began in 2019 and were paid in Japanese yen at 2014 Bitcoin valuations as defined by Bitcoin consensus rules enforced by all full nodes","Creditors waited approximately 7 years; distributions began in 2021 and were partially repaid in BCH following the 2017 fork as defined by Bitcoin consensus rules enforced by all full nodes","Creditors waited approximately 10 years; distributions began in 2024 but were paid only in fiat at 2014 prices per court order"]},{q:"How did Bitcoin's price respond to the Mt. Gox collapse in early 2014, and how long did recovery take?",a:"Bitcoin dropped from roughly $800 to roughly $350 and took nearly 3 years to reclaim its pre-Mt. Gox price",wrong:["Bitcoin dropped from roughly $1,200 to roughly $150 and took nearly 5 years to reclaim its pre-Mt. Gox price","Bitcoin dropped from roughly $800 to roughly $600 and recovered within 6 months as markets shrugged off the exchange failure","Bitcoin dropped from roughly $500 to roughly $50 and took over 4 years to reclaim its pre-collapse all-time high"]},{q:"What lasting contribution to Bitcoin's security culture did the Mt. Gox failure accelerate?",a:"It drove rapid development of hardware wallets and normalized self-custody as the standard practice for holding Bitcoin",wrong:["It accelerated the development of proof-of-reserve auditing standards that all major exchanges now publish quarterly","It prompted the creation of the Bitcoin Foundation to lobby for exchange insurance requirements in major jurisdictions","It caused Bitcoin developers to implement mandatory withdrawal delays on-protocol to prevent rapid theft from online wallets"]},{q:"Despite being the largest exchange failure in crypto history, what did the Mt. Gox debacle definitively prove about the Bitcoin protocol itself?",a:"The Bitcoin protocol was never compromised — it was Mt. Gox's internal systems that were hacked, not the Bitcoin network",wrong:["The Bitcoin protocol's transaction malleability bug was the root cause, proving base layer security vulnerabilities are existential","The Bitcoin protocol survived only because developers issued an emergency patch within 48 hours of the malleability exploit","The Bitcoin protocol was briefly compromised but miners voluntarily reorganized the chain to restore 200,000 stolen coins"]}],mining_hardware:[{q:"What was the correct order of Bitcoin mining hardware evolution?",a:"CPU → GPU → FPGA → ASIC",wrong:["GPU → CPU → ASIC → FPGA","CPU → FPGA → GPU → ASIC","FPGA → GPU → CPU → ASIC"]},{q:"In what year did CPU mining of Bitcoin begin?",a:"2009",wrong:["2010","2011","2008"]},{q:"Who co-founded Bitmain, the dominant ASIC manufacturer?",a:"Jihan Wu and Micree Zhan",wrong:["Roger Ver and Charlie Lee","Adam Back and Greg Maxwell","Hal Finney and Nick Szabo"]},{q:"What is the efficiency metric used to measure ASIC mining performance?",a:"Joules per terahash (J/TH)",wrong:["Kilowatts per gigahash (kW/GH)","Watts per megahash (W/MH)","Terahash per kilowatt-hour (TH/kWh)"]},{q:"Approximately what hash rate does the open-source Bitaxe home miner achieve?",a:"About 3 TH/s",wrong:["About 30 TH/s","About 300 GH/s","About 0.3 PH/s"]},{q:"Why can ASICs not be repurposed once Bitcoin mining becomes unprofitable?",a:"They are application-specific and can only run the SHA-256 algorithm",wrong:["They require proprietary firmware that prevents other software from running","Their cooling systems are designed exclusively for Bitcoin network voltage requirements","They use encrypted memory modules that are locked to Bitcoin pool credentials"]},{q:"Which early Bitcoin miner was also known as a prolific GPU miner around 2010–2011?",a:"Laszlo Hanyecz (the Bitcoin Pizza guy)",wrong:["Hal Finney, who mined the first transaction from Satoshi","Roger Ver, who mined the first blocks on Bitcoin testnet","Nick Szabo, who later sold his GPU rigs to fund Bit Gold research"]},{q:"What milestone did the Bitcoin network hashrate reach in 2025?",a:"1 ZH/s (1 zettahash per second)",wrong:["1 EH/s (1 exahash per second)","1 PH/s (1 petahash per second)","100 EH/s (100 exahashes per second)"]},{q:"What notable event happened with a Bitaxe miner in July 2024?",a:"A Bitaxe solo-mined a valid Bitcoin block, beating billion-to-one odds",wrong:["A Bitaxe achieved a world record hash rate of 10 TH/s for a home device","A Bitaxe was the first open-source device submitted to a major mining pool","A Bitaxe operator won a class-action lawsuit against an ASIC manufacturer"]},{q:"How are some miners repurposing the waste heat from ASIC rigs?",a:"Heating homes, greenhouses, and swimming pools",wrong:["Powering adjacent data centers through thermoelectric generators","Generating steam to drive small turbines for on-site electricity recovery","Pre-heating industrial boilers to reduce natural gas consumption at factories"]}],mining_economics:[{q:"What is the current Bitcoin block subsidy after the April 2024 halving?",a:"3.125 BTC per block",wrong:["Whether mining pool operators should be legally required to hold a reserve of Bitcoin to guarantee block rewards","Whether national governments can legally impose confiscatory taxes on mining revenue without undermining security","Whether rising global energy costs will eventually make proof-of-work mining permanently economically unviable"]},{q:'What is "hashprice" in Bitcoin mining economics?',a:"Revenue earned per unit of hashrate per day, usually expressed in $/TH/day",wrong:["The market price of a new ASIC miner measured in USD per terahash of rated capacity","The electricity cost required to produce one terahash of mining output per hour","The break-even Bitcoin price at which a miner's marginal cost equals block reward value"]},{q:"What electricity cost range do large-scale miners typically target to remain competitive?",a:"$0.02–$0.05 per kWh",wrong:["$0.08–$0.12 per kWh","$0.10–$0.15 per kWh","$0.01–$0.02 per kWh"]},{q:"What percentage of a Bitcoin miner's operating costs does energy typically represent?",a:"60–80% of total operating costs",wrong:["20–35% of total operating costs","40–55% of total operating costs","85–95% of total operating costs"]},{q:'What is the "security budget" debate in Bitcoin mining?',a:"Whether transaction fees will be sufficient to incentivize miners after block subsidies approach zero",wrong:["Whether mining pool operators should be required to hold a reserve of BTC as collateral as defined by Bitcoin consensus rules enforced by all full nodes","Whether governments can legally tax mining revenue without undermining network security as defined by Bitcoin consensus rules enforced by all full nodes","Whether energy costs will eventually make proof-of-work mining economically impossible as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"What is the typical mining pool fee that pools charge for shared mining rewards?",a:"Around 1–2% of earned rewards",wrong:["Around 5–10% of earned rewards","Around 0.1–0.25% of earned rewards","Around 3–5% of earned rewards"]},{q:"How does Bitcoin's difficulty adjustment maintain the ~10-minute block time?",a:"It recalibrates every 2,016 blocks to keep average block time near 10 minutes regardless of hashrate changes",wrong:["It automatically throttles miners' submission rate if blocks are found faster than every 9 minutes","It uses a rolling 144-block average to smoothly adjust the proof-of-work target every day as defined by Bitcoin consensus rules enforced by all full nodes","It resets the target difficulty at each block based on the hash of the previous block header as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"Approximately how much energy does Bitcoin consume annually?",a:"About 150 TWh per year",wrong:["About 50 TWh per year","About 500 TWh per year","About 1,000 TWh per year"]},{q:"What proportion of Bitcoin mining is estimated to use renewable energy sources?",a:"Over 50% is estimated to come from renewable sources",wrong:["About 10–15% is estimated to come from renewable sources","About 25–30% is estimated to come from renewable sources","About 75–80% is estimated to come from renewable sources"]},{q:"Why do transaction fees become proportionally more important after each halving?",a:"The block subsidy is cut in half, so fees make up a larger share of total miner revenue",wrong:["More transactions are broadcast after each halving due to increased Bitcoin adoption and price","Mining difficulty resets after each halving, temporarily increasing the fee market competitiveness","ASIC efficiency improvements slow after halvings, raising the cost basis miners must recover"]}],taproot_assets:[{q:"What company developed the Taproot Assets protocol?",a:"Lightning Labs",wrong:["They can automatically convert local fiat currency to Bitcoin at the best available exchange rate with no fees","They can access zero-fee remittance payment corridors by routing transactions through sovereign node operators","They can participate in DeFi yield farming protocols directly without ever leaving the Bitcoin network layer"]},{q:"What was the original name of the Taproot Assets protocol before it was renamed?",a:"Taro",wrong:["Omni","Fabric","Sapio"]},{q:"Where does the actual asset data live in the Taproot Assets protocol?",a:"Off-chain, with cryptographic proofs committed on-chain via Taproot",wrong:["Fully on-chain inside OP_RETURN outputs attached to each UTXO","In a federated sidechain pegged to the Bitcoin mainchain via a two-way peg","Distributed across Lightning Network gossip messages anchored by node signatures"]},{q:"What Bitcoin upgrade was a technical prerequisite for the Taproot Assets protocol?",a:"Taproot (BIP341/342), which introduced MAST and tapscript commitment structures",wrong:["SegWit (BIP141), which introduced the witness discount and fixed transaction malleability","CheckSequenceVerify (BIP112), which introduced relative timelocks for channel safety","P2SH (BIP16), which introduced hash-locked scripts and multi-signature spending conditions"]},{q:"What key benefit does Taproot Assets offer to users in high-inflation countries?",a:"They can hold USD-pegged stablecoins and transact over Lightning while inheriting Bitcoin's security",wrong:["They can convert local currency to BTC automatically at the best available exchange rate","They can access zero-fee remittance corridors by routing through sovereign node operators","They can participate in DeFi yield protocols without leaving the Bitcoin network stack as defined by Bitcoin consensus rules enforced by all full nodes"]},{q:"When did Taproot Assets launch on Bitcoin mainnet?",a:"Late 2023",wrong:["Early 2021, shortly after the Taproot soft fork activated","Mid 2022, following a year-long testnet deployment by Lightning Labs","Early 2024, alongside the Bitcoin halving block at height 840,000"]},{q:"How does edge routing work in a Taproot Assets Lightning payment?",a:"Intermediate routing nodes handle only BTC; the final recipient receives the Taproot Asset",wrong:["Every routing node must hold the specific Taproot Asset being transferred along the path","Taproot Asset payments are split into BTC-equivalent shards that each routing node recombines","The sender converts the asset to BTC at the first hop and the receiver converts back at the last hop"]},{q:"How does Taproot Assets differ from Ethereum ERC-20 tokens?",a:"Taproot Assets inherit Bitcoin's security and require no separate smart contract execution environment",wrong:["Taproot Assets use a layer-2 virtual machine that runs alongside the Bitcoin script interpreter","Taproot Assets require validator nodes to stake BTC as a bond to attest to correct asset issuance","Taproot Assets rely on zero-knowledge rollups posted to Bitcoin rather than on-chain contract state"]},{q:"What data structure does Taproot Assets use to commit asset state to Bitcoin?",a:"Merkle trees committed inside Taproot's MAST structure",wrong:["Verkle trees embedded in the SegWit witness field of Bitcoin transactions","Sparse Merkle tries anchored via OP_RETURN outputs to each Bitcoin block","Patricia tries stored in Lightning channel state and settled during channel closure"]},{q:"What type of assets can be issued using the Taproot Assets protocol?",a:"Fixed-supply tokens, reissuable stablecoins, and other custom asset types",wrong:["Only non-fungible tokens representing unique Bitcoin UTXOs with inscribed metadata","Only fiat-pegged stablecoins backed by proof-of-reserve attestations from custodians","Only wrapped versions of existing ERC-20 tokens bridged from Ethereum via atomic swaps"]}],op_codes_bitcoin:[{q:"What is the foundational opcode that verifies a digital signature in Bitcoin Script?",a:"OP_CHECKSIG",wrong:["OP_VERIFY","OP_EQUALVERIFY","OP_HASH160"]},{q:"What Bitcoin scripting language property prevents infinite loops and ensures termination?",a:"Bitcoin Script is non-Turing-complete with no loops or recursion",wrong:["Bitcoin Script has a hard gas limit that terminates execution after a fixed number of opcodes","Bitcoin Script requires all scripts to be pre-registered in a whitelist of approved templates","Bitcoin Script uses a time-boxed interpreter that terminates any script exceeding 10 milliseconds"]},{q:"What does OP_RETURN do in Bitcoin Script?",a:"Marks an output as permanently unspendable and allows arbitrary data to be embedded",wrong:["Returns the top stack value to the calling script as an exit code for conditional branches","Refunds the transaction fee to the sender if the script fails to execute successfully","Terminates script execution early and marks the transaction as valid without further checks"]},{q:"What is OP_CHECKLOCKTIMEVERIFY (CLTV) commonly used for?",a:"Locking coins until a specified block height or Unix timestamp, used in Lightning HTLCs",wrong:["Verifying that a transaction was signed before a certain block height to prevent replay attacks","Checking whether a block timestamp is within a valid range to prevent time-warp exploits","Requiring that spending transactions include a minimum number of confirmations before being valid"]},{q:"What is OP_CHECKSEQUENCEVERIFY (CSV) and how does it differ from CLTV?",a:"A relative timelock locking a coin for N blocks after the UTXO was created, unlike CLTV's absolute lock",wrong:["An absolute timelock identical to CLTV but measured in seconds rather than block heights as defined by Bitcoin consensus rules enforced by all full nodes","A relative fee check ensuring a transaction pays at least N satoshis per byte before being relayed","A sequence number validator that confirms inputs are signed with the correct nSequence bitmask"]},{q:"Why was OP_CAT originally disabled in Bitcoin Script?",a:"Satoshi disabled it as a precaution against potential vulnerabilities and memory exhaustion attacks",wrong:["Miners voted to disable it in 2011 to prevent concatenation-based denial-of-service on full nodes","The BIP process rejected OP_CAT because it duplicated functionality already covered by OP_SUBSTR","Core developers disabled it during the 2013 database fork to reduce script complexity mid-crisis"]},{q:"What capability would re-enabling OP_CAT provide to Bitcoin Script?",a:"Covenants, ZK proof verification on-chain, vaults, and expanded smart contract functionality",wrong:["Turing-complete execution, allowing arbitrary programs to run inside Bitcoin transactions","Native cross-chain atomic swaps without requiring hash time-locked contracts or pre-images","Dynamic fee adjustment inside scripts, allowing self-amending transactions based on mempool state"]},{q:"What is BitVM and who proposed it?",a:"A system by Robin Linus enabling Turing-complete computation via optimistic execution and fraud proofs",wrong:["A formal verification framework by Andrew Poelstra for proving Bitcoin script correctness at compile time","A proposed opcode suite by Jeremy Rubin enabling covenants and recursive transaction templates natively","A sidechain design by Adam Back using Bitcoin opcodes for confidential transaction verification"]},{q:"What does OP_VAULT (BIP345) enable for Bitcoin holders?",a:"Coin vaults with enforced withdrawal delays and a recovery path to thwart theft",wrong:["Multi-party time-locked escrow contracts that release funds based on external oracle attestations","Automatic re-locking of coins to a cold storage address if a spending transaction is unconfirmed","Covenant-based inheritance schemes where heirs receive coins after a fixed block height delay"]},{q:"What is the Simplicity language and who developed it?",a:"A formally verifiable smart contract language for Bitcoin developed by Andrew Poelstra at Blockstream",wrong:["A high-level scripting language for Bitcoin compiled to opcodes, developed by Robin Linus at BitVM Labs","A zero-knowledge proof system for Bitcoin scripts created by Pieter Wuille at Chaincode Labs","A stack-based Turing-complete language for Bitcoin sidechains designed by Gregory Maxwell at Blockstream"]}],bip_standards:[{q:"What does BIP stand for in Bitcoin development?",a:"Bitcoin Improvement Proposal",wrong:["Bitcoin Integration Protocol","Bitcoin Implementation Parameter","Bitcoin Infrastructure Patch"]},{q:"What does BIP32 define?",a:"Hierarchical deterministic (HD) wallets that generate a full key tree from one master seed",wrong:["The mnemonic seed phrase standard using a 2048-word wordlist for human-readable backups","The derivation path format m/purpose'/coin'/account'/change/index for wallet compatibility","The Pay-to-Script-Hash address format allowing complex redemption scripts to use short addresses"]},{q:"How many words are in a standard BIP39 mnemonic seed phrase?",a:"12 or 24 words drawn from a 2048-word wordlist",wrong:["8 or 16 words drawn from a 4096-word phonetically distinct wordlist","10 or 20 words drawn from a 1024-word wordlist filtered for international readability","6 or 12 words drawn from a 512-word wordlist designed for maximum memorability"]},{q:"What unique property do BIP39 words share that aids disambiguation?",a:"The first 4 letters of each word are unique across the entire 2048-word wordlist",wrong:["Each word contains exactly one vowel cluster, making audio transcription unambiguous","No two words share more than two consecutive letters, preventing handwriting confusion","Every word has a unique last two letters, enabling checksummed manual entry validation"]},{q:"What critical bug did BIP141 (SegWit) fix in the Bitcoin protocol?",a:"Transaction malleability, which had prevented safe construction of the Lightning Network",wrong:["The block size limit bug that allowed miners to produce blocks larger than 1 MB without penalty","The time-warp attack that allowed difficulty manipulation by lying about block timestamps","The inflation bug that briefly allowed miners to create more coinbase outputs than permitted"]},{q:"What three major improvements did BIP341/342 (Taproot) introduce?",a:"Schnorr signatures, MAST (Merkelized Abstract Syntax Trees), and Tapscript",wrong:["Bulletproofs, covenant opcodes, and cross-input signature aggregation for privacy","Confidential transactions, threshold signatures, and probabilistic payment channels","Adaptor signatures, recursive covenants, and scriptless script channel factories"]},{q:"What does BIP119 (CTV / CheckTemplateVerify) propose?",a:"A covenant opcode constraining how a coin can be spent to a set of pre-defined transaction templates",wrong:["A threshold signature scheme allowing n-of-m signers to collaboratively authorize transactions","A payment channel factory design enabling thousands of channels from a single on-chain transaction","A fee estimation algorithm that pre-commits to a fee rate before mining to reduce fee sniping"]},{q:"What privacy mechanism does BIP47 (PayNym) provide?",a:"Payment codes letting senders derive unique per-payment addresses via ECDH without address reuse",wrong:["CoinJoin coordination codes that allow trustless mixing of outputs across multiple participants","Stealth addresses generated per-block so receivers never publish a static on-chain identifier","Blind signature tokens allowing receivers to request payments without revealing their public key"]},{q:"How does BIP78 (PayJoin) disrupt blockchain surveillance?",a:"Sender and receiver both contribute inputs, breaking common chain analysis ownership heuristics",wrong:["It replaces transaction IDs with unlinkable blinded identifiers stored in the witness field","It batches multiple payments into one transaction with deliberately indistinguishable output values","It routes payments through an intermediary node that reassembles split UTXOs before broadcast"]},{q:"What is the derivation path structure defined by BIP44?",a:"m/purpose'/coin'/account'/change/index",wrong:["m/account'/coin'/purpose'/index/change","m/index/change/account'/coin'/purpose'","m/coin'/purpose'/change/account'/index"]}]};var STATIC_QUESTS=function(){var e=[];return Object.keys(QUESTION_BANK).forEach(function(t){if("_general"!==t)for(var o=QUESTION_BANK[t],n=Math.floor(o.length/5),i=0;i{visitedForQuest.includes(e)||visitedForQuest.push(e)}),void 0!==auth&&auth.currentUser?(loadCompletedQuests(auth.currentUser.uid),_loadWeeklyCompleted()):setTimeout(initQuests,2e3)}function _getDailyActivities(){var e=(new Date).toISOString().split("T")[0],t=safeJSON("btc_daily_activities",{});return t.date!==e&&(t={date:e,quiz:!1,trivia:!1,poll:!1,sfAwarded:!1}),t}function _markDailyActivity(e){var t=_getDailyActivities();t[e]=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(t))}function _checkDailyAllThree(){var e=_getDailyActivities();if(e.quiz&&e.trivia&&e.poll&&!e.sfAwarded){e.sfAwarded=!0,localStorage.setItem("btc_daily_activities",JSON.stringify(e));var t=(new Date).toISOString().split("T")[0];void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({dailyAllThreeDate:t,dailyQuizDone:!0,dailyTriviaDone:!0,dailyPollDone:!0}).catch(function(){}),"function"==typeof window.contributeSatoshiFavor&&window.contributeSatoshiFavor("daily_all_three")}}async function loadCompletedQuests(e){if(db)try{const t=await db.collection("users").doc(e).get();t.exists&&t.data().completedQuests&&(t.data().completedQuests.forEach(e=>completedQuests.add(e)),questCount=completedQuests.size)}catch(e){}}function onChannelVisitForQuest(e){visitedForQuest.includes(e)||visitedForQuest.push(e);const t=visitedForQuest.length;for(const e of QUEST_TRIGGERS)if(t===e&&!currentQuest){setTimeout(()=>{"function"==typeof showToast&&showToast("⚡ You have explored "+e+" channels! A Quest is ready!"),setTimeout(()=>generateAndShowQuest(),3e3)},2e3);break}}function generateAndShowQuest(e,t,o){var n=(new Date).toISOString().split("T")[0],i=safeJSON("btc_quest_daily",{});if(i.date!==n&&(i={date:n,count:0}),i.count>=1&&!o)return void(e&&"function"==typeof showToast&&showToast("⏰ You've completed your daily quiz! Go to Quiz Quests to retake it for a perfect score."));const a=safeJSON("btc_asked_questions",[]);let r=[];var s=null,l=t;if(t&&-1!==t.indexOf("||")){var c=t.split("||");if(l=c[0],parseInt(c[1]),s=STATIC_QUESTS.find(function(e){return e.topicKey===l&&e.partNum===parseInt(c[1])})){var d="q__"+l+"__"+c[1];if(completedQuests.has(d))return void(e&&"function"==typeof showToast&&showToast("✅ You already aced "+l.replace(/[-_]+/g," ")+" Part "+c[1]+" with a perfect score!"));var u=s.questions.map(function(e){var t=[e.a,...e.wrong].sort(()=>Math.random()-.5);return{q:e.q,options:t,answer:t.indexOf(e.a)}});return currentQuest={id:d,topicKey:l,partNum:parseInt(c[1]),totalParts:s.totalParts,title:_getStaticQuestTitle(l,parseInt(c[1]),s.totalParts),questions:u},window._currentQuestServerId=null,"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("startQuest")({questions:u.map(function(e){return{answer:e.answer}}),topicKey:l}).then(function(e){window._currentQuestServerId=e.data.questId}).catch(function(e){console.warn("Quest registration failed:",e)}),void showQuest(currentQuest,!1)}}if(l&&QUESTION_BANK[l]&&QUESTION_BANK[l].forEach(e=>r.push({...e,source:l})),!t){for(const e of visitedForQuest){const t=QUESTION_BANK[e];t&&t.forEach(t=>r.push({...t,source:e}))}if(QUESTION_BANK._general&&QUESTION_BANK._general.forEach(e=>r.push({...e,source:"_general"})),r.length<5)for(const[e,t]of Object.entries(QUESTION_BANK))if(t.forEach(t=>{r.some(e=>e.q===t.q)||r.push({...t,source:e})}),r.length>=10)break}var p=t?Math.min(3,r.length):5;if(r.length!a.includes(e.q));function m(e){for(var t=e.q.toLowerCase(),o=[[/nostr/i,"nostr"],[/lightning/i,"lightning"],[/halving/i,"halving"],[/mining/i,"mining"],[/node/i,"node"],[/wallet/i,"wallet"],[/seed.?phrase/i,"seed"],[/private.?key/i,"privkey"],[/satoshi/i,"satoshi"],[/block.?chain/i,"blockchain"],[/proof.?of.?work/i,"pow"],[/fud\b/i,"fud"],[/self.?custody/i,"custody"],[/etf/i,"etf"],[/taproot/i,"taproot"],[/difficulty/i,"difficulty"],[/mempool/i,"mempool"],[/hash.?rate/i,"hashrate"],[/white.?paper/i,"whitepaper"],[/21.?million/i,"21m"],[/inflation/i,"inflation"],[/kyc/i,"kyc"],[/privacy/i,"privacy"],[/multisig/i,"multisig"],[/dca|dollar.cost/i,"dca"],[/el.?salvador/i,"elsalvador"]],n=0;nMath.random()-.5);var g=t?Math.min(h.length,5):5,f=[],y={};if(t)for(var b=0;be.q)];localStorage.setItem("btc_asked_questions",JSON.stringify(k));const B=f.map(e=>{const t=[e.a,...e.wrong].sort(()=>Math.random()-.5),o=t.indexOf(e.a);return{q:e.q,options:t,answer:o}});currentQuest={id:x,topicKey:l||null,title:getQuestTitle(questCount,l),questions:B},window._currentQuestServerId=null,"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("startQuest")({questions:B.map(function(e){return{answer:e.answer}}),topicKey:t||null}).then(function(e){window._currentQuestServerId=e.data.questId}).catch(function(e){console.warn("Quest registration failed:",e)}),showQuest(currentQuest,!1)}function _getStaticQuestTitle(e,t,o){return({mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",energy:"🔋",cryptography:"🔐","pow-vs-pos":"⚔️","blockchain-timechain":"⛓️",books:"📚",cbdc:"🏦",cypherpunks:"🏴",mtgox:"💀",block_size_wars:"⚔️","evidence-against-alts":"⚠️",austrian_economics:"📐",gold_standard_history:"🥇",bitcoin_vs_real_estate:"🏠",satoshi_nakamoto_deep:"🧩",mining_hardware:"🖥️",mining_economics:"💹",taproot_assets:"🌳",op_codes_bitcoin:"⚙️",bip_standards:"📋",human_rights_deep:"✊",books_deep:"📚",consensus:"🤝",regulation:"⚖️",maximalism:"🔥",nostr:"🟣","investment-strategy":"📊",philosophy:"🤔",taproot:"🌳",fedimints:"🏛️",softwar:"🪖",time_preference:"⏳",governance:"🏛️","misconceptions-fud":"🚫",elevator_pitches:"🗣️"}[e]||"📖")+" "+e.replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()})+(o>1?" — Part "+t:"")}function getQuestTitle(e,t){if(t&&"_general"!==t){var o={mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",energy:"🔋",cryptography:"🔐",consensus:"🤝",regulation:"⚖️",maximalism:"🔥","difficulty-adjustment":"🎯",books:"📚",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊","smart-contracts":"📝","blockchain-timechain":"⛓️","pow-vs-pos":"⚔️","evidence-against-alts":"⚠️",organic:"🌳",peaceful:"☮️",supranational:"🔔"},n=t.replace(/_pt\d+$/,""),i=o[t]||o[n]||"⚡",a=t.replace(/_pt(\d+)$/,"").replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),r=t.match(/_pt(\d+)$/);return r&&(a+=" (Part "+r[1]+")"),i+" "+a+" Quest"}const s=["₿ Bitcoin Basics Quest","⚡ Lightning Learner Quest","🔒 Security Scholar Quest","💰 Economics Expert Quest","⛓ Technical Titan Quest","🟠 Culture Connoisseur Quest","🛡️ Sovereignty Sage Quest","👑 Satoshi Scholar Quest"];return s[e%s.length]}function playWarriorDrum(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const t=new(window.AudioContext||window.webkitAudioContext),o="undefined"!=typeof audioVolume?audioVolume:.5,n=t.currentTime;function e(e){const i=t.createOscillator(),a=t.createGain();i.connect(a),a.connect(t.destination),i.type="sine",i.frequency.setValueAtTime(150,n+e),i.frequency.exponentialRampToValueAtTime(60,n+e+.15),a.gain.setValueAtTime(.7*o,n+e),a.gain.exponentialRampToValueAtTime(.001,n+e+.4),i.start(n+e),i.stop(n+e+.4);const r=t.createOscillator(),s=t.createGain();r.connect(s),s.connect(t.destination),r.type="sine",r.frequency.setValueAtTime(80,n+e),r.frequency.exponentialRampToValueAtTime(50,n+e+.3),s.gain.setValueAtTime(.5*o,n+e),s.gain.exponentialRampToValueAtTime(.001,n+e+.5),r.start(n+e),r.stop(n+e+.5);const l=Math.floor(.08*t.sampleRate),c=t.createBuffer(1,l,t.sampleRate),d=c.getChannelData(0);for(let e=0;e",i+="

    "+(t?"Retry! Get 3+ correct for 25 XP!":"Answer 5 questions. 3+ correct = 50 XP. All 5 = 100 XP!")+"

    ",i+="",i+='
    ',e.questions.forEach((e,t)=>{i+='
    ',i+='
    Question '+(t+1)+" of 5
    ",i+='
    '+e.q+"
    ",i+='
    ',e.options.forEach((e,o)=>{i+='"}),i+="
    "}),i+="
    ",i+='',i+='',n.innerHTML=i,o.classList.add("open"),window._questAnswers=new Array(5).fill(-1),window._questCorrect=e.questions.map(e=>e.answer)}function selectAnswer(e,t,o){e.parentElement.querySelectorAll(".quest-opt").forEach(e=>e.classList.remove("selected")),e.classList.add("selected"),window._questAnswers[t]=o,window._questAnswers.every(e=>e>=0)&&(document.getElementById("questSubmitBtn").disabled=!1)}async function submitQuest(){if(window._questSubmitted)return;window._questSubmitted=!0;var e=document.getElementById("questSubmitBtn");e&&(e.disabled=!0,e.style.opacity="0.5",e.textContent="Grading...");const t=window._questAnswers,o=window._questCorrect;let n=0,i=0;if(window._currentQuestServerId&&"undefined"!=typeof firebase&&firebase.functions)try{var a=await firebase.functions().httpsCallable("gradeQuest")({questId:window._currentQuestServerId,answers:t,isRetry:!!isRetry});n=a.data.score,i=a.data.pts}catch(e){console.error("Server quest grading failed, falling back:",e),t.forEach((e,t)=>{e===o[t]&&n++})}else t.forEach((e,t)=>{e===o[t]&&n++});document.querySelectorAll(".quest-q").forEach((e,n)=>{e.querySelectorAll(".quest-opt").forEach((e,i)=>{e.disabled=!0,i===o[n]&&e.classList.add("correct"),i===t[n]&&i!==o[n]&&e.classList.add("wrong")})});let r="";var s=5===n,l=!!currentQuest.topicKey;if(isRetry)n>=3?(i||(i=25),r="🎉 "+n+"/5 correct on retry! +"+i+" XP!",!s&&l||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 - Better luck next time! Keep reading and try again.";else if(s){if(i||(i=100),r="🏆 PERFECT! 5/5! +"+i+" XP!",completedQuests.add(currentQuest.id),questCount++,"function"==typeof window.nachoGlobalAnnounce&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var c=void 0!==currentUser&¤tUser&¤tUser.username||auth.currentUser.displayName||"A mystery Bitcoiner",d=currentQuest.title||"a Quiz Quest";window.nachoGlobalAnnounce("🏆 @"+c+" just aced "+d+" with a PERFECT 5/5! Think you can do the same? ➡️ [Quest Hub](#quests)",auth.currentUser.uid)}}else n>=3?(i||(i=50),r="🎉 "+n+"/5 correct! +"+i+" XP!",l||completedQuests.add(currentQuest.id),questCount++):r="😅 "+n+"/5 - You can retry for 25 XP!";if(i>0){"function"==typeof notifySelfQuest&¬ifySelfQuest(currentQuest.title),"function"==typeof notifySelfPoints&¬ifySelfPoints(i,"🏆 Quest: "+(currentQuest.title||"Quest")),"function"==typeof window._raidOnQuizComplete&&window._raidOnQuizComplete(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(i);var u=(new Date).toISOString().split("T")[0],p=safeJSON("btc_quest_daily",{});p.date!==u&&(p={date:u,count:0}),p.count++,p.lastScore=n,p.lastTopic=currentQuest.topicKey||null,p.lastTitle=currentQuest.title||null,localStorage.setItem("btc_quest_daily",JSON.stringify(p)),_markDailyActivity("quiz"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({questsCompletedToday:p.count||0,lastQuestDate:u}).catch(function(e){console.error("Quest sync failed:",e)})}try{completedQuests.has(currentQuest.id)&&void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&(await db.collection("users").doc(auth.currentUser.uid).update({completedQuests:firebase.firestore.FieldValue.arrayUnion(currentQuest.id)}),db.collection("stats").doc("global").set({questsCompleted:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){}))}catch(e){console.error("Quest completion sync failed:",e)}const h=document.getElementById("questSubmitBtn");h&&(h.style.display="none");const m=document.querySelector(".quest-skip");m&&(m.style.display="none"),window._questScore=n,window._questMsg=r,window._questPts=i;const g=document.querySelector(".quest-header");g&&(g.innerHTML='
    ⚡ QUEST COMPLETE

    '+currentQuest.title+'

    '+(5===n?"🏆":n>=3?"🎉":"😅")+'
    '+n+' / 5 Correct
    Review your answers below - green is correct, red is wrong
    ');const f=document.getElementById("questInner");f&&f.scrollTo({top:0,behavior:"smooth"}),"function"==typeof showToast&&showToast(r)}function playHooraySound(){if(("function"!=typeof canPlaySound||canPlaySound())&&("undefined"==typeof audioEnabled||audioEnabled))try{const e=new(window.AudioContext||window.webkitAudioContext),t="undefined"!=typeof audioVolume?audioVolume:.5,o=e.currentTime;[523,659,784,1047].forEach((n,i)=>{const a=e.createOscillator(),r=e.createGain();a.connect(r),r.connect(e.destination),a.type="sine",a.frequency.value=n,r.gain.setValueAtTime(.15*t,o+.1*i),r.gain.exponentialRampToValueAtTime(.001,o+.1*i+.4),a.start(o+.1*i),a.stop(o+.1*i+.4);const s=e.createOscillator(),l=e.createGain();s.connect(l),l.connect(e.destination),s.type="triangle",s.frequency.value=2*n,l.gain.setValueAtTime(.06*t,o+.1*i),l.gain.exponentialRampToValueAtTime(.001,o+.1*i+.3),s.start(o+.1*i),s.stop(o+.1*i+.3)}),[1047,1319,1568].forEach(n=>{const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.type="sine",i.frequency.value=n,a.gain.setValueAtTime(.12*t,o+.45),a.gain.linearRampToValueAtTime(.1*t,o+.7),a.gain.exponentialRampToValueAtTime(.001,o+1.3),i.start(o+.45),i.stop(o+1.3)})}catch(e){}}function _resolveQuestChannel(e){if(!e||void 0===CHANNELS)return null;if(CHANNELS[e])return e;var t=e.replace(/_pt\d+$/,"");if(CHANNELS[t])return t;var o={cycles:"cyles",dlcs:"discrete_log_contracts__dlcs",first_principles:"1_first_principles",foss:"free_and_open_source_software__foss",ordinals_inscriptions:"ordinals",spv:"simplified_payment_verification__spv",halving:"scarce","el-salvador":"regulation"};if(o[e]&&CHANNELS[o[e]])return o[e];if(o[t]&&CHANNELS[o[t]])return o[t];for(var n=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper"],i=0;i=3&&playHooraySound();const n=document.querySelector(".quest-questions");n&&(n.style.display="none");var i=_resolveQuestChannel(currentQuest?currentQuest.topicKey:null);if(!i&&void 0!==CHANNELS){var a=["history","mining","layer-2-lightning","self-custody","problems-of-money","whitepaper","cryptography","philosophy","energy","nodes"].filter(function(e){return!!CHANNELS[e]}).sort(function(){return Math.random()-.5});a.length&&(i=a[0])}var r="";if(i&&void 0!==CHANNELS&&CHANNELS[i]){var s=CHANNELS[i].title;r='
    '+(currentQuest&¤tQuest.topicKey&&_resolveQuestChannel(currentQuest.topicKey)?5===e?"📚 Keep learning":"📖 Study up on":"🔍 Explore next")+'
    '+s+" →
    "}const l=document.querySelector(".quest-header");l&&(l.innerHTML='
    ⚡ QUEST COMPLETE

    '+currentQuest.title+'

    '+(5===e?"🏆":e>=3?"🎉":"😅")+'
    '+e+' / 5 Correct
    '+t+"
    "+(o>0?'
    +'+o+" XP earned!
    ":"")+r+(e<5?'":"")+'');const c=document.getElementById("questInner");c&&(c.scrollTop=0)}function retryQuest(){currentQuest.questions.forEach(e=>{const t=e.options[e.answer];e.options.sort(()=>Math.random()-.5),e.answer=e.options.indexOf(t)}),showQuest(currentQuest,!0)}function startQuestManual(e){if(!currentQuest)if(e){if(generateAndShowQuest(!0,e),"function"==typeof isMobile&&isMobile()){const e=document.getElementById("sidebar");e&&e.classList.remove("open")}}else _showQuestTopicPicker()}function _getDailyRecommendedQuiz(e){if(!e||0===e.length)return null;for(var t=e.map(function(e){return e.key}).sort(),o=t.length,n=new Date("2026-01-01T00:00:00Z").getTime(),i=(new Date).toISOString().split("T")[0],a=new Date(i+"T00:00:00Z").getTime(),r=Math.floor((a-n)/864e5),s=r%o,l=Math.floor(r/o),c=t.slice(),d=7919*l+31337,u=c.length-1;u>0;u--){var p=(d=(16807*d+0)%2147483647)%(u+1),h=c[u];c[u]=c[p],c[p]=h}var m=c[s];return e.find(function(e){return e.key===m})||null}function _showQuestTopicPicker(){var e=[],t={_general:"🌐",mining:"⛏️",nodes:"🖥️","privacy-nonkyc":"🕵️","problems-of-money":"💸","layer-2-lightning":"⚡","self-custody":"🔑",halving:"📉",history:"📜","satoshi-nakamoto":"🧩",whitepaper:"📄",money:"💰",scarce:"💎",secure:"🛡️",decentralized:"🌍",programmable:"💻",dominant:"👑",philosophy:"🤔",energy:"🔋",cryptography:"🔐",consensus:"🤝",taproot:"🌳",regulation:"⚖️",maximalism:"🔥",utxos:"📦","difficulty-adjustment":"🎯",transaction_fees:"💳",game_theory:"♟️",books:"📚","orange-pilling":"🍊",nostr:"🟣","use-cases":"🛠️","investment-strategy":"📊",geopolitics___macroeconomics:"🌎",human_rights__social_justice_and_freedo:"✊","smart-contracts":"📝",sidechains:"🔗",stablecoins:"🏦",fedimints:"🏛️","pow-vs-pos":"⚔️","blockchain-timechain":"⛓️",softwar:"🪖",time_preference:"⏳",governance:"🏛️","apps-tools":"🧰","misconceptions-fud":"🚫",elevator_pitches:"🗣️"};STATIC_QUESTS.forEach(function(o){var n=o.topicKey,i=o.id,a=n.replace(/_pt\d+$/,""),r=t[n]||t[a]||"📖",s=n.replace(/[-_]+/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),l=o.totalParts>1?s+" — Part "+o.partNum:s,c=completedQuests.has(i);e.push({key:n+"||"+o.partNum,label:l,emoji:r,count:5,done:c,questId:i})}),e.sort(function(e,t){return e.done!==t.done?e.done?1:-1:e.label.localeCompare(t.label)});var o=e.filter(function(e){return e.done}).length,n=document.getElementById("questModal");if(n){var i=document.getElementById("questInner");if(i){var a='

    Choose a Quest Topic

    Pick a Bitcoin topic to test your knowledge

    '+o+"/"+e.length+' topics completed
    ',r=_getDailyRecommendedQuiz(e);r&&(a+=""),a+='',a+='',a+='
    ',e.forEach(function(e){var t=e.done?"rgba(34,197,94,0.06)":"rgba(255,255,255,0.02)",o=e.done?"rgba(34,197,94,0.2)":"var(--border)",n=e.done?'':''+e.count+"Q";a+=""}),a+="
    ",a+='',i.innerHTML=a,setTimeout(function(){var e=document.querySelectorAll("#questTopicList button");e.forEach(function(e){var t=(e.getAttribute("onclick")||"").match(/_startQuestTopic\('([^']+)'\)/);t&&(e.dataset.key=t[1]),e.dataset.label=e.textContent.trim()});var t=document.getElementById("questSearch");t&&t.addEventListener("input",function(){var t=this.value.toLowerCase();e.forEach(function(e){var o=e.dataset.label.toLowerCase();e.style.display=o.includes(t)?"":"none"})})},0),n.classList.add("open")}}}function skipQuest(){closeQuest()}function closeQuest(){document.getElementById("questModal").classList.remove("open"),currentQuest=null,isRetry=!1}function _renderFavorTab(e){if(e){var t="function"==typeof window._resolveFavorState?window._resolveFavorState():null,o=t&&t.favorActive,n=t&&t.points||0,i=Math.min(100,n/21*100),a='
    ✨⛏️
    Satoshi\'s Favor
    Community mining when the community earns 21 points.
    Chance to win 21,000 sats! ⚡
    ';if(o){var r=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();a+='
    🎉 SATOSHI\'S FAVOR IS ACTIVE!
    '+Math.floor(r/6e4)+"m "+Math.floor(r%6e4/1e3)+'s
    Mine below 1,000 to win 21,000 sats!
    ',a+=''}else a+='
    '+n+'/21 points
    '+(21-n)+" more points to activate
    ";if(a+='
    ⚔️ Faction SF Competition
    🐝
    Cyber Hornets
    0
    SF points
    VS
    🦡
    Honey Badgers
    0
    SF points
    👤Unaffiliated - Choose a Faction!
    0pts
    ',a+='
    How it works:
    This is a community challenge - everyone\'s points combine!

    • Complete the daily Quiz Quest, Trivia & Poll = 1 point
    • Earn a badge = 1 point
    • Level up to Pleb/Stacker ranks = 1 point each
    • Level up to Maxi ranks = 5 points each
    • Level up to Papa John or higher = 10 points
    • At 21 points, a mining competition opens for 60 minutes
    • Extra points beyond 21 add +3 min each (even while active!)
    • 10 hashes max per minute per user (60 second cooldown)
    • Generate a random hash. Below 1,000 = win 21,000 sats!',a+='
    🏆 All-Time Lowest Hashes
    Loading...
    ',a+='
    ⭐ Your Personal Best
    Loading...
    ',a+="
    ",e.innerHTML=a,_startFactionScoreboardListener(),_loadFavorLeaderboards(),o){var s=document.getElementById("favorTabTimer");if(s)var l=setInterval(function(){if(s){if(!t||!t.favorActive)return s.textContent="EXPIRED",void clearInterval(l);var e=(t.favorEndBase?t.favorEndBase.toMillis():0)+60*(t.bonusMinutes||0)*1e3-Date.now();if(e<=0)s.textContent="00:00";else{var o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);s.textContent=o+"m "+n+"s"}}else clearInterval(l)},1e3)}}}function _startFactionScoreboardListener(){if(window._factionScoreUnsub&&(window._factionScoreUnsub(),window._factionScoreUnsub=null),void 0!==db){var e=db.collection("satoshiFavor").doc("factionTotals");window._factionScoreUnsub=e.onSnapshot(function(e){var t=e.exists?e.data():{cyber_hornets:0,honey_badgers:0,unaffiliated:0},o=t.cyber_hornets||0,n=t.honey_badgers||0,i=o+n,a=document.getElementById("sfScoreHornets"),r=document.getElementById("sfScoreBadgers"),s=document.getElementById("sfScoreUnaffiliated"),l=document.getElementById("sfScoreLeader"),c=document.getElementById("sfScoreBar"),d=document.getElementById("sfScoreBarFill"),u=document.getElementById("sfNoFactionNote"),p=t.unaffiliated||0;if(a&&(a.textContent=o.toLocaleString()),r&&(r.textContent=n.toLocaleString()),s&&(s.textContent=p.toLocaleString()),l&&(l.textContent=o>n?"🐝 Leading":n>o?"🦡 Leading":i>0?"Tied!":""),c&&d&&i>0){c.style.display="block";var h=Math.round(o/i*100);d.style.background="linear-gradient(90deg, #f7931a "+h+"%, #a855f7 "+h+"%)"}var m=void 0!==currentUser&¤tUser&¤tUser.faction||"";u&&(u.style.display=m?"none":"block");var g=document.getElementById("sfAdminBackfill");if(g){var f=void 0!==currentUser&¤tUser&&"needcreations@gmail.com"===currentUser.email;g.style.display=f?"block":"none"}var y=void 0!==currentUser&¤tUser&¤tUser.faction||"",b=document.getElementById("factionScoreboardInner");if(b&&y){var v=b.querySelectorAll('div[style*="flex:1"]');v[0]&&(v[0].style.borderWidth="cyber_hornets"===y?"3px":"2px"),v[1]&&(v[1].style.borderWidth="honey_badgers"===y?"3px":"2px")}},function(e){console.warn("[FACTION-SCORE] Listener error:",e)})}}window._retakeLastQuiz=function(){var e=safeJSON("btc_quest_daily",{}).lastTopic||null,t=document.getElementById("questHubOverlay");t&&t.remove(),setTimeout(function(){generateAndShowQuest(!0,e,!0)},200)},window._startQuestTopic=function(e){var t=document.getElementById("questModal");if(t&&t.classList.remove("open"),currentQuest=null,!e){var o=[];for(var n in QUESTION_BANK)"_general"!==n&&(QUESTION_BANK[n].length<3||completedQuests.has("quest_"+n)||completedQuests.has(n)||-1!==weeklyCompleted.indexOf(n)||o.push(n));if(o.length>0)e=o[Math.floor(Math.random()*o.length)];else{var i=Object.keys(QUESTION_BANK).filter(function(e){return"_general"!==e&&QUESTION_BANK[e].length>=3});e=i[Math.floor(Math.random()*i.length)]}}setTimeout(function(){generateAndShowQuest(!0,e)},200)},setTimeout(initQuests,3e3),window.closeQuestHubForFavor=function(){var e=document.getElementById("questHubOverlay");e&&e.remove(),window._cleanupRaidBoss&&window._cleanupRaidBoss(),window._factionScoreUnsub&&(window._factionScoreUnsub(),window._factionScoreUnsub=null)},window._runFactionBackfill=function(){if("undefined"!=typeof firebase){var e=document.querySelector("#sfAdminBackfill button");e&&(e.textContent="⏳ Running backfill...",e.disabled=!0),firebase.functions().httpsCallable("backfillFactionTotals")({}).then(function(t){var o=t.data;"function"==typeof showToast&&showToast("✅ Backfill done! 🐝 "+(o.totals&&o.totals.cyber_hornets||0)+" vs 🦡 "+(o.totals&&o.totals.honey_badgers||0)),e&&(e.textContent="✅ Done!")}).catch(function(t){"function"==typeof showToast&&showToast("❌ Backfill error: "+t.message),e&&(e.textContent="⚡ Backfill historical data (admin)",e.disabled=!1),console.error("[BACKFILL]",t)})}};var _favorTopHashesUnsub=null,_favorPBUnsub=null;function _renderTopHashesHTML(e){var t=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null,o=Date.now(),n="";function i(e,n){var i=t&&e.username===t,a=n+1,r=1===a?"🥇":2===a?"🥈":3===a?"🥉":a+".",s="function"==typeof escapeHtml?escapeHtml(e.username||"Anon"):e.username||"Anon",l=e.value<1e3,c=e.timestamp&&"function"==typeof e.timestamp.toMillis?e.timestamp.toMillis():e.timestamp?Number(e.timestamp):0;return'
    '+r+''+(l?"🏆 ":"")+s+(i?" (you)":"")+(c&&o-c<2592e5?'NEW':"")+'
    '+e.value.toLocaleString()+"
    "}for(var a=e.slice(0,10),r=e.slice(10),s=0;s0){n+='",i&&void 0!==db&&db.collection("trivia_stats").doc(n).get().then(function(e){var t=e.exists?e.data():{},o=t.total||0;if(!(o<1))for(var n=0;n
    💡 Explanation
    '+("function"==typeof escapeHtml?escapeHtml(a.explanation):a.explanation)+"
    ",r+='
    Come back tomorrow for a new trivia question! 🧠
    '),e.innerHTML=r}else e.innerHTML='
    Trivia questions loading...
    '}function _getPollToday(){if("undefined"==typeof POLL_BANK||!POLL_BANK||!POLL_BANK.length)return null;var e=new Date,t=new Date(e.getFullYear(),0,0),o=(13*Math.floor((e-t)/864e5)+e.getFullYear())%POLL_BANK.length;return{index:o,poll:POLL_BANK[o]}}function _getPollState(){try{return JSON.parse(localStorage.getItem("btc_poll_state")||"{}")}catch(e){return{}}}function _setPollState(e){try{localStorage.setItem("btc_poll_state",JSON.stringify(e))}catch(e){}}function _renderPollTab(e){var t=_getPollToday();if(t&&t.poll){var o=_getPollState(),n=(new Date).toISOString().split("T")[0],i=o.date===n&&"number"==typeof o.chosen,a=t.poll,r='
    📊
    Poll Quest
    Vote daily - see what the community thinks
    +50 XP for voting
    ';if(r+='
    '+("function"==typeof escapeHtml?escapeHtml(a.q):a.q)+"
    ",i)_renderPollResults(e,r,a,o,n);else{var s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null,l=a.id||"poll_day_"+n;s&&void 0!==db?db.collection("poll_votes").doc(l).get().then(function(i){if(i.exists&&i.data().voters&&-1!==i.data().voters.indexOf(s)){var l=o.chosen;_setPollState(o={date:n,index:t.index,chosen:"number"==typeof l?l:-1,pollId:a.id}),_renderPollResults(e,r,a,o,n)}else _showPollVoteButtons(e,r,a)}).catch(function(){_showPollVoteButtons(e,r,a)}):_showPollVoteButtons(e,r,a)}}else e.innerHTML='
    Polls loading...
    '}function _showPollVoteButtons(e,t,o){t+='
    ';for(var n=0;n'+String.fromCharCode(65+n)+""+i+""}t+="
    ",e.innerHTML=t}function _renderPollResults(e,t,o,n,i){var a=o.id||"poll_day_"+i;void 0!==db?db.collection("poll_votes").doc(a).get().then(function(i){var a=i.exists&&i.data().votes||[0,0,0,0],r=a.reduce(function(e,t){return e+t},0)||1;_drawPollResults(e,t,o,a,r,n.chosen)}).catch(function(){_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}):_drawPollResults(e,t,o,[0,0,0,0],1,n.chosen)}function _drawPollResults(e,t,o,n,i,a){var r=t,s=["#f7931a","#3b82f6","#22c55e","#8b5cf6"];r+='
    ';for(var l=0;l
    '+(u?"✓":String.fromCharCode(65+l))+''+c+'
    '+d+"%
    "}r+="",r+='
    '+i+" total vote"+(1!==i?"s":"")+" · Come back tomorrow for a new poll!
    ",e.innerHTML=r}function _renderRaidTab(e){e.innerHTML='
    Loading Raid Boss...
    ',window._loadRaidBoss()}function _raidEmptyState(){return'
    ⚔️
    Raid Boss
    No active raid boss right now.
    Check back soon for community boss fights!
    '}function _raidVictoryBanner(e){var t="function"==typeof escapeHtml?escapeHtml(e.name||"Raid Boss"):e.name||"Raid Boss",o=_getRaidBossImage(e);return'
    '+(o?'
    '+t+'
    💀
    ':'
    💀
    ')+'
    BOSS DEFEATED! 🎉
    '+t+' has fallen!
    The community worked together and took it down! Great job everyone!
    🏆 Community reward unlocked!
    Extra orange ticket drawing for 21,000 sats - this Friday night!
    '}window._charityThankYou=function(e,t,o){var n=document.getElementById("charityThankYouOverlay");n&&n.remove();var i=document.createElement("div");i.id="charityThankYouOverlay",i.style.cssText="position:fixed;inset:0;z-index:300000;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;padding:20px;";var a=document.createElement("div");a.style.cssText="background:var(--card-bg);border:1px solid rgba(239,68,68,0.4);border-radius:20px;padding:28px 24px;max-width:360px;width:100%;text-align:center;position:relative;";var r='
    ❤️
    Thank You!
    You donated '+e.toLocaleString()+" XP - that's "+e.toLocaleString()+" sats pledged to charity.
    ";o>0&&(r+='
    +'+o.toLocaleString()+" bonus XP earned!
    "),t&&t.length>0&&(r+='
    🏼 New badge'+(t.length>1?"s":"")+" unlocked: "+t.join(", ")+"
    "),r+='
    The community will vote on which charities receive these sats.
    ',a.innerHTML=r,i.appendChild(a),i.addEventListener("click",function(e){e.target===i&&i.remove()}),document.body.appendChild(i)},window._renderCharityHome=function(){var e=document.getElementById("charityDonateHome");e&&"undefined"!=typeof firebase&&firebase.firestore&&firebase.firestore().collection("charity_stats").doc("global").get().then(function(t){var o=t.exists?t.data():{totalDonated:0,factionTotals:{}},n=o.totalDonated||0,i=o.factionTotals&&o.factionTotals.cyber_hornets||0,a=o.factionTotals&&o.factionTotals.honey_badgers||0;e.innerHTML='
    ❤️ Donate XP for Charity
    Tap to donate →
    '+n.toLocaleString()+' sats pledged
    🐝 '+i.toLocaleString()+' XP🦡 '+a.toLocaleString()+" XP
    "}).catch(function(){})},window.triviaAnswer=function(e){var t=_getTriviaToday();if(t&&t.trivia){var o=t.trivia,n=(new Date).toISOString().split("T")[0],i=_getTriviaState();if(i.date!==n){var a=e===o.answer,r=a?50:10;if(_setTriviaState(i={date:n,index:t.index,chosen:e,correct:a}),"function"==typeof awardPoints&&awardPoints(r,a?"🧠 Trivia Quest correct!":"🧠 Trivia Quest attempt"),a&&"function"==typeof window._raidOnTriviaCorrect&&window._raidOnTriviaCorrect(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(r),_markDailyActivity("trivia"),_checkDailyAllThree(),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({lastTriviaDate:n,triviaAnswered:firebase.firestore.FieldValue.increment(1),triviaCorrect:firebase.firestore.FieldValue.increment(a?1:0)}).catch(function(){}),void 0!==db){var s={total:firebase.firestore.FieldValue.increment(1)};s["option_"+e]=firebase.firestore.FieldValue.increment(1),db.collection("trivia_stats").doc(n).set(s,{merge:!0}).catch(function(){})}var l=document.getElementById("questHubBody");l&&_renderTriviaTab(l),"function"==typeof showToast&&showToast(a?"✅ Correct! +50 XP 🧠":"❌ Wrong - +10 XP for trying!",3e3)}}},window.pollVote=function(e){var t=_getPollToday();if(t&&t.poll){var o=t.poll,n=(new Date).toISOString().split("T")[0],i=_getPollState();if(i.date!==n||"number"!=typeof i.chosen){var a=document.querySelectorAll("#pollOptions button");a.forEach(function(e){e.disabled=!0,e.style.opacity="0.5",e.style.cursor="default"});var r=o.id||"poll_day_"+n,s=void 0!==auth&&auth&&auth.currentUser?auth.currentUser.uid:null;if(void 0!==db&&s){var l=db.collection("poll_votes").doc(r);db.runTransaction(function(t){return t.get(l).then(function(n){var i=n.exists?n.data():{},a=i.voters||[];if(-1!==a.indexOf(s))return Promise.reject({code:"already-voted"});var c=i.votes||[0,0,0,0];c[e]=(c[e]||0)+1,a.push(s),t.set(l,{pollId:r,question:o.q,options:o.options,votes:c,voters:a,lastUpdated:firebase.firestore.FieldValue.serverTimestamp()},{merge:!0})})}).then(function(){_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof awardPoints&&awardPoints(50,"📊 Poll Quest vote"),"function"==typeof window._raidOnPollVote&&window._raidOnPollVote(),"function"==typeof window._raidOnXPEarned&&window._raidOnXPEarned(50),"function"==typeof showToast&&showToast("📊 Vote recorded! +50 XP",3e3),_markDailyActivity("poll"),_checkDailyAllThree(),auth.currentUser.isAnonymous||db.collection("users").doc(s).update({lastPollDate:n,pollsVoted:firebase.firestore.FieldValue.increment(1)}).catch(function(){});var a=document.getElementById("questHubBody");a&&_renderPollTab(a)}).catch(function(r){if(!r||"already-voted"!==r.code)return console.error("[POLL] Vote failed:",r),"function"==typeof showToast&&showToast("⚠️ Vote failed - try again",3e3),void a.forEach(function(e){e.disabled=!1,e.style.opacity="1",e.style.cursor="pointer"});_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("You already voted on this poll today!",3e3);var s=document.getElementById("questHubBody");s&&_renderPollTab(s)})}else{_setPollState(i={date:n,index:t.index,chosen:e,pollId:o.id}),"function"==typeof showToast&&showToast("📊 Vote recorded locally",3e3);var c=document.getElementById("questHubBody");c&&_renderPollTab(c)}}}},window._raidBossUnsub=null,window._raidParticipantsUnsub=null,window._raidTimerInterval=null,window._cleanupRaidBoss=function(){window._raidBossUnsub&&(window._raidBossUnsub(),window._raidBossUnsub=null),window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null),window._raidTimerInterval&&(clearInterval(window._raidTimerInterval),window._raidTimerInterval=null),window._raidDamageDealersOpen=!1},window._loadRaidBoss=function(){window._cleanupRaidBoss();var e=document.getElementById("raidBossContent");e&&(void 0!==db?window._raidBossUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.innerHTML=_raidEmptyState();else{var o=Date.now(),n=null,i=null,a=null;if(t.forEach(function(e){var t=e.data();t._id=e.id;var r=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,s=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime?i.startTime.toMillis?i.startTime.toMillis():i.startTime:0))&&(i=t):t.defeated&&(a||(a=t))}),a&&(i||n)&&!n){window._defeatedBossId=a._id;var r=_raidVictoryBanner(a);e.innerHTML=r;var s=document.createElement("div");return s.id="raidUpcomingSection",e.appendChild(s),window._currentRaidBoss=i||a,void _renderRaidBossCard(s,i)}var l=n||i||a;l?(window._currentRaidBoss=l,_renderRaidBossCard(e,l)):e.innerHTML=_raidEmptyState()}},function(t){console.error("[RAID] Boss listener error:",t),e.innerHTML='
    ⚠️ Failed to load raid boss
    '}):e.innerHTML='
    ⚠️ Database not available
    ')};var RAID_BOSS_IMAGES={"Channel-Crawler":"images/raid-bosses/channel-crawler.png","Quiz-Crusader":"images/raid-bosses/quiz-crusader.png","TV-Titan":"images/raid-bosses/tv-titan.png","Beats-Baron":"images/raid-bosses/beats-baron.png","Flash-Flash":"images/raid-bosses/flash-flash.png","XP-Hoarder":"images/raid-bosses/xp-hoarder.png","Poll-Patroller":"images/raid-bosses/poll-patroller.png","Chat-Charger":"images/raid-bosses/chat-charger.png","Badge-Builder":"images/raid-bosses/badge-builder.png","Streak-Sage":"images/raid-bosses/streak-sage.png","Topic-Explorer":"images/raid-bosses/topic-explorer.png","Lightning-Lancer":"images/raid-bosses/lightning-lancer.png","Forum-Forge":"images/raid-bosses/forum-forge.png","Trivia-Tactician":"images/raid-bosses/trivia-tactician.png","Content-Conqueror":"images/raid-bosses/content-conqueror.png"};function _getRaidBossImage(e){return e.image||RAID_BOSS_IMAGES[e.name]||""}function _renderRaidBossCard(e,t){Date.now();var o=t.startTime?t.startTime.toMillis?t.startTime.toMillis():t.startTime:0,n=t.endTime?t.endTime.toMillis?t.endTime.toMillis():t.endTime:0,i=_getRaidBossImage(t);if(t.placeholder){var a=o?new Date(o):null,r=a?a.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"Soon",s=i?''+(t.name||':'
    ⚔️
    ';return e.innerHTML='
    '+s+'
    '+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
    '+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
    '+("function"==typeof escapeHtml?escapeHtml(r):r)+'
    Get ready to team up and take it down!
    🏆 Community Prize
    Defeat the boss = extra orange ticket giveaway for 21,000 sats!
    ',void _startRaidCountdown("raidCountdownPlaceholder",o)}if(t.defeated){var l=t.winners||[],c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:null;if(c&&-1!==l.indexOf(c)&&localStorage.setItem("btc_raid_winner","true"),l.length>0)for(var d=0;d'+(t.name||
    💀
    ':'
    💀
    ';return e.innerHTML='
    '+u+'
    DEFEATED!
    '+("function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss")+'
    '+("function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"")+'
    🎉 Community reward unlocked!
    Extra orange ticket giveaway for 21,000 sats!
    ',void(window._defeatedBossId=t._id)}var p=void 0!==t.current?t.current:void 0!==t.currentHP?t.currentHP:0,h=t.target||t.targetHP||1,m=Math.min(100,Math.round(p/h*100)),g=Math.max(0,h-p),f=Math.max(0,100-m),y="function"==typeof escapeHtml?escapeHtml(t.name||"Raid Boss"):t.name||"Raid Boss",b="function"==typeof escapeHtml?escapeHtml(t.description||""):t.description||"",v=i?''+y+'':'
    👹
    ';if(e.innerHTML='
    '+v+'
    '+y+'
    '+b+'
    ❤️ Boss Health'+g.toLocaleString()+" / "+h.toLocaleString()+' HP
    '+m+'% damage dealt
    ⏰ Time Remaining
    🏆 Community Prize
    Defeat the boss and the community earns an extra orange ticket giveaway for 21,000 sats!
    Loading...
    ',!document.getElementById("raidShimmerStyle")){var w=document.createElement("style");w.id="raidShimmerStyle",w.textContent="@keyframes raidShimmer{0%{transform:translateX(-100%)}100%{transform:translateX(100%)}}",document.head.appendChild(w)}_startRaidCountdown("raidTimer",n),window._raidActiveTab="current",window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),_listenRaidParticipants(t._id)}function _startRaidCountdown(e,t){function o(){var o=document.getElementById(e);if(!o)return clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var n=Math.max(0,t-Date.now());if(n<=0)return o.textContent="Time's up!",clearInterval(window._raidTimerInterval),void(window._raidTimerInterval=null);var i=Math.floor(n/864e5),a=Math.floor(n%864e5/36e5),r=Math.floor(n%36e5/6e4),s=Math.floor(n%6e4/1e3);o.textContent=(i>0?i+"d ":"")+(a>0?a+"h ":"")+(r<10?"0":"")+r+"m "+(s<10?"0":"")+s+"s"}window._raidTimerInterval&&clearInterval(window._raidTimerInterval),o(),window._raidTimerInterval=setInterval(o,1e3)}function _listenRaidParticipants(e){window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),void 0!==db&&(window._raidParticipantsUnsub=db.collection("raid_bosses").doc(e).collection("participants").orderBy("contributed","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t)if(e.empty)t.innerHTML='
    No raiders yet - be the first! ⚔️
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,l=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] Participants listener error:",e)}))}function _listenAllTimeRaiders(){window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),void 0!==db&&(window._raidAllTimeUnsub=db.collection("users").where("raidDamageAllTime",">",0).orderBy("raidDamageAllTime","desc").limit(20).onSnapshot(function(e){var t=document.getElementById("raidParticipants");if(t&&"alltime"===window._raidActiveTab)if(e.empty)t.innerHTML='
    No all-time damage recorded yet.
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.raidDamageAllTime||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,l=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] All-time raiders listener error:",e);var t=document.getElementById("raidParticipants");t&&"alltime"===window._raidActiveTab&&(t.innerHTML='
    Could not load all-time data.
    ')}))}window._raidDamageDealersOpen=!1,window._raidDamageDealersUnsub=null,window._toggleRaidDamageDealers=function(){var e=document.getElementById("raidDamageDealers"),t=document.getElementById("raidDamageDealersBtn");if(e){if(window._raidDamageDealersOpen=!window._raidDamageDealersOpen,!window._raidDamageDealersOpen)return e.style.display="none",t&&(t.textContent="⚔️ Top Damage Dealers"),void(window._raidDamageDealersUnsub&&(window._raidDamageDealersUnsub(),window._raidDamageDealersUnsub=null));e.style.display="block",t&&(t.textContent="▲ Hide Damage Dealers"),e.innerHTML='
    Loading...
    ';var o=window._defeatedBossId||(window._currentRaidBoss&&window._currentRaidBoss._id?window._currentRaidBoss._id:null);o&&void 0!==db?window._raidDamageDealersUnsub=db.collection("raid_bosses").doc(o).collection("participants").orderBy("contributed","desc").limit(30).onSnapshot(function(e){var t=document.getElementById("raidDamageDealers");if(t)if(e.empty)t.innerHTML='
    No damage recorded for this boss.
    ';else{var o="",n=0;e.docs.forEach(function(e){n++;var t=e.data(),i="function"==typeof escapeHtml?escapeHtml(t.displayName||t.username||"Anonymous"):t.displayName||t.username||"Anonymous",a=t.contributed||0,r=1===n?"👑":2===n?"🥈":3===n?"🥉":n+".",s=void 0!==auth&&auth&&auth.currentUser&&e.id===auth.currentUser.uid,l=e.id;o+='
    '+r+"'+i+(s?" (you)":"")+'
    '+a.toLocaleString()+" dmg
    "}),t.innerHTML=o}},function(e){console.error("[RAID] Damage dealers listener error:",e);var t=document.getElementById("raidDamageDealers");t&&(t.innerHTML='
    Failed to load damage data.
    ')}):e.innerHTML='
    No damage data available.
    '}},window._raidActiveTab="current",window._raidAllTimeUnsub=null,window._switchRaidTab=function(e){if(e!==window._raidActiveTab){window._raidActiveTab=e;var t=document.getElementById("raidTabCurrent"),o=document.getElementById("raidTabAllTime");t&&(t.style.borderBottomColor="current"===e?"#8b5cf6":"transparent",t.style.color="current"===e?"#8b5cf6":"var(--text-faint)"),o&&(o.style.borderBottomColor="alltime"===e?"#8b5cf6":"transparent",o.style.color="alltime"===e?"#8b5cf6":"var(--text-faint)");var n=document.getElementById("raidParticipants");n&&(n.innerHTML='
    Loading...
    '),"current"===e?(window._raidAllTimeUnsub&&(window._raidAllTimeUnsub(),window._raidAllTimeUnsub=null),window._currentRaidBoss&&window._currentRaidBoss._id&&_listenRaidParticipants(window._currentRaidBoss._id)):(window._raidParticipantsUnsub&&(window._raidParticipantsUnsub(),window._raidParticipantsUnsub=null),_listenAllTimeRaiders())}};var RAID_GUIDANCE={uniqueUsers5Topics:{action:"Visit 5+ learning topics to deal damage!",nav:"home"},quizCompletions:{action:"Complete quiz quests to deal damage!",nav:"quests"},watchMinutes:{action:"Watch Timechain TV to deal damage!",nav:"tctv"},beatsMinutes:{action:"Listen to Bitcoin Beats to deal damage!",nav:"beats"},flashcardCompletions:{action:"Complete flashcard sets to deal damage!",nav:"quests"},totalXP:{action:"Earn XP from any activity to deal damage!",nav:"home"},pollVotes:{action:"Vote in Quest Hub polls to deal damage!",nav:"quests"},chatMessages:{action:"Send messages in Global Chat to deal damage!",nav:"chat"},badgesEarned:{action:"Earn badges to deal damage! Find them in the Leaderboard button 🏆",nav:"badges"},streakUsers:{action:"Maintain a 7-day daily visit streak to deal damage!",nav:"home"},uniqueTopicsVisited:{action:"Visit learning topics you haven't read yet!",nav:"home"},tipsSent:{action:"Send Lightning tips to deal damage!",nav:"home"},forumPosts:{action:"Create forum posts to deal damage!",nav:"forum"},triviaCorrect:{action:"Answer trivia correctly in Quest Hub to deal damage!",nav:"quests"},totalTopicReads:{action:"Read learning topics to deal damage!",nav:"home"}};window._contributeRaid=function(){var e=window._currentRaidBoss;if(e){var t=RAID_GUIDANCE[e.metric]||{action:"Complete activities on the site to deal damage!",nav:"home"};"function"==typeof showToast&&showToast("⚔️ "+t.action,3500);var o=document.getElementById("questHubOverlay");if(o&&o.remove(),"badges"===t.nav){if("function"==typeof toggleLeaderboard){var n=document.getElementById("leaderboard");if(n&&n.classList.contains("open")){n.classList.remove("open");var i=document.getElementById("lbFloatBtn");i&&(i.style.display="flex")}toggleLeaderboard(),setTimeout(function(){var e=document.getElementById("leaderboard");if(e)for(var t=e.querySelectorAll("h4"),o=0;o'+i.emoji+'
    '+i.title+'
    '+i.desc+"
    "}t+='',t+="";var a=document.createElement("div");a.id="forumRulesOverlay",a.innerHTML=t,document.body.appendChild(a)}window.acceptForumRules=function(){localStorage.setItem("btc_forum_rules_accepted","true");var e=document.getElementById("forumRulesOverlay");e&&e.remove()},window.showForumRulesBtn=function(){i()};var a=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","retard","nazi","hitler","kkk","porn","hentai","rape","pedo"];function r(e){for(var t=e.toLowerCase().replace(/[^a-z\s]/g,"").split(/\s+/),o=0;o=4&&-1!==t[o].indexOf(a[n]))return!1}return!0}function s(e){return"function"==typeof escapeHtml?escapeHtml(e):String(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}window.forumBack=function(){history.back()};var l="recent",c=sessionStorage.getItem("btc_forum_category")||"all",d=null,u="discussions",p=["Bitcoin Basics","Lightning","Mining","Privacy","Self-Custody","Economics","Technical","Culture","Opinion","Tutorial","News Analysis"];function h(e,n){if(n)if(0!==e.length){var i="";e.forEach(function(e){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},a=o.find(function(t){return t.id===e.category}),r=a?a.emoji+" "+a.name:"",l=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),c=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid);i+='
    '+(e.upvotes||0)+'
    '+s(e.title)+"
    "+(e.body?'
    '+s(e.body).substring(0,120)+(e.body.length>120?"...":"")+"
    ":"")+"
    '+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'💬 '+(e.replyCount||0)+""+(r?''+r+"":"")+(l?"':"")+"
    "}),n.innerHTML=i}else n.innerHTML='
    🦌
    No posts yet. Be the first to start a discussion!
    '}async function m(e){var o=document.getElementById("forumReplies");if(o)try{var n=await db.collection("forum_replies").where("postId","==",e).orderBy("createdAt","asc").limit(100).get(),i=[];if(n.forEach(function(e){i.push({id:e.id,...e.data()})}),0===i.length)return void(o.innerHTML='
    No replies yet. Be the first!
    ');var a=[],r={};i.forEach(function(e){e.parentReplyId?(r[e.parentReplyId]||(r[e.parentReplyId]=[]),r[e.parentReplyId].push(e)):a.push(e)});var l='
    '+i.length+" "+(1===i.length?"reply":"replies")+"
    ";function c(e,o){var n="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},i=e.voters&&auth&&auth.currentUser&&-1!==e.voters.indexOf(auth.currentUser.uid),a=s(e.body).replace(/\n/g,"
    ");a=T(a=a.replace(/(https?:\/\/[^\s<]+)/g,'$1'));var r=auth&&auth.currentUser&&e.authorId===auth.currentUser.uid||t(),l=auth&&auth.currentUser&&!auth.currentUser.isAnonymous;return'
    '+(e.parentAuthorName?'
    ↩ '+s(e.parentAuthorName)+"
    ":"")+'
    "+n.emoji+" "+s(e.authorName||"Anon")+''+timeAgo(e.createdAt)+'
    '+a+'
    "+(l?'':"")+(r?"':"")+"
    "}a.forEach(function(e){l+=c(e,!1),(r[e.id]||[]).forEach(function(e){l+=c(e,!0)})}),Object.keys(r).forEach(function(e){a.some(function(t){return t.id===e})||r[e].forEach(function(e){l+=c(e,!1)})}),o.innerHTML=l}catch(d){o.innerHTML='
    Error loading replies
    '}}window.renderForum=function(){var e=document.getElementById("forumContainer");if(e){e.innerHTML="";var t='
    ';if(t+='
    Home
    ',t+='

    🗣️ Pleb Talk

    Discuss Bitcoin with fellow learners
    ',t+='
    ',"stacker"===u){var n=window._snSearchQuery||"";t+='
    ',t+='',t+='',n&&(t+=''),t+="
    ";var a=window._snSub||"",r=[{id:"",label:"All"},{id:"bitcoin",label:"bitcoin"},{id:"lightning",label:"lightning"},{id:"nostr",label:"nostr"},{id:"privacy",label:"privacy"},{id:"tech",label:"tech"},{id:"meta",label:"meta"}];t+='
    ';for(var d=0;d'+S(p.label)+""}if(t+="
    ",n)t+='
    Search results for: '+S(n)+"
    ";else{var m=window._snSort||"top",g=window._snWhen||"day";t+='
    ';for(var f=[{id:"top",label:"🔥 Top"},{id:"recent",label:"🕐 Recent"},{id:"random",label:"🎲 Random"}],y=0;y'+b.label+""}if("top"===m){t+='"}t+='stacker.news ↗',t+="
    "}return t+='
    Loading Stacker News...
    ',t+="
    ",e.innerHTML=t,void(n?function(e){var t=document.getElementById("snFeed");if(t){var o="https://embed-proxy.needcreations.workers.dev/api/sn/search?q="+encodeURIComponent(e);fetch(o).then(function(e){return e.json()}).then(function(o){if(o&&o.data&&o.data.search&&o.data.search.items){var n=o.data.search.items;n.length?t.innerHTML=v(n):t.innerHTML='
    No results found for "'+S(e)+'"
    '}else t.innerHTML='
    No results found
    '}).catch(function(){t.innerHTML='
    Search failed.
    '})}}(n):loadStackerNewsFeed(window._snSort||"top",window._snWhen||"day",a))}"articles"!==u?(t+='
    ',["recent","top","discussed"].forEach(function(e){var o=l===e;t+=""}),t+='
    ",t+='
    Loading posts...
    ',t+="",e.innerHTML=t,document.getElementById("main").scrollTop=0,"true"!==localStorage.getItem("btc_forum_rules_accepted")&&i(),forumLoadPosts()):function(e,t){var o=e;o+='
    ',o+='
    ',["recent","top"].forEach(function(e){var t=l===e;o+=""}),o+="
    ",o+='
    Loading articles...
    ',o+="",t.innerHTML=o,document.getElementById("main").scrollTop=0,async function(){var e=document.getElementById("articlesList");if(e&&void 0!==db)try{var t="top"===l?"upvotes":"createdAt",o=await db.collection("articles").where("status","==","published").orderBy(t,"desc").limit(15).get(),n=[];if(o.forEach(function(e){n.push({id:e.id,...e.data()})}),0===n.length)return void(e.innerHTML='
    📝
    No articles yet
    Be the first to publish a Bitcoin article!
    ');var i="";n.forEach(function(e){var t="function"==typeof getLevel?getLevel(e.authorPoints||0):{emoji:"🟢"},o=Math.max(1,Math.round((e.wordCount||500)/200)),n=e.createdAt&&e.createdAt.toDate?e.createdAt.toDate().toLocaleDateString():"",a=e.pinned?'📌 PINNED ':"";i+="
    ',e.coverUrl&&(i+='
    '),i+='
    ',i+=a+'

    '+s(e.title)+"

    ",e.subtitle&&(i+='
    '+s(e.subtitle)+"
    "),e.tags&&e.tags.length&&(i+='
    ',e.tags.forEach(function(e){i+=''+s(e)+""}),i+="
    "),i+='
    "+t.emoji+" "+s(e.authorName||"Anon")+"·"+o+" min read"+(n?"·"+n+"":"")+"
    ",i+='
    👍 '+(e.upvotes||0)+"💬 "+(e.replyCount||0)+""+(e.tipTotal?"⚡ "+e.tipTotal+" sats":"")+"
    ",i+="
    "}),e.innerHTML=i}catch(t){console.error("Articles load error:",t),e.innerHTML='
    Error loading articles
    '}}()}(t,e)}},window._forumUnsubscribe=null,window.forumLoadPosts=async function(){document.getElementById("forumPosts")&&void 0!==db&&(window._forumUnsubscribe&&(window._forumUnsubscribe(),window._forumUnsubscribe=null),async function(){var e=document.getElementById("forumPosts");if(e)try{var t="top"===l?"upvotes":"discussed"===l?"replyCount":"createdAt",o=c+"_"+l,n=Date.now();if(window._forumCache&&window._forumCache.key===o&&n-window._forumCache.time<12e4)return window._forumCache.posts,void h(window._forumCache.posts,e);var i="all"!==c?db.collection("forum_posts").where("category","==",c).orderBy(t,"desc").limit(50):db.collection("forum_posts").orderBy(t,"desc").limit(50),a=await i.get(),r=[];a.forEach(function(e){r.push({id:e.id,...e.data()})}),window._forumCache={key:o,time:Date.now(),posts:r},h(r,e)}catch(t){e.innerHTML='
    Error loading posts. Try refreshing.
    '}}())},window.forumSetSort=function(e){l=e,renderForum()},window.forumSetCategory=function(e){c=e,sessionStorage.setItem("btc_forum_category",e),renderForum()},window.forumViewPost=async function(e,o){var n=document.getElementById("forumContainer");if(n&&void 0!==db){o||history.pushState({channel:"forum",forumPost:e},"","#forum/post/"+e),n.innerHTML='
    ';try{var i=await db.collection("forum_posts").doc(e).get();if(!i.exists)return void renderForum();var a={id:i.id,...i.data()};d=a;var r="function"==typeof getLevel?getLevel(a.authorPoints||0):{emoji:"🟢"},l=a.voters&&auth&&auth.currentUser&&-1!==a.voters.indexOf(auth.currentUser.uid),c='
    ';if(c+='
    Home
    ',c+='',c+='

    '+s(a.title)+'

    "+r.emoji+" "+s(a.authorName||"Anon")+''+timeAgo(a.createdAt)+"
    ",a.body){var u=s(a.body).replace(/\n/g,"
    ").replace(/\*\*(.+?)\*\*/g,"$1");c+='
    '+(u=T(u=u.replace(/(https?:\/\/[^\s<]+)/g,'$1')))+"
    "}a.link&&(c+='🔗 '+s(a.link).substring(0,60)+(a.link.length>60?"...":"")+"
    ");var p=auth&&auth.currentUser&&a.authorId===auth.currentUser.uid||t();c+='
    💬 '+(a.replyCount||0)+" replies"+(p?"':"")+"
    ",c+="
    ",auth&&auth.currentUser&&!auth.currentUser.isAnonymous?c+='
    ':c+='
    🔒
    Want to join the conversation?
    ',c+='
    Loading replies...
    ',c+="
    ",n.innerHTML=c,document.getElementById("main").scrollTop=0,m(e)}catch(e){n.innerHTML='
    Error loading post
    '}}},window.forumNewPost=function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){history.pushState({channel:"forum-new"},"","#forum");var e=document.getElementById("forumContainer");if(e){var t='
    ';t+='
    Home
    ',t+='',t+='

    📝 Create New Post

    ',t+='
    ';var n="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;";t+='",t+='',t+='',t+='',t+='
    ',t+='',t+='
    ',t+="
    ",window._forumFormOpenTime=Date.now(),e.innerHTML=t,document.getElementById("main").scrollTop=0}}else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
    🔒

    Registration Required

    Create a free account to post in the forum, join discussions, and earn XP! It only takes a few seconds.
    ')}};var g=0;function f(e){if(!e)return"";var t=s(e);return T(t='

    '+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,'$1')).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/(?$1')).replace(/^### (.+)$/gm,'

    $1

    ')).replace(/^## (.+)$/gm,'

    $1

    ')).replace(/^# (.+)$/gm,'

    $1

    ')).replace(/\*\*(.+?)\*\*/g,'$1')).replace(/\*(.+?)\*/g,"$1")).replace(/`(.+?)`/g,'$1')).replace(/^> (.+)$/gm,'
    $1
    ')).replace(/^- (.+)$/gm,'
  • $1
  • ')).replace(/^\d+\. (.+)$/gm,'
  • $1
  • ')).replace(/---/g,'
    ')).replace(/\n{2,}/g,'

    '))+"

    ")}window.forumSubmitPost=async function(){if(!window._forumSubmitting){var e=Date.now();if(e-g<3e4)"function"==typeof showToast&&showToast("⏳ Wait 30 seconds between posts");else{g=e,window._forumSubmitting=!0;var t=document.getElementById("forumPostStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o=document.getElementById("forumHoneypot");if(o&&o.value)t&&(t.innerHTML='Something went wrong. Please try again.');else if(window._forumFormOpenTime&&Date.now()-window._forumFormOpenTime<5e3)t&&(t.innerHTML='Please take a moment to write your post.');else{var n=(document.getElementById("forumNewTitle").value||"").trim(),i=(document.getElementById("forumNewBody").value||"").trim(),a=(document.getElementById("forumNewLink").value||"").trim(),l=document.getElementById("forumNewCat").value;if("function"==typeof sanitizeInput&&(n=sanitizeInput(n),i=sanitizeInput(i)),!n||n.length<5)t&&(t.innerHTML='Title must be at least 5 characters');else if(!r(n)||i&&!r(i))t&&(t.innerHTML='Post contains inappropriate language. Keep it clean!');else{a&&!/^https?:\/\//i.test(a)&&(a="https://"+a);var c=parseInt(localStorage.getItem("btc_forum_post_count")||"0"),d=localStorage.getItem("btc_forum_post_date")||"",u=(new Date).toISOString().split("T")[0];if(d!==u&&(c=0),c>=5)t&&(t.innerHTML='You\'ve reached the daily post limit (5). Try again tomorrow!');else{t&&(t.innerHTML='Posting...');try{var p=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",h=void 0!==currentUser&¤tUser&¤tUser.points||0,m=await db.collection("forum_posts").add({title:n,body:i.substring(0,2e3),link:a.substring(0,200)||null,category:l,authorId:auth.currentUser.uid,authorName:p,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:h,upvotes:0,voters:[],replyCount:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()});if(localStorage.setItem("btc_forum_post_count",(c+1).toString()),localStorage.setItem("btc_forum_post_date",u),"function"==typeof awardPoints&&awardPoints(10,"📝 Forum post"),"function"==typeof awardTickets&&awardTickets(5,"📝 Forum post"),forumNotifyMentions(i,"forum_post",m.id,n),db.collection("users").doc(auth.currentUser.uid).update({forumPosts:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumPosts=(currentUser.forumPosts||0)+1),"function"==typeof window._raidOnForumPost&&window._raidOnForumPost(),"function"==typeof window.nachoGlobalAnnounce){var f=s(n).substring(0,80),y=s(i).substring(0,120);window.nachoGlobalAnnounce("🗣️ New Forum Post: "+f+" by "+s(p)+": "+y+(i.length>120?"...":"")+" ➡️ [Open PlebTalk](#forum)")}forumBack()}catch(e){t&&(t.innerHTML='Error posting. Try again.')}}}}}else t&&(t.innerHTML='You must be signed in')}}},window._forumReplyingTo=null,window.forumReplyToReply=function(e,t){window._forumReplyingTo={replyId:e,authorName:t};var o=document.getElementById("forumReplyIndicator");o&&(o.style.display="flex",o.querySelector("span").textContent="↩ Replying to "+t);var n=document.getElementById("forumReplyInput");n&&(n.focus(),n.placeholder="Reply to "+t+"...")},window.forumCancelReplyTo=function(){window._forumReplyingTo=null;var e=document.getElementById("forumReplyIndicator");e&&(e.style.display="none");var t=document.getElementById("forumReplyInput");t&&(t.placeholder="Write a reply...")},window.forumSubmitReply=async function(e){if(!window._forumReplySubmitting){window._forumReplySubmitting=!0;var t=document.getElementById("forumReplyStatus"),o=document.getElementById("forumReplyInput");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&o){var n=o.value.trim();if(!n||n.length<2)return t&&(t.innerHTML='Reply is too short'),void(window._forumReplySubmitting=!1);if(!r(n))return t&&(t.innerHTML='Reply contains inappropriate language'),void(window._forumReplySubmitting=!1);t&&(t.innerHTML='Posting...');try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0,s={postId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorFaction:void 0!==currentUser&¤tUser&¤tUser.faction?currentUser.faction:null,authorPoints:a,upvotes:0,voters:[],createdAt:firebase.firestore.FieldValue.serverTimestamp()},l=window._forumReplyingTo;l&&l.replyId&&(s.parentReplyId=l.replyId,s.parentAuthorName=l.authorName||""),await db.collection("forum_replies").add(s),await db.collection("forum_posts").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Forum reply");var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";if(l&&l.replyId){try{var u=await db.collection("forum_replies").doc(l.replyId).get();u.exists&&u.data().authorId&&"function"==typeof sendNotification&&sendNotification(u.data().authorId,"reply",c+' replied to your comment on "'+(d?(d.title||"").substring(0,40):"a post")+'"',"forum_post",e)}catch(e){}d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",c+' replied in your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e)}else d&&d.authorId&&"function"==typeof sendNotification&&sendNotification(d.authorId,"reply",c+' replied to your post "'+(d.title||"").substring(0,40)+'"',"forum_post",e);forumNotifyMentions(n,"forum_post",e,d?d.title:""),db.collection("users").doc(auth.currentUser.uid).update({forumReplies:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[forum] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.forumReplies=(currentUser.forumReplies||0)+1),o.value="",window.forumCancelReplyTo(),t&&(t.innerHTML='✅ Reply posted!'),m(e)}catch(e){t&&(t.innerHTML='Error posting reply')}window._forumReplySubmitting=!1}else window._forumReplySubmitting=!1}},window.forumVotePost=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_posts").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your post "'+(a.title||"").substring(0,40)+'"',"forum_post",e)}}d&&d.id===e?forumViewPost(e):forumLoadPosts()}catch(e){}},window.forumVoteReply=async function(e){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to upvote!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());try{var t=db.collection("forum_replies").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;-1!==n.indexOf(i)?await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)}):await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)}),d&&m(d.id)}catch(e){}},window.forumDeletePost=async function(e){if(auth&&auth.currentUser){var o=t();if(confirm(o?"Admin: Delete this post and all its replies?":"Delete your post? This cannot be undone."))try{var n=await db.collection("forum_replies").where("postId","==",e).get(),i=db.batch();n.forEach(function(e){i.delete(e.ref)}),i.delete(db.collection("forum_posts").doc(e)),await i.commit(),"function"==typeof showToast&&showToast("🗑️ Post deleted"),forumBack()}catch(e){"function"==typeof showToast&&showToast("Error deleting post")}}},window.forumDeleteReply=async function(e,o){if(auth&&auth.currentUser){var n=t();if(confirm(n?"Admin: Delete this reply?":"Delete your reply? This cannot be undone."))try{await db.collection("forum_replies").doc(e).delete(),await db.collection("forum_posts").doc(o).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Reply deleted"),d&&m(o)}catch(e){"function"==typeof showToast&&showToast("Error deleting reply")}}},window.forumSwitchTab=function(e){u=e,renderForum()};var y=["Content must be Bitcoin-focused or Bitcoin-adjacent","Minimum 500 words, maximum 10,000 words","No promotion of altcoins, scams, or affiliate spam","Original content only — no plagiarism","No hate speech or personal attacks","Author grants the archive a non-exclusive license to display the content","Moderators may remove content that violates these guidelines"];async function b(e){var o=document.getElementById("articleReplies");if(o)try{var n=await db.collection("article_replies").where("articleId","==",e).orderBy("createdAt","asc").limit(50).get();if(n.empty)return void(o.innerHTML='
    No comments yet. Be the first!
    ');var i="";n.forEach(function(o){var n=o.data(),a="function"==typeof getLevel?getLevel(n.authorPoints||0):{emoji:"🟢"},r=n.createdAt&&n.createdAt.toDate?"function"==typeof timeAgo?timeAgo(n.createdAt.toDate()):n.createdAt.toDate().toLocaleDateString():"",l=auth&&auth.currentUser&&(auth.currentUser.uid===n.authorId||t());i+='
    "+a.emoji+" "+s(n.authorName||"Anon")+'· '+r+""+(l?"':"")+'
    '+T(s(n.body).replace(/\n/g,"
    ").replace(/(https?:\/\/[^\s<]+)/g,'$1'))+"
    "}),o.innerHTML=i}catch(e){o.innerHTML='
    Error loading comments
    '}}function v(e){for(var t="",o=0;o",t+='
    ',t+='
    ',t+='
    '+B(n.sats)+"
    ",t+='
    sats
    ',t+="
    ",t+='
    ',t+='
    '+S(n.title)+"
    ",t+='
    ',t+='@'+S(n.user.name)+"",t+="·",t+=""+i+"",n.ncomments>0&&(t+="·",t+="💬 "+n.ncomments+""),a&&(t+="·",t+=''+S(a)+""),r&&(t+=''+S(r)+""),t+="
    ",t+='',t+="
    "}return t}function w(e,t){for(var o="",n=0;n',o+='
    ',o+='@'+S(i.user.name)+"",o+="·",o+=""+k(i.createdAt)+"",i.sats>0&&(o+="·",o+='⚡ '+B(i.sats)+""),o+="
    ",i.text&&(o+='
    '+x(i.text)+"
    "),o+="",i.comments&&i.comments.comments&&i.comments.comments.length>0&&(o+=w(i.comments.comments,t+1))}return o}function x(e){if(!e)return"";var t=S(e);return'

    '+(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/^#{3}\s+(.+)$/gm,'

    $1
    ')).replace(/^#{2}\s+(.+)$/gm,'
    $1
    ')).replace(/^#{1}\s+(.+)$/gm,'
    $1
    ')).replace(/\*\*\*(.+?)\*\*\*/g,"$1")).replace(/\*\*(.+?)\*\*/g,"$1")).replace(/\*(.+?)\*/g,"$1")).replace(/\[([^\]]+)\]\(([^)]+)\)/g,'$1')).replace(/`([^`]+)`/g,'$1')).replace(/\n\n/g,'

    ')).replace(/\n/g,"
    "))+"

    "}function k(e){var t=Math.floor((Date.now()-new Date(e).getTime())/1e3);return t<60?"just now":t<3600?Math.floor(t/60)+"m ago":t<86400?Math.floor(t/3600)+"h ago":Math.floor(t/86400)+"d ago"}function B(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"k":String(e)}function S(e){return e?e.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""):""}function T(e){return e&&-1!==e.indexOf("@")?e.replace(/(<[^>]+>)|(@([a-zA-Z0-9_\-\.]{2,20}))/g,function(e,t,o,n){return t||'"+o+""}):e}window.articleNew=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void("function"==typeof showToast&&showToast("🔒 Sign in to write articles"));if((void 0!==currentUser&¤tUser&¤tUser.points||0)<100)"function"==typeof showToast&&showToast("📝 You need 100+ points to publish articles. Keep exploring!");else{var e=null;try{e=JSON.parse(localStorage.getItem("btc_article_draft"))}catch(e){}var t=document.getElementById("forumContainer");if(t){var o="width:100%;padding:12px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;color:var(--text);font-size:16px;font-family:inherit;outline:none;box-sizing:border-box;margin-bottom:12px;-webkit-appearance:none;",n='
    ';n+='',n+='

    ✍️ Write an Article

    ',n+='
    ',n+='',n+='',n+='
    ';var i=e&&e.tags?e.tags:[];p.forEach(function(e){var t=-1!==i.indexOf(e);n+=""}),n+="
    ",n+='
    ',n+='
    0 words · Min 500
    ',n+='',n+='
    📋 Content Guidelines
    ',y.forEach(function(e){n+='
    • '+e+"
    "}),n+='
    ',n+='
    ',n+='
    ',n+="
    ",t.innerHTML=n,document.getElementById("main").scrollTop=0;var a=document.getElementById("articleBody");a&&(a.addEventListener("input",function(){var e=this.value.trim().split(/\s+/).filter(function(e){return e.length>0}).length,t=document.getElementById("articleWordCount");t&&(t.textContent=e+" words · Min 500")}),window._articleAutoSave=setInterval(function(){articleSaveDraft(!0)},3e4))}}},window.toggleArticleTag=function(e,t){if(-1!==e.style.borderColor.indexOf("var(--accent)")||-1!==e.style.color.indexOf("var(--accent)"))e.style.border="1px solid var(--border)",e.style.background="none",e.style.color="var(--text-muted)";else{if(document.querySelectorAll('#articleTagsContainer button[style*="accent-bg"]').length>=3)return void("function"==typeof showToast&&showToast("Max 3 tags"));e.style.border="1px solid var(--accent)",e.style.background="var(--accent-bg)",e.style.color="var(--accent)"}},window.articleInsert=function(e,t,o){var n=document.getElementById("articleBody");if(n){n.focus();var i=n.selectionStart,a=n.selectionEnd,r=n.value.substring(i,a),s=r||o,l=e+s+t;n.setRangeText(l,i,a,"select"),r||(n.selectionStart=i+e.length,n.selectionEnd=i+e.length+s.length),n.dispatchEvent(new Event("input"))}},window.articleInsertLink=function(){var e=document.getElementById("articleBody");if(e){var t=e.value.substring(e.selectionStart,e.selectionEnd),o=document.getElementById("articleLinkDialog");o&&o.remove();var n=document.createElement("div");n.id="articleLinkDialog",n.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",n.onclick=function(e){e.target===n&&n.remove()};var i="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";n.innerHTML='

    🔗 Insert Link

    ',document.body.appendChild(n),setTimeout(function(){document.getElementById("linkDialogUrl").focus()},100)}},window.articleDoInsertLink=function(){var e=(document.getElementById("linkDialogText").value||"").trim()||"link",t=(document.getElementById("linkDialogUrl").value||"").trim();if(t){t.match(/^https?:\/\//)||(t="https://"+t);var o=document.getElementById("articleBody");if(o){var n="["+e+"]("+t+")",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleLinkDialog").remove()}else"function"==typeof showToast&&showToast("Enter a URL")},window.articleInsertImage=function(){var e=document.getElementById("articleImageDialog");e&&e.remove();var t=document.createElement("div");t.id="articleImageDialog",t.style.cssText="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.6);padding:16px;",t.onclick=function(e){e.target===t&&t.remove()};var o="width:100%;padding:10px 12px;background:var(--card-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:0.9rem;font-family:inherit;box-sizing:border-box;margin-bottom:10px;";t.innerHTML='

    🖼️ Insert Image

    Or upload from device:
    ',document.body.appendChild(t),setTimeout(function(){var e=document.getElementById("imageDialogFile");e&&e.addEventListener("change",function(){var e=this.files[0];if(e)if(e.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var t=document.getElementById("imageDialogPreview"),o=document.getElementById("imageDialogBtn");if(o&&(o.disabled=!0,o.textContent="Uploading..."),"undefined"!=typeof firebase&&firebase.storage&&void 0!==auth&&auth.currentUser)firebase.storage().ref("article-images/"+auth.currentUser.uid+"/"+Date.now()+"_"+e.name.replace(/[^a-zA-Z0-9._-]/g,"_")).put(e).then(function(e){return e.ref.getDownloadURL()}).then(function(e){document.getElementById("imageDialogUrl").value=e,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image"),"function"==typeof showToast&&showToast("✅ Image uploaded!")}).catch(function(e){"function"==typeof showToast&&showToast("Upload failed: "+(e.message||"Unknown error")),o&&(o.disabled=!1,o.textContent="Insert Image")});else{var n=new FileReader;n.onload=function(e){document.getElementById("imageDialogUrl").value=e.target.result,t&&(t.style.display="block",t.innerHTML=''),o&&(o.disabled=!1,o.textContent="Insert Image")},n.readAsDataURL(e)}}}),document.getElementById("imageDialogUrl").focus()},100)},window.articleDoInsertImage=function(){var e=(document.getElementById("imageDialogUrl").value||"").trim(),t=(document.getElementById("imageDialogAlt").value||"").trim()||"image";if(e){var o=document.getElementById("articleBody");if(o){var n="\n!["+t+"]("+e+")\n",i=o.selectionStart;o.setRangeText(n,i,o.selectionEnd,"end"),o.dispatchEvent(new Event("input"))}document.getElementById("articleImageDialog").remove()}else"function"==typeof showToast&&showToast("Enter an image URL or upload a file")},window.toggleArticlePreview=function(){var e=document.getElementById("articleBody"),t=document.getElementById("articlePreviewArea"),o=document.getElementById("articlePreviewBtn");e&&t&&("none"===t.style.display?(t.innerHTML=f(e.value),t.style.display="block",e.style.display="none",o.textContent="Edit"):(t.style.display="none",e.style.display="",o.textContent="Preview"))},window.articleSaveDraft=function(e){var t=(document.getElementById("articleTitle")||{}).value||"",o=(document.getElementById("articleSubtitle")||{}).value||"",n=(document.getElementById("articleBody")||{}).value||"",i=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&i.push(e.getAttribute("data-tag"))}),(t||n)&&(localStorage.setItem("btc_article_draft",JSON.stringify({title:t,subtitle:o,body:n,tags:i,savedAt:Date.now()})),e||"function"!=typeof showToast||showToast("💾 Draft saved!"))},window.articleSubmit=async function(){if(!window._articleSubmitting){var e=document.getElementById("articleStatus");if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var t=(document.getElementById("articleTitle").value||"").trim(),o=(document.getElementById("articleSubtitle").value||"").trim(),n=(document.getElementById("articleBody").value||"").trim(),i=document.getElementById("articleTerms");if(!t||t.length<10)e&&(e.innerHTML='Title must be at least 10 characters');else{var a=n.split(/\s+/).filter(function(e){return e.length>0}).length;if(a<500)e&&(e.innerHTML='Article must be at least 500 words (currently '+a+")");else if(a>1e4)e&&(e.innerHTML='Article must be under 10,000 words');else{var l=[];if(document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&l.push(e.getAttribute("data-tag"))}),l.length<1)e&&(e.innerHTML='Select at least 1 tag');else if(i&&i.checked)if(r(t)&&r(n)){window._articleSubmitting=!0,e&&(e.innerHTML='Publishing...');try{var c=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",d=void 0!==currentUser&¤tUser&¤tUser.points||0,p=void 0!==currentUser&¤tUser&¤tUser.profilePic?currentUser.profilePic:"",h="",m=document.getElementById("articleCover");if(m&&m.files&&m.files[0]){var g=m.files[0];if(g.size>3145728)return e&&(e.innerHTML='Cover image too large (max 3MB)'),void(window._articleSubmitting=!1);e&&(e.innerHTML='Uploading cover...');try{var f=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),y=await f.put(g);h=await y.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}e&&(e.innerHTML='Publishing article...');var b={title:t.substring(0,120),subtitle:o.substring(0,200),body:n.substring(0,5e4),tags:l.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),authorId:auth.currentUser.uid,authorName:c,authorPoints:d,authorPic:p,upvotes:0,voters:[],replyCount:0,tipTotal:0,status:"published",pinned:!1,agreedToTerms:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp(),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};h&&(b.coverUrl=h),await db.collection("articles").add(b),localStorage.removeItem("btc_article_draft"),window._articleAutoSave&&clearInterval(window._articleAutoSave),"function"==typeof awardPoints&&awardPoints(30,"📝 Article published"),"function"==typeof awardTickets&&awardTickets(20,"📝 Article published");var v=parseInt(localStorage.getItem("btc_articles_published")||"0");localStorage.setItem("btc_articles_published",String(v+1)),"function"==typeof showToast&&showToast("📝 Article published!"),u="articles",renderForum()}catch(t){console.error("Article submit error:",t),e&&(e.innerHTML='Error publishing: '+s(t.message)+"")}window._articleSubmitting=!1}else e&&(e.innerHTML='Content contains inappropriate language');else e&&(e.innerHTML='You must agree to the content guidelines')}}}else e&&(e.innerHTML='Sign in required')}},window.articleView=async function(e){var o=document.getElementById("forumContainer");if(o&&db){o.innerHTML='
    Loading article...
    ';try{var n=await db.collection("articles").doc(e).get();if(!n.exists)return void(o.innerHTML='
    Article not found
    ');var i=n.data();i.id=e;var a="function"==typeof getLevel?getLevel(i.authorPoints||0):{emoji:"🟢"},r=Math.max(1,Math.round((i.wordCount||500)/200)),l=i.createdAt&&i.createdAt.toDate?i.createdAt.toDate().toLocaleDateString():"",c=auth&&auth.currentUser&&auth.currentUser.uid===i.authorId,d=t(),u=auth&&auth.currentUser&&-1!==(i.voters||[]).indexOf(auth.currentUser.uid),p='
    ';if(p+='',i.coverUrl&&(p+='
    Cover
    '),p+='

    '+s(i.title)+"

    ",i.subtitle&&(p+='
    '+s(i.subtitle)+"
    "),p+='
    ',i.authorPic&&(p+=''),p+='
    "+a.emoji+" "+s(i.authorName||"Anon")+'
    '+l+" · "+r+" min read · "+(i.wordCount||0).toLocaleString()+" words
    ",c&&(p+="'),d&&(p+=""),p+="
    ",i.tags&&i.tags.length&&(p+='
    ',i.tags.forEach(function(e){p+=''+s(e)+""}),p+="
    "),p+='
    '+f(i.body)+"
    ",p+='
    ',p+="","function"==typeof tipButtonHtml&&(p+=tipButtonHtml({recipientName:i.authorName,recipientUid:i.authorId,context:"article",contextId:e,label:"⚡ Tip Author",size:"md"})),(c||d)&&(p+="'),p+="
    ",p+='

    💬 Comments

    ',p+='
    Loading comments...
    ',auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&(p+='
    '),p+="
    ",o.innerHTML=p,document.getElementById("main").scrollTop=0,b(e),auth&&auth.currentUser){var h="btc_article_read_"+e;localStorage.getItem(h)||setTimeout(function(){document.getElementById("articleReplies")&&(localStorage.setItem(h,"1"),"function"==typeof awardPoints&&awardPoints(5,"📖 Read an article"),"function"==typeof showToast&&showToast("📖 +5 points for reading!"))},6e4)}}catch(e){console.error("Article view error:",e),o.innerHTML='
    Error loading article
    '}}},window.articleVote=async function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{var t=db.collection("articles").doc(e),o=await t.get();if(!o.exists)return;var n=o.data().voters||[],i=auth.currentUser.uid;if(-1!==n.indexOf(i))await t.update({upvotes:firebase.firestore.FieldValue.increment(-1),voters:firebase.firestore.FieldValue.arrayRemove(i)});else{await t.update({upvotes:firebase.firestore.FieldValue.increment(1),voters:firebase.firestore.FieldValue.arrayUnion(i)});var a=o.data();if(a.authorId&&"function"==typeof sendNotification){var r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(a.authorId,"upvote",r+' upvoted your article "'+(a.title||"").substring(0,40)+'"',"article",e)}}articleView(e)}catch(e){}else"function"==typeof showToast&&showToast("🔒 Sign in to upvote")},window.articleSubmitReply=async function(e){var t=document.getElementById("articleReplyInput"),o=document.getElementById("articleReplyStatus");if(t&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var n=t.value.trim();if(!n||n.length<2)o&&(o.innerHTML='Comment too short');else if(r(n))try{var i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anon",a=void 0!==currentUser&¤tUser&¤tUser.points||0;await db.collection("article_replies").add({articleId:e,body:n.substring(0,1e3),authorId:auth.currentUser.uid,authorName:i,authorPoints:a,createdAt:firebase.firestore.FieldValue.serverTimestamp()}),await db.collection("articles").doc(e).update({replyCount:firebase.firestore.FieldValue.increment(1)}),"function"==typeof awardPoints&&awardPoints(5,"💬 Article comment");try{var s=await db.collection("articles").doc(e).get();if(s.exists&&s.data().authorId&&"function"==typeof sendNotification){var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(s.data().authorId,"comment",l+' commented on your article "'+(s.data().title||"").substring(0,40)+'"',"article",e)}forumNotifyMentions(n,"article",e,s&&s.exists?s.data().title:"")}catch(e){}t.value="",o&&(o.innerHTML='✅ Comment posted!'),b(e)}catch(e){o&&(o.innerHTML='Error posting comment')}else o&&(o.innerHTML='Inappropriate language')}},window.articleDeleteReply=async function(e,t){if(confirm("Delete this comment?"))try{await db.collection("article_replies").doc(e).delete(),await db.collection("articles").doc(t).update({replyCount:firebase.firestore.FieldValue.increment(-1)}),"function"==typeof showToast&&showToast("🗑️ Comment deleted"),b(t)}catch(e){}},window.articleEdit=async function(e){try{var o=await db.collection("articles").doc(e).get();if(!o.exists)return;var n=o.data();if(auth.currentUser.uid!==n.authorId&&!t())return;localStorage.setItem("btc_article_draft",JSON.stringify({title:n.title,subtitle:n.subtitle||"",body:n.body,tags:n.tags||[]})),window._articleEditId=e,articleNew(),setTimeout(function(){var e=document.querySelector('[onclick="articleSubmit()"]');e&&(e.textContent="✏️ Update Article",e.setAttribute("onclick","articleUpdate()"))},100)}catch(e){"function"==typeof showToast&&showToast("Error loading article for edit")}},window.articleUpdate=async function(){var e=window._articleEditId;if(e){var t=document.getElementById("articleStatus"),o=(document.getElementById("articleTitle").value||"").trim(),n=(document.getElementById("articleSubtitle").value||"").trim(),i=(document.getElementById("articleBody").value||"").trim(),a=i.split(/\s+/).filter(function(e){return e.length>0}).length;if(!o||o.length<10)t&&(t.innerHTML='Title must be at least 10 characters');else if(a<500)t&&(t.innerHTML='Min 500 words');else{var r=[];document.querySelectorAll("#articleTagsContainer button").forEach(function(e){e.style.color&&-1!==e.style.color.indexOf("var(--accent)")&&r.push(e.getAttribute("data-tag"))}),t&&(t.innerHTML='Updating...');try{var s=null,l=document.getElementById("articleCover");if(l&&l.files&&l.files[0]){var c=l.files[0];if(c.size>3145728)return void(t&&(t.innerHTML='Cover too large (max 3MB)'));t&&(t.innerHTML='Uploading cover...');try{var d=firebase.storage().ref("articles/"+auth.currentUser.uid+"/"+Date.now()+"_cover"),u=await d.put(c);s=await u.ref.getDownloadURL()}catch(e){console.warn("Cover upload failed:",e)}}var p={title:o.substring(0,120),subtitle:n.substring(0,200),body:i.substring(0,5e4),tags:r.slice(0,3),wordCount:a,readTime:Math.max(1,Math.round(a/200)),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};s&&(p.coverUrl=s),t&&(t.innerHTML='Saving...'),await db.collection("articles").doc(e).update(p),localStorage.removeItem("btc_article_draft"),window._articleEditId=null,"function"==typeof showToast&&showToast("✏️ Article updated!"),articleView(e)}catch(e){t&&(t.innerHTML='Error updating')}}}},window.articleTogglePin=async function(e,t){try{await db.collection("articles").doc(e).update({pinned:t}),"function"==typeof showToast&&showToast(t?"📌 Article pinned!":"📌 Article unpinned"),articleView(e)}catch(e){}},window.articleDelete=async function(e){if(confirm("Delete this article and all its comments? This cannot be undone."))try{var t=await db.collection("article_replies").where("articleId","==",e).get(),o=db.batch();t.forEach(function(e){o.delete(e.ref)}),o.delete(db.collection("articles").doc(e)),await o.commit(),"function"==typeof showToast&&showToast("🗑️ Article deleted"),u="articles",renderForum()}catch(e){"function"==typeof showToast&&showToast("Error deleting article")}},window.loadStackerNewsFeed=function(e,t,o){var n=document.getElementById("snFeed");if(n){var i="https://embed-proxy.needcreations.workers.dev/api/sn?sort="+encodeURIComponent(e)+"&when="+encodeURIComponent(t)+"&limit=21";o&&(i+="&sub="+encodeURIComponent(o)),fetch(i).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.items&&e.data.items.items){var t=e.data.items.items;t.length?n.innerHTML=v(t):n.innerHTML='
    No posts found
    '}else n.innerHTML='
    Could not load Stacker News feed
    '}).catch(function(){n.innerHTML='
    Failed to load feed.
    '})}},window.snDoSearch=function(){var e=document.getElementById("snSearchInput");if(e){var t=e.value.trim();t.length<2||(window._snSearchQuery=t,renderForum())}},window.snClearSearch=function(){window._snSearchQuery="",renderForum()},window.snOpenPost=function(e){var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading post...
    ',fetch("https://embed-proxy.needcreations.workers.dev/api/sn/item?id="+e).then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.item){var o=e.data.item;!function(e,t){var o='
    ';if(o+='',o+='
    ',o+='

    '+S(t.title)+"

    ",o+='
    ',o+='⚡ '+B(t.sats)+" sats",o+="·",o+='@'+S(t.user.name)+"",o+="·",o+=""+k(t.createdAt)+"",t.ncomments>0&&(o+="·",o+="💬 "+t.ncomments+" comments"),o+="
    ",t.url){var n="";try{n=new URL(t.url).hostname.replace("www.","")}catch(e){}o+='🔗 '+S(n||t.url)+" ↗"}t.text&&(o+='
    '+x(t.text)+"
    "),o+='",o+="
    ",t.comments&&t.comments.comments&&t.comments.comments.length>0&&(o+='
    ',o+='
    💬 Comments ('+t.ncomments+")
    ",o+=w(t.comments.comments,0),o+="
    "),o+="
    ",e.innerHTML=o,e.scrollTop=0}(t,o)}else t.innerHTML='
    Post not found.
    '}).catch(function(){t.innerHTML='
    Failed to load post. ·
    '}))},window.forumMentionClick=function(e){e&&void 0!==db&&db.collection("users").where("username","==",e).limit(1).get().then(function(t){t.empty?db.collection("users").where("username_lower","==",e.toLowerCase()).limit(1).get().then(function(t){t.empty?"function"==typeof showToast&&showToast("User @"+e+" not found"):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){}):"function"==typeof showUserProfile&&showUserProfile(t.docs[0].id)}).catch(function(){})},window.forumNotifyMentions=async function(e,t,o,n){if(e&&void 0!==db&&auth&&auth.currentUser){var i=e.match(/@([a-zA-Z0-9_\-\.]{2,20})/g);if(i){var a={},r=[];i.forEach(function(e){var t=e.substring(1).toLowerCase();a[t]||(a[t]=!0,r.push(e.substring(1)))});for(var s=auth.currentUser.uid,l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone",c=(n||"").substring(0,40),d=0;d=",e).where("username","<=",e+"").limit(5).get().then(function(e){e.forEach(function(e){var t=e.data();t.username&&!a[e.id]&&(a[e.id]=!0,i.push({uid:e.id,username:t.username,points:t.points||0}))})}).catch(function(){}).then(function(){++r>=t.length&&(i.sort(function(e,t){return(t.points||0)-(e.points||0)}),_.activeTextarea&&function(e,t){if(A(),t&&0!==t.length){_.results=t,_.selectedIdx=0;var o=document.createElement("div");o.id="mentionDropdown",o.style.cssText="position:absolute;z-index:9999;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,0.4);overflow:hidden;max-height:220px;overflow-y:auto;min-width:200px;",t.forEach(function(e,t){var n=document.createElement("div");n.className="mention-item",n.setAttribute("data-idx",t);var i="function"==typeof getLevel?getLevel(e.points||0):{emoji:"🟢"};n.innerHTML=''+i.emoji+' '+s(e.username)+""+(e.points?''+(e.points||0).toLocaleString()+" XP":""),n.style.cssText="padding:10px 14px;cursor:pointer;display:flex;align-items:center;gap:8px;font-size:0.85rem;color:var(--text);transition:background 0.15s;"+(0===t?"background:var(--accent-bg);":""),n.onmouseenter=function(){_.selectedIdx=t,C()},n.onmousedown=function(e){e.preventDefault(),E(t)},o.appendChild(n)});var n=e.getBoundingClientRect();window.pageYOffset||document.documentElement.scrollTop,o.style.position="fixed",o.style.left=n.left+"px",o.style.top=n.bottom+4+"px",o.style.width=Math.min(n.width,320)+"px",document.body.appendChild(o),_.dropdown=o}}(_.activeTextarea,i.slice(0,5)))})})}}(t.prefix)},300))}),e.addEventListener("keydown",function(e){_.dropdown&&("ArrowDown"===e.key?(e.preventDefault(),_.selectedIdx=Math.min(_.selectedIdx+1,_.results.length-1),C()):"ArrowUp"===e.key?(e.preventDefault(),_.selectedIdx=Math.max(_.selectedIdx-1,0),C()):"Enter"===e.key||"Tab"===e.key?_.results.length>0&&_.selectedIdx>=0&&(e.preventDefault(),E(_.selectedIdx)):"Escape"===e.key&&A())}),e.addEventListener("blur",function(){setTimeout(A,200)}))}function L(){var e=["forumNewBody","forumReplyInput","articleReplyInput"];if(e.forEach(function(e){var t=document.getElementById(e);t&&z(t)}),"undefined"!=typeof MutationObserver){var t=new MutationObserver(function(){e.forEach(function(e){var t=document.getElementById(e);t&&z(t)})}),o=document.getElementById("forumContainer");if(o)t.observe(o,{childList:!0,subtree:!0});else{var n=new MutationObserver(function(){var o=document.getElementById("forumContainer");o&&(n.disconnect(),t.observe(o,{childList:!0,subtree:!0}),e.forEach(function(e){var t=document.getElementById(e);t&&z(t)}))});n.observe(document.body,{childList:!0,subtree:!0})}}}var M=document.createElement("style");M.textContent=".forum-mention{color:var(--accent);cursor:pointer;font-weight:600;transition:opacity 0.15s;}.forum-mention:hover{opacity:0.8;text-decoration:underline;}",document.head.appendChild(M),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(L,1e3)}):setTimeout(L,1e3)}(),function(){"use strict";var e=[{emoji:"⚡",title:"Bitcoin Payments Only",desc:"All transactions use Bitcoin (Lightning or on-chain). No fiat payments. Buyers and sellers handle payment directly — LightningMart is not an escrow or payment processor."},{emoji:"🚫",title:"No Illegal or Illicit Items",desc:"Strictly prohibited: drugs, weapons, stolen goods, counterfeit items, hacking tools, malware, pirated content, illegal services of any kind. Violation results in immediate ban and may be reported to authorities."},{emoji:"🔞",title:"No Adult or Sexual Content",desc:"No selling or advertising of sexual services, adult content, escort services, or any sexually explicit material. This is an educational Bitcoin marketplace — keep it appropriate for all ages."},{emoji:"🎭",title:"No Fraud or Misrepresentation",desc:"List items honestly. No fake photos, misleading descriptions, bait-and-switch tactics, or counterfeit goods. If it's used, say so. If it has defects, disclose them."},{emoji:"🛡️",title:"Buyer & Seller Safety",desc:"Meet in public places for local trades. Never share your seed phrase, private keys, or send Bitcoin before receiving the item. Use Lightning for instant, irreversible payments."},{emoji:"💰",title:"No Money Laundering or Wash Trading",desc:"No using the marketplace to launder money, create fake transactions, artificially inflate sales, or manipulate pricing. All listings must represent genuine offers."},{emoji:"📋",title:"Accurate Listings",desc:"Titles must clearly describe the item. Include condition, shipping options, and price in sats. One listing per item — no duplicate spam listings."},{emoji:"🤝",title:"Be Professional & Respectful",desc:"Communicate clearly with buyers/sellers. Respond to messages promptly. No harassment, threats, discrimination, or abusive language in any marketplace interaction."},{emoji:"🚫",title:"No Financial Products or Securities",desc:'No selling of financial instruments, investment schemes, MLM/pyramid schemes, "guaranteed returns," or unregistered securities. This is a marketplace for goods and services, not investments.'},{emoji:"⚖️",title:"Disputes & Moderation",desc:"LightningMart does not mediate disputes. All sales are final between buyer and seller. Report fraudulent listings using the 🚩 button. Moderators may remove listings and ban users without notice."}];function t(t){for(var o='

    LightningMart Rules

    Read before buying or selling
    ',n=0;n'+i.emoji+'
    '+i.title+'
    '+i.desc+"
    "}o+='',o+="
    ";var a=document.createElement("div");a.id="marketRulesOverlay",a.innerHTML=o,document.body.appendChild(a)}function o(){if(!auth||!auth.currentUser)return!1;var e=auth.currentUser.email||"";return"needcreations@gmail.com"===e||"info.603btc@gmail.com"===e}window.acceptMarketRules=function(){localStorage.setItem("btc_market_rules_accepted","true");var e=document.getElementById("marketRulesOverlay");e&&e.remove()},window.showMarketRulesBtn=function(){t()};var n=[{id:"educational",name:"Educational Products",emoji:"🎓",desc:"Learn Bitcoin with the best tools"},{id:"general",name:"Other Products",emoji:"🛒",desc:"Buy & sell everything else"},{id:"merchants",name:"More Bitcoin Merchants",emoji:"🏪",desc:"Browse more Bitcoin merchants"},{id:"noderunners",name:"Even More Merchants",emoji:"🌐",desc:"Bitcoin shops via Node Runners"}],i=[{id:"books",name:"Books",emoji:"📚",section:"educational"},{id:"courses",name:"Courses & Workshops",emoji:"🎓",section:"educational"},{id:"hardware_edu",name:"Hardware Wallets",emoji:"🔐",section:"educational"},{id:"nodes",name:"Node Kits & Guides",emoji:"💻",section:"educational"},{id:"kids",name:"Kids & Family",emoji:"👨‍👩‍👧‍👦",section:"educational"},{id:"tools",name:"Learning Tools",emoji:"🧰",section:"educational"},{id:"edu_other",name:"Other Educational",emoji:"📦",section:"educational"},{id:"mining",name:"Mining Equipment",emoji:"⛏️",section:"general"},{id:"merch",name:"Apparel & Merch",emoji:"👕",section:"general"},{id:"art",name:"Art & Collectibles",emoji:"🎨",section:"general"},{id:"stickers",name:"Stickers & Prints",emoji:"🖼️",section:"general"},{id:"services",name:"Services",emoji:"🛠️",section:"general"},{id:"electronics",name:"Electronics & Tech",emoji:"📱",section:"general"},{id:"other",name:"Other",emoji:"📦",section:"general"}],a=[{id:"new",label:"New",color:"#22c55e"},{id:"like_new",label:"Like New",color:"#84cc16"},{id:"good",label:"Good",color:"#eab308"},{id:"fair",label:"Fair",color:"#f97316"},{id:"for_parts",label:"For Parts",color:"#ef4444"}],r=[{id:"newest",label:"Newest First"},{id:"price_low",label:"Price: Low → High"},{id:"price_high",label:"Price: High → Low"},{id:"popular",label:"Most Saved"}];function s(e,t){"listing"===e?history.pushState({channel:"marketplace",mktView:"listing",listingId:t},"","#marketplace/listing/"+t):"my"===e&&history.pushState({channel:"marketplace",mktView:"my"},"","#marketplace/my")}window.handleMarketplacePopState=function(e,t){if(e&&"listing"===e.mktView&&e.listingId)return renderMarketplace({listingId:e.listingId,_noHistory:!0}),!0;if(e&&"my"===e.mktView)return showMyListings(!0),!0;if(t&&0===t.indexOf("marketplace/listing/")){var o=t.replace("marketplace/listing/","");return renderMarketplace({listingId:o,_noHistory:!0}),!0}return"marketplace/my"===t?(showMyListings(!0),!0):(renderMarketplace({_noHistory:!0}),!0)};var l=!1,c=!1;function d(e,t){var o=document.getElementById(e),n=document.getElementById(t);if(o&&n){var i=n.getBoundingClientRect();o.style.cssText="position:fixed;left:"+i.left+"px;top:"+i.top+"px;width:"+i.width+"px;height:"+i.height+"px;z-index:100;border-radius:12px;overflow:hidden;border:1px solid var(--border);background:var(--card-bg);pointer-events:auto;",o._reposition=function(){var e=n.getBoundingClientRect();o.style.left=e.left+"px",o.style.top=e.top+"px",o.style.width=e.width+"px",o.style.height=e.height+"px"},window.addEventListener("scroll",o._reposition,!0),window.addEventListener("resize",o._reposition)}}function u(e){var t=document.getElementById(e);t&&(t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t._reposition&&(window.removeEventListener("scroll",t._reposition,!0),window.removeEventListener("resize",t._reposition),t._reposition=null))}function p(e){var t=document.getElementById("forumContainer");if(t){t.style.display="block",t.innerHTML="";var l=e.category||"all",c=e.search||"",p=e.sort||"newest",h=e.listingId||null;if(h)return e._noHistory||s("listing",h),void function(e,t){e.innerHTML='
    Loading...
    ',db.collection("marketplace").doc(t).get().then(function(n){if(n.exists){var r={id:n.id,...n.data()},s=a.find(function(e){return e.id===r.condition}),l=s?s.label:"",c=s?s.color:"var(--text-faint)",d=i.find(function(e){return e.id===r.category}),u=d?d.emoji+" "+d.name:"📦 Other",p=-1!==safeJSON("btc_market_saved",[]).indexOf(r.id),h=void 0!==auth&&auth.currentUser&&auth.currentUser.uid===r.sellerUid,g=o(),f=r.priceSats>=1e6?(r.priceSats/1e6).toFixed(2)+"M sats":r.priceSats>=1e3?Math.floor(r.priceSats/1e3)+"K sats":r.priceSats.toLocaleString()+" sats",y="";try{var b=parseFloat(localStorage.getItem("btc_last_price")||"0");b>0&&(y=' (~$'+(r.priceSats/1e8*b).toFixed(2)+")")}catch(e){}var v=m(r.createdAt?r.createdAt.toDate():new Date),w='
    ';w+='',r.imageUrl?w+="
    ]/g,""):"")+"') center/contain no-repeat;background-color:var(--bg-side);border-radius:14px;border:1px solid var(--border);margin-bottom:16px;\">
    ":w+='
    '+(d?d.emoji:"📦")+"
    ",w+='
    '+escapeHtml(r.title)+'
    ⚡ '+f+y+"
    ",w+='
    '+l+''+u+'🕐 '+v+""+(r.shipping?'📦 Ships':"")+(r.localPickup?'📍 Local pickup':"")+"
    ",w+='
    Description
    '+escapeHtml(r.description||"No description provided.")+"
    ",w+='
    Seller
    '+(r.sellerName?r.sellerName.charAt(0).toUpperCase():"?")+'
    '+escapeHtml(r.sellerName||"Anonymous")+"
    "+(r.sellerRank?'
    '+escapeHtml(r.sellerRank)+"
    ":"")+'
    👤
    ',h?w+='
    ':(w+='
    '+(g?"':"")+"
    ",w+='
    🛡️ Safety Tips: Use escrow when possible. Never send payment before receiving the item. Meet in public if trading locally. Report suspicious listings.
    ',r.lightningAddress&&(w+='
    ⚡ This seller accepts Lightning payments
    ')),w+="
    ",e.innerHTML=w,db.collection("marketplace").doc(t).update({views:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})}else e.innerHTML='
    😕
    Listing not found
    '}).catch(function(){e.innerHTML='
    Error loading listing.
    '})}(t,h);var g='
    ';g+='
    Home
    ',g+='
    Lightning Mart
    Buy & sell with Bitcoin ⚡
    ',g+='
    ';var f=e.section||"merchants";if("all"!==l&&"all"===f){var y=i.find(function(e){return e.id===l});y&&(f=y.section)}g+='
    ';for(var b=[{id:"all",name:"All",emoji:"🛒"}].concat(n),v=0;v'+w.emoji+" "+w.name+""}if(g+="
    ",u("gmIframeWrap"),u("nrIframeWrap"),"merchants"===f)return g+='
    ',g+="
    ",t.innerHTML=g,void d("gmIframeWrap","gmIframePlaceholder");if("noderunners"===f)return g+='
    ',g+="",t.innerHTML=g,void d("nrIframeWrap","nrIframePlaceholder");var k="all"===f?i:i.filter(function(e){return e.section===f});g+='
    ',g+="';for(var B=0;B'+S.emoji+" "+S.name+""}g+="
    ","educational"!==f&&"all"!==f||(g+='
    🛒
    603BTC Pleb Shop
    Bitcoin educational products, merch & gear
    '),g+='
    Loading...
    ",g+='
    ',g+="",t.innerHTML=g,function(e,t,o,n){var r=document.getElementById("marketListings"),s=document.getElementById("marketResultCount");if(r&&void 0!==db){for(var l='
    ',c=0;c<6;c++)l+='
    ';l+="
    ",r.innerHTML=l;var d=db.collection("marketplace").where("status","==","active");e&&"all"!==e&&(d=d.where("category","==",e)),(d="price_low"===o?d.orderBy("priceSats","asc"):"price_high"===o?d.orderBy("priceSats","desc"):"popular"===o?d.orderBy("saves","desc"):d.orderBy("createdAt","desc")).limit(50).get().then(function(e){var o=[];if(e.forEach(function(e){o.push({id:e.id,...e.data()})}),n&&"all"!==n){var l=i.filter(function(e){return e.section===n}).map(function(e){return e.id});o=o.filter(function(e){return-1!==l.indexOf(e.category)})}if(t){var c=t.toLowerCase();o=o.filter(function(e){return(e.title||"").toLowerCase().includes(c)||(e.description||"").toLowerCase().includes(c)})}if(s&&(s.textContent=o.length+" listing"+(1!==o.length?"s":"")),0!==o.length){var d=safeJSON("btc_market_saved",[]);r.innerHTML=o.map(function(e){var t,o=-1!==d.indexOf(e.id),n=a.find(function(t){return t.id===e.condition}),r=n?n.color:"var(--text-faint)",s=n?n.label:"",l=i.find(function(t){return t.id===e.category}),c=l?l.emoji:"📦";return t=e.priceSats>=1e6?(e.priceSats/1e6).toFixed(2)+"M sats":e.priceSats>=1e3?Math.floor(e.priceSats/1e3)+"K sats":e.priceSats.toLocaleString()+" sats","
    '+(e.imageUrl?"
    ]/g,""):"")+"') center/cover;border-bottom:1px solid var(--border);\">
    ":'
    '+c+"
    ")+'
    '+escapeHtml(e.title)+'
    ⚡ '+t+"
    "+(satsToUSD(e.priceSats)?'
    '+satsToUSD(e.priceSats)+"
    ":'
    ')+'
    '+s+"'+(o?"❤️":"🤍")+"
    "}).join("")}else r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){console.error("Marketplace load error:",e),r&&("failed-precondition"===e.code?(console.log("Trying fallback marketplace query..."),db.collection("marketplace").orderBy("createdAt","desc").limit(50).get().then(function(e){var t=[];e.forEach(function(e){var o=e.data();o.id=e.id,"active"===o.status&&t.push(o)}),t.length>0?(r.innerHTML=t.map(function(e){return"
    '+escapeHtml(e.title||"Untitled")+'
    ⚡ '+(e.priceSats||0).toLocaleString()+" sats
    "}).join(""),s&&(s.textContent=t.length+" listing"+(1!==t.length?"s":""))):r.innerHTML='
    🏜️
    No listings yet
    '}).catch(function(e){r.innerHTML='
    ⚙️ Marketplace needs a database index.
    This is a one-time setup.

    Click here to create the index manually if requested →
    '})):r.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+". Try refreshing.
    ")})}}(l,c,p,f)}}window._hideMarketIframes=function(){u("gmIframeWrap"),u("nrIframeWrap")},window.renderMarketplace=function(e){if(e=e||{},document.getElementById("forumContainer")){if(l||(l=!0,"true"!==localStorage.getItem("btc_market_rules_accepted")&&t()),function(){if(!c){if(c=!0,!document.getElementById("gmIframeWrap")){var e=document.createElement("div");e.id="gmIframeWrap",e.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",e.innerHTML='',document.body.appendChild(e)}if(!document.getElementById("nrIframeWrap")){var t=document.createElement("div");t.id="nrIframeWrap",t.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;pointer-events:none;",t.innerHTML='',document.body.appendChild(t)}}}(),"function"==typeof showSkeletonLoader&&!e.listingId&&!e.search)return showSkeletonLoader("forumContainer"),void setTimeout(()=>p(e),300);p(e)}},window.showCreateListing=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to create a listing!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e='
    📝 Create Listing
    — or paste an image URL —
    ',t=document.createElement("div");t.innerHTML=e,document.body.appendChild(t.firstChild)};var h=0;function m(e){var t=Math.floor((new Date-e)/1e3);if(t<60)return"just now";var o=Math.floor(t/60);if(o<60)return o+"m ago";var n=Math.floor(o/60);if(n<24)return n+"h ago";var i=Math.floor(n/24);return i<30?i+"d ago":Math.floor(i/30)+"mo ago"}window.submitListing=function(){if(!window._mktSubmitting){var e=Date.now();if(e-h<6e4)"function"==typeof showToast&&showToast("⏳ Wait 60 seconds between listings");else{h=e;var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim();"function"==typeof sanitizeInput&&(t=sanitizeInput(t),a=sanitizeInput(a));var r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),l=document.getElementById("mktShipping").checked,c=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1||o>1e11)showToast("Price must be between 1 and 100B sats");else{var d=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Anonymous",u="";if(void 0!==currentUser&¤tUser&&"function"==typeof getLevel){var p=getLevel(currentUser.points||0);u=p.emoji+" "+p.name}var m={title:t,description:a,priceSats:o,category:n,condition:i,imageUrl:r||null,lightningAddress:s||null,shipping:l,localPickup:c,sellerUid:auth.currentUser.uid,sellerName:d,sellerRank:u,status:"active",views:0,saves:0,createdAt:firebase.firestore.FieldValue.serverTimestamp()};db.collection("marketplace").add(m).then(function(){window._mktUploadedImage=null;var e=document.getElementById("createListingOverlay");e&&e.remove(),"function"==typeof showToast&&showToast("🛒 Listing posted!"),"function"==typeof awardPoints&&awardPoints(15,"🛒 Marketplace listing!"),auth&&auth.currentUser&&(db.collection("users").doc(auth.currentUser.uid).update({marketListings:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketListings=(currentUser.marketListings||0)+1)),renderMarketplace()}).catch(function(e){console.error("Marketplace post error:",e),showToast("Error posting: "+(e.code||e.message||"Unknown error"))})}}}},window.toggleMarketSave=function(e){var t=safeJSON("btc_market_saved",[]),o=t.indexOf(e);-1!==o?(t.splice(o,1),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(-1)}).catch(function(e){console.error("[marketplace] Error:",e)})):(t.push(e),db.collection("marketplace").doc(e).update({saves:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)})),localStorage.setItem("btc_market_saved",JSON.stringify(t)),void 0!==db&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("users").doc(auth.currentUser.uid).update({marketSaved:t}).catch(function(e){console.error("[marketplace] Error:",e)});var n=document.getElementById("forumContainer");n&&n.innerHTML.includes("marketListings")&&renderMarketplace()},window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return showToast("🔒 Sign in to contact sellers"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var o='
    💬 Message '+escapeHtml(t)+'
    ',n=document.createElement("div");n.innerHTML=o,document.body.appendChild(n.firstChild)},window.sendMarketMessage=function(e){var t=(document.getElementById("mktMessage").value||"").trim();if(t){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Buyer";db.collection("marketplace").doc(e).get().then(function(n){if(n.exists){var i=n.data().sellerUid||"";return db.collection("marketplace_messages").add({listingId:e,buyerUid:auth.currentUser.uid,sellerUid:i,buyerName:o,message:t,createdAt:firebase.firestore.FieldValue.serverTimestamp(),read:!1})}showToast("Listing not found")}).then(function(){var t=document.getElementById("contactSellerOverlay");t&&t.remove(),showToast("💬 Message sent to seller!"),"function"==typeof sendNotification&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists&&t.data().sellerUid){var o=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Someone";sendNotification(t.data().sellerUid,"dm","🛒 "+o+" is interested in your listing!","marketplace",e)}}).catch(function(){}),db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(e){console.error("[marketplace] Error:",e)}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1)}).catch(function(){showToast("Error sending message. Try again.")})}else showToast("Please write a message")},window.showMyListings=function(e){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous){e||s("my");var t=document.getElementById("forumContainer");t&&(t.innerHTML='
    Loading your listings...
    ',db.collection("marketplace").where("sellerUid","==",auth.currentUser.uid).orderBy("createdAt","desc").get().then(function(e){var o,n='
    ';n+='',n+='
    📋 My Listings
    ',e.empty?n+='
    No listings yet. Create one!
    ':e.forEach(function(e){var t=e.data(),o="active"===t.status?"#22c55e":"sold"===t.status?"#ef4444":"var(--text-faint)";n+='
    '+escapeHtml(t.title)+'
    ⚡ '+(t.priceSats||0).toLocaleString()+' sats
    👁️ '+(t.views||0)+" views · ❤️ "+(t.saves||0)+' saves
    '+(t.status||"active")+""+("active"===t.status?"':"")+"
    "}),n+='
    💬 Messages
    ',n+='
    Loading messages...
    ',n+="
    ",t.innerHTML=n,(o=document.getElementById("myMarketMessages"))&&db.collection("marketplace_messages").orderBy("createdAt","desc").limit(20).get().then(function(e){var t=auth.currentUser.uid,n=[];e.forEach(function(e){var o=e.data();o.buyerUid===t&&n.push({id:e.id,...o,role:"buyer"})}),db.collection("marketplace").where("sellerUid","==",t).get().then(function(i){var a=[];i.forEach(function(e){a.push(e.id)}),e.forEach(function(e){var o=e.data();-1!==a.indexOf(o.listingId)&&o.buyerUid!==t&&n.push({id:e.id,...o,role:"seller"})}),0!==n.length?o.innerHTML=n.map(function(e){var t=e.createdAt?m(e.createdAt.toDate()):"";return'
    '+("seller"===e.role?"📩 From ":"📤 To seller · ")+escapeHtml(e.buyerName||"Buyer")+''+t+'
    '+escapeHtml(e.message)+"
    "}).join(""):o.innerHTML='
    No messages yet.
    '})})}).catch(function(e){console.error("My listings error:",e),"failed-precondition"===e.code?t.innerHTML='
    ⚙️ Setting up marketplace database (index)...
    Please refresh in 1 minute.
    ':t.innerHTML='
    Error: '+(e.code||e.message||"Unknown")+"
    "}))}else showToast("🔒 Sign in to see your listings")},window.markSold=function(e){db.collection("marketplace").doc(e).update({status:"sold"}).then(function(){showToast("✅ Marked as sold!"),showMyListings()})},window.editListing=function(e){auth&&auth.currentUser&&db.collection("marketplace").doc(e).get().then(function(t){if(t.exists){var n=t.data();n.sellerUid===auth.currentUser.uid||o()?(showCreateListing(),setTimeout(function(){var t=document.getElementById("mktTitle"),o=document.getElementById("mktPrice"),i=document.getElementById("mktCategory"),a=document.getElementById("mktCondition"),r=document.getElementById("mktDesc"),s=document.getElementById("mktImage"),l=document.getElementById("mktLightning"),c=document.getElementById("mktShipping"),d=document.getElementById("mktLocal");t&&(t.value=n.title||""),o&&(o.value=n.priceSats||"",updateMktPriceUSD()),i&&(i.value=n.category||""),a&&(a.value=n.condition||""),r&&(r.value=n.description||""),s&&n.imageUrl&&!n.imageUrl.startsWith("data:")&&(s.value=n.imageUrl||""),l&&(l.value=n.lightningAddress||""),c&&(c.checked=!!n.shipping),d&&(d.checked=!!n.local);var u=document.getElementById("createListingOverlay");if(u){var p=u.querySelector('div[style*="font-size:1.2rem"]');p&&(p.textContent="✏️ Edit Listing")}var h=u?u.querySelector('button[onclick*="submitListing"]'):null;h&&(h.textContent="✏️ Update Listing",h.onclick=function(){updateExistingListing(e)})},100)):showToast("You can only edit your own listings")}else showToast("Listing not found")}).catch(function(e){showToast("Error loading listing: "+(e.message||"Unknown"))})},window.updateExistingListing=function(e){var t=(document.getElementById("mktTitle").value||"").trim(),o=parseInt(document.getElementById("mktPrice").value),n=document.getElementById("mktCategory").value,i=document.getElementById("mktCondition").value,a=(document.getElementById("mktDesc").value||"").trim(),r=window._mktUploadedImage||(document.getElementById("mktImage").value||"").trim(),s=(document.getElementById("mktLightning").value||"").trim(),l=document.getElementById("mktShipping").checked,c=document.getElementById("mktLocal").checked;if(!t||t.length<3)showToast("Please enter a title (3+ characters)");else if(!o||o<1)showToast("Please enter a price in sats");else{var d={title:t.substring(0,80),priceSats:o,category:n,condition:i,description:a.substring(0,1e3),lightningAddress:s,shipping:l,local:c,updatedAt:firebase.firestore.FieldValue.serverTimestamp()};r&&(d.imageUrl=r),db.collection("marketplace").doc(e).update(d).then(function(){var t=document.getElementById("createListingOverlay");t&&t.remove(),showToast("✅ Listing updated!"),window._mktUploadedImage=null,renderMarketplace({listingId:e})}).catch(function(e){showToast("Error updating: "+(e.message||"Unknown"))})}},window.deleteListing=function(e){if(auth&&auth.currentUser){var t=o();confirm(t?"Admin: Delete this listing?":"Delete this listing?")&&db.collection("marketplace").doc(e).update({status:"deleted",deletedBy:t?"admin":"owner",deletedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){showToast("🗑️ Listing deleted"),renderMarketplace()})}},window.updateMktPriceUSD=function(){var e=parseInt(document.getElementById("mktPrice").value)||0,t=document.getElementById("mktPriceUSD");if(t)if(e<=0)t.textContent="";else{var o=parseFloat(localStorage.getItem("btc_last_price")||"0");if(o<=0)return fetch("https://mempool.space/api/v1/prices").then(function(e){return e.json()}).then(function(e){e&&e.USD&&(localStorage.setItem("btc_last_price",e.USD),updateMktPriceUSD())}).catch(function(e){console.error("[marketplace] Error:",e)}),void(t.textContent="Loading USD price...");var n=e/1e8*o;t.textContent="≈ $"+n.toFixed(2)+" USD"}},window.satsToUSD=function(e){var t=parseFloat(localStorage.getItem("btc_last_price")||"0");return t<=0||!e?"":"~$"+(e/1e8*t).toFixed(2)},window.handleMktImageUpload=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else{var o=new FileReader;o.onload=function(e){var t=new Image;t.onload=function(){var e=t.width,o=t.height;e>800&&(o=Math.round(800*o/e),e=800);var n=document.createElement("canvas");n.width=e,n.height=o,n.getContext("2d").drawImage(t,0,0,e,o);var i=n.toDataURL("image/jpeg",.8),a=document.getElementById("mktImagePreview"),r=document.getElementById("mktImagePreviewImg");a&&r&&(r.src=i,a.style.display="block"),window._mktUploadedImage=i;var s=document.getElementById("mktImage");s&&(s.value="")},t.src=e.target.result},o.readAsDataURL(t)}},window._plebShopOpen=!1,window._togglePlebShop=function(){var e=document.getElementById("plebShopEmbed"),t=document.getElementById("plebShopToggle");e&&(window._plebShopOpen=!window._plebShopOpen,window._plebShopOpen?(e.style.display="block",e.style.height="calc(100vh - 280px)",e.style.minHeight="500px",e.querySelector("iframe")||(e.innerHTML=''),t&&(t.textContent="Close Shop",t.style.background="var(--border)")):(e.style.height="0",e.style.minHeight="0",setTimeout(function(){e.style.display="none"},300),t&&(t.textContent="Open Shop",t.style.background="var(--accent)")))},window.clearMktImage=function(){window._mktUploadedImage=null;var e=document.getElementById("mktImagePreview");e&&(e.style.display="none");var t=document.getElementById("mktImageFile");t&&(t.value="")}}();var MSG_CONFIG={onlineThreshold:3e5,awayThreshold:9e5,presenceInterval:6e4,maxMsgLength:500,maxMsgsPerHour:30,maxConvoHistory:100,unreadPollInterval:3e4,maxNewConvosPerDay:5,newAccountCooldownMs:864e5,minPointsToDM:50,duplicateWindowMs:5e3},SUSPICIOUS_PATTERNS=[/send\s*(?:me|ur|your)\s*(?:btc|bitcoin|sats|seed|key|phrase)/i,/(?:double|triple|multiply)\s*(?:your|ur)\s*(?:btc|bitcoin|sats|crypto)/i,/(?:free|win|won|claim|airdrop)\s*(?:btc|bitcoin|sats|crypto|nft)/i,/(?:invest|deposit)\s*(?:now|today|here)\b/i,/(?:guaranteed|100%)\s*(?:return|profit|roi)/i,/send\s*\d+\s*(?:btc|sats)\s*(?:to|and)\s*(?:get|receive|earn)/i,/(?:seed|private)\s*(?:phrase|key)\s*(?:here|now|please|share)/i,/(?:validate|verify|sync)\s*(?:your|ur)\s*(?:wallet|account)/i,/(?:connect|link)\s*(?:your|ur)\s*(?:wallet|metamask|phantom)/i,/(?:nigerian|prince|inheritance|lottery)\s*(?:fund|money|payment)/i],SUSPICIOUS_URLS=[/bit\.ly|tinyurl|t\.co|goo\.gl|is\.gd|buff\.ly|ow\.ly|rebrand\.ly/i,/(?:discord\.gift|discordapp\.gift|nitro.*free)/i,/(?:steamcommunity|steampowered).*(?:gift|trade|login)/i,/(?:wallet|connect|validate|sync|claim|airdrop).*(?:\.com|\.io|\.xyz|\.site|\.app)/i,/(?:dapp|defi|swap|bridge|mint).*(?:\.com|\.io|\.xyz|\.site)/i],BLOCKED_CONTENT=[/(?:child|minor|underage).*(?:porn|nude|nsfw)/i,/(?:kill|murder|attack|bomb|shoot).*(?:yourself|someone|them|people|school)/i,/\b(?:doxx|doxing|swat)\b/i,/\b(?:nigger|nigga|faggot|kike|spic|wetback|chink|gook|towelhead|raghead|beaner|coon|darkie|zipperhead)\b/i,/\b(?:white\s*power|white\s*supremacy|sieg\s*heil|race\s*war|ethnic\s*cleansing|final\s*solution)\b/i,/\b(?:gas\s*the|death\s*to)\s+\w+/i,/\b(?:heil\s*hitler|genocide)\b/i,/\b(?:i\s*(?:will|wanna|gonna|want\s*to)\s*(?:kill|hurt|stab|shoot|beat|attack|find)\s*(?:you|u|him|her|them))\b/i,/\b(?:i\s*know\s*where\s*(?:you|u)\s*live)\b/i,/\b(?:watch\s*your\s*back|you(?:'re|\s*are)\s*dead)\b/i,/\b(?:track\s*(?:you|u)\s*down|come\s*find\s*(?:you|u))\b/i,/\b(?:kill\s*myself|cut(?:ting)?\s*myself|slit\s*my\s*wrist|hang\s*myself|end\s*my\s*life)\b/i,/\b(?:want(?:a)?\s*(?:to\s*)?die|kys|kill\s*yourself)\b/i,/\b(?:self[\s-]*harm|overdose\s*on|jump\s*off\s*a)\b/i,/\b(?:blowjob|handjob|gangbang|threesome|deepthroat|rimjob|creampie)\b/i,/\b(?:send\s*(?:me\s*)?nudes|dick\s*pic|show\s*(?:me\s*)?(?:your|ur)\s*(?:body|tits|boobs|ass|pussy|dick))\b/i,/\b(?:wanna|want\s*to|lets)\s*(?:fuck|bang|screw|bone|smash)\b/i,/\b(?:suck\s*my|sit\s*on\s*my|bend\s*over|get\s*on\s*your\s*knees)\b/i,/\b(?:masturbat|fingering|bondage|bdsm|fetish|dominatrix)\b/i,/\b(?:escort|prostitut|hooker|camgirl|sexting)\b/i],PII_PATTERNS=[/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:phone|number|address|email|ssn|social|zip|location|real name|full name|home|where.*live)/i,/(?:what(?:'s| is)|send|share|give|tell)\s*(?:me\s+)?(?:your|ur)\s*(?:id|passport|driver.?s?\s*license|bank|routing|account\s*number|credit\s*card|debit\s*card)/i,/(?:dm|message|text|call|contact)\s*(?:me\s+)?(?:on|at|@)\s*(?:whatsapp|telegram|signal|insta|instagram|snap|snapchat|facebook|messenger|wechat|line)\b/i,/(?:my|here(?:'s| is))\s*(?:phone|number|cell|whatsapp|telegram|signal)\s*(?:is|:|\s)\s*[\+\d\(\)\-\s]{7,}/i,/(?:my|here(?:'s| is))\s*(?:email|e-mail)\s*(?:is|:|\s)\s*\S+@\S+\.\S+/i,/(?:my|here(?:'s| is))\s*(?:address|location)\s*(?:is|:)/i];function containsSuspiciousLink(e){for(var t=e.match(/https?:\/\/[^\s<>"{}|\\^`\[\]]+/gi)||[],o=0;o]*>/g,"")).trim()).length>MSG_CONFIG.maxMsgLength&&(e=e.substring(0,MSG_CONFIG.maxMsgLength)),e):""}function containsPII(e){for(var t=0;t"']+)/gi,function(e){return''+e+""})}function _getDailyConvoLog(){try{var e=localStorage.getItem("btc_dm_daily_log");if(!e)return{date:"",recipients:[]};var t=JSON.parse(e),o=(new Date).toISOString().slice(0,10);return t.date!==o?{date:o,recipients:[]}:t}catch(e){return{date:(new Date).toISOString().slice(0,10),recipients:[]}}}function _logNewConvo(e){var t=_getDailyConvoLog();t.date=(new Date).toISOString().slice(0,10),-1===t.recipients.indexOf(e)&&t.recipients.push(e),localStorage.setItem("btc_dm_daily_log",JSON.stringify(t))}function _canStartNewConvo(e){var t=_getDailyConvoLog();return-1!==t.recipients.indexOf(e)||t.recipients.length
    🚨
    "Friends in Distress" Scam
    Scammers will impersonate people you know and trust — your friends, family, even coworkers. They can:
    • Clone their profile picture, name, and bio
    • Copy their writing style and messages
    • Use AI-generated voice clones that sound exactly like them
    • Create fake emergencies — "I\'m stuck," "I need help," "send me Bitcoin and I\'ll pay you back"
    The scammer will pressure you to act fast so you don\'t have time to think or verify. They prey on your emotions and trust.
    🛡️ How to protect yourself:
    NEVER send Bitcoin to anyone claiming to be in distress over a message
    Verify their identity through a separate channel — call them, video chat, or meet in person
    Real friends will understand if you take time to verify
    Bitcoin transactions are irreversible — once sent, it\'s gone forever
    • If it feels urgent and emotional, that\'s exactly what the scammer wants
    ',document.body.appendChild(e.firstChild)};var _lastSentMsg={text:"",time:0};function _isDuplicateMessage(e){var t=Date.now();return e===_lastSentMsg.text&&t-_lastSentMsg.time
    Why are you reporting this user?
    ',i=document.createElement("div");return i.innerHTML=n,void document.body.appendChild(i.firstChild)}},window.submitReport=function(e,t,o){var n=document.getElementById("reportModal");if(n&&n.remove(),db&&auth&&auth.currentUser){var i=void 0!==currentUser&¤tUser?currentUser.username:"Anonymous";db.collection("reports").add({reportedUid:e,reportedName:t,reporterUid:auth.currentUser.uid,reporterName:i,reason:o,createdAt:firebase.firestore.FieldValue.serverTimestamp(),status:"pending"}).then(function(){"function"==typeof showToast&&showToast("🚩 Report submitted. Thank you for keeping the community safe."),blockUser(e,t)}).catch(function(){"function"==typeof showToast&&showToast("Failed to submit report")})}};var _presenceTimer=null;function updatePresence(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e="false"!==localStorage.getItem("btc_online_status");try{e?db.collection("users").doc(auth.currentUser.uid).update({lastSeen:firebase.firestore.FieldValue.serverTimestamp(),isOnline:!0}).catch(function(){}):db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:null}).catch(function(){})}catch(e){}}}function startPresenceTracking(){updatePresence(),_presenceTimer&&clearInterval(_presenceTimer),_presenceTimer=setInterval(updatePresence,MSG_CONFIG.presenceInterval),window.addEventListener("beforeunload",function(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db)try{db.collection("users").doc(auth.currentUser.uid).update({isOnline:!1,lastSeen:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){}}),document.addEventListener("visibilitychange",function(){"visible"===document.visibilityState&&updatePresence()})}function profileStat(e,t,o){return'
    '+e+'
    '+t+'
    '+o+"
    "}window.toggleOnlineStatus=function(){updatePresence()},window.getOnlineStatus=function(e){if(!e)return{status:"offline",color:"#6b7280",label:"Offline",dot:"⚫"};var t=e.toDate?e.toDate().getTime():"number"==typeof e?e:new Date(e).getTime(),o=Date.now()-t;return o'},window.showUserProfile=function(e){if(e&&db){var t=document.createElement("div");t.innerHTML='
    Loading profile...
    ',document.body.appendChild(t.firstChild),db.collection("users").doc(e).get().then(function(t){if(!t.exists)return(h=document.getElementById("userProfileModal"))&&h.remove(),void("function"==typeof showToast&&showToast("User not found"));var o=t.data(),n=getOnlineStatus(o.lastSeen),i="function"==typeof getLevel?getLevel(o.points||0):{name:"Newbie",emoji:"🌱"},a=o.createdAt&&o.createdAt.toDate?o.createdAt.toDate().toLocaleDateString():"Unknown",r="function"==typeof escapeHtml?escapeHtml(o.displayBadge||o.equippedBadge||""):(o.displayBadge||o.equippedBadge||"").replace(//g,">").replace(/"/g,"""),s=0;o.visibleBadges&&(s+=o.visibleBadges.length),o.hiddenBadges&&(s+=o.hiddenBadges.length);var l="";if(r){var c=r;if(void 0!==HIDDEN_BADGES&&r.length>5){var d=HIDDEN_BADGES.find(e=>e.id===r);d&&(c=d.emoji)}l='
    '+c+' '+i.emoji+"
    "}else l='
    '+i.emoji+"
    ";var u,p,h,m=auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&auth.currentUser.uid!==e,g=m?_canAccountDM():{ok:!1},f='
    '+l+'
    '+escapeHtml(o.username||"Bitcoiner")+'
    '+i.name+" · "+(o.points||0).toLocaleString()+' XP
    '+n.label+'
    '+("cyber_hornets"===o.faction?'🐝 Cyber Hornets':"honey_badgers"===o.faction?'🦡 Honey Badgers':'👤 Unaffiliated')+''+(o.country?"🌍 "+escapeHtml(o.country):"🌍 Not specified")+"
    "+(o.bio?'
    About
    '+escapeHtml(o.bio)+"
    ":"")+(o.twitter||o.nostr||o.website?'
    '+(o.twitter?'𝕏 '+escapeHtml(o.twitter)+"":"")+(o.nostr?'🟣 Nostr':"")+(o.website&&!/^(javascript|data|vbscript|blob):/i.test(o.website.trim())?'🌐 Website':"")+"
    ":"")+'
    '+profileStat("🏅",s,"Badges")+profileStat("📖",Array.isArray(o.visitedChannelsList)?o.visitedChannelsList.length:Array.isArray(o.readChannels)?o.readChannels.length:0,"Channels")+profileStat("🎟️",o.orangeTickets||0,"Tickets")+'
    '+profileStat("🗣️",o.forumPosts||0,"Posts")+profileStat("🔥",(o.streak||0)+"("+(o.bestStreak||o.streak||0)+")","Streak")+profileStat("📅",a,"Joined")+"
    "+(o.pvpWins||o.pvpLosses?'
    '+profileStat("⚔️",(o.pvpWins||0)+"W","PVP Wins")+profileStat("💀",(o.pvpLosses||0)+"L","PVP Losses")+profileStat("📊",((o.pvpWins||0)+(o.pvpLosses||0)>0?Math.round((o.pvpWins||0)/((o.pvpWins||0)+(o.pvpLosses||0))*100):0)+"%","Win Rate")+"
    ":"")+(o.predictions&&o.predictions.total?(p=(u=o.predictions).total>0?Math.round(u.correct/u.total*100):0,'
    '+profileStat("📈",u.total,"Predictions")+profileStat("🎯",p+"%","Accuracy")+profileStat("🔥",u.bestStreak||u.streak||0,"Best Streak")+"
    "):"")+(o.lightningAddress||o.lightning?(window._profileTipData={recipientName:o.username||"Bitcoiner",recipientUid:e,lightningAddress:o.lightningAddress||o.lightning||"",label:"Tip "+(o.username||"Bitcoiner"),context:"profile"},'
    '+escapeHtml(o.lightningAddress||o.lightning)+'
    "):"")+(m&&g.ok?"":m&&!g.ok?'
    '+escapeHtml(g.reason)+"
    ":auth&&auth.currentUser&&!auth.currentUser.isAnonymous?"":"")+(m?'
    '+(isUserBlocked(e)?"":"")+"
    ':"")+ +(auth&&auth.currentUser&&auth.currentUser.uid===e&&!o.country?'
    🌍Add your country → earn +100 XP + 🌍 Global Citizen badge
    ':"")+"
    ";(h=document.getElementById("userProfileModal"))&&h.remove();var y=document.createElement("div");y.innerHTML=f,document.body.appendChild(y.firstChild)}).catch(function(t){console.error("Profile load error:",t);var o=document.getElementById("userProfileModal");o&&o.remove(),"function"==typeof showToast&&showToast("Could not load profile ["+e+"]: "+(t.message||"permission error"))})}},window._tipFromProfile=function(){var e=window._profileTipData;if(e){var t=document.getElementById("userProfileModal");t&&t.remove(),"function"==typeof showTipOverlay?showTipOverlay(e):"function"==typeof showToast&&showToast("⚡ Lightning tips still loading, try again in a moment")}};var _msgSentTimestamps=[];function checkRateLimit(){var e=Date.now();return(_msgSentTimestamps=_msgSentTimestamps.filter(function(t){return e-t<36e5})).length
    💬 '+escapeHtml(o)+'
    ⚠️ Never share your seed phrase, private keys, or send Bitcoin to strangers or "friends in distress."
    ',s=document.createElement("div");s.innerHTML=r,document.body.appendChild(s.firstChild),setTimeout(function(){var e=document.getElementById("dmInput");e&&e.focus()},300),loadDMMessages(e,n,t,o),db.collection("dm_conversations").doc(e).get().then(function(e){if(e.exists&&e.data().isBuddyMatch){var t=document.getElementById("dmWindow");if(!t)return;var o=t.querySelector('div[style*="rgba(234,179,8,0.1)"]');o&&(o.style.background="rgba(34,197,94,0.08)",o.style.borderColor="rgba(34,197,94,0.2)",o.style.color="#22c55e",o.innerHTML="🦌 Nacho is in this chat! Ask any Bitcoin question and Nacho will jump in. Teachers can add context to help learners.")}}).catch(function(){}),db.collection("users").doc(t).get().then(function(e){if(e.exists){var t=getOnlineStatus(e.data().lastSeen),o=document.getElementById("dmStatusDot");o&&(o.innerHTML='')}}).catch(function(){})}function loadDMMessages(e,t,o,n){var i=document.getElementById("dmMessages");i&&(i.innerHTML='
    Loading messages...
    ',window._dmUnsubscribe=db.collection("dm_conversations").doc(e).collection("messages").orderBy("createdAt","asc").limit(MSG_CONFIG.maxConvoHistory).onSnapshot(function(o){if(i.innerHTML="",o.empty)i.innerHTML='
    💬
    Start a conversation with '+escapeHtml(n)+'!
    Messages are private between you two.
    ';else{var a="";o.forEach(function(e){var o=e.data(),n=o.senderUid===t;if(n||o.isNachoAuto||"function"!=typeof isUserBlocked||!isUserBlocked(o.senderUid)){var r=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):new Date,s=r.toLocaleDateString();s!==a&&(i.innerHTML+='
    '+s+"
    ",a=s);var l=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),c="nacho-bot"===o.senderUid||!0===o.isNachoAuto,d=n||c||!containsScamPattern(o.text)&&!containsSuspiciousLink(o.text)?"":'
    ⚠️ This message may contain a scam. Never send money to strangers.
    ',u=n||c||!containsPII(o.text)?"":'
    ⚠️ This person is asking for personal info. Only share details for Lightning Mart transactions.
    ',p=c?"rgba(34,197,94,0.08)":n?"var(--accent)":"var(--card-bg)",h=c?"1px solid rgba(34,197,94,0.25)":"none",m=c?"var(--text)":n?"#fff":"var(--text)",g=c?'
    🦌 Nacho
    ':"",f=linkifyText(escapeHtml(o.text)).replace(/\n/g,"
    "),y="";o.imageUrl&&(y=''),i.innerHTML+='
    '+g+(f||"")+y+d+u+'
    '+l+"
    "}}),i.scrollTop=i.scrollHeight,markDMRead(e,t)}},function(e){i.innerHTML='
    💬
    Start a conversation!
    Send your first message below.
    '}))}window.openDM=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to send messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var o=_canAccountDM();if(o.ok)if(isUserBlocked(e))"function"==typeof showToast&&showToast("🚫 This user is blocked. Unblock them to message.");else if(_canStartNewConvo(e)){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";showDMWindow(getConversationId(n,e),e,t,n,i)}else"function"==typeof showToast&&showToast("⏳ You can only message "+MSG_CONFIG.maxNewConvosPerDay+" new people per day. This helps keep the community safe.");else"function"==typeof showToast&&showToast(o.reason)},window.closeDM=function(){window._dmUnsubscribe&&(window._dmUnsubscribe(),window._dmUnsubscribe=null);var e=document.getElementById("dmWindow");e&&e.remove()},window.handleDMImage=function(e,t,o,n){if(e&&e.files&&e.files[0]){var i=e.files[0];if(e.value="",i.type.startsWith("image/"))if(i.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var a=null;try{a=firebase.storage()}catch(e){}if(a){"function"==typeof showToast&&showToast("📷 Uploading image…");var r=auth.currentUser.uid,s=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",l=i.type.indexOf("png")>-1?"png":i.type.indexOf("gif")>-1?"gif":i.type.indexOf("webp")>-1?"webp":"jpg",c=Date.now()+"_"+Math.random().toString(36).substr(2,6)+"."+l,d=a.ref("dm-images/"+r+"/"+c),u=document.getElementById("dmMessages");u&&(u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML=""),(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),u.innerHTML+='
    📷
    Uploading…
    ',u.scrollTop=u.scrollHeight),d.put(i,{contentType:i.type}).then(function(e){return e.ref.getDownloadURL()}).then(function(e){var i=u&&u.querySelector("[data-dm-img-uploading]");i&&i.remove();var a=db.collection("dm_conversations").doc(t),l={senderUid:r,senderName:s,text:"",imageUrl:e,createdAt:firebase.firestore.FieldValue.serverTimestamp()},c={lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r};return c["unread_"+o]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(o,"dm","📷 Image from @"+s,"dm",t),a.update(c).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[r,o],lastMessage:"📷 Image",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:r,participantNames:{}};return t.participantNames[r]=s,t.participantNames[o]=n,t["unread_"+o]=firebase.firestore.FieldValue.increment(1),a.set(t)}throw e}).then(function(){return a.collection("messages").add(l)}).then(function(){"function"==typeof showToast&&showToast("📷 Image sent!"),u&&document.getElementById("dmMessages")&&loadDMMessages(t,r,o,n)})}).catch(function(e){console.error("[DM Image] Upload failed:",e),"function"==typeof showToast&&showToast("Failed to send image: "+(e.message||"upload error"));var t=u&&u.querySelector("[data-dm-img-uploading]");t&&t.remove()})}else"function"==typeof showToast&&showToast("Image upload unavailable")}else"function"==typeof showToast&&showToast("Sign in to send images");else"function"==typeof showToast&&showToast("Only images are allowed")}},window.showDMGifPicker=function(e,t,o){var n=document.getElementById("dmGifPicker");if(n)n.remove();else{var i=document.createElement("div");i.id="dmGifPicker",i.style.cssText="position:fixed;bottom:80px;left:50%;transform:translateX(-50%);z-index:600000;background:var(--card-bg,#1a1a2e);border:1px solid var(--border);border-radius:16px;padding:12px;width:90%;max-width:360px;max-height:350px;display:flex;flex-direction:column;box-shadow:0 8px 32px rgba(0,0,0,0.5);",window._dmGifConvo={convoId:e,recipientUid:t,recipientName:o},i.innerHTML='
    Type to search or tap a category
    ',document.body.appendChild(i),document.getElementById("dmGifSearchInput").focus()}};var _dmGifSearchTimer=null;function markDMRead(e,t){db.collection("dm_conversations").doc(e).update({["unread_"+t]:0}).catch(function(){})}window.searchDMGifs=function(e){_dmGifSearchTimer&&clearTimeout(_dmGifSearchTimer);var t=document.getElementById("dmGifResults");if(t)if(!e||e.length<2)t.innerHTML='
    Type to search
    ';else{var o=document.getElementById("dmGifSearchInput");o&&o.value!==e&&(o.value=e),t.innerHTML='
    Searching...
    ',_dmGifSearchTimer=setTimeout(function(){fetch("https://g.tenor.com/v1/search?q="+encodeURIComponent(e)+"&key=LIVDSRZULELA&limit=20&media_filter=minimal").then(function(e){return e.json()}).then(function(e){if(e.results&&0!==e.results.length){for(var o="",n=0;n')}t.innerHTML=o||'
    No GIFs found
    '}else t.innerHTML='
    No GIFs found
    '}).catch(function(){t.innerHTML='
    Search failed
    '})},400)}},window.sendDMGifUrl=function(){var e=document.getElementById("dmGifUrlInput");e&&e.value.trim()&&sendDMGif(e.value.trim())},window.sendDMGif=function(e){if(e){var t=window._dmGifConvo;if(t){var o=document.getElementById("dmGifPicker");if(o&&o.remove(),auth&&auth.currentUser){var n=auth.currentUser.uid,i=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner",a=t.convoId,r=t.recipientUid,s=t.recipientName,l=document.getElementById("dmMessages");if(l){var c=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});l.innerHTML+='
    '+c+"
    ",l.scrollTop=l.scrollHeight}var d=db.collection("dm_conversations").doc(a),u={senderUid:n,senderName:i,text:"",imageUrl:e,isGif:!0,createdAt:firebase.firestore.FieldValue.serverTimestamp()},p={lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n};p["unread_"+r]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(r,"dm","GIF from @"+i,"dm",a),d.update(p).catch(function(e){if("not-found"===e.code||-1!==e.message.indexOf("NOT_FOUND")){var t={participants:[n,r],lastMessage:"GIF",lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:n,participantNames:{}};return t.participantNames[n]=i,t.participantNames[r]=s,t["unread_"+r]=firebase.firestore.FieldValue.increment(1),d.set(t)}throw e}).then(function(){return d.collection("messages").add(u)}).then(function(){l&&document.getElementById("dmMessages")&&loadDMMessages(a,n,r,s)}).catch(function(e){console.error("[DM GIF] Send failed:",e),"function"==typeof showToast&&showToast("Failed to send GIF")})}else"function"==typeof showToast&&showToast("Sign in to send GIFs")}else"function"==typeof showToast&&showToast("Error: no conversation context")}},window.sendDM=function(e,t,o){var n=document.getElementById("dmInput");if(n){var i=sanitizeMessage(n.value);if(i)if(i.length>MSG_CONFIG.maxMsgLength)"function"==typeof showToast&&showToast("Message too long (max "+MSG_CONFIG.maxMsgLength+" chars)");else if(_isDuplicateMessage(i))"function"==typeof showToast&&showToast("⏳ Message already sent");else if(isUserBlocked(t))"function"==typeof showToast&&showToast("🚫 You have blocked this user");else if(containsBlockedContent(i))"function"==typeof showToast&&showToast("⛔ Message contains prohibited content");else{if(containsPII(i)&&!confirm("⚠️ This message appears to contain or request personal information (phone numbers, addresses, emails, etc.).\n\nSharing personal info with strangers is risky. Only share contact details for Lightning Mart transactions.\n\nSend anyway?"))return;if(!containsScamPattern(i)||confirm("⚠️ This message contains patterns commonly used in scams. Are you sure you want to send it?"))if(containsSuspiciousLink(i)&&"function"==typeof showToast&&showToast("⚠️ Warning: Suspicious link detected. Be cautious with URLs."),checkRateLimit()){var a=auth.currentUser.uid,r=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"Bitcoiner";n.value="",_msgSentTimestamps.push(Date.now()),_logNewConvo(t);var s=db.collection("dm_conversations").doc(e),l={senderUid:a,senderName:r,text:i,createdAt:firebase.firestore.FieldValue.serverTimestamp()},c={lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a};c["unread_"+t]=firebase.firestore.FieldValue.increment(1);var d={participants:[a,t],lastMessage:i,lastMessageTime:firebase.firestore.FieldValue.serverTimestamp(),lastSenderUid:a,participantNames:{}};d.participantNames[a]=r,d.participantNames[t]=o,d["unread_"+t]=firebase.firestore.FieldValue.increment(1),"function"==typeof sendNotification&&sendNotification(t,"dm","💬 New message from @"+r,"dm",e);var u=document.getElementById("dmMessages");if(u){u.querySelector('div[style*="text-align:center"]')&&1===u.children.length&&(u.innerHTML="");var p=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),h=(new Date).toLocaleDateString(),m=u.querySelector("div[data-dm-date]:last-of-type");h!==(m?m.getAttribute("data-dm-date"):"")&&(u.innerHTML+='
    '+h+"
    "),u.innerHTML+='
    '+linkifyText(escapeHtml(i))+'
    '+p+"
    ",u.scrollTop=u.scrollHeight}s.update(c).catch(function(e){if("not-found"===e.code||"permission-denied"===e.code||-1!==e.message.indexOf("NOT_FOUND")||-1!==e.message.indexOf("No document to update")||-1!==e.message.indexOf("PERMISSION_DENIED"))return s.set(d,{merge:!0});throw e}).then(function(){return s.collection("messages").add(l)}).then(function(){u&&document.getElementById("dmMessages")&&loadDMMessages(e,a,t,o);var n=parseInt(localStorage.getItem("btc_dms_sent")||"0");localStorage.setItem("btc_dms_sent",String(n+1)),"function"==typeof checkBadges&&setTimeout(checkBadges,500)}).catch(function(e){console.error("DM send error:",e),"function"==typeof showToast&&showToast("Failed to send: "+(e.code||e.message||"Unknown error"));var t=u&&u.querySelector("[data-optimistic]");t&&t.remove()})}else"function"==typeof showToast&&showToast("⏳ Slow down! Max "+MSG_CONFIG.maxMsgsPerHour+" messages per hour.")}}},window.showInbox=function(){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to see messages"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());var e=auth.currentUser.uid,t=document.getElementById("dmInbox");t&&t.remove();var o=document.createElement("div");o.innerHTML='
    📬 Messages
    Loading...
    ',document.body.appendChild(o.firstChild),db.collection("dm_conversations").where("participants","array-contains",e).orderBy("lastMessageTime","desc").limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");o&&(console.log("Inbox snap size:",t.size),t.empty?o.innerHTML='
    📬
    No messages yet
    Tap a user on the leaderboard to start chatting!
    ':(o.innerHTML="",t.forEach(function(t){var n=t.data(),i=n.participants.find(function(t){return t!==e}),a=n.participantNames&&n.participantNames[i]||"User",r=n["unread_"+e]||0,s=n.lastMessage||"";s.length>50&&(s=s.substring(0,50)+"...");var l=n.lastMessageTime?timeAgo(n.lastMessageTime):"",c=n.lastSenderUid===e,d=!0===n.isBuddyMatch,u=d?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+';" onmouseover="this.style.background=\'var(--card-bg)\'" onmouseout="this.style.background=\''+(r>0?"var(--accent-bg,rgba(247,147,26,0.05))":d?"rgba(34,197,94,0.03)":"none")+'\'">
    '+(d?"🦌":a.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(a)+u+'
    '+l+'
    0?"600":"400")+';white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">'+(c?"You: ":"")+escapeHtml(s)+"
    "+(r>0?'
    '+r+"
    ":"")+"
    "})))}).catch(function(t){console.error("Inbox load error:",t);var o=document.getElementById("dmInboxList");o&&("failed-precondition"!==t.code?o.innerHTML='
    💬
    No messages yet
    Tap a user on the leaderboard or in PlebTalk to start chatting!
    ':db.collection("dm_conversations").where("participants","array-contains",e).limit(30).get().then(function(t){var o=document.getElementById("dmInboxList");if(o)if(t.empty)o.innerHTML='
    📬
    No messages yet
    ';else{o.innerHTML="";var n=[];t.forEach(function(e){n.push({id:e.id,...e.data()})}),n.sort(function(e,t){return(t.lastMessageTime||0)-(e.lastMessageTime||0)}),n.forEach(function(t){var n=t.participants.find(function(t){return t!==e}),i=t.participantNames&&t.participantNames[n]||"User",a=t["unread_"+e]||0,r=t.lastMessage||"";r.length>50&&(r=r.substring(0,50)+"...");var s=t.lastSenderUid===e,l=!0===t.isBuddyMatch,c=l?'':"";o.innerHTML+="
    0?"var(--accent-bg,rgba(247,147,26,0.05))":l?"rgba(34,197,94,0.03)":"none")+';">
    '+(l?"🦌":i.charAt(0).toUpperCase()||"?")+'
    '+escapeHtml(i)+c+'
    '+(s?"You: ":"")+escapeHtml(r)+"
    "+(a>0?'
    '+a+"
    ":"")+"
    "})}}).catch(function(e){var t=document.getElementById("dmInboxList");t&&(t.innerHTML='
    💬
    No messages yet
    ')}))})};var _unreadCount=0,_unreadTimer=null;function checkUnreadCount(){if(auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db){var e=auth.currentUser.uid;db.collection("dm_conversations").where("participants","array-contains",e).get().then(function(t){var o=0;t.forEach(function(t){var n=t.data();o+=n["unread_"+e]||0}),_unreadCount=o,updateUnreadBadge()}).catch(function(){})}}function updateUnreadBadge(){document.querySelectorAll(".dm-unread-badge").forEach(function(e){_unreadCount>0?(e.textContent=_unreadCount>99?"99+":_unreadCount,e.style.display="inline-flex"):e.style.display="none"});var e=document.getElementById("bnavMsgBadge");e&&(_unreadCount>0?(e.textContent=_unreadCount,e.style.display="block"):e.style.display="none")}function startUnreadPolling(){checkUnreadCount(),_unreadTimer&&clearInterval(_unreadTimer),_unreadTimer=setInterval(checkUnreadCount,MSG_CONFIG.unreadPollInterval)}window.initMessaging=function(){startPresenceTracking(),restoreBlockedList(),setTimeout(startUnreadPolling,5e3)},void 0!==auth&&auth&&auth.currentUser&&initMessaging();const HIDDEN_BADGES=[{id:"nacho_friend",name:"Nacho's Friend",emoji:"🦌",pts:25,desc:"Interact with Nacho",hint:"Click on Nacho!",hidden:!1,check:function(){return"true"===localStorage.getItem("btc_nacho_clicked")}},{id:"genesis",name:"Genesis Reader",emoji:"📜",pts:75,desc:"Read the whitepaper channel",hint:"Open the Whitepaper channel",hidden:!1,check:function(){return"undefined"!=typeof currentChannelId&&"whitepaper"===currentChannelId}},{id:"nacho_curious",name:"Curious Deer",emoji:"❓",pts:50,desc:"Ask Nacho your first question",hint:"Ask Nacho anything!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=1}},{id:"ticket_bronze",name:"Ticket Fish",emoji:"🐟",pts:200,desc:"Earn 25 Orange Tickets",hint:"Spin daily + referrals!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=25},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,25)+"/25":"0/25"}},{id:"ticket_silver",name:"Ticket Shark",emoji:"🦈",pts:500,desc:"Earn 50 Orange Tickets",hint:"Keep spinning & referring!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=50},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,50)+"/50":"0/50"}},{id:"ticket_gold",name:"Ticket Whale",emoji:"🐋",pts:1e3,desc:"Earn 100 Orange Tickets",hint:"The ultimate ticket badge!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.orangeTickets||0)>=100},progress:function(){return void 0!==currentUser&¤tUser?Math.min(currentUser.orangeTickets||0,100)+"/100":"0/100"}},{id:"nacho_10q",name:"Inquisitive Buck",emoji:"🔍",pts:200,desc:"Ask Nacho 10 questions",hint:"Keep asking Nacho!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=10},progress:function(){return Math.min(parseInt(localStorage.getItem("btc_nacho_questions")||"0"),10)+"/10"}},{id:"collector",name:"Collector",emoji:"💎",pts:150,desc:"Save 10+ topics to favorites",hint:"Star your favorite topics",hidden:!1,check:function(){return safeJSON("btc_favs",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_favs",[]).length,10)+"/10"}},{id:"first_post",name:"Town Crier",emoji:"📣",pts:100,desc:"Make your first Pleb Talk post",hint:"Post in PlebTalk!",hidden:!1,check:function(){return parseInt(localStorage.getItem("btc_forum_post_count")||"0")>=1||void 0!==currentUser&¤tUser&¤tUser.forumPosts>=1}},{id:"first_reply",name:"Conversationalist",emoji:"💬",pts:75,desc:"Reply to a forum post",hint:"Join a discussion!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.forumReplies>=1}},{id:"market_seller",name:"Merchant",emoji:"🏪",pts:150,desc:"List an item on Lightning Mart",hint:"Sell something for sats on Lightning Mart!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketListings>=1}},{id:"market_buyer",name:"Shopper",emoji:"🛍️",pts:150,desc:"Contact a seller on the marketplace",hint:"Find something to buy!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&¤tUser.marketMessages>=1}},{id:"donor_100",name:"Giving Pleb",emoji:"🫷",pts:50,desc:"Donate 100 XP for charity",hint:"Donate 100 XP in the Charity tab!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=100},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,100)+"/100"}},{id:"donor_500",name:"Stack Sharer",emoji:"💛",pts:150,desc:"Donate 500 XP for charity",hint:"Keep donating!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=500},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,500)+"/500"}},{id:"donor_1000",name:"Community Builder",emoji:"🧡",pts:300,desc:"Donate 1,000 XP for charity",hint:"A true community builder!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e3)+"/1,000"}},{id:"donor_5000",name:"Archive Patron",emoji:"❤️",pts:1e3,desc:"Donate 5,000 XP for charity",hint:"An archive patron — legendary!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e3)+"/5,000"}},{id:"donor_10000",name:"Sats Saint",emoji:"🔥",pts:2e3,desc:"Donate 10,000 XP for charity",hint:"A sats saint among us!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e4)+"/10,000"}},{id:"donor_25000",name:"Lightning Philanthropist",emoji:"⚡",pts:4e3,desc:"Donate 25,000 XP for charity",hint:"A lightning philanthropist!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=25e3},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,25e3)+"/25,000"}},{id:"donor_50000",name:"Satoshi's Steward",emoji:"🏆",pts:7500,desc:"Donate 50,000 XP for charity",hint:"Satoshi's Steward — incredible!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=5e4},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,5e4)+"/50,000"}},{id:"donor_100000",name:"Legend of the Archive",emoji:"👑",pts:15e3,desc:"Donate 100,000 XP for charity",hint:"A true legend of the archive!",hidden:!1,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.pointsDonated||0)>=1e5},progress:function(){return Math.min(void 0!==currentUser&¤tUser&¤tUser.pointsDonated||0,1e5)+"/100,000"}},{id:"night_owl",name:"Night Owl",emoji:"🦉",pts:50,desc:"Visit the archive after midnight",hidden:!0,check:function(){return(new Date).getHours()>=0&&(new Date).getHours()<5}},{id:"speed_runner",name:"Speed Runner",emoji:"⚡",pts:100,desc:"Visit 15+ channels in one session",hidden:!0,check:function(){return void 0!==sessionChannels&&sessionChannels.size>=15}},{id:"scholar",name:"Bitcoin Scholar",emoji:"🎓",pts:300,desc:"Pass the Scholar Certification",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_scholar_passed")}},{id:"nacho_20q",name:"20 Questions",emoji:"🏅",pts:500,desc:"Ask Nacho 20 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=20}},{id:"explorer_10",name:"Curious Pleb",emoji:"🗺️",pts:100,desc:"Explore 10 topics",hint:"Keep exploring!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=10},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,10)+"/10"}},{id:"explorer_25",name:"Rabbit Holer",emoji:"🐇",pts:250,desc:"Explore 25 topics",hint:"Dive deeper!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=25},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,25)+"/25"}},{id:"explorer_50",name:"Half Stack",emoji:"📚",pts:500,desc:"Explore 50 topics",hint:"Halfway there!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=50},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,50)+"/50"}},{id:"explorer_100",name:"Century Club",emoji:"💯",pts:1e3,desc:"Explore 100 topics",hint:"Almost all of them!",hidden:!1,check:function(){return safeJSON("btc_visited_channels",[]).length>=100},progress:function(){return Math.min(safeJSON("btc_visited_channels",[]).length,100)+"/100"}},{id:"explorer_all",name:"Archive Master",emoji:"👑",pts:2e3,desc:"Explore every single topic",hint:"Visit them all!",hidden:!0,check:function(){return void 0!==CHANNELS&&safeJSON("btc_visited_channels",[]).length>=Object.keys(CHANNELS).length}},{id:"marathon",name:"Marathon Reader",emoji:"🏃",pts:150,desc:"Spent 30+ minutes reading in one session",hidden:!0,check:function(){return Date.now()-(window._sessionStart||Date.now())>18e5}},{id:"early_adopter",name:"Early Adopter",emoji:"🌅",pts:200,desc:"Browsing between 5am and 7am",hidden:!0,check:function(){var e=(new Date).getHours();return e>=5&&e<7}},{id:"weekend_warrior",name:"Weekend Warrior",emoji:"🎉",pts:75,desc:"Learning Bitcoin on a weekend",hidden:!0,check:function(){var e=(new Date).getDay();return 0===e||6===e}},{id:"triple_threat",name:"Triple Threat",emoji:"🎯",pts:300,desc:"Completed a quest, sent a chat message, and read a channel in one session",hidden:!0,check:function(){return"true"===sessionStorage.getItem("btc_quest_done")&&"true"===sessionStorage.getItem("btc_chat_sent")&&void 0!==sessionChannels&&sessionChannels.size>=1}},{id:"nacho_50q",name:"Nacho Sage",emoji:"🧙",pts:500,desc:"Ask Nacho 50 questions",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_nacho_questions")||"0")>=50}},{id:"bookmark_collector",name:"Bookmark Hoarder",emoji:"📚",pts:100,desc:"Bookmarked 20+ messages",hidden:!0,check:function(){return safeJSON("btc_bookmarks",[]).length>=20}},{id:"pvp_streak",name:"Undefeated",emoji:"🔱",pts:250,desc:"Won 5 PVP battles in a row",hidden:!0,check:function(){return parseInt(localStorage.getItem("btc_pvp_win_streak")||"0")>=5}},{id:"sats_maxed",name:"Faucet King",emoji:"👑",pts:1e3,desc:"Claimed all 10,000 sats from the faucet",hidden:!0,check:function(){return void 0!==currentUser&¤tUser&&(currentUser.satsWithdrawn||0)>=1e4}},{id:"streak_freeze",name:"Ice Shield",emoji:"🧊",pts:50,desc:"Used a streak freeze to save your streak",hidden:!0,check:function(){return"true"===localStorage.getItem("btc_freeze_used")}},{id:"nacho_closet_full",name:"Fashionista",emoji:"👗",pts:200,desc:"Unlocked all Nacho closet items from the spin wheel",hidden:!0,check:function(){return safeJSON("btc_spin_closet_items",[]).length>=10}}];function _syncPredictionToFirestore(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db)return;var t=auth.currentUser.uid;db.collection("users").doc(t).set({predictions:{lastPrediction:{direction:e.direction,price:e.price,time:e.time}}},{merge:!0}).catch(function(){}),db.collection("active_predictions").doc(t).set({uid:t,direction:e.direction,price:e.price,time:e.time,resolved:!1}).catch(function(){})}catch(e){}}function _updatePredictionStats(e){try{if(void 0===auth||!auth.currentUser||auth.currentUser.isAnonymous)return;if(void 0===db||"undefined"==typeof firebase)return;var t=auth.currentUser.uid,o=firebase.firestore.FieldValue.increment,n=parseInt(localStorage.getItem("btc_predict_streak")||"0"),i=parseInt(localStorage.getItem("btc_predict_best_streak")||"0"),a={"predictions.total":o(1),"predictions.lastResolved":Date.now()};if(e){a["predictions.correct"]=o(1);var r=n+1;a["predictions.streak"]=r,r>i&&(a["predictions.bestStreak"]=r,localStorage.setItem("btc_predict_best_streak",r.toString()))}else a["predictions.streak"]=0;db.collection("users").doc(t).set(a,{merge:!0}).catch(function(){});var s={total:o(1)};e&&(s.correct=o(1)),db.collection("stats").doc("predictions").set(s,{merge:!0}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.predictions||(currentUser.predictions={total:0,correct:0,streak:0,bestStreak:0}),currentUser.predictions.total=(currentUser.predictions.total||0)+1,e?(currentUser.predictions.correct=(currentUser.predictions.correct||0)+1,currentUser.predictions.streak=(currentUser.predictions.streak||0)+1,currentUser.predictions.streak>(currentUser.predictions.bestStreak||0)&&(currentUser.predictions.bestStreak=currentUser.predictions.streak)):currentUser.predictions.streak=0)}catch(e){}}!function(){const e=["🎓 Someone just passed the Bitcoin Basics Certification! Can you?","⚡ A pleb just completed a Lightning Network quest — 50 XP earned!","🗺️ Someone just finished all 10 steps of the Bitcoin Journey!","🎮 A Bitcoiner just aced a quiz in Nacho Mode — 10/10!","📚 A new user just explored their first 3 topics — features unlocking!","🧠 Someone just asked Nacho 100 questions — Bitcoin Scholar status!","🎯 A pleb just scored 5/5 on a Conversation Quest!","📖 Someone just read through the entire Timechain channel!","🔥 A Bitcoiner just hit a 30-day streak! Legendary dedication!","🔥 Someone just started a 7-day streak — can you beat them?","🏆 A pleb just crossed 5,000 XP! Climbing the leaderboard!","⭐ Someone just earned 200 XP in a single session!","🔥 A user just protected their streak with a Freeze Ticket! Smart move.","📈 Someone just jumped 10 spots on the Leaderboard!","🧡 A Bitcoiner just leveled up to Bitcoin Believer!","🏔 Someone just reached Maxi status — top of the mountain!","👑 A pleb just entered the Top 25 on the Leaderboard!","🌱 A brand new user just earned their first 50 XP! Welcome!","🎡 Someone just spun the daily wheel and won 5 Orange Tickets!","🎟️ A pleb just earned bonus tickets from a referral!","🧊 Someone won a Streak Freeze on the daily spin — lucky!","🎡 A Bitcoiner just won a closet item from the spin wheel!","💬 New discussion in PlebTalk: 'Best cold storage for beginners?'","💬 Someone just posted in PlebTalk — join the conversation!","🛒 New listing on LightningMart — check it out!","🤝 A meetup was just created in IRL Sync — find one near you!","💬 A PlebTalk post just got 5 upvotes!","⚡ Someone just tipped a forum post with Lightning!","🦌 Someone just entered Nacho Mode for a 30-minute deep dive!","🎽 A pleb just equipped Diamond Hooves in Nacho's Closet! 💎","🕶️ Someone just unlocked Cool Shades from the spin wheel!","👑 A Bitcoiner just equipped the Royal Crown — looking regal!","🦌 Nacho just helped someone understand seed phrases!","🗺️ Someone just explored their 50th channel — almost full coverage!","🦉 A Night Owl badge was just earned at 2 AM!","🎲 Someone just used Random Channel and discovered 'cypherpunks'!","🎨 A user just browsed the Art Gallery — 200+ Bitcoin artworks!","📡 A Bitcoiner just opted in to The Signal newsletter!","🎉 Over 100 users are learning Bitcoin here right now!","📊 The archive has been visited over 10,000 times this month!","🧡 146 channels of pure Bitcoin education — and growing!","⚡ Over 500 Nacho conversations happened this week!","🏆 The Leaderboard top 10 just shuffled — who's climbing?"];async function t(){const t=safeJSON("btc_visited_channels",[]).length,o=firebase.auth().currentUser&&!firebase.auth().currentUser.isAnonymous;if(t<3&&!o)return;const n=document.getElementById("activity-ticker"),i=document.getElementById("ticker-content");if(n&&i){var a=e.slice();try{var r=firebase.firestore();(await r.collection("forum_posts").orderBy("createdAt","desc").limit(3).get()).forEach(function(e){var t=e.data(),o=t.authorName||"A pleb";a.push("💬 "+o+' just posted in PlebTalk: "'+(t.title||"").substring(0,40)+'..."')});try{(await r.collection("marketplace").where("status","==","active").orderBy("createdAt","desc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🛒 New on LightningMart: "'+(t.title||"Item").substring(0,35)+'" for '+(t.priceSats||t.price||"???")+" sats!")})}catch(e){}try{var s=await r.collection("users").orderBy("points","desc").limit(10).get(),l=[];if(s.forEach(function(e){var t=e.data();t.username&&l.push(t.username)}),l.length>=3){a.push("👑 "+l[0]+" is holding #1 on the Leaderboard! Can you catch them?");var c=l[Math.floor(Math.random()*Math.min(5,l.length))];a.push("📈 "+c+" just climbed the Leaderboard — competition is heating up!")}}catch(e){}try{(await r.collection("irl_events").where("date",">=",(new Date).toISOString()).orderBy("date","asc").limit(2).get()).forEach(function(e){var t=e.data();a.push('🤝 Upcoming meetup: "'+(t.title||"Bitcoin Meetup").substring(0,35)+'" — RSVP in IRL Sync!')})}catch(e){}}catch(e){console.log("Ticker live data skipped:",e)}for(var d=a.length-1;d>0;d--){var u=Math.floor(Math.random()*(d+1)),p=a[d];a[d]=a[u],a[u]=p}n.style.display="flex";var h=0;m(),setInterval(m,12e3)}function m(){i.style.animation="none",i.offsetHeight,i.textContent=a[h],i.style.animation="tickerScroll 12s linear infinite",h=(h+1)%a.length}}const o=document.createElement("style");o.textContent="\n #ticker-content { \n white-space: nowrap !important;\n overflow: visible !important;\n text-overflow: clip !important;\n display: inline-block !important;\n width: auto !important;\n padding-right: 50px;\n }\n @keyframes tickerScroll {\n 0% { transform: translateX(100%); }\n 100% { transform: translateX(-100%); }\n }\n ",document.head.appendChild(o),window.rateChannel=async function(e,t){const o=document.getElementById("sentiment-"+e);if(o){o.innerHTML='
    Thank you! 🦌
    Nacho will use this to organize better content.
    ';try{const o=firebase.firestore();await o.collection("channel_feedback").add({channelId:e,rating:t,uid:firebase.auth().currentUser?firebase.auth().currentUser.uid:"anon",createdAt:firebase.firestore.FieldValue.serverTimestamp()}),"function"==typeof awardPoints&&awardPoints(5,"Feedback bonus")}catch(e){console.log("Feedback save skipped:",e)}}},window.checkNewsletterPrompt=function(){localStorage.getItem("btc_newsletter_prompt_shown")||safeJSON("btc_visited_channels",[]).length>=10&&(function(){const e=document.createElement("div");e.id="newsletterModal",e.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,0.85);z-index:10000;display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(5px);",e.innerHTML='
    📡

    Stay Orange-Pilled

    You\'ve explored 10+ channels! Stay connected with Bitcoin updates and community news.

    📱 Join Telegram Updates📧 Subscribe on Substack
    ',document.body.appendChild(e)}(),localStorage.setItem("btc_newsletter_prompt_shown","true"))},window.optInNewsletter=async function(){const e=document.getElementById("newsletterModal"),t=firebase.auth().currentUser;if(!t||t.isAnonymous)return showToast("Please sign in with email to join the newsletter!"),"function"==typeof showUsernamePrompt&&showUsernamePrompt(),void(e&&e.remove());try{const e=firebase.firestore();await e.collection("users").doc(t.uid).update({newsletterOptIn:!0,newsletterOptInDate:firebase.firestore.FieldValue.serverTimestamp()}),showToast("🎉 Welcome to the Orange Pill newsletter!")}catch(e){console.log("Newsletter opt-in failed:",e)}e&&e.remove()},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){t(),checkNewsletterPrompt()}):(t(),checkNewsletterPrompt())}(),window.showNachoStory=function(e){var t=[{title:"Chapter 1: The Genesis Block",text:"In the beginning, there was nothing but fiat. Nacho was just a young buck growing up in the White Mountains of New Hampshire — the Live Free or Die state. He spent his fawn days splashing in the Pemigewasset River, racing chipmunks through birch groves, and nibbling on leaves of debt from the forest of traditional finance. His mama always said the acorns were getting smaller every year, but nobody could explain why. One cold January day in 2009, a mysterious message appeared carved into a sugar maple: 'Chancellor on brink of second bailout for banks.' Nacho didn't understand it yet, but something had changed forever. A new kind of money had been born — one that no government could print, no bank could freeze, and no deer could counterfeit. It was called Bitcoin."},{title:"Chapter 2: The Pizza That Changed Everything",text:"Nacho heard a rumor from a blue jay passing through Franconia Notch: someone had traded 10,000 bitcoins for two pizzas. 'That's crazy!' he thought, nearly choking on a wild blueberry. But was it? Those pizzas proved Bitcoin had real value — people would actually exchange goods for it. Nacho realized this wasn't just internet magic beans. It was the beginning of price discovery. He thought about all the acorns he'd traded with the squirrels over the years — weren't those his first 'transactions' too? Every great journey starts with a single trade, and Bitcoin's started with pepperoni and cheese."},{title:"Chapter 3: Down the Rabbit Hole",text:"Nacho found a weathered copy of the whitepaper pinned to a bulletin board at a general store in Lincoln, New Hampshire. Only 9 pages, but each one hit different. Peer-to-peer. No trusted third party. Proof of work. 21 million cap. He read it by the light of a campfire near the Kancamagus Highway, the stars of the Granite State blazing overhead. The deeper he went, the more he understood: Bitcoin wasn't just new money. It was a paradigm shift. Sound money that couldn't be debased. A monetary network with no CEO, no headquarters, no off switch. Nacho's antlers tingled — literally. His first set was coming in. He was growing up, and he was becoming a Bitcoiner."},{title:"Chapter 4: HODL Through the Storm",text:"A nor'easter hit New Hampshire that winter, and the price of Bitcoin crashed right along with the temperature. Then crashed again. Nacho watched his sats lose 80% of their dollar value from a snow-covered ridge overlooking the Presidential Range. His forest friends laughed. 'Told you it was a scam!' chirped a skeptical chickadee. But Nacho had done his homework. He understood the halving cycles. He knew that every 210,000 blocks, the new supply gets cut in half. Scarcity + time = value. So Nacho did what legends do: he stood firm in the blizzard and held. Not because he was reckless, but because he understood what he held. The storms always pass. The mountains remain."},{title:"Chapter 5: Not Your Keys, Not Your Cheese",text:"One crisp autumn morning, as the New Hampshire maples blazed orange and gold, Nacho woke up to terrible news. An exchange had been hacked. Billions gone. Friends who kept their bitcoin on the exchange lost everything. A young doe from Vermont had her entire savings wiped out. Nacho felt sick — but also relieved. He'd moved his sats to a hardware wallet weeks ago, buried it in a waterproof case near his favorite granite boulder in the White Mountains. Cold storage. Air-gapped. His keys, his bitcoin. From that day forward, Nacho's motto was clear: 'Not your keys, not your cheese.' 🧀🔑 He even carved it into a birch tree so no deer would forget."},{title:"Chapter 6: The Halving",text:"Every four years, something magical happens — and Nacho had the perfect view from Mount Washington's summit. The block reward — the number of new bitcoins created with each block — gets cut in half. He watched the countdown with a group of bitcoiners who'd hiked up for the occasion, huddled together at 6,288 feet with thermoses of coffee and Lightning-powered phones. From 6.25 BTC to 3.125 BTC per block. Less new supply entering the market. Same or growing demand. The wind howled, but nobody cared. It's not magic; it's math. And it's the most predictable monetary policy in the history of money. Nacho shed a single tear — which immediately froze to his fur."},{title:"Chapter 7: Nacho's Mission",text:"Nacho looked out from his favorite overlook in the White Mountains — the same spot where he'd first read the whitepaper by campfire light. He'd grown from a gangly fawn into a strong buck with a magnificent rack of antlers (seven points, if you're counting). But so many deer — so many people — still didn't understand Bitcoin. They heard 'crypto' and thought of scams, memecoins, and celebrity tokens. But Bitcoin is different. It's the signal in the noise. So Nacho decided to dedicate his life to education, right here from the Live Free or Die state. Not shilling. Not pumping. Teaching. Because the best way to orange-pill someone isn't to tell them to buy — it's to help them understand WHY. And that's why you're here. Welcome to the Archive. 🦌🟠"}],o=(new Date).toISOString().split("T")[0],n=safeJSON("btc_nacho_story_days",[]);(0===n.length||-1===n.indexOf(o))&&(n.push(o),localStorage.setItem("btc_nacho_story_days",JSON.stringify(n)));var i,a=Math.min(n.length,t.length);if(void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryProgress:a,nachoStoryDate:o,nachoStoryDays:n}).catch(function(){})}catch(e){}localStorage.setItem("btc_nacho_story_highest",a.toString()),localStorage.setItem("btc_nacho_story_date",o),"number"==typeof e?(i=Math.min(e,a-1))<0&&(i=0):(i=a-1)<0&&(i=0);var r=t[i],s=document.createElement("div");s.id="nachoStoryOverlay",s.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",s.onclick=function(e){e.target===s&&s.remove()};for(var l='
    ',c=0;c'+(c+1)+"":''}l+="
    ";var u,p=i>0?"':"";u=i+1Next →':i>=t.length-1?'✅ Story Complete!':'🔒 Come back tomorrow!';var h=document.createElement("div");h.style.cssText="background:#1a1a2e;border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:500px;width:100%;margin:40px auto;color:#e2e8f0;font-family:inherit;",h.innerHTML='
    🦌📖
    '+l+'

    '+r.title+'

    '+r.text+'

    📖 Chapter '+(i+1)+" of "+t.length+" · "+a+" unlocked ("+(t.length-a)+' remaining)
    '+p+u+'
    ',s.appendChild(h),document.body.appendChild(s);var m=safeJSON("btc_nacho_story_awarded",[]);if("function"==typeof awardPoints&&-1===m.indexOf(i)){m.push(i),localStorage.setItem("btc_nacho_story_awarded",JSON.stringify(m));var g=i===t.length-1?50:15;awardPoints(g,"📖 Completed Chapter "+(i+1)),"function"==typeof showToast&&showToast("📖 +"+g+" XP — Chapter "+(i+1)+" complete!"),m.length===t.length&&setTimeout(function(){if(awardPoints(100,"📖🎉 Completed Nacho's Story!"),"function"==typeof awardOrangeTickets)awardOrangeTickets(25,"📖 Nacho's Story Complete!");else{var e=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(e+25).toString())}"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound();var t=document.createElement("div");if(t.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",t.onclick=function(){t.style.opacity="0",t.style.transition="opacity 0.4s",setTimeout(function(){t.remove()},400)},t.innerHTML='
    🦌📖🎉
    STORY COMPLETE!
    You\'ve followed Nacho\'s entire Bitcoin journey from the Genesis Block to his mission of education. You\'re officially a Story Master! 🏆
    +100
    BONUS PTS
    +25
    🎟️ TICKETS
    ',document.body.appendChild(t),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous)try{db.collection("users").doc(auth.currentUser.uid).update({nachoStoryComplete:!0,nachoStoryCompletedAt:(new Date).toISOString()}).catch(function(){})}catch(e){}},800)}},window.showPricePrediction=function(){var e=parseFloat(localStorage.getItem("btc_last_price"))||0;if(!e&&"undefined"!=typeof _lastWsPrice&&_lastWsPrice&&(e=_lastWsPrice,localStorage.setItem("btc_last_price",e.toString())),!e&&"undefined"!=typeof _dashData&&_dashData&&_dashData.price&&(e=_dashData.price,localStorage.setItem("btc_last_price",e.toString())),!e)return"function"==typeof showToast&&showToast("⏳ Fetching price..."),void fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").then(function(e){return e.json()}).then(function(e){e&&e.bitcoin&&e.bitcoin.usd?(localStorage.setItem("btc_last_price",e.bitcoin.usd.toString()),showPricePrediction()):"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")}).catch(function(){"function"==typeof showToast&&showToast("⚠️ Could not load price. Try opening the dashboard first.")});var t=document.createElement("div");t.style.cssText="position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.95);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&t.remove()};var o=safeJSON("btc_price_prediction",null),n=document.createElement("div");if(n.style.cssText="background:var(--card-bg,#1a1a2e);border:1px solid #f7931a;border-radius:16px;padding:28px;max-width:420px;width:100%;color:var(--text,#e2e8f0);font-family:inherit;text-align:center;",o&&Date.now()-o.time<864e5){var i=Date.now()-o.time;if(!(i>=864e5)){var a=Math.ceil((864e5-i)/36e5);return n.innerHTML='

    Prediction Locked In!

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+'

    ⏳ Results in ~'+a+" hour"+(1!==a?"s":"")+'
    Come back after 24 hours to see if you were right!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},500),t.appendChild(n),void document.body.appendChild(t)}var r=e-o.price,s=(r/o.price*100).toFixed(2),l="up"===o.direction&&r>0||"down"===o.direction&&r<0;o._notified||("function"==typeof notifyPredictionResult&¬ifyPredictionResult(l,o.direction),o._notified=!0,localStorage.setItem("btc_price_prediction",JSON.stringify(o)));var c=parseInt(localStorage.getItem("btc_predict_streak")||"0");n.innerHTML=''+(l?"🎉":"😅")+'

    Your Prediction

    You predicted '+("up"===o.direction?"📈 UP":"📉 DOWN")+"

    Price when predicted: $"+Math.round(o.price).toLocaleString()+"

    Current price: $"+Math.round(e).toLocaleString()+" ("+(r>=0?"+":"")+s+'%)

    '+(l?"✅ You were RIGHT! +25 XP":"❌ Not this time!")+"

    "+(l&&c>=2?'

    🔥 '+c+" correct in a row!

    ":"")+'
    Come back tomorrow for a new prediction!
    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStatsResult");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 No community data yet."})},100)}else n.innerHTML='📈📉

    Predict Bitcoin\'s Price

    Current BTC Price:

    $'+Math.round(e).toLocaleString()+'

    Will Bitcoin go UP or DOWN in the next 24 hours?

    Loading community stats...
    ',setTimeout(function(){"function"==typeof getGlobalPredictionStats&&getGlobalPredictionStats(function(e){var t=document.getElementById("globalPredStats");if(t)if(e&&e.total){var o=Math.round(e.correct/e.total*100);t.innerHTML="🌍 Community: "+(e.correct||0)+"/"+e.total+" correct ("+o+"% accuracy)"}else t.innerHTML="🌍 Be the first to predict!"})},100);t.appendChild(n),document.body.appendChild(t)},window._savePrediction=function(e){var t={direction:e,price:parseFloat(localStorage.getItem("btc_last_price"))||0,time:Date.now(),resolved:!1};localStorage.setItem("btc_price_prediction",JSON.stringify(t)),"function"==typeof showToast&&showToast("🎯 Prediction saved! Check back tomorrow to see if you were right."),"function"==typeof awardPoints&&awardPoints(5,"📈 Price prediction made"),_syncPredictionToFirestore(t)},window.checkPredictionResult=function(){var e=safeJSON("btc_price_prediction",null);if(e&&!e.resolved&&!(Date.now()-e.time<864e5)){var t=parseFloat(localStorage.getItem("btc_last_price"))||0;if(t&&e.price){var o=t-e.price,n=(o/e.price*100).toFixed(2),i="up"===e.direction&&o>0||"down"===e.direction&&o<0;e.resolved=!0,e.result=i?"correct":"wrong",e.finalPrice=t,localStorage.setItem("btc_price_prediction",JSON.stringify(e)),_updatePredictionStats(i);try{void 0!==auth&&auth.currentUser&&void 0!==db&&db.collection("active_predictions").doc(auth.currentUser.uid).delete().catch(function(){})}catch(e){}if(i){"function"==typeof awardPoints&&awardPoints(25,"🎯 Correct price prediction!");var a=parseInt(localStorage.getItem("btc_predict_streak")||"0")+1;localStorage.setItem("btc_predict_streak",a.toString()),setTimeout(function(){"function"==typeof showToast&&showToast("🎉 Your prediction was RIGHT! Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"% — +25 XP!"+(a>=3?" 🔥 "+a+" correct in a row!":""))},2e3)}else localStorage.setItem("btc_predict_streak","0"),setTimeout(function(){"function"==typeof showToast&&showToast("📉 Your prediction was wrong — Bitcoin went "+(o>0?"UP":"DOWN")+" "+(o>0?"+":"")+n+"%. Try again tomorrow!")},2e3)}}};var _globalPredCache=null,_globalPredCacheTs=0;window.getGlobalPredictionStats=function(e){if(_globalPredCache&&Date.now()-_globalPredCacheTs<12e4)e(_globalPredCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{db.collection("stats").doc("predictions").get().then(function(t){t.exists?(_globalPredCache=t.data(),_globalPredCacheTs=Date.now(),e(_globalPredCache)):e(null)}).catch(function(){e(null)})}catch(t){e(null)}else e(null)},window.getPredictionStats=function(e){var t=e&&e.predictions?e.predictions:null;if(!t||!t.total)return null;var o=t.total>0?Math.round(t.correct/t.total*100):0;return{total:t.total||0,correct:t.correct||0,percentage:o,streak:t.streak||0,bestStreak:t.bestStreak||0}};var _communityStatsCache=null,_communityStatsCacheTs=0,_communityStatsUnsub=null;function _renderCommunityStats(e,t,o){var n=[];o.channelVisits&&n.push("📖 "+_fmtNum(o.channelVisits)+" channel reads"),o.questsCompleted&&n.push("⚡ "+_fmtNum(o.questsCompleted)+" quests completed"),o.chatMessages&&n.push("💬 "+_fmtNum(o.chatMessages)+" chat messages"),o.spins&&n.push("🎡 "+_fmtNum(o.spins)+" daily spins"),o.pvpMatches&&n.push("⚔️ "+_fmtNum(o.pvpMatches)+" PVP battles");var i=document.getElementById("visitCount");if(i&&"—"!==i.textContent&&n.push("👥 "+i.textContent+" total visits"),o.userCount&&n.push("🧑‍🤝‍🧑 "+_fmtNum(o.userCount)+" registered users"),o.watchTimeMinutes){var a=Math.floor(o.watchTimeMinutes/60);n.push("📺 "+(a>0?_fmtNum(a)+" hours":o.watchTimeMinutes+" min")+" Timechain TV watched")}if(0!==n.length){e.innerHTML=n.join("  ·  ");var r=function(e,t){var o=document.getElementById(e);o&&t&&(o.textContent=t.toLocaleString())};if(r("csChannelReads",o.channelVisits),r("csQuests",o.questsCompleted),r("csChatMsgs",o.chatMessages),r("csSpins",o.spins),r("csPvp",o.pvpMatches),r("csUsers",o.userCount),o.watchTimeMinutes){var s=Math.floor(o.watchTimeMinutes/60);r("csWatchTime",s>0?s:o.watchTimeMinutes)}}else e.innerHTML="No stats yet"}function _fmtNum(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function renderExplorationMap(){var e=document.getElementById("explorationMap");if(e&&void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]);void 0!==currentUser&¤tUser&¤tUser.readChannels&¤tUser.readChannels.length>t.length&&(t=currentUser.readChannels);var o=Object.keys(CHANNELS),n=o.length,i=t.length,a=Math.round(i/n*100),r="";o.forEach(function(e){var o=-1!==t.indexOf(e),n=CHANNELS[e].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}|\u{2700}-\u{27BF}|\u{FE00}-\u{FEFF}|\u{1F900}-\u{1F9FF}|\u{1FA00}-\u{1FA6F}|\u{1FA70}-\u{1FAFF}|\u{200D}|\u{FE0F}]+)/u),i=n?n[1]:"📄";r+="
    '+(o?i:"?")+"
    "});var s="true"===localStorage.getItem("btc_explore_map_open");e.innerHTML="
    "+(s?"▾":"▸")+'🗺️ Exploration Map
    '+i+"/"+n+" ("+a+'%)
    '+r+"
    "}}window.loadCommunityStats=function(){var e=document.getElementById("communityStatsInner");if(e){var t=e.parentElement;if(_communityStatsUnsub&&_communityStatsCache)_renderCommunityStats(e,t,_communityStatsCache);else if(void 0!==db&&"undefined"!=typeof firebase)try{_communityStatsUnsub=db.collection("stats").doc("global").onSnapshot(function(e){var t=e.exists?e.data():{};_communityStatsCache=t,_communityStatsCacheTs=Date.now();var o=document.getElementById("communityStatsInner");o&&_renderCommunityStats(o,o.parentElement,t)})}catch(e){}}},setTimeout(function(){"function"==typeof loadCommunityStats&&loadCommunityStats()},5e3),window.updatePredictionLabel=function(){var e=document.getElementById("predAccuracyLabel");return!!e&&void 0!==db&&"undefined"!=typeof firebase&&"function"==typeof getGlobalPredictionStats&&(getGlobalPredictionStats(function(t){var o=[];if(t&&t.total){var n=Math.round(t.correct/t.total*100);o.push("🌍 "+n+"% community accuracy")}if(void 0!==currentUser&¤tUser&¤tUser.predictions&¤tUser.predictions.total){var i=Math.round(currentUser.predictions.correct/currentUser.predictions.total*100);o.push("👤 "+i+"% you")}e.innerHTML=o.join("
    ")}),!0)},function(){var e=0,t=setInterval(function(){e++,(window.updatePredictionLabel&&window.updatePredictionLabel()||e>60)&&clearInterval(t)},1e3)}(),function e(){if("function"==typeof window.goHome){if(!window.goHome.__predHooked){var t=window.goHome;window.goHome=function(){var e=t.apply(this,arguments);return setTimeout(function(){window.updatePredictionLabel&&window.updatePredictionLabel()},400),e},window.goHome.__predHooked=!0}}else var o=setInterval(function(){"function"==typeof window.goHome&&(clearInterval(o),e())},500)}(),window.renderExplorationMap=renderExplorationMap;var BITCOIN_QUOTES=[{text:"If you don't believe it or don't get it, I don't have the time to try to convince you, sorry.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"The root problem with conventional currency is all the trust that's required to make it work.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"It might make sense just to get some in case it catches on.",author:"Satoshi Nakamoto",channel:"satoshi-nakamoto"},{text:"Running bitcoin.",author:"Hal Finney",channel:"history"},{text:"Bitcoin is a remarkable cryptographic achievement and the ability to create something that is not duplicable in the digital world has enormous value.",author:"Eric Schmidt",channel:"dominant"},{text:"Bitcoin is a technological tour de force.",author:"Bill Gates",channel:"one-stop-shop"},{text:"I think the internet is going to be one of the major forces for reducing the role of government. The one thing that's missing, but that will soon be developed, is a reliable e-cash.",author:"Milton Friedman (1999)",channel:"videos"},{text:"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.",author:"Bitcoin Genesis Block",channel:"history"},{text:"Not your keys, not your coins.",author:"Bitcoin Proverb",channel:"self-custody"},{text:"Stay humble, stack sats.",author:"Bitcoin Community",channel:"investment-strategy"},{text:"In the long run, hard money is superior to soft money.",author:"Gigi, 21 Lessons",channel:"articles-threads"},{text:"Bitcoin is the first truly digital solution to the problem of money.",author:"Saifedean Ammous",channel:"books"},{text:"Fix the money, fix the world.",author:"Bitcoin Mantra",channel:"problems-of-money"},{text:"The supply of Bitcoin is limited. Period. No central bank is going to come along and print more.",author:"Andreas Antonopoulos",channel:"scarce"},{text:"Everyone is a scammer until proven otherwise. Don't trust, verify.",author:"Bitcoin Culture",channel:"secure"},{text:"Bitcoin makes money great again. It lets you transact freely, save freely, and live freely.",author:"Michael Saylor",channel:"giga-chad"},{text:"There is no second best.",author:"Michael Saylor",channel:"maximalism"},{text:"I don't think there's anything more important in my lifetime to work on.",author:"Jack Dorsey",channel:"giga-chad"},{text:"Bitcoin is the most important invention in the history of the world since the internet.",author:"Roger Ver (before he fell off)",channel:"history"},{text:"The computer can be used as a tool to liberate and protect people, rather than to control them.",author:"Hal Finney",channel:"cryptography"},{text:"One of the greatest things that Satoshi did was disappear.",author:"Gigi, 21 Lessons",channel:"satoshi-nakamoto"},{text:"Bitcoin has no CEO, no marketing department, no headquarters. It has math.",author:"Bitcoin Education Archive",channel:"decentralized"},{text:"We are all Satoshi.",author:"Bitcoin Community",channel:"satoshi-nakamoto"},{text:"Cypherpunks write code.",author:"Eric Hughes",channel:"cryptography"},{text:"Privacy is necessary for an open society in the electronic age.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Money is a tool for trading human time.",author:"Robert Breedlove",channel:"articles-threads"},{text:"Bitcoin is Time.",author:"Gigi",channel:"time"},{text:"The root cause of the housing crisis, student debt crisis, and healthcare crisis is the money crisis.",author:"Saifedean Ammous",channel:"problems-of-money"},{text:"Tick tock, next block.",author:"Bitcoin Community",channel:"blockchain-timechain"},{text:"The difficulty adjustment is the most elegant feature of Bitcoin.",author:"Bitcoin Educators",channel:"difficulty-adjustment"},{text:"Every informed person needs to know about Bitcoin because it might be one of the world's most important developments.",author:"Leon Luow",channel:"one-stop-shop"},{text:"Bitcoin is the only commodity in the world that the more demand there is, the more supply does NOT increase.",author:"Parker Lewis",channel:"scarce"},{text:"Gradually, then suddenly.",author:"Parker Lewis / Ernest Hemingway",channel:"articles-threads"},{text:"You can't stop an idea whose time has come.",author:"Victor Hugo (on Bitcoin)",channel:"organic"},{text:"Bitcoin is a hedge against the entire system.",author:"Lyn Alden",channel:"investment-strategy"},{text:"The question isn't what Bitcoin's price will be. The question is what the dollar's price will be.",author:"Bitcoiners",channel:"problems-of-money"},{text:"I was once told that nobody ever lost money saving in Bitcoin for 4+ years. I checked. It's true.",author:"Anonymous Bitcoiner",channel:"investment-strategy"},{text:"Bitcoin is the exit.",author:"Bitcoin Maximalists",channel:"maximalism"},{text:"Don't trust, verify.",author:"Bitcoin Ethos",channel:"nodes"},{text:"Number go up technology.",author:"Bitcoin Twitter",channel:"fun-facts"},{text:"Energy is the universal currency. Bitcoin makes that literal.",author:"Bitcoin Mining Community",channel:"energy"},{text:"Bitcoin is not an investment — it is a savings technology.",author:"Bitcoin Educators",channel:"money"},{text:"Fiat currency always returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Give me control of a nation's money supply, and I care not who makes its laws.",author:"Mayer Amschel Rothschild",channel:"problems-of-money"},{text:"Inflation is taxation without legislation.",author:"Milton Friedman",channel:"problems-of-money"},{text:"Bitcoin is for enemies. That's the whole point.",author:"Bitcoin Community",channel:"game_theory"},{text:"When you understand Bitcoin, you understand everything else differently.",author:"Many Bitcoiners",channel:"philosophy"},{text:"Bitcoin doesn't care about your feelings.",author:"Bitcoin Proverb",channel:"fun-facts"},{text:"Stack sats and stay humble.",author:"Matt Odell",channel:"investment-strategy"},{text:"Number go up because money printer go brr.",author:"Bitcoin Memes",channel:"memes-funny"},{text:"Those who would give up essential liberty, to purchase a little temporary safety, deserve neither liberty nor safety.",author:"Benjamin Franklin",channel:"human_rights__social_justice_and_freedo"},{text:"Freedom is never more than one generation away from extinction.",author:"Ronald Reagan",channel:"human_rights__social_justice_and_freedo"},{text:"The only way to deal with an unfree world is to become so absolutely free that your very existence is an act of rebellion.",author:"Albert Camus",channel:"philosophy"},{text:"If the American people ever allow private banks to control the issue of their currency, first by inflation, then by deflation, the banks and corporations that will grow up around them will deprive the people of all property.",author:"Thomas Jefferson",channel:"problems-of-money"},{text:"It is well enough that people of the nation do not understand our banking and monetary system, for if they did, I believe there would be a revolution before tomorrow morning.",author:"Henry Ford",channel:"problems-of-money"},{text:"The most dangerous man to any government is the man who is able to think things out for himself.",author:"H.L. Mencken",channel:"philosophy"},{text:"In a time of deceit, telling the truth is a revolutionary act.",author:"George Orwell",channel:"philosophy"},{text:"The urge to save humanity is almost always a false front for the urge to rule it.",author:"H.L. Mencken",channel:"philosophy"},{text:"A society that puts equality before freedom will get neither. A society that puts freedom before equality will get a high degree of both.",author:"Milton Friedman",channel:"philosophy"},{text:"The state is that great fiction by which everyone tries to live at the expense of everyone else.",author:"Frédéric Bastiat",channel:"austrian_school_of_economics"},{text:"There is no means of avoiding the final collapse of a boom brought about by credit expansion.",author:"Ludwig von Mises",channel:"austrian_school_of_economics"},{text:"The first panacea for a mismanaged nation is inflation of the currency; the second is war. Both bring a temporary prosperity; both bring a permanent ruin.",author:"Ernest Hemingway",channel:"problems-of-money"},{text:"Gold is money. Everything else is credit.",author:"J.P. Morgan",channel:"money"},{text:"We don't have a trillion-dollar debt because we haven't taxed enough; we have a trillion-dollar debt because we spend too much.",author:"Ronald Reagan",channel:"problems-of-money"},{text:"Government is the only institution that can take a valuable commodity like paper, and make it worthless by applying ink.",author:"Ludwig von Mises",channel:"problems-of-money"},{text:"Whenever destroyers appear among men, they start by destroying money.",author:"Ayn Rand",channel:"problems-of-money"},{text:"The way to crush the bourgeoisie is to grind them between the millstones of taxation and inflation.",author:"Vladimir Lenin",channel:"problems-of-money"},{text:"Savings represent goods produced but not yet consumed. That's what real wealth is — not digits in a bank database.",author:"Saifedean Ammous",channel:"money"},{text:"Civilization is in a race between education and catastrophe. Let us learn the truth and spread it as far and wide as our circumstances allow.",author:"H.G. Wells",channel:"one-stop-shop"},{text:"Paper money eventually returns to its intrinsic value — zero.",author:"Voltaire",channel:"problems-of-money"},{text:"Bitcoin is the separation of money and state.",author:"Bitcoin Community",channel:"maximalism"},{text:"Bitcoin is the first money in the history of the world where the supply is entirely unaffected by an increase in demand.",author:"Jeff Booth",channel:"scarce"},{text:"In a world where everything is printed, scarcity is the ultimate feature.",author:"Bitcoin Educators",channel:"scarce"},{text:"Bitcoin is hope for humanity.",author:"Jack Mallers",channel:"one-stop-shop"},{text:"The cost of Bitcoin is measured in electricity. The cost of fiat is measured in human freedom.",author:"Bitcoin Community",channel:"energy"},{text:"Your savings should not be someone else's liability.",author:"Bitcoin Educators",channel:"self-custody"},{text:"Bitcoin is the peaceful protest that cannot be silenced.",author:"Alex Gladstein",channel:"human_rights__social_justice_and_freedo"},{text:"Bitcoin gives us the ability to opt out of a system that was designed to extract value from us.",author:"Many Bitcoiners",channel:"problems-of-money"},{text:"Proof of work means proof of energy. Energy is the one thing that cannot be faked.",author:"Bitcoin Mining Community",channel:"mining"},{text:"The Bitcoin network processes more value per year than Visa. Without a CEO.",author:"Bitcoin Stats",channel:"decentralized"},{text:"If Bitcoin is a bubble, it's the only bubble that reflated itself five times in a row.",author:"Bitcoin Community",channel:"fun-facts"},{text:"Bitcoin has died 474 times according to the media. It's still here.",author:"Bitcoin Obituaries",channel:"misconceptions-fud"},{text:"Your grandchildren will ask you why you didn't buy Bitcoin when it was under six figures.",author:"Bitcoin Twitter",channel:"predictions"},{text:"The next 4 years are going to be very exciting for Bitcoin.",author:"Every Bitcoiner, Every Year",channel:"fun-facts"},{text:"Bitcoin isn't getting more expensive. Your dollars are getting cheaper.",author:"Bitcoin Community",channel:"problems-of-money"},{text:"If you can't hold it, you don't own it. If you didn't earn it, you'll lose it.",author:"Bitcoin Wisdom",channel:"self-custody"},{text:"Think in sats, not dollars.",author:"Bitcoin Community",channel:"sats__or__bits"},{text:"The best time to buy Bitcoin was 10 years ago. The second best time is now.",author:"Bitcoin Proverb",channel:"investment-strategy"},{text:"Work is the transfer of energy over time. Money should measure exactly that.",author:"Jason Lowery",channel:"energy"},{text:"Bitcoin is not anti-government. Bitcoin is anti-fraud.",author:"Bitcoin Educators",channel:"regulation"},{text:"We must defend our own privacy if we expect to have any.",author:"Eric Hughes, A Cypherpunk's Manifesto",channel:"privacy-nonkyc"},{text:"Cryptography is the ultimate form of non-violent direct action.",author:"Julian Assange",channel:"cryptography"},{text:"Strong cryptography can resist an unlimited application of violence.",author:"Jacob Appelbaum",channel:"cryptography"},{text:"The Net interprets censorship as damage and routes around it.",author:"John Gilmore",channel:"privacy-nonkyc"},{text:"Bitcoin is a weapon of peace.",author:"Jason Lowery, Softwar",channel:"geopolitics___macroeconomics"},{text:"Running a node means nobody can change the rules on you.",author:"Bitcoin Node Runners",channel:"nodes"},{text:"Hashrate is the heartbeat of Bitcoin. As long as miners mine, Bitcoin lives.",author:"Bitcoin Mining Community",channel:"mining"},{text:"Lightning is what makes Bitcoin usable for 8 billion people.",author:"Lightning Network Community",channel:"layer-2-lightning"},{text:"2,099,999,997,690,000 satoshis. That's all there will ever be.",author:"The Bitcoin Protocol",channel:"scarce"},{text:"Code is speech. Math is law. Cryptography is defense.",author:"Cypherpunks",channel:"cryptography"},{text:"I predict the Internet will go spectacularly supernova and in 1996 catastrophically collapse.",author:"Robert Metcalfe (1995) — They said this about Bitcoin too",channel:"misconceptions-fud"},{text:"Every generation needs a new revolution.",author:"Thomas Jefferson",channel:"philosophy"},{text:"First they ignore you, then they laugh at you, then they fight you, then you win.",author:"Often attributed to Gandhi",channel:"organic"},{text:"I do not think there is any other quality so essential to success of any kind as the quality of perseverance.",author:"John D. Rockefeller",channel:"philosophy"},{text:"The world is a dangerous place, not because of those who do evil, but because of those who look on and do nothing.",author:"Albert Einstein",channel:"philosophy"},{text:"Hard times create strong men. Strong men create good times. Good times create weak men. Weak men create hard times.",author:"G. Michael Hopf",channel:"time_preference"},{text:"An investment in knowledge pays the best interest.",author:"Benjamin Franklin",channel:"one-stop-shop"}];window.renderDailyQuote=function(){var e=document.getElementById("quoteOfDay");if(e){var t=new Date,o=Math.floor((t-new Date(t.getFullYear(),0,0))/864e5),n=BITCOIN_QUOTES[o%BITCOIN_QUOTES.length];n&&(e.innerHTML="
    💬 Quote of the Day
    "'+n.text+'"
    — '+n.author+"
    ")}},window.renderReadNext=function(e){if(void 0===CHANNELS)return"";var t=CHANNELS[e];if(!t)return"";var o=Object.entries(CHANNELS).filter(function(o){return o[1].cat===t.cat&&o[0]!==e});if(0===o.length)return"";var n=o.sort(function(){return Math.random()-.5}).slice(0,3),i='
    📖 Read Next
    ';return n.forEach(function(e){var t=e[1].title.match(/^([\u{1F000}-\u{1FFFF}|\u{2600}-\u{26FF}]+)/u),o=t?t[1]:"📄";i+=""}),i+="
    "},window.getNachoStoryProgress=function(){return parseInt(localStorage.getItem("btc_nacho_story_highest")||"0")},window.checkHiddenBadges=function(){if(void 0!==HIDDEN_BADGES&&window._hiddenBadgesReady){var e=safeJSON("btc_hidden_badges",[]),t=!1;HIDDEN_BADGES.forEach(function(o){if(-1===e.indexOf(o.id))try{if(o.check&&o.check()&&(e.push(o.id),t=!0,"function"==typeof showToast&&showToast(o.emoji+" Secret Badge: "+(o.revealName||o.name)+"! +"+o.pts+" XP"),"function"==typeof awardPoints&&awardPoints(o.pts,"Hidden Badge: "+(o.revealName||o.name)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:e})}catch(e){}}catch(e){}}),t&&localStorage.setItem("btc_hidden_badges",JSON.stringify(e))}},setInterval(function(){"function"==typeof checkHiddenBadges&&checkHiddenBadges()},3e4),setTimeout(function(){window._hiddenBadgesReady||(window._hiddenBadgesReady=!0)},2e4),window.awardHiddenBadge=function(e,t){var o=safeJSON("btc_hidden_badges",[]);if(-1===o.indexOf(e)&&(o.push(e),localStorage.setItem("btc_hidden_badges",JSON.stringify(o)),t&&"function"==typeof showToast&&showToast("🏅 "+t),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous))try{db.collection("users").doc(auth.currentUser.uid).update({hiddenBadges:o})}catch(e){}},window.awardOrangeTickets=function(e,t){void 0!==currentUser&¤tUser&&(currentUser.orangeTickets=(currentUser.orangeTickets||0)+e,currentUser._isLocal||"function"!=typeof awardPoints||awardPoints(0,"🎟️ "+(t||"Orange Tickets"),null,e));var o=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(o+e).toString()),"function"==typeof showToast&&showToast("🎟️ +"+e+" Orange Ticket"+(e>1?"s":"")+(t?" — "+t:""))},window.setFloatingElementsVisible=function(e){["floatingRandomBtn","lbFloatBtn","mobileSearchBtn","backToTop","scrollToBottom","chatOverlayBtn","aiToolsBtn","dashboardFloatBtn"].forEach(function(t){var o=document.getElementById(t);o&&(o.style.display=e?"":"none")})},window.showCelebration=function(e){var t=e.emoji||"🎉",o=e.title||"Achievement Unlocked!",n=e.message||"",i=e.rewards||[],a=e.btnText||"Amazing! 🎉",r=document.createElement("div");r.style.cssText="position:fixed;inset:0;z-index:100020;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;animation:fadeSlideIn 0.5s ease-out;",r.onclick=function(e){e.target===r&&(r.style.opacity="0",r.style.transition="opacity 0.4s",setTimeout(function(){r.remove()},400))};var s="";i.length>0&&(s='
    ',i.forEach(function(e){s+='
    +'+e.label+'
    '+e.sub+"
    "}),s+="
    "),r.innerHTML='
    '+t+'
    '+o+'
    '+n+"
    "+s+'
    ",document.body.appendChild(r),"function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound(),setTimeout(function(){"function"==typeof launchConfetti&&launchConfetti()},1200)},setInterval(function(){["prop","tech"].forEach(function(e){var t="btc_scholar_"+e+"_passed",o="btc_scholar_"+e+"_celebrated";if("true"===localStorage.getItem(t)&&"true"!==localStorage.getItem(o)){localStorage.setItem(o,"true");var n="tech"===e;setTimeout(function(){showCelebration({emoji:n?"🛠️🎓🏆":"📖🎓🎉",title:n?"PROTOCOL EXPERT!":"BITCOIN SCHOLAR!",message:n?"You passed the Technical Protocol Expert Certification! You understand Bitcoin at the deepest level. True cypherpunk material! 🔐":"You passed the Bitcoin Scholar Certification! You have a thorough understanding of Bitcoin's properties and economics! 🧡",rewards:[{label:"2,100",sub:"PTS",color:"#22c55e"},{label:n?"🛠️":"🎓",sub:"BADGE",color:"#f7931a"}],btnText:n?"Protocol Expert! 🛠️":"Scholar! 🎓"})},500)}})},3e3),function(){var e=[{pct:25,key:"explore_25",emoji:"🗺️🌱",title:"25% EXPLORED!",msg:"A quarter of the archive explored! You're building a solid Bitcoin foundation.",pts:50,tickets:10},{pct:50,key:"explore_50",emoji:"🗺️🔥",title:"50% EXPLORED!",msg:"Halfway through the entire archive! You know more about Bitcoin than most people on Earth.",pts:100,tickets:25},{pct:75,key:"explore_75",emoji:"🗺️⚡",title:"75% EXPLORED!",msg:"Three quarters done! You're in the top tier of Bitcoin knowledge seekers.",pts:200,tickets:50},{pct:100,key:"explore_100",emoji:"🗺️👑🏆",title:"ARCHIVE COMPLETE!",msg:"You've explored EVERY SINGLE channel in the archive. You are a true Bitcoin scholar. Satoshi would be proud! 🧡",pts:500,tickets:100}];window._checkExplorationMilestones=function(){if(void 0!==CHANNELS){var t=safeJSON("btc_visited_channels",[]),o=Object.keys(CHANNELS).length,n=Math.round(t.length/o*100);e.forEach(function(e){if(n>=e.pct&&"true"!==localStorage.getItem("btc_"+e.key+"_celebrated")){if(localStorage.setItem("btc_"+e.key+"_celebrated","true"),"function"==typeof awardPoints&&awardPoints(e.pts,"🗺️ "+e.pct+"% Explored"),"function"==typeof awardOrangeTickets)awardOrangeTickets(e.tickets,"🗺️ "+e.pct+"% Explored");else{var t=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",(t+e.tickets).toString())}if(setTimeout(function(){showCelebration({emoji:e.emoji,title:e.title,message:e.msg,rewards:[{label:e.pts.toString(),sub:"PTS",color:"#22c55e"},{label:e.tickets.toString(),sub:"🎟️ TICKETS",color:"#f7931a"}]})},800),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&!auth.currentUser.isAnonymous){var o={};o["explorationMilestone_"+e.pct]=!0;try{db.collection("users").doc(auth.currentUser.uid).update(o).catch(function(){})}catch(e){}}}})}};var t=window.renderExplorationMap;window.renderExplorationMap=function(){t(),window._checkExplorationMilestones()}}(),function(){var e=window.showQuestFinalResults;e&&(window.showQuestFinalResults=function(){e.apply(this,arguments);var t=window._questScore||0;5===t?("function"==typeof showToast&&showToast("🏆 PERFECT SCORE! You nailed every question!"),"function"==typeof launchConfetti&&setTimeout(launchConfetti,300)):t>=3&&"function"==typeof showToast&&showToast("⚡ Quest passed! +"+(window._questPts||0)+" XP earned!")});var t=window.nachoQuizAnswer;t&&(window.nachoQuizAnswer=function(e,o){t.apply(this,arguments),o&&"function"==typeof haptic&&haptic("success")});var o=window.convoQuizAnswer;o&&(window.convoQuizAnswer=function(e,t){o.apply(this,arguments),t&&"function"==typeof haptic&&haptic("light")})}(),function(){window._scrollPositions={};var e=window.go;e&&(window.go=async function(t,o,n){var i=document.getElementById("main"),a=location.hash.slice(1);a&&i&&(window._scrollPositions[a]=i.scrollTop),await e(t,o,n),window._scrollPositions[t]&&i&&setTimeout(function(){i.scrollTop=window._scrollPositions[t]},100)}),window.haptic=function(e){if("visible"===document.visibilityState&&"false"!==localStorage.getItem("btc_haptic")&&navigator.vibrate)switch(e){case"light":navigator.vibrate(10);break;case"medium":navigator.vibrate(25);break;case"heavy":navigator.vibrate([30,50,30]);break;case"success":navigator.vibrate([15,30,15,30,15]);break;case"error":navigator.vibrate([50,30,50]);break;default:navigator.vibrate(15)}};var t=window.awardPoints;t&&(window.awardPoints=function(){return haptic("success"),t.apply(this,arguments)});var o=window.showLevelUpCelebration;o&&(window.showLevelUpCelebration=function(){return haptic("heavy"),o.apply(this,arguments)}),function(){var e=document.createElement("style");e.textContent="@keyframes slideInRight{from{transform:translateX(30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInLeft{from{transform:translateX(-30px);opacity:0}to{transform:translateX(0);opacity:1}}@keyframes slideInUp{from{transform:translateY(20px);opacity:0}to{transform:translateY(0);opacity:1}}.page-transition-right{animation:slideInRight 0.25s ease-out;}.page-transition-left{animation:slideInLeft 0.25s ease-out;}.page-transition-up{animation:slideInUp 0.2s ease-out;}",document.head.appendChild(e);var t=document.getElementById("main");t&&new MutationObserver(function(){var e=document.getElementById("hero");e&&e.innerHTML&&(e.classList.remove("page-transition-right"),e.offsetWidth,e.classList.add("page-transition-right"))}).observe(document.getElementById("hero")||t,{childList:!0})}();var n=0;document.addEventListener("touchend",function(e){var t=Date.now();if(t-n<300){var o=e.target.closest&&e.target.closest('[onclick*="forumViewPost"]');if(o){var i=o.querySelector('[onclick*="forumVotePost"]');i&&(i.click(),haptic("medium")),e.preventDefault()}}n=t},{passive:!1});var i=(new Date).toISOString().split("T")[0];function a(e){return localStorage.getItem(e+"_"+i)||null}function r(e,t){localStorage.setItem(e+"_"+i,t)}function s(e){return parseInt(a(e)||"0",10)}function l(e){var t=s(e)+1;return r(e,String(t)),t}var c,d=[{id:"read",text:"📖 Read a new channel",check:function(){return"true"===a("btc_new_channel_read")}},{id:"nacho",text:"🦌 Ask Nacho a question",check:function(){return s("btc_nacho_asked")>0}},{id:"quiz",text:"🎮 Complete a quiz question",check:function(){return"true"===a("btc_quiz_done")}},{id:"explore",text:"🗺️ Visit 3 different channels",check:function(){return s("btc_channels_today")>=3}},{id:"forum",text:"🗣️ Visit the PlebTalk",check:function(){return"true"===a("btc_forum_visited")}},{id:"streak",text:"🔥 Log in to keep your streak",check:function(){return!0}},{id:"favorite",text:"⭐ Save a channel to favorites",check:function(){return"true"===a("btc_fav_added")}},{id:"tctv_10m",text:"📺 Watch 10 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=10}},{id:"tctv_visit",text:"📺 Tune in to Timechain TV",check:function(){return"true"===a("btc_tctv_visited")}},{id:"tctv_3ch",text:"📺 Watch 3 different TCTV stations",check:function(){try{var e=a("btc_tctv_stations_visited");return!!e&&JSON.parse(e).length>=3}catch(e){return!1}}},{id:"tctv_30m",text:"📺 Watch 30 min of Timechain TV",check:function(){return s("btc_tctv_minutes")>=30}},{id:"tip_send",text:"⚡ Send a Lightning tip to someone",check:function(){return"true"===a("btc_tip_sent")}},{id:"tip_3",text:"⚡ Send 3 Lightning tips today",check:function(){return s("btc_tips_sent_count")>=3}},{id:"ln_setup",text:"⚡ Set up your Lightning wallet",check:function(){return!!(localStorage.getItem("btc_nwc_url")||localStorage.getItem("btc_ln_address")||void 0!==currentUser&¤tUser&¤tUser.lightningAddress)}},{id:"chat_msg",text:"🌍 Send a message in Global Chat",check:function(){return"true"===a("btc_chat_sent")}},{id:"pvp_battle",text:"⚔️ Complete a PVP trivia battle",check:function(){return"true"===a("btc_pvp_done")}},{id:"beats_listen",text:"🎸 Listen to a track on Bitcoin Beats",check:function(){return"true"===a("btc_beats_played")}},{id:"explore_5",text:"🗺️ Explore 5 different channels today",check:function(){return s("btc_channels_today")>=5}},{id:"nacho_3",text:"🦌 Ask Nacho 3 questions",check:function(){return s("btc_nacho_asked")>=3}}];function u(){var e=(new Date).toISOString().split("T")[0],t=Math.floor(new Date(e).getTime()/864e5);return d[t%d.length]}function p(){var e=u(),t=(new Date).toISOString().split("T")[0],o=localStorage.getItem("btc_challenge_done")===t,n=document.getElementById("dailyChallengeCard");n&&(o?(n.style.borderColor="#22c55e",n.style.background="rgba(34,197,94,0.05)",n.innerHTML='
    Today\'s Challenge ✔️
    '+e.text+" — Done! +100 XP 🎉
    "):(n.style.borderColor="var(--border)",n.style.background="var(--card-bg)",n.innerHTML='
    🎯
    Today\'s Challenge
    '+e.text+"
    "))}if(window.checkDailyChallenge=function(){var e=(new Date).toISOString().split("T")[0];if(localStorage.getItem("btc_challenge_done")!==e&&u().check()){localStorage.setItem("btc_challenge_done",e),"function"==typeof awardPoints&&awardPoints(100,"🎯 Daily challenge!"),"function"==typeof awardOrangeTickets&&awardOrangeTickets(5,"🎯 Daily challenge!"),"function"==typeof showToast&&showToast("🎯 Daily challenge complete! +100 XP + 🎟️ 5 tickets!"),haptic("success"),p();var t=document.getElementById("dailyChallengeCard");t&&(t.style.transition="transform 0.3s, box-shadow 0.3s",t.style.transform="scale(1.03)",t.style.boxShadow="0 0 20px rgba(34,197,94,0.4)",setTimeout(function(){t.style.transform="",t.style.boxShadow=""},1500))}},setInterval(window.checkDailyChallenge,3e3),window._raidHomeUnsub=null,window._raidHomeTimer=null,window.renderRaidBossHome=function(){var e=document.getElementById("raidBossHomeCard");e&&("undefined"!=typeof firebase&&void 0!==db?(window._raidHomeUnsub&&(window._raidHomeUnsub(),window._raidHomeUnsub=null),window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),window._raidHomeUnsub=db.collection("raid_bosses").orderBy("startTime","desc").limit(5).onSnapshot(function(t){if(t.empty)e.style.display="none";else{var o=Date.now(),n=null,i=null,a=null;t.forEach(function(e){var t=e.data();t.id=e.id;var r=t.startTime&&t.startTime.toDate?t.startTime.toDate().getTime():0,s=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0;!t.placeholder&&!t.defeated&&r<=o&&s>o?n||(n=t):t.placeholder&&r>o?(!i||r<(i.startTime&&i.startTime.toDate?i.startTime.toDate().getTime():0))&&(i=t):t.defeated&&(a||(a=t))}),function(e,t,o,n){if(window._raidHomeTimer&&(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null),t||o||n){e.style.display="";var i="if(typeof showQuestHub==='function'){showQuestHub();setTimeout(function(){if(typeof window._questHubTab!=='undefined'){window._questHubTab='raid';if(typeof _renderQuestHubTab==='function')_renderQuestHubTab();}},300)}",a="";if(t){var r=t.endTime&&t.endTime.toDate?t.endTime.toDate().getTime():0,s=t.target>0?Math.min(100,Math.round((t.current||0)/t.target*100)):0,l=Math.max(0,(t.target||0)-(t.current||0)),c=Math.max(0,100-s),d=c<=25?"#ef4444":c<=50?"#f59e0b":"#22c55e",u=t.image||"";if(!u){var p={"Channel-Crawler":"channel-crawler","Quiz-Crusader":"quiz-crusader","TV-Titan":"tv-titan","Beats-Baron":"beats-baron","Flash-Flash":"flash-flash","XP-Hoarder":"xp-hoarder","Poll-Patroller":"poll-patroller","Chat-Charger":"chat-charger","Badge-Builder":"badge-builder","Streak-Sage":"streak-sage","Topic-Explorer":"topic-explorer","Lightning-Lancer":"lightning-lancer","Forum-Forge":"forum-forge","Trivia-Tactician":"trivia-tactician","Content-Conqueror":"content-conqueror"};p[t.name]&&(u="images/raid-bosses/"+p[t.name]+".png")}a+='
    '+(u?'':'⚔️')+'
    ⚔️ CURRENT RAID BOSS
    '+(t.name||"Raid Boss")+'
    ❤️ '+l+"/"+t.target+' HP⏱ '+g(r)+'
    ',window._raidActiveEndMs=r}if(o){var h=o.startTime&&o.startTime.toDate?o.startTime.toDate().getTime():0,m=new Date(h).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"});a+='
    ⚔️
    NEXT BOSS
    '+(o.name||"TBD")+" — "+m+'
    Starts in '+g(h)+'
    ',window._raidUpcomingStartMs=h}n&&!t&&(a='
    💀
    🎉 BOSS DEFEATED!
    '+("function"==typeof escapeHtml?escapeHtml(n.name||"Raid Boss"):n.name||"Raid Boss")+' has fallen!
    🏆 Orange ticket drawing this Friday!
    '+a),e.innerHTML=a,window._raidHomeTimer=setInterval(function(){var e=document.getElementById("raidHomeCountdown");e&&window._raidActiveEndMs&&(e.textContent="⏱ "+g(window._raidActiveEndMs));var t=document.getElementById("raidHomeUpcomingCountdown");t&&window._raidUpcomingStartMs&&(t.textContent="Starts in "+g(window._raidUpcomingStartMs)),e||t||(clearInterval(window._raidHomeTimer),window._raidHomeTimer=null)},1e3)}else e.style.display="none";function g(e){var t=Math.max(0,e-Date.now());if(t<=0)return"⏳ Any moment now...";var o=Math.floor(t/864e5),n=Math.floor(t%864e5/36e5),i=Math.floor(t%36e5/6e4),a=Math.floor(t%6e4/1e3);return o>0?o+"d "+n+"h "+i+"m":n>0?n+"h "+i+"m "+a+"s":i+"m "+a+"s"}}(e,n,i,a)}},function(){e.style.display="none"})):e.style.display="none")},c="",window._trackChallengeNav=function(e){e&&e!==c&&(c=e,"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e||r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},500))},window.go){var h=window.go;window.go=async function(e){var t=!1;e&&"forum"!==e&&"marketplace"!==e&&"bitcoin-beats"!==e&&"irl-sync"!==e&&"dms"!==e&&(t=-1===safeJSON("btc_visited_channels",[]).indexOf(e));var o=await h.apply(this,arguments);return"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e),e&&"forum"!==e&&(l("btc_channels_today"),t&&r("btc_new_channel_read","true")),"forum"===e&&r("btc_forum_visited","true"),setTimeout(function(){"function"==typeof checkDailyChallenge&&checkDailyChallenge()},300),o}}var m=window.nachoUnifiedAnswer;m&&(window.nachoUnifiedAnswer=function(e,t){return l("btc_nacho_asked"),m.apply(this,arguments)}),window.addEventListener("hashchange",function(){var e=location.hash.slice(1);e&&"function"==typeof window._trackChallengeNav&&window._trackChallengeNav(e)}),window.renderProgressRings=function(){var e=document.getElementById("progressRings");if(e){var t=void 0!==CHANNELS?Object.keys(CHANNELS).length:146,o=0;void 0!==currentUser&¤tUser&&(currentUser.readChannels&¤tUser.readChannels.length?o=currentUser.readChannels.length:currentUser.channelsVisited&&(o=currentUser.channelsVisited)),0===o&&(o=safeJSON("btc_visited_channels",[]).length);var n=void 0!==currentUser&¤tUser&¤tUser.streak||0,i=void 0!==currentUser&¤tUser&¤tUser.points||0,a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.innerHTML='
    '+r(Math.min(100,o/t*100),"#f7931a","Channels",o+"/"+t)+r(Math.min(100,5*n),"#22c55e","Streak","🔥"+n)+r(Math.min(100,i/21e3*100),"#8B5CF6","XP",i>999?Math.floor(i/1e3)+"k":i)+r(Math.min(100,2*a),"#3B82F6","Nacho",a)+"
    "}function r(e,t,o,n){var i=2*Math.PI*32;return'
    '+n+'
    '+o+"
    "}};var g=null;function f(){console.log("[MobileUX] Initializing..."),function(){var e=document.createElement("div");e.id="bottomNav",e.className="mobile-nav",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:200000;background:rgba(10,10,10,0.95);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border-top:1px solid rgba(255,255,255,0.1);padding:10px 0 env(safe-area-inset-bottom,10px) 0;padding-bottom:max(env(safe-area-inset-bottom,10px),10px);display:none;transition:transform 0.25s ease;-webkit-transform:translateZ(0);transform:translateZ(0);",e.innerHTML='
    ';var t=document.createElement("style");t.textContent=".bnav-btn{background:none;border:none;color:var(--text-dim,#666);font-size:0.6rem;cursor:pointer;font-family:inherit;padding:6px 0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;touch-action:manipulation;-webkit-tap-highlight-color:transparent;transition:0.2s;flex:1;min-width:0;}.bnav-icon{font-size:1.3rem;line-height:1;display:block;transition:transform 0.2s;}.bnav-label{font-size:0.55rem;line-height:1;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;}.bnav-btn:active .bnav-icon{transform:scale(1.2);}.bnav-btn.active{color:var(--accent);}@media(min-width:901px){#bottomNav{display:none!important;}}@media(max-width:900px){#bottomNav{display:block!important;visibility:visible!important;opacity:1!important;}.messages{padding-bottom:140px!important;}.home-page{padding-bottom:100px!important;}}",document.head.appendChild(t),document.body.appendChild(e)}(),function(){var e=document.getElementById("main");if(e){var t=0,o=document.getElementById("bottomNav");o&&e.addEventListener("scroll",function(){if(!(window.innerWidth>900)){var n=e.scrollTop,i=n-t;i>10&&n>200?o.classList.add("nav-hidden"):(i<-5||n<=10)&&o.classList.remove("nav-hidden"),t=n}},{passive:!0})}}(),setTimeout(function(){!function(){var e=0;if(void 0!==currentUser&¤tUser&&(e=currentUser.streak||0),!(e<2||document.getElementById("streakBanner"))){var t=document.createElement("div");t.id="streakBanner",t.style.cssText="position:fixed;top:32px;left:0;right:0;z-index:300;background:linear-gradient(135deg,#f7931a,#ea580c);color:#fff;padding:10px 16px;text-align:center;font-size:0.85rem;font-weight:700;cursor:pointer;animation:slideInUp 0.3s;",t.innerHTML="🔥 Day "+e+' streak! Keep it alive! tap to dismiss',t.onclick=function(){t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.remove()},300)},document.body.appendChild(t),setTimeout(function(){t.parentNode&&(t.style.transition="0.3s",t.style.transform="translateY(-100%)",setTimeout(function(){t.parentNode&&t.remove()},300))},5e3)}}(),function(){if("function"==typeof forceShowBubble&&!sessionStorage.getItem("btc_welcomed_back")){sessionStorage.setItem("btc_welcomed_back","true");var e="";void 0!==currentUser&¤tUser&¤tUser.username&&(e=currentUser.username);var t,o=void 0!==currentUser&¤tUser&¤tUser.streak||0,n=(new Date).getHours(),i=n<12?"Morning":n<17?"Afternoon":"Evening",a=u();t=e&&o>=2?"Good "+i.toLowerCase()+", "+e+"! ☀️ Day "+o+" streak — you're on fire! 🔥 Today's challenge: "+a.text:e?"Hey "+e+"! 🦌 Welcome back! Today's challenge: "+a.text:"Welcome back! 🦌 Today's challenge: "+a.text,setTimeout(function(){forceShowBubble(t)},3e3)}}(),p(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof renderProgressRings&&renderProgressRings()},2500)}window.addEventListener("beforeinstallprompt",function(e){if(e.preventDefault(),g=e,!window.matchMedia("(display-mode: standalone)").matches){var t=localStorage.getItem("btc_pwa_dismissed");if(t&&Date.now()-parseInt(t)<6048e5)return;window._pwaLoadTime=Date.now(),window._pwaCheckInterval=setInterval(function(){if(!(Date.now()-(window._pwaLoadTime||Date.now())<9e4)){var e=[];try{e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]")}catch(e){}e.length>=3&&(clearInterval(window._pwaCheckInterval),function(){if(!document.getElementById("pwaInstallBanner")){var e=document.createElement("div");if(e.id="pwaInstallBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Install Bitcoin Education
    Add to home screen for the best experience — works offline!
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}}())}},1e4)}}),window.installPWA=function(){g&&(g.prompt(),g.userChoice.then(function(e){"accepted"===e.outcome&&"function"==typeof showToast&&showToast("🦌 Welcome aboard! App installed!"),g=null})),dismissPWABanner()},window.dismissPWABanner=function(){var e=document.getElementById("pwaInstallBanner");e&&e.remove(),localStorage.setItem("btc_pwa_dismissed",Date.now().toString())},function(){var e=/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,t=/Safari/.test(navigator.userAgent)&&!/CriOS|FxiOS|Chrome/.test(navigator.userAgent),o=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone;if(e&&t&&!o){var n=localStorage.getItem("btc_ios_a2hs_dismissed");n&&Date.now()-parseInt(n)<2592e6||setTimeout(function(){if(!document.getElementById("iosA2HSBanner")){var e=document.createElement("div");if(e.id="iosA2HSBanner",e.style.cssText="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);z-index:99999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #f7931a;border-radius:16px;padding:16px 20px;max-width:340px;width:90%;box-shadow:0 8px 32px rgba(247,147,26,0.3);animation:slideUp 0.4s ease;font-family:inherit;",e.innerHTML='
    🦌
    Add to Home Screen
    For the best experience, add this app to your home screen:
    1. Tap the Share button ⬆️ at the bottom
    2. Scroll down and tap Add to Home Screen
    ',!document.getElementById("pwaAnimStyle")){var t=document.createElement("style");t.id="pwaAnimStyle",t.textContent="@keyframes slideUp{from{transform:translateX(-50%) translateY(100px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}",document.head.appendChild(t)}document.body.appendChild(e)}},12e4)}}(),window.dismissIOSA2HS=function(){var e=document.getElementById("iosA2HSBanner");e&&e.remove(),localStorage.setItem("btc_ios_a2hs_dismissed",Date.now().toString())},window.toggleMobileLearnMenu=function(){var e=document.getElementById("mobileLearnMenu");if(e)e.remove();else{var t=document.getElementById("appsMenu");t&&t.remove();var o=document.createElement("div");o.id="mobileLearnMenu",o.style.cssText="position:fixed;bottom:70px;left:8px;right:8px;z-index:250;max-width:400px;margin:0 auto;background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:18px;box-shadow:0 -8px 40px rgba(0,0,0,0.6);animation:fadeSlideIn 0.25s ease-out;",o.innerHTML='

    🎓 Learn

    ',document.body.appendChild(o),setTimeout(function(){document.addEventListener("click",function e(t){var o=document.getElementById("mobileLearnMenu");!o||o.contains(t.target)||t.target.closest("#bnavLearn")||(o.remove(),document.removeEventListener("click",e))})},100)}},window.toggleMobileFlashcards=function(){var e=document.getElementById("mLearnFlashGrid"),t=document.getElementById("mLearnFlashBtn");e&&("none"===e.style.display?(e.style.display="flex",t&&(t.textContent="📚 Flashcards ▼")):(e.style.display="none",t&&(t.textContent="📚 Flashcards ▶")))},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",f):f()}(),function(){"use strict";var e=null,t=null,o=null,n=null;function i(){if(!(e&&e.readyState<=1))try{(e=new WebSocket("wss://ws.coincap.io/prices?assets=bitcoin")).onopen=function(){console.log("[Dashboard] Price WebSocket connected (CoinCap)"),window._wsDataTimer=setTimeout(function(){t||(console.warn("[Dashboard] WS connected but no data — falling back"),r())},1e4)},e.onmessage=function(e){try{window._wsDataTimer&&(clearTimeout(window._wsDataTimer),window._wsDataTimer=null);var i=JSON.parse(e.data);if(!i.bitcoin)return;var a=parseFloat(i.bitcoin);!n&&t&&(n=t),t=a,n&&(o=(t-n)/n*100),n=parseFloat(i.o);var r=document.getElementById("dashLivePrice");r&&(r.textContent="$"+p(t,2));var s=document.getElementById("dashLiveChange");if(s){var l=o>=0?"#22c55e":"#ef4444",c=o>=0?"▲":"▼";s.innerHTML=''+c+" "+Math.abs(o).toFixed(2)+"% (24h)"}var d=document.getElementById("dashBtnPrice");if(d){var u=o>=0?"#22c55e":"#ef4444",h=o>=0?"▲":"▼";d.innerHTML="$"+p(t,0)+' '+h+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}catch(e){}},e.onclose=function(){console.log("[Dashboard] WS closed, reconnecting..."),e=null,setTimeout(i,5e3)},e.onerror=function(t){console.warn("[Dashboard] WS error, falling back to polling");try{e.close()}catch(e){}e=null,r()}}catch(e){r()}}var a=null;function r(){function e(){fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true").then(function(e){return e.json()}).then(function(e){if(e&&e.bitcoin){t=e.bitcoin.usd,o=e.bitcoin.usd_24h_change||0;var n=document.getElementById("dashLivePrice");n&&(n.textContent="$"+p(t,2));var i=document.getElementById("dashLiveChange");if(i){var a=o>=0?"#22c55e":"#ef4444",r=o>=0?"▲":"▼";i.innerHTML=''+r+" "+Math.abs(o).toFixed(2)+"% (24h)"}var s=document.getElementById("dashBtnPrice");if(s){var l=o>=0?"#22c55e":"#ef4444",c=o>=0?"▲":"▼";s.innerHTML="$"+p(t,0)+' '+c+Math.abs(o).toFixed(1)+"%"}window._btcPriceCache={price:t,change:o,ts:Date.now()}}}).catch(function(){})}a||(console.log("[Dashboard] Starting price polling fallback (CoinGecko)"),e(),a=setInterval(e,3e4))}var s="btc_dashboard_cache",l=12e4,c=null,d=!1,u=null;function p(e,t){return null==e?"—":"number"==typeof t?Number(e).toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t}):Number(e).toLocaleString()}function h(e){return null==e?"—":e>=1e12?"$"+(e/1e12).toFixed(1)+"T":e>=1e9?"$"+(e/1e9).toFixed(1)+"B":e>=1e6?"$"+(e/1e6).toFixed(1)+"M":e>=1e3?"$"+(e/1e3).toFixed(0)+"K":"$"+Math.round(e)}function m(e){return null==e?"—":e>=1e12?(e/1e12).toFixed(2)+" T":e>=1e9?(e/1e9).toFixed(2)+" B":p(e)}async function g(){if(d)return await new Promise(function(e){var t=setInterval(function(){d||(clearInterval(t),e())},200);setTimeout(function(){clearInterval(t),d=!1,e()},1e4)}),c||{};d=!0;var e=null;try{var i=JSON.parse(localStorage.getItem(s));if(i&&i.data&&(e=i.data,Date.now()-i.tse.text()).then(e=>{a.blockHeight=parseInt(e);try{localStorage.setItem("btc_last_height",a.blockHeight.toString())}catch(e){}var t=document.getElementById("btcDashCard");t&&!a.price&&a.blockHeight&&(t.innerHTML=f(a))}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/fees/recommended").then(e=>e.json()).then(e=>{a.feeFast=e.fastestFee,a.feeHalf=e.halfHourFee,a.feeHour=e.hourFee,a.feeEcon=e.economyFee,a.feeMin=e.minimumFee}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/mining/hashrate/1m").then(e=>e.json()).then(e=>{if(e.currentHashrate&&(a.hashrate=e.currentHashrate),e.currentDifficulty&&(a.difficulty=e.currentDifficulty),e.hashrates&&e.hashrates.length>=6){var t=e.hashrates.length,o=(e.hashrates[t-1].avgHashrate+e.hashrates[t-2].avgHashrate+e.hashrates[t-3].avgHashrate)/3,n=(e.hashrates[t-4].avgHashrate+e.hashrates[t-5].avgHashrate+e.hashrates[t-6].avgHashrate)/3;n>0&&(a.hashrateChange24h=(o-n)/n*100)}}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/difficulty-adjustment").then(e=>e.json()).then(e=>{a.diffChange=e.difficultyChange,a.diffEstDate=e.estimatedRetargetDate,a.diffRemaining=e.remainingBlocks,a.diffProgress=e.progressPercent}).catch(()=>{})),r.push(fetch("https://mempool.space/api/mempool").then(e=>e.json()).then(e=>{a.mempoolTxs=e.count,a.mempoolSize=e.vsize}).catch(()=>{})),r.push(fetch("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true&include_24hr_vol=true&include_market_cap=true").then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{if(e.bitcoin){a.price=e.bitcoin.usd;try{localStorage.setItem("btc_last_price",e.bitcoin.usd.toString())}catch(e){}a.change24h=e.bitcoin.usd_24h_change,a.volume24h=e.bitcoin.usd_24h_vol,a.marketCap=e.bitcoin.usd_market_cap,!n&&a.price&&a.change24h&&(n=a.price/(1+a.change24h/100),o=a.change24h)}var t=document.getElementById("btcDashCard");return t&&a.price&&(t.innerHTML=f(a)),new Promise(function(e){setTimeout(e,1500)})}).then(function(){return fetch("https://api.coingecko.com/api/v3/coins/bitcoin?localization=false&tickers=false&community_data=false&developer_data=false")}).then(e=>{if(429===e.status)throw new Error("rate-limited");return e.json()}).then(e=>{e.market_data&&(a.supply=e.market_data.circulating_supply,a.ath=e.market_data.ath?e.market_data.ath.usd:null,a.athDate=e.market_data.ath_date?e.market_data.ath_date.usd:null,a.athChange=e.market_data.ath_change_percentage?e.market_data.ath_change_percentage.usd:null,a.high24h=e.market_data.high_24h?e.market_data.high_24h.usd:null,a.low24h=e.market_data.low_24h?e.market_data.low_24h.usd:null,a.mktCapChange24h=e.market_data.market_cap_change_percentage_24h||null)}).catch(()=>{})),r.push(fetch("https://mempool.space/api/v1/lightning/statistics/latest").then(e=>e.json()).then(e=>{e&&(a.lnCapacity=e.latest?e.latest.total_capacity:e.total_capacity,a.lnNodes=e.latest?e.latest.node_count:e.node_count,a.lnChannels=e.latest?e.latest.channel_count:e.channel_count)}).catch(()=>{})),r.push(fetch("https://api.alternative.me/fng/?limit=1").then(e=>e.json()).then(e=>{e.data&&e.data[0]&&(a.fearGreed=parseInt(e.data[0].value),a.fearGreedLabel=e.data[0].value_classification)}).catch(()=>{})),await Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,12e3))]),!a.price&&t&&(a.price=t);for(var u=[s,"btc_dash_backup"],p=0;p'+(r<=2?"Live metrics · Updates every 2 min":"📦 Data from "+(r<60?r+"m":Math.round(r/60)+"h")+" ago · Refreshing...")+"",a+='',a+="";var s=t||n.price,l=null!==o?o:n.change24h||0,c=l>=0?"#22c55e":"#ef4444",d=l>=0?"▲":"▼";if(a+='
    ',a+='
    $'+p(s,2)+"
    ",a+='
    '+d+" "+Math.abs(l).toFixed(2)+"%
    ",a+='
    🔴 Live — updates automatically · All % changes are 24h
    ',a+='
    ',a+='24h High: $'+p(n.high24h,0)+"",a+='24h Low: $'+p(n.low24h,0)+"",a+="
    ",a+="
    ",void 0!==n.halvingDays){var u=n.halving?((21e4-n.halving)/21e4*100).toFixed(1):0,h=n.halvingEta?n.halvingEta.toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"}):"—";a+='
    ',a+='
    ⏳ Next Halving — Block #'+p(n.halvingBlock)+'
    ',window._halvingTargetMs=Date.now()+10*n.halving*60*1e3,a+='
    ',a+='
    '+(n.halvingDays||0)+'
    Days
    ',a+='
    :
    ',a+='
    '+(n.halvingHours||0)+'
    Hours
    ',a+='
    :
    ',a+='
    '+(n.halvingMins||0)+'
    Mins
    ',a+='
    :
    ',a+='
    00
    Secs
    ',a+="
    ",a+='
    Est. '+h+" · "+p(n.halving)+" blocks remaining
    ",a+='
    ',a+='
    ',a+="
    ",a+='
    '+u+"% through epoch · Subsidy drops "+n.subsidy+" → "+(n.nextSubsidy||"?")+" BTC
    ",a+="
    "}a+='
    ',a+=y("⚡","Sats per Dollar",p(n.satsPerDollar),"Moscow Time","How many satoshis (sats) you get for $1 USD. A satoshi is the smallest unit of Bitcoin (0.00000001 BTC). Also called Moscow Time — the number on the clock is how many sats per dollar."),a+=y("⛓️","Block Height",p(n.blockHeight),"","The total number of blocks mined since Bitcoin's Genesis Block on Jan 3, 2009. A new block is added roughly every 10 minutes. This number only goes up — never down."),a+=y("🪙","Block Subsidy",n.subsidy+" BTC",p(n.halving)+" blocks to halving","The reward miners receive for finding each new block. Started at 50 BTC in 2009 and halves every 210,000 blocks (~4 years). Currently 3.125 BTC per block.");var g,f="";if(null!=n.hashrateChange24h){var b=n.hashrateChange24h;f=''+(b>=0?"▲":"▼")+" "+Math.abs(b).toFixed(1)+"%"}a+=y("⛏️","Hashrate",null==(g=n.hashrate)?"—":g>=1e18?(g/1e18).toFixed(2)+" EH/s":g>=1e15?(g/1e15).toFixed(2)+" PH/s":g>=1e12?(g/1e12).toFixed(2)+" TH/s":g>=1e9?(g/1e9).toFixed(2)+" GH/s":g>=1e6?(g/1e6).toFixed(2)+" M":g>=1e3?(g/1e3).toFixed(1)+"K":p(g),f,"The total computing power securing the Bitcoin network, measured in hashes per second. Higher hashrate = more secure network. EH/s = quintillion hashes per second."),a+=y("🎯","Difficulty",m(n.difficulty),"","How hard it is to mine a new block. Adjusts every 2,016 blocks (~2 weeks) to keep block times at ~10 minutes. If miners join, difficulty goes up. If miners leave, it goes down."),a+=y("🔄","Next Adjustment",(n.diffChange>=0?"+":"")+(n.diffChange||0).toFixed(2)+"%",i+" · "+p(n.diffRemaining)+" blocks","The estimated change in mining difficulty at the next adjustment. Positive means blocks are being found faster than 10 min (more miners joined). Negative means slower (miners left)."),a+=y("💸","Fast Fee",(n.feeFast||"—")+" sat/vB","Half-hour: "+(n.feeHalf||"—")+" · Economy: "+(n.feeEcon||"—"),"The recommended transaction fee in satoshis per virtual byte (sat/vB). Fast = next block (~10 min). Half-hour = 1-3 blocks. Economy = lowest priority. Higher fees = faster confirmation."),a+=y("📋","Mempool",p(n.mempoolTxs)+" txs",n.mempoolSize?(n.mempoolSize/1e6).toFixed(1)+" MvB":"","The waiting room for unconfirmed Bitcoin transactions. Shows how many transactions are waiting to be included in a block and their total size. A full mempool means higher fees."),a+=y("💰","Circulating Supply",function(e){return e?(e/1e6).toFixed(2)+"M / 21M":"—"}(n.supply),function(e){return e?(e/21e6*100).toFixed(2)+"%":"—"}(n.supply)+" mined","How many of the 21 million total Bitcoin have been mined so far. No more than 21 million will ever exist — this is enforced by code and consensus. The last Bitcoin will be mined around the year 2140.");var v="";if(null!=n.mktCapChange24h){var w=n.mktCapChange24h;v=''+(w>=0?"▲":"▼")+" "+Math.abs(w).toFixed(1)+"%"}a+=y("📊","Market Cap","$"+m(n.marketCap),v,"Total value of all Bitcoin in circulation (price × circulating supply). Puts Bitcoin's size in perspective compared to gold (~$16T), the S&P 500, or global real estate.");var x="";n.volume24h&&n.marketCap&&(x="Vol/MCap: "+(n.volume24h/n.marketCap*100).toFixed(2)+"%"),a+=y("📈","24h Volume","$"+m(n.volume24h),x,"Total USD value of Bitcoin traded across all exchanges in the last 24 hours. High volume often signals strong market interest or significant price moves.");var k=n.lnCapacity?(n.lnCapacity/1e8).toFixed(0):"—",T=n.lnCapacity&&n.price?"$"+m(n.lnCapacity/1e8*n.price):"",A=(n.lnNodes?p(n.lnNodes)+" nodes · ":"")+(n.lnChannels?p(n.lnChannels)+" channels":"")+(T?"
    "+T:"");a+=y("⚡","Lightning Capacity",p(k)+" BTC",A,"Total Bitcoin locked in Lightning Network payment channels. Lightning enables instant, near-free Bitcoin payments. More capacity = more liquidity for fast payments. Nodes route payments; channels connect them."),n.ath&&(a+='
    ',a+='🏔️',a+='
    All-Time High
    ',a+='
    $'+p(n.ath,0)+"
    ",a+='
    '+(n.athChange||0).toFixed(1)+"%
    ",n.athDate&&(a+='
    '+new Date(n.athDate).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})+"
    "),a+="
    "),a+="
    ";var E=n.marketCap?n.marketCap/1e12:0;return a+='
    ',a+='
    ⚖️ Bitcoin vs Gold
    ',a+='
    ',a+='
    ₿ Bitcoin$'+E.toFixed(2)+"T
    ",a+='
    ',a+='
    🥇 GoldLoading...
    ',a+='
    Fetching live gold price...
    ',a+="
    ",setTimeout(function(){!function(e,t){if(!B)try{var o=JSON.parse(localStorage.getItem("btc_gold_cache"));o&&o.p&&(B=o.p,S=o.t||0)}catch(e){}B&&Date.now()-S<18e5?_(B,e,t):(B&&_(B,e,t),fetch("https://api.coingecko.com/api/v3/simple/price?ids=tether-gold&vs_currencies=usd").then(function(e){return e.json()}).then(function(o){var n=o["tether-gold"]?o["tether-gold"].usd:null;if(n){B=n,S=Date.now();try{localStorage.setItem("btc_gold_cache",JSON.stringify({p:n,t:Date.now()}))}catch(e){}_(n,e,t)}}).catch(function(){B||_(3200,e,t)}))}(E,n.supply||0)},150),a+='
    ',a+='
    🏛️ Bitcoin Treasuries ⓘ tap for top holders
    ',a+='
    Loading live treasury data...
    ',a+="
    ",setTimeout(function(){!function(e){var t=document.getElementById("treasuryData");if(t){if(!I)try{var o=JSON.parse(localStorage.getItem("btc_treasury_cache"));o&&o.d&&(I=o.d,C=o.t||0)}catch(e){}I&&Date.now()-C<18e5?z(t,I,e):(I&&z(t,I,e),fetch("https://api.coingecko.com/api/v3/companies/public_treasury/bitcoin").then(function(e){return e.json()}).then(function(o){I=o,C=Date.now();try{localStorage.setItem("btc_treasury_cache",JSON.stringify({d:o,t:Date.now()}))}catch(e){}z(t,o,e)}).catch(function(){I||(t.innerHTML='
    Could not load treasury data
    ')}))}}(n.price||0)},200),a+='
    ',a+='
    🏦 Bitcoin ETFs top 5 by BTC in custody
    ',a+='
    Loading ETF holdings...
    ',a+="
    ",setTimeout(function(){!function(e,t){var o=document.getElementById("etfHoldingsData");if(o){var n=e||parseFloat(localStorage.getItem("btc_last_price"))||83e3,i=t||1984e4,a=null;try{a=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"))}catch(e){}a&&a.holdings&&P(o,a.holdings,a.totalBtc,n,i,a.updated),fetch("data/etf-holdings.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.holdings&&e.holdings.length){try{localStorage.setItem("btc_etf_holdings_cache",JSON.stringify(e))}catch(e){}P(o,e.holdings,e.totalBtc,n,i,e.updated)}}).catch(function(){a||P(o,L,M,n,i,null)})}}(n.price||0,n.supply||0)},250),a+='
    ',a+='',a+='
    ",a+='
    ',a+="Data Sources: ",a+='mempool.space (blocks, fees, hashrate, difficulty, mempool) · ',a+='CoinGecko (price, market cap, supply, volume) · ',a+='Alternative.me (Fear & Greed Index) · ',a+='BitcoinTreasuries.net (company & government holdings)',a+='
    Last updated: '+new Date(n.ts||Date.now()).toLocaleTimeString()+"
    ",a+="
    ",setTimeout(function(){window._halvingTargetMs&&document.getElementById("halvSecs")&&"function"==typeof window._startHalvingTicker&&window._startHalvingTicker(),"function"==typeof window._attachTipListeners&&window._attachTipListeners()},100),a}function y(e,t,o,n,i){return"
    '+e+" "+t+(i?' ':"")+'
    '+(o||"—")+"
    "+(n?'
    '+n+"
    ":"")+""}setInterval(function(){d&&(console.warn("[Dashboard] Force-clearing stuck loading flag"),d=!1)},15e3);var b="ontouchstart"in window||navigator.maxTouchPoints>0;function v(){injectDashboardButton(),injectHomeDashboardButton(),i()}window.showDashTip=function(e,t){var o=document.getElementById("dashTipPopup");o&&o.remove();var n=document.createElement("div");n.id="dashTipPopup",n.style.cssText="position:absolute;left:50%;transform:translateX(-50%);bottom:calc(100% + 8px);z-index:10;background:var(--bg-side,#1a1a2e);border:1px solid var(--accent);border-radius:10px;padding:10px 14px;max-width:320px;width:max-content;box-shadow:0 8px 24px rgba(0,0,0,0.5);animation:fadeSlideIn 0.2s ease-out;pointer-events:auto;",n.innerHTML='
    '+t.replace(/\\n/g,"
    ").replace(/\n/g,"
    ")+'
    ',e.style.position="relative",e.appendChild(n),setTimeout(function(){document.addEventListener("click",function e(t){n.parentNode&&n.remove(),document.removeEventListener("click",e)},{once:!0})},50)},window.hideDashTip=function(e){var t=e?e.querySelector("#dashTipPopup"):document.getElementById("dashTipPopup");t&&t.remove()},window._attachTipListeners=function(){document.querySelectorAll("[data-dash-tip]:not([data-tip-bound])").forEach(function(e){e.setAttribute("data-tip-bound","1");var t=e.getAttribute("data-dash-tip");t&&(b?e.addEventListener("click",function(o){o.stopPropagation();var n=e.querySelector("#dashTipPopup");n?n.remove():showDashTip(e,t)}):(e.addEventListener("mouseenter",function(){showDashTip(e,t)}),e.addEventListener("mouseleave",function(){hideDashTip(e)})))})},window.injectDashboardButton=function(){},window.injectHomeDashboardButton=function(){},window.toggleDashboard=async function(){var e=document.getElementById("btcDashOverlay");if(e)return e.remove(),clearInterval(u),void(u=null);var t=document.createElement("div");t.id="btcDashOverlay",t.style.cssText="position:fixed;inset:0;z-index:10002;background:rgba(0,0,0,0.88);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);display:flex;align-items:flex-start;justify-content:center;padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;",t.onclick=function(e){e.target===t&&closeDashboard()};var o=document.createElement("div");o.id="btcDashCard",o.style.cssText="background:var(--bg-side,#0f0f23);border:1px solid var(--border);border-radius:20px;padding:24px;max-width:500px;width:100%;margin:40px auto;box-shadow:0 20px 60px rgba(0,0,0,0.5);animation:fadeSlideIn 0.3s ease-out;",t.appendChild(o),document.body.appendChild(t),i();var n=!1;try{var a=JSON.parse(localStorage.getItem(s));a&&a.data&&(a.data.price||a.data.blockHeight)&&(o.innerHTML=f(a.data),n=!0)}catch(e){}if(!n){var r={};if("undefined"!=typeof nachoLiveData&&(nachoLiveData.price&&(r.price=nachoLiveData.price),nachoLiveData.blockHeight&&(r.blockHeight=nachoLiveData.blockHeight)),!r.price)try{r.price=parseFloat(localStorage.getItem("btc_last_price"))||0}catch(e){}if(!r.blockHeight)try{r.blockHeight=parseInt(localStorage.getItem("btc_last_height"))||0}catch(e){}r.price||r.blockHeight?(o.innerHTML=f(r),n=!0):o.innerHTML='
    Loading Bitcoin metrics...
    '}g().then(function(e){var t=document.getElementById("btcDashCard");if(t){var o=document.getElementById("topIndicatorsPanel"),i=o&&"none"!==o.style.display;if(e&&(e.price||e.blockHeight)?t.innerHTML=f(e):n||(t.innerHTML='
    📊
    Unable to load fresh metrics.
    Showing last known data. Try again later.
    '),i){var a=document.getElementById("topIndicatorsPanel"),r=document.getElementById("topIndArrow");a&&(a.style.display="block",w=!1,k()),r&&(r.textContent="▲")}}}),u=setInterval(async function(){if(document.getElementById("btcDashOverlay")){var e=document.getElementById("topIndicatorsPanel"),t=e&&"none"!==e.style.display;localStorage.removeItem(s);var o=await g(),n=document.getElementById("btcDashCard");if(n&&(n.innerHTML=f(o),t)){var i=document.getElementById("topIndicatorsPanel"),a=document.getElementById("topIndArrow");i&&(i.style.display="block",w=!1,k()),a&&(a.textContent="▲")}}else clearInterval(u)},l)},window.closeDashboard=function(){var e=document.getElementById("btcDashOverlay");e&&e.remove(),u&&(clearInterval(u),u=null)},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){setTimeout(v,2e3)}):setTimeout(v,2e3),window.toggleTopIndicators=function(){var e=document.getElementById("topIndicatorsPanel"),t=document.getElementById("topIndArrow");e&&("none"===e.style.display?(e.style.display="block",t.textContent="▲",k()):(e.style.display="none",t.textContent="▼"))};var w=!1,x="btc_top_indicators_cache";function k(){if(!w){w=!0;var e=document.getElementById("topIndContent");if(e){try{var t=JSON.parse(localStorage.getItem(x));if(t&&t.html){var o=Math.round((Date.now()-t.ts)/6e4),n=o>5?'
    📦 Cached '+(o<60?o+"m":Math.round(o/60)+"h")+" ago · refreshing...
    ":"";e.innerHTML=n+t.html}}catch(e){}var i=c||{},a=i.price||0,r=i.blockHeight||0,s=i.supply||0,l=i.fearGreed||0,d=i.fearGreedLabel||"—",u=[];if(r){var h=Math.floor(r/21e4),m=50/Math.pow(2,h)*6*24*365,g=m>0?(s||198e5)/m:0,f=Math.pow(10,3.31954*Math.log10(g)-1.32093),y=a>0?(a/f).toFixed(2):"—";u.push({emoji:"📈",name:"Stock-to-Flow",value:g.toFixed(1),sub:"Model: $"+p(Math.round(f))+" · Ratio: "+y+"x",tip:"Stock-to-Flow measures scarcity. Higher S2F = scarcer asset. Bitcoin's S2F increases with each halving. Gold is ~62, Silver ~22. A ratio below 1x suggests undervalued vs the model."})}if(l){var b=l<=25?"#ef4444":l<=45?"#f97316":l<=55?"#eab308":l<=75?"#84cc16":"#22c55e";u.push({emoji:"😱",name:"Fear & Greed",value:l,color:b,sub:d,tip:"Crypto Fear & Greed Index. 0 = Extreme Fear (potential buy), 100 = Extreme Greed (potential sell). Aggregates volatility, momentum, social media, and surveys."})}if(u.push({emoji:"📐",name:"Mayer Multiple",value:"...",sub:"Loading...",tip:"Price divided by 200-day moving average. Below 1.0 = historically cheap. Above 2.4 = overheated. Named after Trace Mayer.",id:"mayerMultiple"}),r){var v=r%21e4,k=(v/21e4*100).toFixed(1),B=Math.round(10*v/1440),S=B>=365&&B<=730;u.push({emoji:"🔄",name:"Halving Cycle",value:k+"%",sub:"Day "+B+"/~1460"+(S?" · 🔥 Peak Window":""),color:S?"#f97316":null,tip:"Position in the current 4-year halving cycle (210,000 blocks). Historically, price peaks occur 12-24 months after a halving (Day 365-730). We are at day "+B+"."})}if(i.ath&&i.athDate){var T=new Date(i.athDate),_=Math.floor((Date.now()-T.getTime())/864e5),I=i.athChange?Math.abs(i.athChange).toFixed(1):"—";u.push({emoji:"🏔️",name:"ATH Drawdown",value:"-"+I+"%",sub:_+" days since ATH ($"+p(Math.round(i.ath))+")",tip:"Current drawdown from the all-time high. In previous cycles, bear markets saw -70% to -85% drawdowns. Recovery to new ATH has always followed."})}if(a&&s&&r){h=Math.floor(r/21e4);for(var C=0,A=r,E=0;E<=h&&A>0;E++){var z=Math.min(A,21e4);C+=z*(50/Math.pow(2,E)),A-=z}var L=3e4*C,P=L>0?(a*s/L).toFixed(1):"—";u.push({emoji:"🌡️",name:"Thermo Multiple",value:P+"x",sub:"Market Cap / Thermocap",tip:'Thermocap Multiple compares market cap to total miner revenue (a proxy for "energy spent"). Values >5x historically signal overheating (cycle tops hit 4-8x). <10x = accumulation zone.'})}if(a&&s&&i.volume24h){var U=a*s,q=i.volume24h>0?(U/i.volume24h).toFixed(1):"—",N=q<30?"#22c55e":q>150?"#ef4444":"var(--heading)";u.push({emoji:"📡",name:"NVT Ratio",value:q,color:N,sub:q<30?"Undervalued zone":q>150?"Overvalued zone":"Normal range",tip:"Network Value to Transactions ratio. Compares market cap to annualized transaction volume. Below 30 = undervalued relative to usage. Above 150 = potentially overvalued. Think of it like P/E ratio for Bitcoin."})}if(i.marketCap){var H=i.marketCap/.62;(i.marketCap/H*100).toFixed(1),u.push({emoji:"👑",name:"BTC Dominance",value:"~62%",sub:"Market cap share vs all crypto",tip:"Bitcoin's share of the total cryptocurrency market cap. Higher dominance = Bitcoin is outperforming alts. During alt seasons, dominance drops below 40%. During Bitcoin seasons (now), it rises above 55-65%. Historically, increasing dominance signals strength.",id:"btcDominance"})}if(u.push({emoji:"💎",name:"MVRV Z-Score",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Market Value to Realized Value ratio. Compares market cap to realized cap (sum of each coin valued at its last move price). Above 3.0 historically marks cycle tops. Below 1.0 marks bottoms. Data from CBBI open-source API. Top threshold: normalized ≥ 0.7 (≈ MVRV 3+).",id:"mvrvScore"}),a){var D=new Date("2009-01-03T00:00:00Z"),O=Math.floor((Date.now()-D.getTime())/864e5),j=5.82*Math.log10(O)-17.01,R=Math.pow(10,j),W=((a-R)/R*100).toFixed(0),F=parseFloat(W),V=F>200?"#ef4444":F>100?"#f97316":F<-30?"#22c55e":"var(--heading)",G=F>200,Q=F>200?"Far above — extreme ⚠️":F>100?"Above trend — elevated":F>0?"Above fair value":F>-30?"Near fair value":"Below trend — deep value 🟢";u.push({emoji:"📏",name:"Power Law",value:(F>=0?"+":"")+W+"%",color:V,sub:"Fair value: ~$"+p(Math.round(R))+" · "+Q,tip:"Bitcoin Power Law model tracks the long-term price trend using a log-log regression since genesis (Jan 3, 2009). Parameters: P = 10^(5.82 × log₁₀(days) - 17.01). Above +200% = historically extreme (cycle top zone). Below -30% = deep value accumulation. Current: "+O+" days since genesis.",flashing:G})}if(u.push({emoji:"🔵",name:"Pi Cycle Top",value:"...",sub:"Loading...",tip:"When the 111-day MA crosses above the 350-day MA × 2, it has historically signaled the exact top of every Bitcoin cycle. Flashes when the gap narrows to <5%.",id:"piCycleTop",flashing:!1}),r&&a){var J=(144*(i.subsidy?parseFloat(i.subsidy):3.125)*a/27e6).toFixed(2),Y=parseFloat(J);u.push({emoji:"⛏️",name:"Puell Multiple",value:J,color:Y>2.2?"#ef4444":Y<.5?"#22c55e":"var(--heading)",sub:Y>2.2?"Miners overleveraged ⚠️":Y<.5?"Miner capitulation zone 🟢":"Normal range",tip:"Ratio of daily miner revenue to its 365-day moving average. Above 2.2 = miners are earning far more than usual (historically a sell signal). Below 0.5 = miner capitulation (buy signal). Top threshold: ≥ 2.2.",flashing:Y>=2.2})}if(a){for(var X=new Date("2010-07-18"),K=Math.floor((Date.now()-X.getTime())/864e5),$=Math.log(K+1400),Z=[2.775,2.788,2.801,2.815,2.8295,2.8445,2.859,2.872,2.886,2.9],ee=10,te=0;te=9})}if(a){for(var ae=new Date("2009-01-03T00:00:00Z"),re=Math.floor((Date.now()-ae.getTime())/864e5),se=0,le=0;le<1460;le++){var ce=re-le;ce>365&&(se+=Math.pow(10,5.82*Math.log10(ce)-17.01))}var de=se/1460,ue=de>0?(a/de).toFixed(2):"—",pe=parseFloat(ue);u.push({emoji:"📊",name:"4-Year MA Multiple",value:ue+"x",color:pe>=3.5?"#ef4444":pe<1?"#22c55e":"var(--heading)",sub:"Est. 4Y MA: ~$"+p(Math.round(de))+(pe>=3.5?" · Top zone ⚠️":""),tip:"Price divided by the 4-year (1460-day) moving average. Historically, when price exceeds 3.5× the 4-year MA, it signals a cycle top. Below 1× = accumulation zone. Top threshold: ≥ 3.5.",flashing:pe>=3.5})}if(u.push({emoji:"💰",name:"NUPL",value:"...",color:"var(--heading)",sub:"Loading from CBBI...",tip:"Net Unrealized Profit/Loss. Shows aggregate profit/loss of all Bitcoin holders. Above 75% = euphoria (top zone). Below 0% = capitulation (bottom zone). Data from CBBI open-source API. Top threshold: normalized ≥ 0.75.",id:"nuplScore"}),a&&r){var he=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),me=Math.pow(10,5.82*Math.log10(he)-17.01),ge=me>0?(a/me).toFixed(2):"—",fe=parseFloat(ge);u.push({emoji:"🔢",name:"AHR999",value:ge,color:fe>1.2?"#ef4444":fe<.45?"#22c55e":"var(--heading)",sub:fe>1.2?"Overvalued — stop DCA ⚠️":fe<.45?"Deep value — DCA zone 🟢":fe<1?"Below model — DCA":"Near model",tip:"AHR999 compares current price to its long-term model value. Below 0.45 = extreme buy (accumulate aggressively). Above 1.2 = stop DCA, consider selling. Used by cost-averaging investors to time entries. Top threshold: ≥ 1.2.",flashing:fe>=1.2})}if(a){for(var ye=new Date("2009-01-03T00:00:00Z"),be=Math.floor((Date.now()-ye.getTime())/864e5),ve=0,we=0;we<730;we++){var xe=be-we;xe>365&&(ve+=Math.pow(10,5.82*Math.log10(xe)-17.01))}var ke=ve/730,Be=5*ke,Se=a>Be;u.push({emoji:"📉",name:"2-Year MA ×5",value:(a/ke).toFixed(2)+"x",color:Se?"#ef4444":a365&&(Ie+=Math.pow(10,5.82*Math.log10(Ae)-17.01))}var Ee=Ie/350,ze=Ee>0?(a/Ee).toFixed(2):"—",Le=parseFloat(ze),Me=Le>=8?"Above ×8 — max top ⚠️":Le>=5?"Above ×5 — overheated":Le>=3?"Above ×3 — elevated":Le>=1.6?"Above ×1.6 — bullish":"Below ×1.6";u.push({emoji:"🔱",name:"Golden Ratio",value:ze+"x",color:Le>=5?"#ef4444":Le>=3?"#f97316":"var(--heading)",sub:"350d MA: $"+p(Math.round(Ee))+" · "+Me,tip:"Price relative to the 350-day MA using Fibonacci golden ratio multiples (1.6, 2, 3, 5, 8, 13, 21). Each cycle top has touched a lower multiple. Top threshold: ≥ 5×.",flashing:Le>=5})}if(r&&s&&a){for(var Pe=0,Ue=r,qe=0;qe<=Math.floor(r/21e4)&&Ue>0;qe++){var Ne=Math.min(Ue,21e4);Pe+=Ne*(50/Math.pow(2,qe)),Ue-=Ne}var He=21*(s>0?3e4*Pe/s:0),De=He>0?(a/He*100).toFixed(0):"—";u.push({emoji:"🎯",name:"Terminal Price",value:"$"+p(Math.round(He)),color:a>=He?"#ef4444":"var(--heading)",sub:"Current: "+De+"% of terminal · "+(a>=He?"ABOVE — extreme ⚠️":"Below terminal"),tip:"Terminal Price = Transferred Price × 21. Represents a theoretical maximum based on cumulative miner revenue and coin movement. Every cycle top has approached or exceeded this level. Top threshold: price ≥ Terminal Price.",flashing:a>=He})}if(a){var Oe=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),je=Math.pow(10,5.82*Math.log10(Oe)-17.01),Re=(je>0?(Math.log10(a)-Math.log10(je))/.3:0).toFixed(1),We=parseFloat(Re);u.push({emoji:"🫧",name:"Bubble Index",value:Re+"σ",color:We>=2?"#ef4444":We>=1?"#f97316":We<-1?"#22c55e":"var(--heading)",sub:We>=2?"Extreme bubble ⚠️":We>=1?"Elevated":We<-1?"Deep discount 🟢":"Normal",tip:"How many standard deviations Bitcoin's price is above its long-term log trend. Above +2σ = extreme bubble territory (historical tops). Below -1σ = deep value. Top threshold: ≥ 2σ.",flashing:We>=2})}if(a){var Fe=Math.floor((Date.now()-new Date("2009-01-03").getTime())/864e5),Ve=Math.pow(10,5.82*Math.log10(Fe-90)-17.01),Ge=(Ve>0?100*(Math.pow(a/Ve,4)-1):0).toFixed(0),Qe=parseFloat(Ge);u.push({emoji:"🚀",name:"3M Annualized",value:(Qe>=0?"+":"")+Ge+"%",color:Qe>200?"#ef4444":Qe>100?"#f97316":"var(--heading)",sub:Qe>200?"Unsustainable — top risk ⚠️":Qe>100?"Very high":"Normal",tip:"3-month return annualized. When Bitcoin is gaining over 200% annualized, it historically signals the late stages of a bull run. Top threshold: > 200%.",flashing:Qe>200,id:"ann3m"})}if(a){var Je=75694,Ye=762099,Xe=((a-Je)/Je*100).toFixed(1);u.push({emoji:"🏢",name:"MSTR Avg Cost",value:"$"+p(Je),sub:p(Ye)+" BTC · P&L: "+(Xe>=0?"+":"")+Xe+"%",tip:"MicroStrategy (MSTR) average Bitcoin acquisition cost. When price is far above MSTR's cost basis, it indicates broader market euphoria. MSTR holds "+p(Ye)+" BTC. Informational — no top threshold.",flashing:!1,noFlashLogic:!0})}if(u.push({emoji:"🎯",name:"CBBI Index",value:"...",color:"var(--heading)",sub:"Loading CBBI data...",tip:"Colin Talks Crypto Bitcoin Bull Run Index. Combines 9 on-chain metrics into a single 0-100 confidence score. Above 80 = approaching cycle top. Below 20 = approaching bottom. Open source. Top threshold: ≥ 80.",id:"cbbiScore"}),u.push({emoji:"💎",name:"RHODL Ratio",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Realized HODL Ratio. Compares 1-week realized value to 1-2 year realized value, adjusted by market age. High values = speculative activity dominating (top signal). Low values = long-term holders dominating. Top threshold: normalized ≥ 0.85.",id:"rhodlRatio"}),u.push({emoji:"📊",name:"Macro Oscillator",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Bitcoin Macro Oscillator (Woobull). Composite z-score of MVRV, VWAP, CVDD, and Sharpe ratios. Above 0.7 = euphoria zone. Below 0.2 = accumulation zone. Top threshold: normalized ≥ 0.7.",id:"macroOsc"}),a){var Ke=23e4,$e=(a/Ke*100).toFixed(1);u.push({emoji:"🔮",name:"Smithson's Forecast",value:$e+"%",color:parseFloat($e)>=90?"#ef4444":"var(--heading)",sub:"Target: $"+p(175e3)+"-$"+p(Ke)+" · Current: $"+p(Math.round(a)),tip:"Sminston With quantile regression model (99th percentile). Forecasts cycle top at $175K-$230K. Progress shows how close current price is to the upper target. Top threshold: ≥ 90% of target.",flashing:parseFloat($e)>=90})}u.push({emoji:"⏳",name:"LTH/STH Ratio",value:"...",color:"var(--heading)",sub:"Estimated from CBBI data...",tip:"Long-Term Holder to Short-Term Holder supply ratio (estimated). When LTH supply drops sharply (distributing to STH), it signals late-cycle selling. When LTH supply grows, holders are accumulating. Derived from CBBI on-chain metrics. Top threshold: CBBI MVRV + Puell both > 0.7.",id:"lthSthRatio"}),u.push({emoji:"📉",name:"RSI-22 Day",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Relative Strength Index over 22 days. Above 80 = overbought (potential top signal). Below 30 = oversold (potential bottom). 22-day RSI smooths out short-term noise. Top threshold: ≥ 80.",id:"rsi22d"}),u.push({emoji:"🚨",name:"AHR999x",value:"...",color:"var(--heading)",sub:"Loading 200d MA...",tip:"AHR999x Escape Top indicator. Calculated as (price / 200-day MA)². When above 8, signals extreme overvaluation. Above 3.5 = elevated. A complement to the AHR999 DCA indicator. Top threshold: ≥ 8.",id:"ahr999x"}),u.push({emoji:"🏦",name:"ETF/BTC Ratio",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Bitcoin spot ETF total AUM divided by BTC market cap. Shows how much of Bitcoin's value is held in ETFs. High ratios (>8%) could indicate institutional overexposure. Low ratios = room to grow. Top threshold: ≥ 8%.",id:"etfBtcRatio"}),u.push({emoji:"📊",name:"ETF Net Flow",value:"...",color:"var(--heading)",sub:"Loading ETF data...",tip:"Daily Bitcoin spot ETF net inflows/outflows. Sustained outflows (7+ days) can signal institutional selling. Sustained inflows signal demand. Data from Bitbo/BitcoinTreasuries. Top threshold: 7+ consecutive outflow days.",flashing:!1,id:"etfNetFlow"}),u.push({emoji:"📈",name:"ETF 5-Day Flow",value:"...",color:"var(--heading)",sub:"Loading...",tip:"Sum of last 5 trading days of ETF flows. Large negative = sustained selling pressure. Large positive = accumulation. Top threshold: 5-day sum below -$500M.",flashing:!1,id:"etf5dFlow"}),u.forEach(function(e){if(!e.noFlashLogic&&void 0===e.flashing){var t=e.name;e.flashing="Stock-to-Flow"===t?a>0&&f>0&&a>1.5*f:"Fear & Greed"===t?l>=75:"Mayer Multiple"!==t&&("Halving Cycle"===t?e.sub&&-1!==e.sub.indexOf("Peak Window"):"ATH Drawdown"===t?parseFloat(e.value)>-5:"Thermo Multiple"===t?parseFloat(e.value)>5:"NVT Ratio"===t&&parseFloat(e.value)>150)}});var Ze=u.filter(function(e){return e.flashing}).length,et=u.filter(function(e){return!e.noFlashLogic}).length,tt="",ot=et>0?Math.round(Ze/et*100):0,nt=0===Ze?"#22c55e":ot<15?"#eab308":ot<40?"#f97316":"#ef4444";tt+='
    ',tt+='
    '+Ze+" / "+et+"
    ",tt+='
    '+(0===Ze?"No top signals — Accumulate 🟢":ot<15?"Few signals — Monitor 🟡":ot<40?"Multiple signals — Caution 🟠":"Many signals — Extreme caution 🔴")+"
    ",tt+='
    Top indicators flashing 🔴 = potential cycle top signal
    ',tt+="
    ",u.forEach(function(e){var t=e.flashing?"rgba(239,68,68,0.5)":"var(--border)",o=e.flashing?"background:rgba(239,68,68,0.04);":"";tt+="",e.noFlashLogic||(e.flashing?tt+='
    🔴 TOP
    ':tt+='
    🟢 OK
    '),tt+='
    '+e.emoji+" "+e.name+(e.tip?' ':"")+"
    ",tt+='
    '+(e.value||"—")+"
    ",e.sub&&(tt+='
    '+e.sub+"
    "),tt+=""}),tt+='',e.innerHTML=tt,setTimeout(function(){"function"==typeof window._attachTipListeners&&window._attachTipListeners()},50);try{localStorage.setItem(x,JSON.stringify({html:tt,ts:Date.now()}))}catch(e){}fetch("https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=365&interval=daily").then(function(e){return e.json()}).then(function(e){if(e&&e.prices&&e.prices.length>=200){for(var t=e.prices,o=t.length,n=0,i=Math.max(0,o-200);i2.4?"#ef4444":"var(--heading)";l.style.color=c,l.textContent=s+"x";var d=l.nextElementSibling;d&&(d.textContent="200d MA: $"+p(Math.round(a))+(s<1?" · Below MA ✅":s>2.4?" · Overheated ⚠️":""));var u=l.closest('div[style*="border-radius:12px"]');if(u&&s>2.4){u.style.borderColor="rgba(239,68,68,0.5)",u.style.background="rgba(239,68,68,0.04)";var h=u.querySelector('div[style*="OK"]');h&&(h.innerHTML="🔴 TOP",h.style.color="#ef4444",h.style.background="rgba(239,68,68,0.15)",h.style.borderColor="rgba(239,68,68,0.4)")}}if(o>=111){for(var m=0,g=o-111;g0?((f-w)/w*100).toFixed(1):0,k=parseFloat(x),B=document.getElementById("piCycleTop");if(B){var S=k>=0;B.textContent=(k>=0?"+":"")+x+"%",B.style.color=S?"#ef4444":k>-5?"#f97316":"var(--heading)";var T=B.nextElementSibling;T&&(T.textContent="111d: $"+p(Math.round(f))+" vs 350d×2: $"+p(Math.round(w))+(S?" · CROSSED ⚠️":k>-5?" · Narrowing!":""));var _=B.closest('div[style*="border-radius:12px"]');if(_&&S){_.style.borderColor="rgba(239,68,68,0.5)",_.style.background="rgba(239,68,68,0.04)";var I=_.querySelector('div[style*="OK"]');I&&(I.innerHTML="🔴 TOP",I.style.color="#ef4444",I.style.background="rgba(239,68,68,0.15)",I.style.borderColor="rgba(239,68,68,0.4)")}}}if(o>=23){for(var C=0,A=0,E=o-22;E0?C+=z:A-=z}var L=A/22,M=0===L?100:100-100/(1+C/22/L),P=M.toFixed(1),U=document.getElementById("rsi22d");if(U){var q=M>=80;U.textContent=P,U.style.color=M>=80?"#ef4444":M<=30?"#22c55e":"var(--heading)";var N=U.nextElementSibling;if(N&&(N.textContent=M>=80?"Overbought ⚠️":M<=30?"Oversold ✅":M>=60?"Bullish":M<=40?"Bearish":"Neutral"),q){var H=U.closest('div[style*="border-radius:12px"]');if(H){H.style.borderColor="rgba(239,68,68,0.5)",H.style.background="rgba(239,68,68,0.04)";var D=H.querySelector('div[style*="OK"]');D&&(D.innerHTML="🔴 TOP",D.style.color="#ef4444",D.style.background="rgba(239,68,68,0.15)",D.style.borderColor="rgba(239,68,68,0.4)")}}}}var O=Math.pow(r/a,2).toFixed(2),j=document.getElementById("ahr999x");if(j){var R=parseFloat(O),W=R>=8;j.textContent=O,j.style.color=R>=8?"#ef4444":R>=3.5?"#f97316":"var(--heading)";var F=j.nextElementSibling;if(F&&(F.textContent="200d MA: $"+p(Math.round(a))+(R>=8?" · Extreme top ⚠️":R>=3.5?" · Elevated":R<1?" · Below MA":" · Normal")),W){var V=j.closest('div[style*="border-radius:12px"]');if(V){V.style.borderColor="rgba(239,68,68,0.5)",V.style.background="rgba(239,68,68,0.04)";var G=V.querySelector('div[style*="OK"]');G&&(G.innerHTML="🔴 TOP",G.style.color="#ef4444",G.style.background="rgba(239,68,68,0.15)",G.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("mayerMultiple");e&&(e.textContent="N/A")}),fetch("https://api.coingecko.com/api/v3/global").then(function(e){return e.json()}).then(function(e){if(e&&e.data&&e.data.market_cap_percentage&&e.data.market_cap_percentage.btc){var t=e.data.market_cap_percentage.btc.toFixed(1),o=document.getElementById("btcDominance");if(o){o.textContent=t+"%";var n=t>55?"#22c55e":t<40?"#ef4444":"var(--heading)";o.style.color=n;var i=o.nextElementSibling;i&&(i.textContent=t>55?"Bitcoin season 👑":t<40?"Alt season ⚠️":"Neutral")}}}).catch(function(){}),fetch("https://colintalkscrypto.com/cbbi/data/latest.json").then(function(e){return e.json()}).then(function(e){if(e&&e.Confidence){var t=Object.keys(e.Confidence).sort(),o=t[t.length-1],n=(100*e.Confidence[o]).toFixed(0),i=parseInt(n),a=document.getElementById("cbbiScore");if(a){a.textContent=n+"%",a.style.color=i>=80?"#ef4444":i<=20?"#22c55e":"var(--heading)";var r=a.nextElementSibling;if(r&&(r.textContent=i>=80?"Approaching top ⚠️":i<=20?"Approaching bottom 🟢":i>=50?"Mid-cycle bullish":"Early cycle"),i>=80){var s=a.closest('div[style*="border-radius:12px"]');if(s){s.style.borderColor="rgba(239,68,68,0.5)",s.style.background="rgba(239,68,68,0.04)";var l=s.querySelector('div[style*="OK"]');l&&(l.innerHTML="🔴 TOP",l.style.color="#ef4444",l.style.background="rgba(239,68,68,0.15)",l.style.borderColor="rgba(239,68,68,0.4)")}}}var c=Object.keys(e.RHODL).sort(),d=e.RHODL[c[c.length-1]],u=document.getElementById("rhodlRatio");if(u){u.textContent=(100*d).toFixed(0)+"%",u.style.color=d>=.85?"#ef4444":d<=.2?"#22c55e":"var(--heading)";var p=u.nextElementSibling;if(p&&(p.textContent=d>=.85?"Speculative frenzy ⚠️":d<=.2?"Accumulation zone 🟢":"Normalized: "+(100*d).toFixed(0)+"%"),d>=.85){var h=u.closest('div[style*="border-radius:12px"]');if(h){h.style.borderColor="rgba(239,68,68,0.5)",h.style.background="rgba(239,68,68,0.04)";var m=h.querySelector('div[style*="OK"]');m&&(m.innerHTML="🔴 TOP",m.style.color="#ef4444",m.style.background="rgba(239,68,68,0.15)",m.style.borderColor="rgba(239,68,68,0.4)")}}}var g=Object.keys(e.Woobull).sort(),f=e.Woobull[g[g.length-1]],y=document.getElementById("macroOsc");if(y){y.textContent=(100*f).toFixed(0)+"%",y.style.color=f>=.7?"#ef4444":f<=.2?"#22c55e":"var(--heading)";var b=y.nextElementSibling;if(b&&(b.textContent=f>=.7?"Euphoria zone ⚠️":f<=.2?"Accumulation 🟢":"Normalized: "+(100*f).toFixed(0)+"%"),f>=.7){var v=y.closest('div[style*="border-radius:12px"]');if(v){v.style.borderColor="rgba(239,68,68,0.5)",v.style.background="rgba(239,68,68,0.04)";var w=v.querySelector('div[style*="OK"]');w&&(w.innerHTML="🔴 TOP",w.style.color="#ef4444",w.style.background="rgba(239,68,68,0.15)",w.style.borderColor="rgba(239,68,68,0.4)")}}}var x=Object.keys(e.MVRV).sort(),k=Object.keys(e.Puell).sort(),B=e.MVRV[x[x.length-1]],S=e.Puell[k[k.length-1]],T=document.getElementById("lthSthRatio");if(T){var _=((B+S)/2*100).toFixed(0),I=parseInt(_);T.textContent=I+"%",T.style.color=I>=70?"#ef4444":I<=25?"#22c55e":"var(--heading)";var C=T.nextElementSibling;if(C&&(C.textContent=I>=70?"LTH distributing ⚠️":I<=25?"LTH accumulating 🟢":"Distribution score: "+I+"%"),I>=70){var A=T.closest('div[style*="border-radius:12px"]');if(A){A.style.borderColor="rgba(239,68,68,0.5)",A.style.background="rgba(239,68,68,0.04)";var E=A.querySelector('div[style*="OK"]');E&&(E.innerHTML="🔴 TOP",E.style.color="#ef4444",E.style.background="rgba(239,68,68,0.15)",E.style.borderColor="rgba(239,68,68,0.4)")}}}var z=document.getElementById("mvrvScore");if(z){var L=(100*B).toFixed(0);z.textContent=L+"%",z.style.color=B>=.7?"#ef4444":B<=.2?"#22c55e":"var(--heading)";var M=z.nextElementSibling;if(M&&(M.textContent=B>=.7?"Overvalued — top zone ⚠️":B<=.2?"Undervalued — accumulate 🟢":"Normalized: "+L+"%"),B>=.7){var P=z.closest('div[style*="border-radius:12px"]');if(P){P.style.borderColor="rgba(239,68,68,0.5)",P.style.background="rgba(239,68,68,0.04)";var U=P.querySelector('div[style*="OK"]');U&&(U.innerHTML="🔴 TOP",U.style.color="#ef4444",U.style.background="rgba(239,68,68,0.15)",U.style.borderColor="rgba(239,68,68,0.4)")}}}var q=Object.keys(e.RUPL).sort(),N=e.RUPL[q[q.length-1]],H=document.getElementById("nuplScore");if(H){var D=(100*N).toFixed(0);H.textContent=D+"%",H.style.color=N>=.75?"#ef4444":N<=.2?"#22c55e":"var(--heading)";var O=H.nextElementSibling;if(O&&(O.textContent=N>=.75?"Euphoria ⚠️":N<=.2?"Capitulation zone 🟢":"Normalized: "+D+"%"),N>=.75){var j=H.closest('div[style*="border-radius:12px"]');if(j){j.style.borderColor="rgba(239,68,68,0.5)",j.style.background="rgba(239,68,68,0.04)";var R=j.querySelector('div[style*="OK"]');R&&(R.innerHTML="🔴 TOP",R.style.color="#ef4444",R.style.background="rgba(239,68,68,0.15)",R.style.borderColor="rgba(239,68,68,0.4)")}}}var W=Object.keys(e.ReserveRisk).sort();e.ReserveRisk[W[W.length-1]];try{localStorage.setItem("cbbi_cache",JSON.stringify({ts:Date.now(),confidence:n,rhodl:d,woobull:f,mvrv:B,puell:S}))}catch(e){}}}).catch(function(){try{var e=JSON.parse(localStorage.getItem("cbbi_cache"));if(e&&Date.now()-e.ts<864e5){var t=document.getElementById("cbbiScore");t&&(t.textContent=e.confidence+"%")}}catch(e){}}),fetch("data/etf-flows.json?v="+Math.floor(Date.now()/36e5)).then(function(e){return e.json()}).then(function(e){if(e&&e.latestFlow){var t=document.getElementById("etfNetFlow");if(t){var o=e.latestFlow,n=(o>=0?"+":"")+o.toFixed(1)+"M";t.textContent=n,t.style.color=o>0?"#22c55e":o<-100?"#ef4444":o<0?"#f97316":"var(--heading)";var i=t.nextElementSibling;if(i&&(i.textContent=e.latestDate+" · "+e.outflowDays+"/"+e.totalDays+" outflow days"+(e.outflowDays>=7?" ⚠️":"")),e.outflowDays>=7){var a=t.closest('div[style*="border-radius:12px"]');if(a){a.style.borderColor="rgba(239,68,68,0.5)",a.style.background="rgba(239,68,68,0.04)";var r=a.querySelector('div[style*="OK"]');r&&(r.innerHTML="🔴 TOP",r.style.color="#ef4444",r.style.background="rgba(239,68,68,0.15)",r.style.borderColor="rgba(239,68,68,0.4)")}}}var s=document.getElementById("etf5dFlow");if(s){var l=e.sum5d;s.textContent=(l>=0?"+":"")+l.toFixed(1)+"M",s.style.color=l>100?"#22c55e":l<-500?"#ef4444":l<0?"#f97316":"var(--heading)";var c=s.nextElementSibling;if(c&&(c.textContent="5-day total"+(l<-500?" · Heavy selling ⚠️":l>500?" · Strong inflows 🟢":"")),l<-500){var d=s.closest('div[style*="border-radius:12px"]');if(d){d.style.borderColor="rgba(239,68,68,0.5)",d.style.background="rgba(239,68,68,0.04)";var u=d.querySelector('div[style*="OK"]');u&&(u.innerHTML="🔴 TOP",u.style.color="#ef4444",u.style.background="rgba(239,68,68,0.15)",u.style.borderColor="rgba(239,68,68,0.4)")}}}var p=M;try{var h=JSON.parse(localStorage.getItem("btc_etf_holdings_cache"));h&&h.totalBtc&&(p=h.totalBtc)}catch(e){}var m=parseFloat(localStorage.getItem("btc_last_price"))||83e3,g=p*m,f=1984e4*m,y=f>0?(g/f*100).toFixed(1):"—",b=document.getElementById("etfBtcRatio");if(b){var v=parseFloat(y);b.textContent=y+"%",b.style.color=v>=8?"#ef4444":"var(--heading)";var w=b.nextElementSibling;if(w&&(w.textContent="ETF AUM: ~$"+(g/1e9).toFixed(0)+"B / Mkt Cap: ~$"+(f/1e12).toFixed(2)+"T"+(v>=8?" · High exposure ⚠️":"")),v>=8){var x=b.closest('div[style*="border-radius:12px"]');if(x){x.style.borderColor="rgba(239,68,68,0.5)",x.style.background="rgba(239,68,68,0.04)";var k=x.querySelector('div[style*="OK"]');k&&(k.innerHTML="🔴 TOP",k.style.color="#ef4444",k.style.background="rgba(239,68,68,0.15)",k.style.borderColor="rgba(239,68,68,0.4)")}}}}}).catch(function(){var e=document.getElementById("etfNetFlow");e&&(e.textContent="N/A")})}}}var B=null,S=0,T=212582*32150.7;function _(e,t,o){var n=e*T/1e12,i=t>0?(t/n*100).toFixed(1):"—",a=o>0?Math.round(1e12*n/o):"—",r=document.getElementById("goldMktCapLabel");r&&(r.textContent="$"+n.toFixed(1)+"T");var s=document.getElementById("goldBar");s&&(s.style.width=Math.min(parseFloat(i)||0,100)+"%");var l=document.getElementById("goldPctArea");l&&(l.innerHTML='
    '+i+'% of Gold Market Cap
    BTC needs ~$'+("number"==typeof a?p(a):a)+'/coin to match Gold
    Gold: $'+p(Math.round(e))+"/oz · Live via CoinGecko
    ");var c=document.getElementById("goldCompareCard");if(c){var d="Gold has been humanitys store of value for 5,000+ years. Bitcoin is digital gold — scarce, durable, portable, divisible, and verifiable. Gold price: $"+p(Math.round(e))+"/oz. Total above-ground gold: ~212,582 tonnes (~6.83B troy oz). Gold market cap: ~$"+n.toFixed(1)+"T. The flippening = Bitcoin absorbs golds entire monetary premium.";c.setAttribute("data-dash-tip",d),"function"==typeof window._attachTipListeners&&window._attachTipListeners()}}var I=null,C=0,A=[{name:"🇺🇸 United States",btc:325293},{name:"🇨🇳 China",btc:19e4},{name:"🇬🇧 United Kingdom",btc:61245},{name:"🇧🇹 Bhutan",btc:10635},{name:"🇸🇻 El Salvador",btc:6135}],E=649864;function z(e,t,o){var n=(t.companies||[]).slice(0,5),i=Math.round(t.total_holdings||0),a=t.total_value_usd||0,r=o||(i>0?a/i:0),s=n.map(function(e){return'
    '+(e.name||"?")+''+p(e.total_holdings)+" BTC
    "}).join(""),l=A.map(function(e){return'
    '+e.name+''+p(e.btc)+" BTC
    "}).join(""),c=i+E;e.innerHTML='
    🏢 Public Companies
    '+p(i)+'
    BTC · ~'+h(a||i*r)+'
    🏛️ Governments
    '+p(E)+'
    BTC · ~'+h(E*r)+'
    Total: '+p(c)+" BTC ("+(c/21e6*100).toFixed(1)+'% of supply)
    TOP 5 COMPANIES
    '+s+'
    TOP 5 GOVERNMENTS
    '+l+'
    Companies: live via CoinGecko · Governments: bitcointreasuries.net
    ';var d=document.getElementById("treasuryCard");d&&d.removeAttribute("onclick")}var L=[{ticker:"IBIT",name:"BlackRock",btc:787044,color:"#6366f1"},{ticker:"FBTC",name:"Fidelity",btc:213399,color:"#22c55e"},{ticker:"GBTC",name:"Grayscale",btc:180584,color:"#eab308"},{ticker:"ARKB",name:"ARK 21Shares",btc:63920,color:"#f97316"},{ticker:"BITB",name:"Bitwise",btc:53930,color:"#06b6d4"}],M=1367239;function P(e,t,o,n,i,a){var r=o*n,s=(o/i*100).toFixed(1),l=t[0].btc,c=t.map(function(e){var t=Math.max(4,e.btc/l*100).toFixed(0),o=h(e.btc*n);return'
    '+e.ticker+' '+e.name+''+p(e.btc)+' BTC
    '+o+"
    "}).join(""),d="";if(a){var u=Math.round((Date.now()-new Date(a).getTime())/36e5);d=u<1?"Updated just now":u<24?"Updated "+u+"h ago":"Updated "+Math.round(u/24)+"d ago"}e.innerHTML='
    '+p(o)+' BTC
    ~'+h(r)+" AUM · "+s+'% of supply held in ETFs
    '+c+'
    Data: SEC filings + CoinGlass'+(d?" · "+d:"")+"
    "}var U=null;window._startHalvingTicker=function(){U&&clearInterval(U),U=setInterval(function(){if(window._halvingTargetMs){var e=document.getElementById("halvSecs");if(!e)return clearInterval(U),void(U=null);var t=Math.max(0,window._halvingTargetMs-Date.now()),o=Math.floor(t/1e3),n=Math.floor(o/86400),i=Math.floor(o%86400/3600),a=Math.floor(o%3600/60),r=o%60,s=document.getElementById("halvDays"),l=document.getElementById("halvHours"),c=document.getElementById("halvMins");s&&(s.textContent=n),l&&(l.textContent=i),c&&(c.textContent=a),e.textContent=r<10?"0"+r:r}},1e3)}}(),function(){if(window._sessionStart=window._sessionStart||Date.now(),window._cleanUrl=function(e){if(!e)return"/";var t=window.location.pathname;return t==="/"+e||t==="/app/"+e?t:"#"+e},window._parseCleanUrl=function(){var e,t=window.location.pathname;return(e=t.match(/^\/channels\/(.+)$/))||(e=t.match(/^\/app\/(.+)$/))?e[1]:"/timechain-tv"===t||"/tv"===t?"timechain-tv":"/meetup-builder"===t?"meetup-builder":"/irl-sync"===t||"/meet"===t?"irl-sync":"/forum"===t?"forum":"/marketplace"===t?"marketplace":"/bitcoin-beats"===t||"/beats"===t?"bitcoin-beats":"/chat"===t?"chat":"/pvp"===t?"pvp":window.location.hash.replace("#","")||null},!document.getElementById("lb")){var e=document.createElement("div");e.id="lb",e.onclick=function(){document.getElementById("lb").classList.remove("open")},e.innerHTML='',document.body.appendChild(e)}function t(e){document.getElementById("lb-img").src=e,document.getElementById("lb").classList.add("open")}function o(){return window.innerWidth<=900}function n(){const e="light"!==document.body.getAttribute("data-theme");document.body.setAttribute("data-theme",e?"light":"dark"),localStorage.setItem("theme",e?"light":"dark");const t=document.getElementById("themeBtn");t&&(t.textContent=e?"☀️":"🌙");const o=document.getElementById("mobileThemeBtn");o&&(o.textContent=e?"☀️":"🌙")}function i(){var e=document.getElementById("sidebar");e&&(e.classList.toggle("open"),"function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!e.classList.contains("open")))}function a(){var e=document.getElementById("sidebar");if(e){var t=e.classList.toggle("sidebar-collapsed");try{localStorage.setItem("sidebar-collapsed",t?"1":"0")}catch(e){}}}function r(e){var t=e.nextElementSibling;if(t){var o=e.querySelector(".cat-arrow");"true"===e.getAttribute("data-expanded")?(t.style.display="none",e.setAttribute("data-expanded","false"),o&&(o.textContent="▶")):(t.style.display="",e.setAttribute("data-expanded","true"),o&&(o.textContent="▼"))}}function s(e){if(e){var t=e.closest(".cat-group");if(t&&"none"===t.style.display){var o=t.previousElementSibling;if(o&&o.classList.contains("cat-toggle")){t.style.display="",o.setAttribute("data-expanded","true");var n=o.querySelector(".cat-arrow");n&&(n.textContent="▼")}}}}function l(){return safeJSON("btc_favs",[])}function c(){var e=document.getElementById("favsList"),t=document.getElementById("favsSection");if(e){var o=l(),n=safeJSON("btc_bookmarks",[]);if(!(o.length>0||n.length>0))return e.innerHTML="",(i=document.getElementById("bookmarksList"))&&(i.innerHTML=""),void(t&&(t.style.display="none"));t&&(t.style.display="block");var i,a="";if(o.forEach(function(e){var t=void 0!==CHANNELS?CHANNELS[e]:null,o=t?(t.emoji||"")+" "+(t.name||e):e;a+="
    "+o+"
    "}),e.innerHTML=a,i=document.getElementById("bookmarksList"))if(0===n.length)i.innerHTML="";else{var r='
    🔖 Bookmarked Messages
    ';n.slice(0,15).forEach(function(e){var t=void 0!==CHANNELS&&CHANNELS[e.channel]?CHANNELS[e.channel]:null,o=t?(t.emoji||"")+" "+(t.name||e.channel):e.channel;r+="
    🔖 "+o+"
    "}),i.innerHTML=r}}}function d(e,t){let o=l();if(o.includes(e))o=o.filter(t=>t!==e),t&&(t.innerHTML="☆ Save");else{o.push(e),t&&(t.innerHTML="⭐ Saved");try{var n=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_fav_added_"+n,"true")}catch(e){}}var i;i=o,localStorage.setItem("btc_favs",JSON.stringify(i)),c(),"function"==typeof syncFavsToFirebase&&syncFavsToFirebase()}!function(){try{if(window.innerWidth>900&&"1"===localStorage.getItem("sidebar-collapsed")){var e=document.getElementById("sidebar");e&&e.classList.add("sidebar-collapsed")}}catch(e){}}();let u=!1,p=null,h=null;function m(e){u=!u;const t=document.getElementById("galleryBtn");t&&(t.classList.toggle("active",u),t.textContent=u?"📄 List View":"🖼️ Gallery View"),g(e)}function g(e){const t=p;if(!t)return;const n=document.getElementById("msgs");if(u){let e=[];t.msgs.forEach(t=>{t.imgs&&t.imgs.forEach(t=>e.push(t))});let i='",e.length>a&&(window._galleryImgs=e,window._galleryOffset=a,i+='"),n.innerHTML=i}else{const i=o()?20:50,a=t.msgs;let r=function(){const t=a.slice(0,0+i);let n="";{const t=void 0!==CHANNELS?CHANNELS[e]:null;t&&t.desc&&(n+='
    🦌
    Nacho\'s Summary
    '+t.desc+"
    ")}return t.forEach((t,i)=>{if(n+='
    ',t.text){let e=t.text,i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return i.push(t),"%%YT"+(i.length-1)+"%%"});let a=[];e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){const t=e.startsWith("http")?e:"https://"+e;return a.push(t),"%%TW"+(a.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){const n=a[parseInt(t)],i="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),l=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+l+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),n+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?n+='':n+=''});var a=0+i,r=safeJSON("btc_bookmarks",[]).some(function(t){return t.channel===e&&t.idx===a});n+="',n+="
    "}),n}();a.length>i&&(r+='"),n.innerHTML=r,window._currentMsgs=a,window._currentOffset=i}window._sidebarOrder||(window._sidebarOrder=[...document.querySelectorAll(".ch-btn")].map(e=>{const t=e.getAttribute("onclick").match(/go\('([^']+)'/);return t?t[1]:null}).filter(Boolean));const i=window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),a=i.indexOf(e),r=a0?i[a-1]:i[i.length-1]);CHANNELS[s]&&CHANNELS[s].title;let l='
    ';l+="',l+='',l+='',l+='',l+='',l+="',l+="
    ",l+='
    ',l+='',l+="
    ","function"==typeof renderReadNext&&(l+=renderReadNext(e)),l+='
    Disclaimer
    This Bitcoin education is presented authentically and from a first-principles standpoint that maximizes truth. However, this is not financial, investment, legal, or tax advice and anyone reading this material should still verify its validity by doing their own research. Bitcoin is volatile and you can lose money. Bitcoin Education Archive, its operators, and contributors make no warranty regarding the accuracy, completeness, or timeliness of any educational content and accept no liability for decisions made based on it. Always consult a licensed professional before making financial decisions. Terms · Privacy
    ',n.innerHTML+=l,n.classList.add("fade-in")}let f=!1;function y(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML='
    Loading tweet...
    ',f)b(e,t);else{const o=document.createElement("script");o.src="https://platform.twitter.com/widgets.js",o.async=!0,o.onload=function(){f=!0,b(e,t)},document.head.appendChild(o)}}function b(e,t){const o=document.getElementById(e);if(o)if(o.innerHTML="",window.twttr&&window.twttr.widgets){const e=t.match(/status\/(\d+)/);if(e){const n=document.createElement("div");o.appendChild(n),twttr.widgets.createTweet(e[1],n,{theme:"light"===document.body.getAttribute("data-theme")?"light":"dark",align:"center",conversation:"none",width:500}).then(function(e){e||(o.innerHTML='')})}}else o.innerHTML=''}async function v(){window._keepFloatingBtn=!0;const e=Object.keys(CHANNELS);window._randomChannelHistory||(window._randomChannelHistory=[]);var t=e.filter(function(e){return-1===window._randomChannelHistory.indexOf(e)});0===t.length&&(window._randomChannelHistory.length=0,t=e);const o=t[Math.floor(Math.random()*t.length)];window._randomChannelHistory.push(o),window._randomChannelHistory.length>Math.floor(.3*e.length)&&window._randomChannelHistory.shift(),await go(o),window._keepFloatingBtn=!1,S("__random__","🎲","Next Random Channel")}async function w(e,t,o){window._keepFloatingBtn=!0;const n=CHANNELS[e];if(!n)return void(window._keepFloatingBtn=!1);let i;if(G[e])i=G[e];else try{const t=await fetch(n.file);i=await t.json(),G[e]=i}catch(e){return}const a=i.msgs.length>1?i.msgs.slice(1):i.msgs,r=[];if(a.forEach((e,t)=>{e.imgs&&e.imgs.length>0&&r.push(t)}),0!==r.length){window._randomHistory||(window._randomHistory={}),window._randomHistory[e]||(window._randomHistory[e]=[]);var s=window._randomHistory[e],l=Math.min(Math.floor(.2*r.length),50),c=r.filter(function(e){return-1===s.indexOf(e)});0===c.length&&(s.length=0,c=r);var d=c[Math.floor(Math.random()*c.length)];s.push(d),s.length>l&&s.shift();var u=a[d];if(u&&u.imgs&&u.imgs.forEach(function(e){(new Image).src=e}),await go(e),d>=50){const e=document.getElementById("loadMoreBtn");for(var p=0;window._currentOffset<=d&&e&&document.contains(e)&&p<50;)window.loadMoreMsgs(),p++}setTimeout(function(){const n=document.getElementById("msg-"+d);n&&(n.querySelectorAll('img[loading="lazy"]').forEach(function(e){e.loading="eager"}),n.scrollIntoView({behavior:"smooth",block:"center"}),n.style.transition="box-shadow 0.3s, border-color 0.3s",n.style.boxShadow="0 0 20px rgba(247,147,26,0.4)",n.style.borderColor="#f7931a",setTimeout(function(){n.style.boxShadow="",n.style.borderColor=""},2e3),window._keepFloatingBtn=!1,S(e,t,o))},300)}}function x(){return w("memes-funny","😂","Next Random Meme")}function k(){return w("art-inspiration","🎨","Next Random Art")}function B(){return w("graphics","📊","Next Random Graphic")}function S(e,t,o){var n=document.getElementById("floatingRandomBtn");n||((n=document.createElement("button")).id="floatingRandomBtn",n.style.cssText="position:fixed;bottom:140px;right:180px;z-index:150;padding:12px 20px;background:var(--accent);color:#fff;border:none;border-radius:12px;font-size:0.9rem;font-weight:700;cursor:pointer;font-family:inherit;box-shadow:0 4px 20px rgba(0,0,0,0.3);transition:0.2s;display:flex;align-items:center;gap:6px;",document.body.appendChild(n)),n.innerHTML=t+" "+o,n.onclick="__random__"===e?function(){v()}:function(){w(e,t,o)},n.style.display="flex",window.addEventListener("popstate",function e(){n.style.display="none",window.removeEventListener("popstate",e)},{once:!0})}function T(e,t){const o=e+"\n\n"+t;navigator.clipboard.writeText(o).then(()=>{showToast("📋 Note copied! Paste it in Primal to post.")}).catch(()=>{}),window.open("https://primal.net/home","_blank")}window.goRandomMeme=x,window.goRandomArt=k,window.goRandomGraphic=B,window.toggleBookmark=function(e,t,o){var n=safeJSON("btc_bookmarks",[]),i=n.findIndex(function(o){return o.channel===e&&o.idx===t});-1!==i?(n.splice(i,1),o&&(o.style.opacity="0.3",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Bookmark removed")):(n.push({channel:e,idx:t,ts:Date.now()}),o&&(o.style.opacity="1",o.innerHTML="🔖"),"function"==typeof showToast&&showToast("🔖 Saved to sidebar")),localStorage.setItem("btc_bookmarks",JSON.stringify(n)),c(),"function"==typeof syncBookmarksToFirebase&&syncBookmarksToFirebase()},window.loadMoreGallery=function(){const e=window._galleryImgs,o=window._galleryOffset,n=document.querySelector(".gallery-grid"),i=document.getElementById("loadMoreGallery");e.slice(o,o+100).forEach(e=>{const o=document.createElement("img");o.src=e,o.loading="lazy",o.onclick=function(){t(this.src)},n.appendChild(o)}),window._galleryOffset=o+100,window._galleryOffset>=e.length?i.remove():i.textContent="Load more ("+(e.length-window._galleryOffset)+" remaining)"},window.showSpinWheel=function(){var e=localStorage.getItem("btc_last_spin_date"),t=(new Date).toDateString();if(e!==t){var o=document.getElementById("spinModal");o&&o.remove();var n=document.createElement("div");n.id="spinModal",n.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.85);-webkit-overflow-scrolling:touch;overflow-y:auto;padding:20px;";var i=[{label:"🎟️ 1 Ticket",value:"ticket_1",weight:25,color:"#f7931a"},{label:"🎟️ 2 Tickets",value:"ticket_2",weight:22,color:"#ea580c"},{label:"⭐ 25 XP",value:"points_25",weight:18,color:"#22c55e"},{label:"🎟️ 3 Tickets",value:"ticket_3",weight:12,color:"#fbbf24"},{label:"⭐ 50 XP",value:"points_50",weight:8,color:"#3b82f6"},{label:"👔 Closet!",value:"closet_item",weight:5,color:"#ec4899"},{label:"🧊 Freeze!",value:"freeze",weight:4,color:"#06b6d4"},{label:"⭐ 100 XP",value:"points_100",weight:3,color:"#8b5cf6"},{label:"🎟️ 5 Tickets",value:"ticket_5",weight:1.5,color:"#a855f7"},{label:"💎 RARE!",value:"rare_drop",weight:1.5,color:"#ef4444"}],a=[{label:"🎟️ 10 Tickets",value:"ticket_10",weight:1e3},{label:"🎟️ 25 Tickets",value:"ticket_25",weight:500},{label:"🎟️ 50 Tickets",value:"ticket_50",weight:100},{label:"🎟️ 100 Tickets!",value:"ticket_100",weight:50},{label:"🎟️ 500 Tickets!!",value:"ticket_500",weight:10},{label:"🎟️💎 1,000 Tickets!!!",value:"ticket_1000",weight:3},{label:"🎟️👑 10,000 TICKETS!!!!",value:"ticket_10000",weight:1}];n.innerHTML='
    🎡
    Daily Spin

    Spin for Orange Tickets, XP, Nacho Closet items, and rare Freeze Tickets!

    ',document.body.appendChild(n);var r=document.getElementById("spinCanvas").getContext("2d"),s=125,l=125,c=2*Math.PI/i.length;i.forEach(function(e,t){r.beginPath(),r.moveTo(s,l),r.arc(s,l,120,t*c,(t+1)*c),r.fillStyle=e.color,r.fill(),r.strokeStyle="#fff",r.lineWidth=2,r.stroke(),r.save(),r.translate(s,l),r.rotate(t*c+c/2),r.textAlign="right",r.fillStyle="#fff",r.font="bold 12px sans-serif",r.fillText(e.label,105,4),r.restore()});var d=!1,u=document.getElementById("spinBtn"),p=document.getElementById("spinResult");u.addEventListener("click",function(){if(!d){d=!0,u.disabled=!0,u.style.opacity="0.5";for(var e=i.reduce(function(e,t){return e+t.weight},0),o=Math.random()*e,n=0,h=0,m=0;mMath.floor(30*(d-.01))&&"function"==typeof playSpinTick&&playSpinTick(),requestAnimationFrame(e);else{"function"==typeof playSpinWin&&playSpinWin();var m="",f=g.value.split("_")[0],y=parseInt(g.value.split("_")[1])||1;if("rare_drop"===g.value){for(var b=a.reduce(function(e,t){return e+t.weight},0),w=Math.random()*b,x=a[0],B=0,S=0;S.01&&(T=100,x={label:"🎟️ 100 Tickets!",value:"ticket_100"}),m="💎 RARE DROP! "+x.label,"function"==typeof awardOrangeTickets)awardOrangeTickets(T,"Rare Spin Drop");else{var _=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",_+T)}T>=100&&("function"==typeof launchConfetti&&launchConfetti(),"function"==typeof playBadgeSound&&playBadgeSound())}else if("closet"===f){var I=safeJSON("btc_spin_closet_items",[]),C=["orange_scarf","sunglasses","bowtie","mining_helmet","lightning_chain","party_hat","hodl_hoodie","crown","steak","diamond_hooves"].filter(function(e){return-1===I.indexOf(e)});if(C.length>0){var A=C[Math.floor(Math.random()*C.length)];if(I.push(A),localStorage.setItem("btc_spin_closet_items",JSON.stringify(I)),void 0!==currentUser&¤tUser&&!currentUser._isLocal)try{db.collection("users").doc(auth.currentUser.uid).update({spinClosetItems:firebase.firestore.FieldValue.arrayUnion(A)}).catch(function(){})}catch(e){}m="👔 CLOSET ITEM! You unlocked: "+({orange_scarf:"Bitcoin Scarf 🧣",sunglasses:"Cool Shades 🕶️",bowtie:"Fancy Bowtie 🎀",mining_helmet:"Mining Helmet ⛑️",lightning_chain:"Lightning Chain ⚡",party_hat:"Party Hat 🎉",hodl_hoodie:"HODL Hoodie 🧥",crown:"Royal Crown 👑",steak:"Proof of Steak 🥩",diamond_hooves:"Diamond Hooves 💎"}[A]||A)+"! Equip it in Nacho's Closet!"}else m="👔 You already own all spin closet items! +25 bonus XP instead!","function"==typeof awardPoints&&awardPoints(25,"Closet bonus")}else if("freeze"===f){m="🧊 STREAK FREEZE TICKET! Your streak is protected for 1 missed day!";var E=parseInt(localStorage.getItem("btc_streak_freezes")||"0");localStorage.setItem("btc_streak_freezes",E+1),"function"==typeof awardPoints&&awardPoints(0,"🧊 Streak Freeze",null,0,1),void 0!==currentUser&¤tUser&&(currentUser.streakFreezes=(currentUser.streakFreezes||0)+1)}else if("ticket"===f)if(m="🎟️ You won "+y+" Orange Ticket"+(y>1?"s":"")+"!","function"==typeof awardOrangeTickets)awardOrangeTickets(y,"Daily Spin");else{var z=parseInt(localStorage.getItem("btc_orange_tickets")||"0");localStorage.setItem("btc_orange_tickets",z+y)}else if("points"===f)if(m="⭐ You won "+y+" XP!","function"==typeof awardPoints)awardPoints(y,"Daily Spin");else{var L=parseInt(localStorage.getItem("btc_points")||"0");localStorage.setItem("btc_points",L+y)}p.innerHTML='
    '+g.label.split(" ")[0]+'
    '+m+'
    ',"function"==typeof notifySelfSpin&¬ifySelfSpin(m);var M=parseInt(localStorage.getItem("btc_spin_count")||"0");localStorage.setItem("btc_spin_count",String(M+1));var P=localStorage.getItem("btc_spin_last_day")||"";if(P===new Date(Date.now()-864e5).toISOString().slice(0,10)){var U=parseInt(localStorage.getItem("btc_spin_streak")||"0");localStorage.setItem("btc_spin_streak",String(U+1))}else P!==t&&localStorage.setItem("btc_spin_streak","1");localStorage.setItem("btc_spin_last_day",t),"rare_drop"===g.value&&localStorage.setItem("btc_spin_hit_rare","true"),localStorage.setItem("btc_last_spin_date",t),"undefined"!=typeof firebase&&firebase.functions&&firebase.functions().httpsCallable("dailySpin")({}).catch(function(e){console.log("[SPIN] Server validation:",e.message||"ok")}),void 0!==currentUser&¤tUser&¤tUser._isLocal}})}}),n.addEventListener("click",function(e){e.target===n&&n.remove()})}else showToast("🎡 You already spun today! Come back tomorrow!")};var _=null;function I(e,t,o,n,i){var a="dc_"+Math.random().toString(36).substr(2,6),r=n?'Open ↗':"";return'
    '+e+"
    "+(i?'
    '+e+' QR
    ':"")+(t?'
    "+o+'
    "+r+"
    ":"")+"
    "}function C(e,t){navigator.clipboard.writeText(e).then(()=>{t.classList.add("copied"),t.textContent="✅ Copied!",setTimeout(()=>{t.classList.remove("copied"),t.innerHTML="🔗 Copy Link"},2e3)})}setTimeout(function(){var e=new Image;e.crossOrigin="anonymous",e.src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:spontaneousleopard54@zeuspay.com",e.onload=function(){try{var t=document.createElement("canvas");t.width=e.width,t.height=e.height,t.getContext("2d").drawImage(e,0,0),_=t.toDataURL("image/png")}catch(t){_=e.src}}},3e3),window.showDonateModal=function(){var e=document.getElementById("donateModal");e&&e.remove();var t=document.createElement("div");t.id="donateModal",t.style.cssText="position:fixed;top:0;left:0;right:0;bottom:0;z-index:9999;display:flex;align-items:flex-start;justify-content:center;background:rgba(2,6,23,0.9);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);padding:20px;overflow-y:auto;-webkit-overflow-scrolling:touch;";var o="spontaneousleopard54@zeuspay.com",n=_||"https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=lightning:"+o;t.innerHTML='
    🧡
    Support the Archive

    Your sats help keep this archive free and open for the next billion Bitcoiners! 🦌⚡

    Lightning QR Code
    '+o+"

    ⚠️ Donations are non-refundable

    "+I("💵 Cash App","$NEEDcreations","$NEEDcreations","https://cash.app/$NEEDcreations","images/donate/cashapp-qr.jpg")+I("💜 Venmo","@Phil2140","@Phil2140","https://venmo.com/code?user_id=1358236213051392692&created=1773155307","images/donate/venmo-qr.jpg")+I("💙 PayPal","paypal.me/PhilipFazioli","paypal.me/PhilipFazioli","https://paypal.me/PhilipFazioli","images/donate/paypal-qr.jpg")+I("💚 Zelle",null,null,null,"images/donate/zelle-qr.jpg")+I("₿ On-Chain Bitcoin","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf","bc1qvukgml6t5cnv6jk3gkx3ufd7eqs7veycuqxwrf",null,"images/donate/onchain-qr.jpg")+I("🔒 BIP47 Payment Code","PM8TJWpq8HqPeBEuz3dAoB3uyZADVxQjWekQJCJYddpWPce9nDaeK6XjYnifBUnjjKcWF8Y98EkfPZYaftC7uDJkiFqBTBYrd8TJhRg5qQwXtfnTTg89","PM8TJWpq8Hq...Tg89",null,"images/donate/bip47-qr.jpg")+"
    ",document.body.appendChild(t);var i=document.getElementById("donateCopyBtn");i&&i.addEventListener("click",function(e){e.stopPropagation();var t=this;if(navigator.clipboard)navigator.clipboard.writeText(o).then(function(){t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)});else{var n=document.createElement("textarea");n.value=o,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t.textContent="✅ Copied!",setTimeout(function(){t.textContent="📋 Copy Address"},2e3)}}),t.addEventListener("click",function(e){e.target===t&&t.remove()})};let A=!1;function E(){const e=document.getElementById("supportBtn");A?(navigator.clipboard.writeText("info.603btc@gmail.com").then(function(){e.innerHTML="✅ Copied!",e.style.color="#22c55e",setTimeout(function(){e.innerHTML='info.603btc@gmail.com tap to copy',e.style.color="var(--text)"},1500)}).catch(function(){}),window.location.href="mailto:info.603btc@gmail.com?subject=Support%20-%20Bitcoin%20Education%20Archive"):(A=!0,e.style.transition="0.3s",e.style.background="var(--accent)",e.style.color="#fff",e.style.borderColor="var(--accent)",e.innerHTML='info.603btc@gmail.com tap to copy',setTimeout(function(){e.style.background="var(--card-bg)",e.style.color="var(--text)",e.style.borderColor="var(--border)"},400))}function z(e){if(!e)return"";var t=new Date(e),o=t.getHours(),n=t.getMinutes(),i=o>=12?"PM":"AM";return 0==(o%=12)&&(o=12),o+":"+(n<10?"0":"")+n+" "+i}window._nachoMode=!1,window._nachoModeEarnings={points:0,badges:[],interactions:0},window.enterNachoMode=function(e){if(window._nachoMode=!0,window._nachoBusy=!0,window._nachoModeEarnings={points:0,badges:[],interactions:0},window._nachoModeStartTime=Date.now(),window._nachoModeTopics=[],window._nachoConvoQuizOffered=!1,!window._nachoPointsHooked){window._nachoPointsHooked=!0;var t=window.awardPoints;t&&(window.awardPoints=function(e,o){return window._nachoMode&&window._nachoModeEarnings&&(window._nachoModeEarnings.points+=e),t.apply(this,arguments)});var o=window.showToast;o&&(window.showToast=function(e){return window._nachoMode&&window._nachoModeEarnings&&"string"==typeof e&&(-1!==e.indexOf("badge")||-1!==e.indexOf("Badge")||-1!==e.indexOf("🏅"))&&window._nachoModeEarnings.badges.push(e),o.apply(this,arguments)})}e||history.pushState({nachoMode:!0},"","/app/nacho"),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="none")});var n=document.querySelector(".mobile-bar");n&&(n.style.display="none");var i=document.getElementById("main");i.scrollTop=0,"undefined"!=typeof NACHO_SVG&&NACHO_SVG,void 0!==currentUser&¤tUser&¤tUser.username&¤tUser.username;var a=!(!window.SpeechRecognition&&!window.webkitSpeechRecognition),r=a?'':"";window._nachoChatHistory=safeJSON("btc_nacho_chat",[]),window._nachoSentHistory=safeJSON("btc_nacho_sent",[]),window._nachoSentIdx=-1;var s=document.createElement("div");s.id="nachoModeScreen",s.style.cssText="display:flex;flex-direction:column;height:calc(100vh - 32px);margin-top:32px;animation:fadeSlideIn 0.4s ease-out;position:relative;z-index:9999;",s.innerHTML='
    Nacho
    '+("function"==typeof nachoNickname?nachoNickname():"Nacho").toUpperCase()+' MODE
    Home
    '+r+'
    ',i.appendChild(s),q(),setTimeout(function(){var e=document.getElementById("nachoModeChat");e&&(e.scrollTop=e.scrollHeight)},100),j();var l=document.getElementById("nachoEli5Btn");l&&(l.style.opacity=window._nachoEli5?"1":"0.5"),function(){var e=document.getElementById("nachoModeOverlay");if(e&&(e.innerHTML="","function"==typeof getEquippedItem)){var t=getEquippedItem();if(t){var o=t.hidden?t.revealEmoji:t.emoji,n=document.createElement("span");n.textContent=t.overlay&&t.overlay.custom?t.overlay.custom:o,n.style.cssText="position:absolute;font-size:2.5rem;pointer-events:none;",t.overlay&&(t.overlay.top&&(n.style.top=t.overlay.top),t.overlay.left&&(n.style.left=t.overlay.left),t.overlay.right&&(n.style.right=t.overlay.right),t.overlay.bottom&&(n.style.bottom=t.overlay.bottom),t.overlay.transform&&(n.style.transform=t.overlay.transform)),e.appendChild(n)}}}(),setTimeout(function(){var e=document.getElementById("nachoModeInput");e&&e.focus()},300)},window.nachoModeKeydown=function(e){if("Enter"!==e.key){var t=document.getElementById("nachoModeInput");if(t){var o=window._nachoSentHistory||[];if("ArrowUp"===e.key){if(0===o.length)return;-1===window._nachoSentIdx&&(window._nachoSentDraft=t.value),window._nachoSentIdx=Math.min(window._nachoSentIdx+1,o.length-1),t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault(),setTimeout(function(){t.setSelectionRange(t.value.length,t.value.length)},0)}else if("ArrowDown"===e.key){if(window._nachoSentIdx<=0)return window._nachoSentIdx=-1,void(t.value=window._nachoSentDraft||"");window._nachoSentIdx--,t.value=o[o.length-1-window._nachoSentIdx],e.preventDefault()}}}else nachoModeSend()};var L=["There will only ever be 21 million Bitcoin. No government, company, or person can change this. 🔒","The Bitcoin network has been running non-stop since January 3, 2009 — over 99.98% uptime. No bank can say that! 🏦","The first Bitcoin transaction was 10,000 BTC for two pizzas. Today that's worth hundreds of millions! 🍕","Bitcoin processes over $10 billion in transactions daily — more than most countries' payment systems. 💸","Bitcoin mining now uses more renewable energy than almost any other industry — over 50%! ⚡","Satoshi Nakamoto's true identity remains unknown. They hold about 1 million BTC and have never spent any. 🕵️","A 'satoshi' (sat) is the smallest unit of Bitcoin: 0.00000001 BTC. You don't need to buy a whole coin! 🪙","The Bitcoin Lightning Network can process millions of transactions per second — faster than Visa! ⚡","El Salvador became the first country to adopt Bitcoin as legal tender in September 2021. 🇸🇻","Bitcoin's code is completely open source — anyone can read, verify, and contribute to it. 📖","Every 4 years, Bitcoin's new supply gets cut in half. This is called the 'halving.' The next one is in 2028! 📉","There are more Bitcoin wallets than bank accounts in most countries. Over 100 million and growing! 📈","Bitcoin can be sent anywhere in the world in minutes, 24/7, with no middleman. Try that on a Sunday with a bank! 🌍","The Genesis Block contains a hidden message: 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.' 📰","About 20% of all Bitcoin is estimated to be permanently lost — mostly from early users who lost their keys. 🔑","Bitcoin's difficulty adjustment is like a thermostat — it automatically adapts every 2 weeks to keep blocks at ~10 minutes. ⚙️","Running a Bitcoin node means YOU verify every transaction yourself. No trust required. Don't trust, verify! ✅","The Lightning Network lets you send payments as small as 1 sat (~$0.0003). Try doing that with a credit card! 💳","Bitcoin has survived 400+ declared 'deaths' by media. It keeps coming back stronger every time. 💪","Over 50 publicly traded companies now hold Bitcoin on their balance sheets, led by MicroStrategy. 🏢","Bitcoin transactions are pseudonymous, not anonymous. Every transaction is recorded on the public blockchain forever. 🔍","The Bitcoin network is protected by more computing power than all the world's supercomputers combined. 🖥️","You can run a full Bitcoin node on a Raspberry Pi — a $50 computer can verify the entire monetary system. 🥧","Bitcoin's inflation rate is currently lower than gold's. After the 2028 halving, it'll be even lower. 🥇","Multisig wallets require multiple keys to spend Bitcoin — like a safety deposit box that needs 2 of 3 keys. 🗝️","Bitcoin doesn't care about borders, politics, or holidays. It works the same everywhere, always. 🌐","The last Bitcoin won't be mined until approximately the year 2140. We're still very early! ⏰","Jack Dorsey, Elon Musk, and many tech leaders have publicly supported Bitcoin's vision. 🚀","A Bitcoin block is mined roughly every 10 minutes. That's about 144 blocks per day, every day, forever. ⛏️","Nostr is a decentralized social protocol that many Bitcoiners are building on — social media you can't be censored from. 📡"];window.nachoModeChip=function(e){var t=document.getElementById("nachoModeInput");t&&(t.value=e,nachoModeSend())},window._nachoEli5="true"===localStorage.getItem("btc_nacho_eli5"),window.toggleNachoEli5=function(){window._nachoEli5=!window._nachoEli5,localStorage.setItem("btc_nacho_eli5",window._nachoEli5?"true":"false");var e=document.getElementById("nachoEli5Btn");e&&(e.style.opacity=window._nachoEli5?"1":"0.5",e.title=window._nachoEli5?"ELI5 Mode ON — Simple language":"Explain Like I'm 5"),"function"==typeof showToast&&showToast(window._nachoEli5?"🧒 ELI5 Mode ON — Nacho will use simple language!":"🧒 ELI5 Mode OFF — Back to normal")},window.showEli5Prompt=function(){var e=window._nachoEli5,t='
    🧒
    ELI5 Mode
    Explain Like I\'m 5

    When turned on, Nacho will answer your questions using super simple language — like explaining Bitcoin to a 5-year-old! 🦌

    Perfect for beginners or anyone who wants the basics without the jargon.
    Currently: '+(e?"ON ✅":"OFF")+'
    ',o=document.createElement("div");o.innerHTML=t,document.body.appendChild(o.firstChild)},window.nachoShareAnswer=function(e){var t="🦌 I learned this from Nacho at bitcoineducation.quest:\n\n"+e.replace(/<[^>]+>/g,"").replace(/🦌\s*/g,"").substring(0,280);if(navigator.share)navigator.share({title:"Bitcoin Fact from Nacho 🦌",text:t,url:"https://bitcoineducation.quest"}).catch(function(){});else{var o=document.createElement("textarea");o.value=t,document.body.appendChild(o),o.select();try{document.execCommand("copy")}catch(e){}document.body.removeChild(o),"function"==typeof showToast&&showToast("📋 Copied to clipboard!")}};var M=!1,P=[{step:1,emoji:"📘",title:"What is Bitcoin?",q:"What is Bitcoin and how does it work?"},{step:2,emoji:"💡",title:"Why Bitcoin Matters",q:"Why is Bitcoin important? Why should I care?"},{step:3,emoji:"📈",title:"Bitcoin vs Money",q:"How is Bitcoin different from regular money and gold?"},{step:4,emoji:"🛒",title:"Buying Your First Bitcoin",q:"How do I buy my first Bitcoin? Where do I start?"},{step:5,emoji:"💼",title:"Wallets & Storage",q:"What Bitcoin wallet should I use? What are the types?"},{step:6,emoji:"🔑",title:"Seed Phrases & Security",q:"What is a seed phrase and how do I keep my Bitcoin safe?"},{step:7,emoji:"⚡",title:"Lightning Network",q:"What is the Lightning Network and why does it matter?"},{step:8,emoji:"⛏️",title:"Mining & Proof of Work",q:"How does Bitcoin mining work? What is proof of work?"},{step:9,emoji:"🏃",title:"Running a Node",q:"What is a Bitcoin node and should I run one?"},{step:10,emoji:"🔒",title:"Privacy & KYC",q:"How private is Bitcoin? What is KYC and why does it matter?"}];window.nachoLearningPath=function(){var e=parseInt(localStorage.getItem("btc_nacho_path_step")||"0");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth&&auth?auth.currentUser:null;if(document.getElementById("nachoModeChat")){var o='
    🗺️ Your Bitcoin Journey
    '+Math.round(e/P.length*100)+"% concepts mastered
    ";o+='
    ✅ All Features Unlocked

    Every app and feature is available to you. Explore freely! 🦌

    🗣️ Pleb Talk
    🤝 IRL Sync
    ⚡ Lightning Mart
    🔹 Sign Up: 🏁 Profile & Persistence
    ',o+='
    ';for(var n=0;n'+(a?"✅":i.emoji)+'
    Level '+i.step+": "+i.title+"
    "+(r?'NEXT →':"")+""}e>=P.length&&(o+='
    🎓🦌🎉
    Journey Complete!
    You\'ve covered all the Bitcoin basics. You\'re officially not a normie anymore!
    '),H("nacho","",o)}},window.nachoPathStep=function(e){var t=P[e];t&&(e>=parseInt(localStorage.getItem("btc_nacho_path_step")||"0")&&localStorage.setItem("btc_nacho_path_step",(e+1).toString()),nachoModeChip(t.q))};const U=[{q:"What is the primary benefit of running a Bitcoin full node?",a:"You can independently verify the consensus rules and your own transactions.",w:["It earns you a small percentage of every transaction fee on the network.","It automatically mines new Bitcoins using your computer's idle CPU.","It hides your IP address from everyone else using the network.","It increases the speed of your internet connection by 21%."]},{q:"What does 'Satoshi' represent in the context of Bitcoin?",a:"The smallest unit of Bitcoin, equal to 0.00000001 BTC.",w:["A type of advanced encryption used for private messages.","The official name for a Bitcoin wallet's public address.","A digital certificate of ownership for a single Bitcoin.","The name of the first computer used to mine block zero."]},{q:"Why is Bitcoin's difficulty adjustment important?",a:"It ensures blocks are produced roughly every 10 minutes regardless of total hash rate.",w:["It prevents the price of Bitcoin from dropping below its mining cost.","It automatically updates the Bitcoin Core software for all users.","It calculates the total number of users active on the network daily.","It decides which transactions are most important for the miners."]},{q:"What happens if you lose your 12 or 24-word seed phrase?",a:"You lose access to your funds forever, as there is no central 'reset' authority.",w:["You can call Bitcoin's customer support to verify your identity and reset it.","The government can recover your coins using your social security number.","Your hardware wallet will automatically generate a new phrase after 24 hours.","Your Bitcoin is donated to a pool for new developers to use for testing."]},{q:"What is the primary function of the Lightning Network?",a:"To enable instant, near-free Bitcoin payments by moving them off-chain.",w:["To increase the total number of Bitcoins that will ever exist to 42 million.","To allow Bitcoin to be mined using only mobile phones and tablets.","To encrypt the entire blockchain so it cannot be read by anyone.","To create a secondary blockchain that is faster but less secure than Bitcoin."]}];function q(){var e=document.getElementById("nachoModeChat");if(e){var t=window._nachoChatHistory||[];if(0!==t.length){for(var o,n="",i="",a=0;a'+s+"",i=s),"user"===r.role?n+='
    '+escapeHtml(r.text)+'
    '+z(r.ts)+"
    ":n+='
    🦌 '+escapeHtml("function"==typeof nachoNickname?nachoNickname():"Nacho")+": "+r.html+'
    '+z(r.ts)+"
    "}e.innerHTML=n,e.scrollTop=e.scrollHeight}else{var l=void 0!==currentUser&¤tUser&¤tUser.username?currentUser.username:"";e.innerHTML='
    Nacho
    🦌 NACHO MODE
    '+(l?"Hey "+escapeHtml(l)+"! Let's talk Bitcoin.":"Hey! Let's talk Bitcoin.")+'
    💡 DID YOU KNOW?
    '+(o=Math.floor((Date.now()-new Date((new Date).getFullYear(),0,0))/864e5),L[o%L.length]+'
    Tap a topic or ask me anything:
    ')+function(){for(var e=[{emoji:"📘",label:"What is Bitcoin?",q:"What is Bitcoin and what problem does it solve?"},{emoji:"💰",label:"Why Bitcoin?",q:"Why is Bitcoin better than regular money and why should I care?"},{emoji:"🔒",label:"21 Million",q:"Why is the 21 million cap important and why can't it be changed?"},{emoji:"🛒",label:"How to Buy",q:"How do I buy my first Bitcoin and start stacking sats?"},{emoji:"🔑",label:"Self-Custody",q:"What is self-custody and why is it the most important thing in Bitcoin?"},{emoji:"⚡",label:"Lightning",q:"What is the Lightning Network and how does it make Bitcoin faster?"},{emoji:"🪙",label:"Why Not Altcoins?",q:"Why do Bitcoiners only focus on Bitcoin and not other cryptocurrencies?"},{emoji:"🌍",label:"Fix the World",q:"How is Bitcoin actually changing the world for the better?"}],t='
    ',o=0;o"+e[o].emoji+" "+e[o].label+"";return t+"
    "}()+'
    '}}}function N(e,t,o){var n={role:e,text:t||"",html:o||escapeHtml(t||""),ts:Date.now()};return window._nachoChatHistory.push(n),nachoChatSave(),n}function H(e,t,o){var n=document.getElementById("nachoModeChat");if(n){window._nachoChatHistory.length<=1&&n.querySelector("#nachoModeAvatar")&&(n.innerHTML="");var i=z(Date.now()),a=document.createElement("div");if(a.className="nm-msg "+("user"===e?"nm-user":"nm-nacho"),"user"===e)a.innerHTML=""+escapeHtml(t)+'
    '+i+"
    ";else{var r="function"==typeof nachoNickname?nachoNickname():"Nacho";a.innerHTML='🦌 '+escapeHtml(r)+": "+o+'
    '+i+"
    "}n.appendChild(a),"user"===e?n.scrollTop=n.scrollHeight:a.scrollIntoView({behavior:"smooth",block:"start"})}}function D(){if(window._nachoMode){var e=document.getElementById("nachoModeInput");if(e&&e===document.activeElement)setTimeout(D,3e4);else if(document.querySelector(".nm-nacho .thinking, .nm-thinking"))setTimeout(D,1e4);else{var t=window._nachoModeTopics||[];if(!(t.length<3)){var o=[],n=[],i=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;if(i&&"object"==typeof i&&Object.keys(i).forEach(function(e){var t=i[e];Array.isArray(t)&&t.forEach(function(t){n.push({question:t.q,options:[t.a].concat(t.wrong||[]),answer:t.a,category:e})})}),n.length>0){for(var a=0;a3&&-1!==c.indexOf(r[d])){o.push(l);break}}for(;o.length<3&&n.length>0;){var u=n[Math.floor(Math.random()*n.length)];-1===o.indexOf(u)&&o.push(u)}}0!==o.length&&(H("nacho","",'
    🎯
    Conversation Quest!
    You\'ve been learning a lot! Let\'s see how much you remember from our chat.
    '),window._convoQuizQuestions=o)}}}}function O(){var e,t,o,n,i=window._convoQuizQuestions||[],a=window._convoQuizIdx||0;if(a>=window._convoQuizTotal||a>=i.length)e=window._convoQuizScore||0,t=window._convoQuizTotal||3,H("nacho","",'
    '+(o>=80?"🏆":o>=60?"⭐":o>=40?"💪":"📚")+'
    Conversation Quest Complete!
    '+e+"/"+t+' correct
    '+(o>=80?"Outstanding! You really paid attention!":o>=60?"Great job! You learned a lot from our chat!":o>=40?"Not bad! Keep learning and you'll get there!":"Keep going! Every question is a learning opportunity!")+"
    "+((n=5*e)>0?'
    +'+n+" XP earned! 🎉
    ":"")+"
    "),n>0&&("function"==typeof awardPoints&&awardPoints(n,"🎯 Conversation Quest!"),"function"==typeof showToast&&showToast("🎯 +"+n+" XP — Conversation Quest!"));else{for(var r=i[a],s='
    Question '+(a+1)+" of "+window._convoQuizTotal+'
    '+escapeHtml(r.question)+"
    ",l=r.options||[],c=0;c'+escapeHtml(l[c])+""}H("nacho","",s+="
    ")}}function j(){var e=document.getElementById("nachoModeFriendship");if(e){var t="function"==typeof getNachoFriendship?getNachoFriendship():{emoji:"🦌",name:"Unknown",level:0},o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0");e.textContent=t.emoji+" Friendship: "+t.name+" · "+o+" interactions"}}function R(){const e=document.getElementById("continueReading");if(!e)return;const t=localStorage.getItem("btc_last_channel");if(t&&CHANNELS[t]){const o=CHANNELS[t];e.style.display="block",e.innerHTML='
    📖 Continue Reading
    "+o.title+'
    '+o.cat+"
    "}else e.style.display="none"}window.nachoQuizMe=function(e){if(!window._nachoMode)return void("function"==typeof enterNachoMode&&(enterNachoMode(),setTimeout(function(){nachoQuizMe(e)},500)));let t=[];var o=void 0!==QUESTION_BANK?QUESTION_BANK:"undefined"!=typeof QUEST_QUESTIONS?QUEST_QUESTIONS:null;o&&"object"==typeof o&&Object.keys(o).length>0&&Object.keys(o).forEach(e=>{var n=o[e];Array.isArray(n)&&n.forEach(o=>{t.push({question:o.q,options:fisherYates([o.a,...o.wrong||o.w||[]]),answer:o.a,category:e})})}),U.forEach(e=>{t.push({question:e.q,options:fisherYates([e.a,...e.w]),answer:e.a,category:"generic"})});var n=e?t.filter(function(t){return t.category&&-1!==t.category.toLowerCase().indexOf(e.toLowerCase())}):t;0===n.length&&(n=t);for(var i=n[Math.floor(Math.random()*n.length)],a='
    🎮 Quiz Time!
    '+(e?"Topic: "+e:"Nacho Challenge")+'
    '+escapeHtml(i.question)+"
    ",r=i.options||[],s=0;s'+escapeHtml(r[s])+""}a+="
    ",e||(a+='
    🦌 Pro Tip: Chat with me first! Future quizzes will be based on the questions you ask me.
    '),H("nacho","",a+="')},window.nachoQuizAnswer=function(e,t){try{var o=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_quiz_done_"+o,"true")}catch(e){}var n,i=e.parentElement.querySelectorAll("button");i.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.7"}),t?(e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1","function"==typeof awardPoints&&awardPoints(10,"🎮 Quiz correct!"),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(34,197,94,0.1);border:1px solid #22c55e;border-radius:8px;color:#22c55e;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="✅ Correct! +10 XP",e.parentElement.appendChild(n)):(e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",i.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.borderColor="#22c55e",t.style.color="#22c55e",t.style.opacity="1")}),(n=document.createElement("div")).style.cssText="margin-top:8px;padding:8px;background:rgba(239,68,68,0.1);border:1px solid #ef4444;border-radius:8px;color:#ef4444;font-size:0.85rem;font-weight:700;text-align:center;",n.textContent="❌ Incorrect. Try another!",e.parentElement.appendChild(n))},window.nachoChatSave=function(){var e=window._nachoChatHistory||[];e.length>100&&(e=e.slice(e.length-100)),window._nachoChatHistory=e;try{localStorage.setItem("btc_nacho_chat",JSON.stringify(e))}catch(e){}},window.startConversationQuiz=function(){var e=window._convoQuizQuestions||[];0!==e.length&&(window._convoQuizIdx=0,window._convoQuizScore=0,window._convoQuizTotal=Math.min(e.length,5),O())},window.convoQuizAnswer=function(e,t){var o=e.parentElement,n=o.querySelectorAll("button");if(n.forEach(function(e){e.disabled=!0,e.style.cursor="default",e.style.opacity="0.6"}),t){e.style.background="#22c55e",e.style.color="#fff",e.style.borderColor="#22c55e",e.style.opacity="1",window._convoQuizScore=(window._convoQuizScore||0)+1;var i=document.createElement("div");i.style.cssText="margin-top:6px;color:#22c55e;font-size:0.8rem;font-weight:700;",i.textContent="✅ Correct!",o.appendChild(i)}else{e.style.background="#ef4444",e.style.color="#fff",e.style.borderColor="#ef4444",e.style.opacity="1",n.forEach(function(t){t!==e&&"1"===t.getAttribute("data-correct")&&(t.style.background="#22c55e",t.style.color="#fff",t.style.borderColor="#22c55e",t.style.opacity="1")});var a=document.createElement("div");a.style.cssText="margin-top:6px;color:#ef4444;font-size:0.8rem;font-weight:700;",a.textContent="❌ Not quite!",o.appendChild(a)}window._convoQuizIdx=(window._convoQuizIdx||0)+1,setTimeout(O,1500)},window.nachoChatExport=function(){var e=window._nachoChatHistory||[];if(0!==e.length){for(var t=["=== Nacho Mode Chat Export ===","Exported: "+(new Date).toLocaleString(),""],o=0;o]+>/g,"");t.push("["+i+"] "+a+": "+r)}t.push("","--- bitcoineducation.quest ---");var s=new Blob([t.join("\n")],{type:"text/plain"}),l=document.createElement("a");l.href=URL.createObjectURL(s),l.download="nacho-chat-"+(new Date).toISOString().slice(0,10)+".txt",l.click(),URL.revokeObjectURL(l.href),"function"==typeof showToast&&showToast("💾 Chat saved!")}else"function"==typeof showToast&&showToast("No chat to save!")},window.nachoChatClear=function(){confirm("Clear all chat history with Nacho?")&&(window._nachoChatHistory=[],localStorage.removeItem("btc_nacho_chat"),q(),"function"==typeof showToast&&showToast("🗑️ Chat cleared"))},window.nachoModeSend=function(){var e=document.getElementById("nachoModeInput");if(e){var t=e.value.trim();if(t){e.value="",window._nachoSentIdx=-1,window._nachoSentDraft="",window._nachoAskedQuestions||(window._nachoAskedQuestions=[]),window._nachoAskedQuestions.push(t.toLowerCase()),window._nachoAskedQuestions.length>30&&(window._nachoAskedQuestions=window._nachoAskedQuestions.slice(-20)),window._nachoSentHistory.push(t),window._nachoSentHistory.length>50&&window._nachoSentHistory.shift();try{localStorage.setItem("btc_nacho_sent",JSON.stringify(window._nachoSentHistory))}catch(e){}var o;(o=document.getElementById("nachoHeroAvatar"))&&o.classList.add("talking"),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,window._nachoModeTopics&&t.length>10&&window._nachoModeTopics.push(t),!window._nachoConvoQuizOffered&&window._nachoModeStartTime&&window._nachoModeTopics&&(Date.now()-window._nachoModeStartTime)/6e4>=15&&window._nachoModeTopics.length>=5&&(window._nachoConvoQuizOffered=!0,setTimeout(function(){D()},8e3)),N("user",t),H("user",t),function(){var e=document.getElementById("nachoModeChat");if(e){e.querySelector("#nachoModeAvatar")&&(e.innerHTML="");var t=document.createElement("div");t.id="nmThinking",t.className="nm-msg nm-nacho",t.innerHTML='🦌 Thinking',e.appendChild(t),e.scrollTop=e.scrollHeight;var o=t.querySelector(".nacho-dots"),n=0;window._nmDotsTimer=setInterval(function(){n=(n+1)%4,o&&(o.textContent=".".repeat(n))},400)}}();var n="nm_"+Date.now()+"_"+Math.random().toString(36).substr(2,4),i=!1,a=setTimeout(function(){i||(i=!0,console.warn("[Nacho] Master timer fired — pipeline took >15s for:",t),s("That's a great question! I'm having a little trouble with my brain right now 🦌 Try asking me again in a moment, or explore the channels on the left to learn about Bitcoin!","fallback"))},15e3);if("function"!=typeof nachoUnifiedAnswer){if(!document.querySelector("script[data-nacho-retry]")){var r=document.createElement("script");r.src="nacho-qa.js?v="+Date.now(),r.setAttribute("data-nacho-retry","1"),document.head.appendChild(r)}setTimeout(function(){if("function"==typeof nachoUnifiedAnswer)try{nachoUnifiedAnswer(t,l)}catch(e){console.warn("Nacho pipeline retry error:",e),l({type:"fallback",answer:"I'm still loading up my Bitcoin knowledge! Try again in a moment 🦌"})}else!function(e,t){if("function"==typeof checkOffTopic){var o=checkOffTopic(e);if(o)return void t("function"==typeof personalize?personalize(o):o,"offtopic")}var n=e.toLowerCase().trim();if(/^(hey|hi|hello|yo|sup|howdy|hola|what'?s up|how are you|how'?s it going|good morning|good evening|good afternoon|gm|greetings)$/i.test(n)||/^(hey|hi|hello|yo) (nacho|there|buddy|friend|deer)/i.test(n)){var i=["Hey there! 🦌 Doing great — just hanging out waiting for someone to ask me about Bitcoin! What's on your mind?","Hey hey! 🧡 Welcome! I'm Nacho, your Bitcoin buddy. What would you like to learn about today?","Well hello! 🦌 Nice to see you. Ask me anything about Bitcoin — I've got 146 channels of knowledge in these antlers!","Hey! 👋 I'm good, thanks for asking! Ready to talk Bitcoin whenever you are. What's on your mind?"];t(i[Math.floor(Math.random()*i.length)],"offtopic")}else"function"==typeof nachoTrackMiss&&nachoTrackMiss(e),t("Give me just a moment — I'm loading up my Bitcoin knowledge! Try again in a few seconds. 🦌","fallback")}(t,s)},2e3)}else try{console.log("[Nacho] Calling nachoUnifiedAnswer for:",t),nachoUnifiedAnswer(t,function(e){console.log("[Nacho] Pipeline returned:",e?e.type:"null"),l(e)})}catch(e){console.error("[Nacho] Pipeline CRASH:",e),l({type:"fallback",answer:"Oops, my brain hit a bump! 🦌 Try asking again — I know a LOT about Bitcoin!"})}}}function s(e,o){!function(){window._nmDotsTimer&&(clearInterval(window._nmDotsTimer),window._nmDotsTimer=null);var e=document.getElementById("nmThinking");e&&e.remove()}(),function(){var e=document.getElementById("nachoHeroAvatar");e&&e.classList.remove("talking")}();var i="";if(o&&"safety"!==o){window._nachoAnswerData||(window._nachoAnswerData={}),window._nachoAnswerData[n]=e;var a="background:none;border:1px solid var(--border);border-radius:16px;cursor:pointer;font-size:0.75rem;padding:4px 10px;transition:0.2s;color:var(--text-muted);display:inline-flex;align-items:center;gap:3px;touch-action:manipulation;",r='
    ';"function"==typeof nachoRatingHtml&&(r+='",r+='"),r+="',i+=r+="
    ",i+=function(e){if(!e||0===e.length)return"";for(var t='
    ',o=0;o💬 "+e[o]+"";return t+"
    "}("function"==typeof nachoFollowUps?nachoFollowUps((t||"")+" "+(e||"")):[])}N("nacho","",e+i),H("nacho","",e+i),j(),"function"==typeof nachoTrackTopic&&nachoTrackTopic(t,o||"unknown");var s=function(){if(M)return null;for(var e=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),t=[10,25,50,100,200,500],o=safeJSON("btc_nacho_q_milestones",[]),n=null,i=0;i=a&&-1===o.indexOf(r)&&-1===o.indexOf(a)&&(o.push(r),n=a)}return null===n?null:(localStorage.setItem("btc_nacho_q_milestones",JSON.stringify(o)),void 0!==db&&void 0!==auth&&auth&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({nachoMilestones:o}).catch(function(){}),M=!0,{10:"🎉 10 questions! You're officially a Bitcoin Beginner! Keep going — there's so much to learn! 🦌",25:"🎉 25 questions! You've leveled up to Bitcoin Explorer! You're asking the right questions! 💪",50:"🎉 50 questions! Bitcoin Apprentice unlocked! You know more than most people already! 🧠",100:"🏆 100 questions! You're a Bitcoin Scholar now! Satoshi would be proud! 🎓",200:"🔥 200 questions! Bitcoin Expert status! You could probably teach ME a thing or two! 🦌💡",500:"👑 500 QUESTIONS! You are a Bitcoin LEGEND! There's nothing Nacho can't discuss with you now! 🦌🏆🔥"}[n]||null)}();s&&setTimeout(function(){N("nacho","",s),H("nacho","",s)},1500)}function l(e){if(!i){i=!0,clearTimeout(a);var t="";e&&e.siteAction?t='

    ":e&&e.channel&&(t='

    📖 Read more: '+(e.channelName||e.channel)+" →"),s((e&&e.answer?e.answer:"Hmm, let me think about that... Try asking another way! 🦌")+t,e&&e.type||"fallback")}}},window.nachoModeAvatarTap=function(){var e=document.getElementById("nachoModeAvatar");e&&(e.style.transform="scale(1.1) rotate("+(Math.random()>.5?"5":"-5")+"deg)",setTimeout(function(){e.style.transform=""},300),"function"==typeof trackNachoInteraction&&trackNachoInteraction(),window._nachoModeEarnings.interactions++,j())},window._nachoModeRecognition=null,window._nachoModeListening=!1,window.nachoModeVoice=function(){var e=window.SpeechRecognition||window.webkitSpeechRecognition;if(e){var t=document.getElementById("nachoModeInput"),o=document.getElementById("nachoModeMic");if(t&&o)if(window._nachoModeListening&&window._nachoModeRecognition)window._nachoModeRecognition.stop();else{var n=new e;window._nachoModeRecognition=n,n.lang="en-US",n.interimResults=!0,n.maxAlternatives=1,n.continuous=!0,o.style.opacity="1",o.innerHTML="🛑",t.placeholder="Nacho is listening... (Tap 🛑 to finish)",t.style.borderColor="#f7931a",window._nachoModeListening=!0;var i="";n.onresult=function(e){for(var o="",n=e.resultIndex;n0&&nachoModeSend()},n.onerror=function(){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6",t.style.borderColor="var(--border,#333)",t.placeholder="Voice error — try typing"};try{n.start()}catch(e){window._nachoModeListening=!1,o.innerHTML="🎙️",o.style.opacity="0.6"}}}},window.exitNachoMode=function(e){window._nachoMode=!1,window._nachoBusy=!1,window._btcPriceTimer&&(clearInterval(window._btcPriceTimer),window._btcPriceTimer=null);var t=document.getElementById("nachoModeScreen");t&&t.remove(),document.querySelectorAll("aside, #rankBar, #lbFloatBtn, #dashboardFloatBtn, #floatingRandomBtn, #chatOverlayBtn, #aiToolsBtn, #userDisplay, #backToTop, #scrollToBottom, #nacho-container, #nacho-toggle, #guestPointsBanner").forEach(function(e){e&&(e.style.display="")});var o=document.querySelector(".mobile-bar");if(o&&window.innerWidth<=900&&(o.style.display="flex"),!e){var n=window._nachoModeEarnings,i=window._nachoModeStartTime||Date.now(),a=Math.round((Date.now()-i)/6e4);if("function"==typeof showToast){var r=[];a>0&&r.push("⏱️ "+a+" min"),n&&n.interactions>0&&r.push("🦌 "+n.interactions+" interactions"),n&&n.points>0&&r.push("+"+n.points+" XP");var s=n?Array.isArray(n.badges)?n.badges.length:n.badges||0:0;s>0&&r.push("🏅 "+s+" badge"+(s>1?"s":"")),r.length>0?showToast(r.join(" · ")):showToast("🦌 Thanks for hanging out with "+("function"==typeof nachoNickname?nachoNickname():"Nacho")+"!")}goHome()}},window.goHome=function(e){if(document.activeElement&&document.activeElement.blur&&document.activeElement.blur(),"function"==typeof hideUsernamePrompt){var t=document.getElementById("usernameModal");t&&t.classList.contains("open")&&hideUsernamePrompt()}"function"==typeof _tctvStopTracker&&_tctvStopTracker();var n=document.getElementById("bottomNav");n&&n.classList.remove("nav-hidden"),"function"==typeof _updateSEO&&_updateSEO("home","Learn Bitcoin","A curated Bitcoin education archive with 146 topics, 8800+ messages, and community tools.");var i=document.getElementById("floatingRandomBtn");i&&(i.style.display="none");var a=document.getElementById("lbFloatBtn");a&&a.classList.remove("chat-shifted"),(c=document.getElementById("forumContainer"))&&(c.style.display="none"),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes();var r=document.getElementById("msgs");r&&(r.style.display="none");var s=document.getElementById("hero");s&&(s.style.display="none");var l=void 0!==auth&&auth?auth.currentUser:null;l&&l.email,void 0!==currentUser&¤tUser&¤tUser.totalVisits;try{safeJSON("btc_visited_channels",[]).length}catch(e){}var c,d=document.querySelector('[onclick*="showSpinWheel"]'),u=(document.querySelector('[onclick*="showPricePrediction"]'),document.querySelector('[onclick*="showNachoStory"]'),document.getElementById("dailyChallengeCard")),p=document.querySelector("[onclick*=\"go('bitcoin-beats'\"]"),h=document.querySelector("[onclick*=\"go('forum'\"]"),m=document.querySelector("[onclick*=\"go('marketplace'\"]"),g=document.querySelector('[onclick*="enterNachoMode"]');d&&(d.parentElement.style.display="grid"),u&&(u.style.display=""),h&&(h.style.display=""),p&&(p.style.display=""),m&&(m.style.display=""),g&&(g.style.display=""),(c=document.getElementById("forumContainer"))&&(c.style.display="none",c.innerHTML="");var f=document.getElementById("hero");f&&(f.style.display="none",f.innerHTML="");var y=document.getElementById("msgs");if(y&&(y.style.display="none",y.innerHTML=""),document.getElementById("home").classList.remove("hidden"),document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),document.getElementById("main").scrollTop=0,e||history.pushState({channel:null},"","/"),"function"==typeof window._renderSatoshiFavorHome&&window._renderSatoshiFavorHome(),o()){document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0);var b=document.querySelector(".mobile-bar");b&&(b.style.display="flex"),"function"==typeof updateRankUI&&updateRankUI()}R(),"function"==typeof renderExplorationMap&&renderExplorationMap(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof loadCommunityStats&&loadCommunityStats(),"function"==typeof renderRaidBossHome&&renderRaidBossHome(),"function"==typeof window._renderCharityHome&&window._renderCharityHome(),"1"===sessionStorage.getItem("btc_return_guide")&&"function"==typeof showGuideReturnBtn&&showGuideReturnBtn()},document.addEventListener("keydown",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.isContentEditable){var t=e.key.toLowerCase();if(!e.ctrlKey&&!e.metaKey)if("h"!==t)if("/"!==t)if("c"!==t)if("r"!==t)if("m"!==t)if("a"!==t)if("t"!==t)if("s"!==t)if("l"!==t)if("q"!==t)if("f"!==t)if("n"!==t)if("d"!==t)if("v"!==t)if("g"!==t)if("p"!==t)if("x"!==t)if("j"!==t)if("k"!==t){if(" "===t)return e.preventDefault(),void document.getElementById("main").scrollBy({top:.8*window.innerHeight,behavior:"smooth"});if("?"===t||e.shiftKey&&"/"===t)!function(){var e=document.getElementById("kbHelpModal");if(e)e.remove();else{var t=document.createElement("div");t.id="kbHelpModal",t.style.cssText="position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.7);",t.onclick=function(e){e.target===t&&t.remove()},t.innerHTML='

    ⌨️ Keyboard Shortcuts

    Press ? to toggle this menu
    Navigation
    '+V("H","Go home")+V("/","Search")+V("C","Random topic")+V("M","Random Meme")+V("R","Random Art")+V("G","Random Graphic")+V("B","Back to last channel")+V("T","PlebTalk (Forum)")+V("S","Lightning Mart")+'
    Actions
    '+V("F","Favorite channel")+V("A","Ask Nacho")+V("N","Nacho Mode")+V("D","Dark / Light mode")+V("L","Leaderboard")+V("Q","Start quest")+V("V","Gallery view")+V("X","PVP Battle")+V("P","Donate")+V("I","Settings")+'
    Scrolling
    '+V("J","Scroll down")+V("K","Scroll up")+V("Space","Page down")+V("Esc","Close modals")+'
    Mobile Gestures
    '+V("2-finger","Nacho Mode")+V("3-finger","Settings")+V("Long-press","Explore Apps (on logo)")+"
    ",document.body.appendChild(t)}}();else if("i"!==t)if("b"!==t)if("2"!==t)if("3"!==t)if("1"!==t){if("0"===t)return F("Don't trust. Verify."),void("function"==typeof earnSticker&&earnSticker("cool"));if("9"===t)return F("Number go up!"),void("function"==typeof nachoFly&&nachoFly());if("2"!==window._eggBuffer||"1"!==t)if("w"!==t){if(window._eggBuffer=(window._eggBuffer||"")+t,window._eggBuffer.length>10&&(window._eggBuffer=window._eggBuffer.slice(-10)),-1!==window._eggBuffer.indexOf("btc")&&(window._eggBuffer="",localStorage.setItem("btc_bitcoin_eyes_unlocked","true"),"function"==typeof showToast&&showToast("₿₿ Secret unlocked: Bitcoin Eyes! Check Nacho's Closet!"),"function"==typeof haptic&&haptic("success")),"escape"===t){e.preventDefault();var i=document.getElementById("lb");if(i&&i.classList.contains("open"))return void i.classList.remove("open");var a=document.getElementById("usernameModal");if(a&&a.classList.contains("open"))return void("function"==typeof hideUsernamePrompt&&hideUsernamePrompt());var r=document.getElementById("questModal");if(r&&r.classList.contains("open"))return void r.classList.remove("open");var s=document.getElementById("searchOverlay");if(s&&"none"!==s.style.display)return void(s.style.display="none");var l=document.getElementById("nachoStoryOverlay");if(l)return void l.remove();var c=document.getElementById("spinModal");if(c)return void c.remove();var d=document.getElementById("donateModal");if(d)return void d.remove();var u=document.getElementById("kbHelpModal");if(u)return void u.remove();if(document.getElementById("pvpOverlay"))return void("function"==typeof exitPVPMode&&exitPVPMode());var p=document.getElementById("appsMenu");if(p&&"block"===p.style.display)return void(p.style.display="none");if(o()){var h=document.getElementById("sidebar");if(h&&h.classList.contains("open"))return h.classList.remove("open"),void("function"==typeof setFloatingElementsVisible&&setFloatingElementsVisible(!0))}if(window._nachoMode&&"function"==typeof exitNachoMode)return void exitNachoMode()}}else F("Stay humble. Stack sats.");else F("Twenty-one million. Final and absolute.")}else F("One more block.");else F("Three point one two five. The current block reward.");else F("There is no second best.");else{var m=localStorage.getItem("btc_last_channel");m&&go(m)}else"function"==typeof showSettingsPage&&showSettingsPage("account")}else document.getElementById("main").scrollBy({top:-300,behavior:"smooth"});else document.getElementById("main").scrollBy({top:300,behavior:"smooth"});else"function"==typeof _launchPVP&&_launchPVP();else showDonateModal();else B();else{var g=document.getElementById("galleryBtn");g&&g.click()}else n();else"function"==typeof enterNachoMode&&enterNachoMode();else{var f=document.getElementById("favBtn");f&&f.click()}else{var y=document.getElementById("questBtn");y&&y.click()}else"function"==typeof toggleLeaderboard&&toggleLeaderboard();else go("marketplace");else go("forum");else"function"==typeof showNachoInput&&showNachoInput();else x();else k();else v();else{e.preventDefault();var b=document.getElementById("searchInput");b&&(b.focus(),o()&&document.getElementById("sidebar").classList.add("open"))}else goHome()}});var W=0;function F(e){var t=Date.now();if(!(t-W<3e3)){W=t,"function"==typeof showToast&&showToast("🟠 "+e);try{var o=new SpeechSynthesisUtterance(e);o.rate=.9,o.pitch=.85,o.volume=.8;var n=speechSynthesis.getVoices().find(function(e){return-1!==e.name.indexOf("Daniel")||-1!==e.name.indexOf("Google UK English Male")||-1!==e.name.indexOf("Male")});n&&(o.voice=n),speechSynthesis.cancel(),speechSynthesis.speak(o)}catch(e){}}}function V(e,t){return'
    '+e+'
    '+t+"
    "}"undefined"!=typeof speechSynthesis&&speechSynthesis.getVoices(),function(){if("ontouchstart"in window){var e=0,t=0;window.addEventListener("devicemotion",function(o){var n=o.acceleration&&null!==o.acceleration.x?o.acceleration:null;if(n&&Math.abs(n.x)+Math.abs(n.y)+Math.abs(n.z)>25){if(e++,clearTimeout(window._shakeResetTimer),window._shakeResetTimer=setTimeout(function(){e=0},1e3),e<3)return;e=0;var i=Date.now();if(i-t<1e4)return;t=i;var a=["There is no second best.","One more block.","Don't trust. Verify.","Number go up!","Stay humble. Stack sats.","Not your keys, not your coins.","Bitcoin fixes this.","Tick tock, next block."];F(a[Math.floor(Math.random()*a.length)]),Math.random()<.3&&"function"==typeof nachoFly&&nachoFly()}});var o=0,n=0,i=0,a=document.getElementById("main");a.addEventListener("touchstart",function(e){"INPUT"===e.target.tagName||"TEXTAREA"===e.target.tagName||e.target.closest(".no-swipe")||(o=e.touches[0].clientX,n=e.touches[0].clientY,i=Date.now())},{passive:!0}),a.addEventListener("touchend",function(e){if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&!e.target.closest(".no-swipe")){var t=e.changedTouches[0].clientX-o,a=e.changedTouches[0].clientY-n,r=Date.now()-i,s=Math.abs(t),l=Math.abs(a);r>600||s>150&&s>2.5*l&&(t>0?(goPrev(),"function"==typeof haptic&&haptic("light")):(goNext(),"function"==typeof haptic&&haptic("light")))}},{passive:!0});var r=0,s=0;document.getElementById("main").addEventListener("touchstart",function(e){2===e.touches.length&&(s=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(s&&0===e.touches.length&&e.changedTouches.length>=1){var t=Date.now()-s;if(s=0,t>400)return;var o=Date.now();if(o-r<3e3)return;r=o,"function"==typeof enterNachoMode&&enterNachoMode()}},{passive:!0}),document.querySelectorAll(".home-logos img, .channel-logos .channel-logo-img").forEach(d),new MutationObserver(function(){document.querySelectorAll(".channel-logos .channel-logo-img").forEach(d)}).observe(document.getElementById("main"),{childList:!0,subtree:!0});var l=0,c=0;document.getElementById("main").addEventListener("touchstart",function(e){3===e.touches.length&&(c=Date.now())},{passive:!0}),document.getElementById("main").addEventListener("touchend",function(e){if(c&&0===e.touches.length){var t=Date.now()-c;if(c=0,t>400)return;var o=Date.now();if(o-l<3e3)return;l=o,"function"==typeof showSettings&&showSettings()}},{passive:!0})}function d(e){var t;e._logoLongPress||(e._logoLongPress=!0,e.addEventListener("touchstart",function(e){t=setTimeout(function(){"function"==typeof toggleAppsMenu&&toggleAppsMenu(),"function"==typeof haptic&&haptic("medium")},800)},{passive:!0}),e.addEventListener("touchend",function(){clearTimeout(t)}),e.addEventListener("touchmove",function(){clearTimeout(t)}))}}();const G={};function Q(){const e=safeJSON("btc_visited_channels",[]).length;void 0!==currentUser&¤tUser&¤tUser.totalVisits;var t=void 0!==auth?auth:null,o=t&&t.currentUser;o&&o.email;var n="function"==typeof getOnboardingProfile?getOnboardingProfile():null;n&&("advanced"===n.level||n.level);const i=document.querySelectorAll(".cat-label.cat-toggle"),a=document.querySelectorAll(".quest-start-btn, .home-cta, #beatsBtnHome, [onclick*=\"go('forum'\"], [onclick*=\"go('marketplace'\"]");function r(e){return function(){var t=e.match(/^go\(['"]([^'"]+)['"]/);if(t)go(t[1]);else{var o=e.match(/^(?:if\(typeof\s+(\w+)==='function'\))?\s*(\w+)\(\)/);if(o){var n=o[2]||o[1];if("function"==typeof window[n])return void window[n]()}var i=e.match(/renderChatHub\(['"](\w+)['"]\)/);if(i&&"function"==typeof window.renderChatHub)window.renderChatHub(i[1]);else{var a=e.match(/showSettingsPage\(['"](\w+)['"]\)/);a&&"function"==typeof window.showSettingsPage?window.showSettingsPage(a[1]):console.warn("[SECURITY] Unrecognized action pattern:",e)}}}}i.forEach(function(e){var t=e.nextElementSibling;t&&t.classList.contains("cat-group")&&(e.style.display="",t.style.display="true"===e.getAttribute("data-expanded")?"":"none")}),a.forEach(e=>{if(e.closest("#appsMenu")||e.closest("#guideOverlay")||e.closest("#questHubOverlay"))return;const t=e.getAttribute("data-name")||e.textContent.replace("🔒 ","").trim();e.getAttribute("data-name")||e.setAttribute("data-name",t);const o=e.getAttribute("data-onclick")||e.getAttribute("onclick");e.getAttribute("data-onclick")||e.setAttribute("data-onclick",o),e.innerHTML=t,e.style.opacity="1",e.style.filter="none",e.style.cursor="pointer",e.title="";var n=e.getAttribute("data-onclick");n&&(e.onclick=r(n))}),document.querySelectorAll("[data-tier]").forEach(t=>{const o=t.getAttribute("data-tier"),n=t.getAttribute("data-unlock-name")||t.textContent.trim(),i=t.getAttribute("data-onclick")||t.getAttribute("onclick");!t.getAttribute("data-onclick")&&i&&t.setAttribute("data-onclick","string"==typeof i?i:i.toString()),!t.getAttribute("data-orig-tooltip")&&t.getAttribute("data-tooltip")&&t.setAttribute("data-orig-tooltip",t.getAttribute("data-tooltip"));let a=!1,s="";if("explorer"===o?(a=true,s="🔒 Visit "+Math.max(0,3-e)+" more channel"+(3-e==1?"":"s")+" to unlock "+n+"!"):"community"===o?(a=true,s="🔒 Explore "+Math.max(0,5-e)+" more channel"+(5-e==1?"":"s")+" to unlock "+n+"!"):"full"===o&&(a=true,s="🔒 Explore "+Math.max(0,10-e)+" more channel"+(10-e==1?"":"s")+" or sign in to unlock "+n+"!"),a){t.innerHTML=n,t.style.opacity="1",t.style.filter="none";var l=t.getAttribute("data-orig-tooltip")||t.getAttribute("data-tooltip");l?(t.title=l,t.setAttribute("data-tooltip",l)):t.title=n,t.style.cursor="pointer",t.title="";var c=t.getAttribute("data-onclick");c&&(t.onclick=r(c))}else t.innerHTML="🔒 "+n,t.style.opacity="0.45",t.style.filter="grayscale(0.8)",t.style.cursor="help",t.title=s,t.setAttribute("data-tooltip",s),t.onclick=function(e){e.preventDefault(),e.stopPropagation(),"function"==typeof showToast&&showToast(s)}});var s=localStorage.getItem("btc_unlocked_tier")||"none",l=["none","explorer","community","full"],c="full",d=l.indexOf(s);if(l.indexOf(c)>d){localStorage.setItem("btc_unlocked_tier",c);var u=document.getElementById("appsMenu");u&&u.remove(),"function"==typeof showToast&&showToast("🚀 ⚡ Lightning Mart unlocked! You have full access!")}var p=document.getElementById("sidebarMilestone");p&&p.remove()}function J(){window.audioEnabled=!window.audioEnabled,localStorage.setItem("btc_audio",window.audioEnabled.toString()),X(),"function"==typeof showToast&&showToast(window.audioEnabled?"🔊 Sound on":"🔇 Sound off")}function Y(e){window.audioVolume=parseFloat(e),localStorage.setItem("btc_volume",window.audioVolume.toString()),window.audioVolume<=0?(window.audioEnabled=!1,localStorage.setItem("btc_audio","false")):window.audioEnabled||(window.audioEnabled=!0,localStorage.setItem("btc_audio","true")),window._beatsAudio&&(window._beatsAudio.volume=window.audioVolume),window._djAudio&&(window._djAudio.volume=window.audioVolume);var t=document.getElementById("beatsVolume");t&&(t.value=Math.round(100*window.audioVolume));var o=document.getElementById("djVolume");o&&(o.value=Math.round(100*window.audioVolume)),X()}function X(){const e=document.getElementById("audioBtn");e&&(e.textContent=window.audioEnabled&&window.audioVolume>0?window.audioVolume>.5?"🔊":"🔉":"🔇");const t=document.getElementById("volumeSlider");t&&(t.value=window.audioEnabled?window.audioVolume:0),document.querySelectorAll('button[onclick*="toggleAudio"]').forEach(function(e){"ON"!==e.textContent&&"OFF"!==e.textContent||(e.textContent=window.audioEnabled?"ON":"OFF",e.style.background=window.audioEnabled?"#22c55e":"var(--bg-side)",e.style.color=window.audioEnabled?"#fff":"var(--text-muted)")})}Q(),window._sidebarTierInterval=setInterval(Q,5e3),window.audioEnabled="false"!==localStorage.getItem("btc_audio"),window.audioVolume=parseFloat(localStorage.getItem("btc_volume")||"0.5"),window.canPlaySound=function(){return window.audioEnabled&&window.audioVolume>0&&"visible"===document.visibilityState},window.goNext=function(){if(void 0===CHANNELS)return;const e=window._sidebarOrder&&window._sidebarOrder.length>0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(h);if(-1===t)return void go(e[0]);const o=t0?window._sidebarOrder:Object.keys(CHANNELS),t=e.indexOf(h);if(-1===t)return void go(e[e.length-1]);const o=t>0?e[t-1]:e[e.length-1];go(o)},window.go=async function(e,t,n){"function"==typeof _tctvStopTracker&&_tctvStopTracker();var i=document.getElementById("bottomNav");i&&i.classList.remove("nav-hidden"),window._nachoMode&&!n&&("function"==typeof nachoChatSave&&nachoChatSave(),window._nachoReturnPending=!0);var a=document.getElementById("msgs"),r=document.getElementById("hero");const c=CHANNELS[e];let d="";c&&(d='"),a.innerHTML=d+'
    \x3c!-- Nacho Summary skeleton --\x3e
    \x3c!-- Message skeletons --\x3e
    \x3c!-- Image skeleton --\x3e
    ',a.style.display="",document.getElementById("home").classList.add("hidden"),r.style.display="none",o()&&document.getElementById("sidebar").classList.remove("open");try{safeJSON("btc_visited_channels",[]).length}catch(e){}void 0!==currentUser&¤tUser&¤tUser.totalVisits;var m,f=void 0!==auth&&auth?auth.currentUser:null;if(f&&f.email,"forum"===e||"marketplace"===e||"bitcoin-beats"===e||"irl-sync"===e||"dms"===e||"lightning"===e||"chat"===e||"first-purchase"===e||"timechain-tv"===e||"trails"===e)return window._nachoMode&&exitNachoMode(!0),document.getElementById("home").classList.add("hidden"),document.getElementById("hero").innerHTML="",document.getElementById("msgs").innerHTML="",document.getElementById("msgs").style.display="none",document.getElementById("hero").style.display="none",(m=document.getElementById("forumContainer"))&&(m.style.display="block"),n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&document.getElementById("sidebar").classList.remove("open"),function e(t,o){if(o=o||0,"first-purchase"===t&&"function"==typeof renderFirstPurchase)renderFirstPurchase(),document.getElementById("main").scrollTop=0;else if("timechain-tv"===t&&"function"==typeof renderTimechainTV)renderTimechainTV(),document.getElementById("main").scrollTop=0,"function"==typeof _tctvStartTracker&&_tctvStartTracker();else if("marketplace"===t&&"function"==typeof renderMarketplace)renderMarketplace();else if("bitcoin-beats"===t&&"function"==typeof renderBitcoinBeats)renderBitcoinBeats();else if("irl-sync"===t&&"function"==typeof renderIRLSync)renderIRLSync();else if("dms"===t&&"function"==typeof showInbox)showInbox();else if("lightning"===t&&"function"==typeof renderLightning)renderLightning();else if("chat"===t&&"function"==typeof renderChatHub)renderChatHub("global");else if("trails"===t&&"function"==typeof renderModules)renderModules();else if("forum"===t&&"function"==typeof renderForum)renderForum();else if(o<20){if(setTimeout(function(){e(t,o+1)},250),0===o){var n=document.getElementById("forumContainer");n&&(n.innerHTML='
    Loading...
    ')}}else if("forum"===t&&"function"==typeof renderForum)renderForum();else{var i=document.getElementById("forumContainer");i&&(i.innerHTML='
    ⚠️
    Still loading...
    This feature is taking longer than expected.
    ')}}(e),document.getElementById("main").scrollTop=0,m&&(m.scrollTop=0),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0,setTimeout(function(){document.getElementById("main").scrollTop=0,document.getElementById("forumContainer")&&(document.getElementById("forumContainer").scrollTop=0),window.scrollTo(0,0)},50),setFloatingElementsVisible(!0),void("function"==typeof nachoOnPage&&nachoOnPage(e));if(!c)return;if(window._nachoMode&&exitNachoMode(!0),(m=document.getElementById("forumContainer"))&&(m.style.display="none",m.innerHTML=""),"function"==typeof window._hideMarketIframes&&window._hideMarketIframes(),document.getElementById("hero").style.display="",document.getElementById("msgs").style.display="",!window._keepFloatingBtn){var y=document.getElementById("floatingRandomBtn");y&&"none"!==y.style.display&&"memes-funny"!==e&&"art-inspiration"!==e&&"graphics"!==e&&(y.style.display="none")}localStorage.setItem("btc_last_channel",e),function(){if(window.canPlaySound())try{const e=new(window.AudioContext||window.webkitAudioContext),t=window.audioVolume,o=e.createOscillator(),n=e.createGain();o.connect(n),n.connect(e.destination),o.frequency.value=880,o.type="sine",n.gain.setValueAtTime(.08*t,e.currentTime),n.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15),o.start(e.currentTime),o.stop(e.currentTime+.15);const i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.frequency.value=1318.5,i.type="sine",a.gain.setValueAtTime(.05*t,e.currentTime+.05),a.gain.exponentialRampToValueAtTime(.001,e.currentTime+.25),i.start(e.currentTime+.05),i.stop(e.currentTime+.25)}catch(e){}}(),document.getElementById("home").classList.add("hidden"),(a=document.getElementById("msgs")).innerHTML=d+'
    ',document.querySelectorAll(".ch-btn").forEach(e=>e.classList.remove("active")),t?(t.classList.add("active"),s(t)):document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&-1!==t.getAttribute("onclick").indexOf("'"+e+"'")&&(t.classList.add("active"),s(t))});const b=["graphics","memes-funny","art-inspiration","charts","swag-merch","fun-facts"].includes(e),v="https://bitcoineducation.quest/#"+e,w=c.title+" — Bitcoin Education Archive";let x;if(document.getElementById("hero").innerHTML='
    Home
    '+c.cat+"

    "+c.title+'

    "+(b?'":""),document.getElementById("hero").classList.remove("fade-in"),document.getElementById("msgs").innerHTML='
    Loading channel...
    ',document.getElementById("main").scrollTop=0,n||history.pushState({channel:e},"",_cleanUrl(e)),o()&&(document.getElementById("sidebar").classList.remove("open"),setFloatingElementsVisible(!0)),G[e])x=G[e];else try{const t=await fetch(c.file);x=await t.json(),G[e]=x}catch(e){return void(document.getElementById("msgs").innerHTML='
    Error loading channel data
    ')}if(p=x,h=e,window.currentChannelId=e,u=!1,"function"==typeof window._raidOnChannelVisit&&window._raidOnChannelVisit(e),"function"==typeof _updateSEO&&void 0!==CHANNELS&&CHANNELS[e]){var k=CHANNELS[e];_updateSEO(e,k.title||k.name,k.desc||"")}if(g(e),window._searchScrollTarget&&window._searchScrollTarget.channel===e){var B=0;setTimeout(function e(){B++,window._searchScrollTarget&&(document.getElementById("msg-"+window._searchScrollTarget.msgIdx)||B>=3?"function"==typeof window._tryScrollToSearchResult&&window._tryScrollToSearchResult():setTimeout(e,400*B))},200)}document.getElementById("hero").classList.add("fade-in"),document.getElementById("msgs").classList.add("fade-in"),window._currentMsgs=x.msgs,window._currentOffset=o()?20:50,window._currentLoadChannel=e,window.loadMoreMsgs=function(){if(window._currentLoadChannel!==h)return;const e=window._currentOffset,t=window._currentMsgs,n=document.getElementById("loadMoreBtn");if(!n)return;const i=t.slice(e,e+50);let a="";i.forEach((t,n)=>{if(a+='
    ',t.text){let e=t.text,n=[],i=[];e=e.replace(/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:[&?][^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?youtu\.be\/([\w-]+)(?:\?[^\s]*)?/g,function(e,t){return n.push(t),"%%YT"+(n.length-1)+"%%"}),e=e.replace(/(?:https?:\/\/)?(?:twitter\.com|x\.com)\/([\w]+)\/status\/(\d+)(?:[^\s]*)?/g,function(e){var t=e.startsWith("http")?e:"https://"+e;return i.push(t),"%%TW"+(i.length-1)+"%%"}),e=e.replace(/(https?:\/\/[^\s<>"]+)/g,'$1'),e=e.replace(/%%YT(\d+)%%/g,function(e,t){return'
    '}),e=e.replace(/%%TW(\d+)%%/g,function(e,t){var n=i[parseInt(t)],a="tw_"+Math.random().toString(36).substr(2,8),r=o(),s=n.match(/(?:twitter\.com|x\.com)\/([\w]+)\//),l=s?"@"+s[1]:n.replace(/https?:\/\/(www\.)?/,"");return'
    𝕏
    '+l+'
    '+(r?"▶ Tap to display tweet":"▶ Click to display tweet")+'
    '}),e=e.replace(/🟠 (.+)/g,'$1'),a+='
    '+e+"
    "}t.imgs&&t.imgs.forEach(e=>{t.link?a+='':a+=''}),a+="
    "}),n.insertAdjacentHTML("beforebegin",a),window._currentOffset=e+50,window._currentOffset>=t.length?(n.remove(),window._scrollObserver&&window._scrollObserver.disconnect()):n.textContent="Load more ("+(t.length-window._currentOffset)+" remaining)"},function(){if(window._scrollObserver&&(window._scrollObserver.disconnect(),window._scrollObserver=null),document.getElementById("loadMoreBtn")){window._scrollObserver=new IntersectionObserver(function(e){e[0].isIntersecting&&"function"==typeof window.loadMoreMsgs&&window.loadMoreMsgs()},{root:null,rootMargin:"300px",threshold:0});var e=document.getElementById("loadMoreBtn");e&&window._scrollObserver.observe(e)}}(),document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")});let S=safeJSON("btc_visited_channels",[]);S.includes(e)||(S.push(e),localStorage.setItem("btc_visited_channels",JSON.stringify(S)),Q());try{void 0!==db&&"undefined"!=typeof firebase&&db.collection("stats").doc("global").set({channelVisits:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}if("function"==typeof window._raidContribute&&window._raidContribute("channelVisit",1,e),x.msgs&&x.msgs.length>0){const t='
    Did this help you learn something?
    Your feedback helps Nacho improve the archive!
    ';a.insertAdjacentHTML("beforeend",t)}window._lastChannelOpenTime=Date.now(),"function"==typeof onChannelOpen&&onChannelOpen(e)};let K=!1,$={},Z=null;const ee=[{id:"_irl",title:"🤝 IRL Sync",desc:"Find and create local Bitcoin meetups and events",keywords:"irl meetup events sync meeting community local map gather conference meetup event rsvp",action:"go('irl-sync')"},{id:"_beats",title:"🎸 Bitcoin Beats",desc:"Community music — discover, upload, and listen to Bitcoin tracks. Upload entire albums and EPs.",keywords:"beats music livestream live video radio stream audio upload song track listen discover artist genre community album ep discography bulk batch dj broadcast",action:"go('bitcoin-beats')"},{id:"_nacho",title:"🦌 Nacho Mode",desc:"Interactive AI-powered Bitcoin tutor",keywords:"nacho mode ai chat ask question tutor learn mascot deer",action:"enterNachoMode()"},{id:"_forum",title:"🗣️ PlebTalk",desc:"Discuss Bitcoin with the community",keywords:"forum community chat discuss talk conversation post plebtalk reply thread threaded replies nested conversation",action:"go('forum')"},{id:"_articles",title:"📝 Articles",desc:"Read and write long-form Bitcoin articles",keywords:"article write publish essay blog read long form content author",action:"forumTab='articles';go('forum')"},{id:"_market",title:"⚡ LightningMart",desc:"Buy and sell with Bitcoin",keywords:"marketplace market buy sell trade shop store bitcoin sats lightning wallet hardware merch",action:"go('marketplace')"},{id:"_settings",title:"⚙️ Settings",desc:"Profile, rank, tickets, referral link, theme",keywords:"settings profile account rank level points tickets referral theme dark light audio sound notifications push",action:"showSettings()"},{id:"_spin",title:"🎡 Daily Spin",desc:"Spin the wheel for free Orange Tickets",keywords:"spin wheel daily reward ticket prize free",action:"showSpinWheel()"},{id:"_quest",title:"⚔️ Quest Hub",desc:"Quiz, Trivia, and Poll quests — earn XP!",keywords:"quest mission journey learn guided start challenge quiz trivia poll hub",action:"showQuestHub()"},{id:"_scholar",title:"🎓 Scholar Certification",desc:"Bitcoin Scholar & Protocol Expert Certifications",keywords:"scholar certification exam test certificate diploma bitcoin technical protocol",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_signal",title:"📡 The Signal",desc:"Weekly curated Bitcoin insights newsletter",keywords:"signal newsletter weekly email updates curated insights",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_flashcards",title:"📚 Flashcards",desc:"Study Bitcoin topics with interactive flashcards",keywords:"flashcard study cards learn review quiz prep memorize practice drill test",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_leaderboard",title:"🏆 Leaderboard",desc:"See top ranked Bitcoiners",keywords:"leaderboard ranking top leaders scoreboard competition",action:"toggleLeaderboard()"},{id:"_tickets",title:"🎟️ Orange Tickets",desc:"Earn tickets for giveaways and rewards",keywords:"tickets orange giveaway raffle prize sats reward earn",action:"showSettings()"},{id:"_referral",title:"🔗 Referral Program",desc:"Invite friends and earn 50 tickets each",keywords:"referral invite share link friend earn bonus",action:"showSettings()"},{id:"_closet",title:"🎽 Nacho's Closet",desc:"Dress up Nacho with items you unlock",keywords:"closet outfit clothes dress costume item equip nacho customize color hat scarf sunglasses crown hoodie accessories wardrobe",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_badges",title:"🏅 Badges",desc:"View your earned badges and goals — chat, DJ, discovery, knowledge",keywords:"badges achievement trophy unlock goal progress medal chat dj streak listener",action:"showSettings();setTimeout(function(){var t=document.querySelector('[onclick*=nacho]');if(t)t.click()},300)"},{id:"_story",title:"📖 Nacho's Story",desc:"Read Nacho's Bitcoin adventure — one chapter per day",keywords:"story chapter read book adventure nacho tale",action:"showNachoStory()"},{id:"_predict",title:"📈 Price Prediction",desc:"Predict if Bitcoin goes up or down in 24 hours",keywords:"predict prediction price bitcoin up down forecast",action:"showPricePrediction()"},{id:"_random",title:"🎲 Random Channel",desc:"Jump to a random Bitcoin channel",keywords:"random channel surprise discover explore dice",action:"goRandom()"},{id:"_meme",title:"😂 Random Meme",desc:"See a random Bitcoin meme",keywords:"meme funny joke random humor laugh memes",action:"goRandomMeme()"},{id:"_art",title:"🎨 Random Art",desc:"See random Bitcoin art and inspiration",keywords:"art random artwork creative inspiration gallery",action:"goRandomArt()"},{id:"_graphic",title:"📊 Random Graphic",desc:"See a random Bitcoin graphic or chart",keywords:"graphic chart data visual infographic random graphics",action:"goRandomGraphic()"},{id:"_quiz",title:"🎮 Quiz Me",desc:"Test your Bitcoin knowledge with Nacho",keywords:"quiz question test knowledge trivia game answer",action:"nachoQuizMe()"},{id:"_pvp",title:"⚔️ PVP Battle",desc:"Real-time Bitcoin trivia battles against other players",keywords:"pvp battle fight 1v1 versus trivia quiz compete multiplayer arena duel challenge opponent leaderboard wins losses",action:"_launchPVP()"},{id:"_donate",title:"💛 Donate",desc:"Support Bitcoin Education Archive with sats",keywords:"donate support tip sats lightning contribute funding",action:"showDonateModal()"},{id:"_theme",title:"🌙 Toggle Theme",desc:"Switch between dark and light mode",keywords:"theme dark light mode toggle switch appearance color night day",action:'document.getElementById("themeToggle").click()'},{id:"_audio",title:"🔊 Toggle Audio",desc:"Turn sound effects on or off",keywords:"audio sound music mute volume effects toggle",action:"toggleAudio()"},{id:"_keyboard",title:"⌨️ Keyboard Shortcuts",desc:"View all keyboard shortcuts",keywords:"keyboard shortcut hotkey key binding keys shortcuts help",action:"showKeyboardHelp()"},{id:"_explore",title:"🗺️ Exploration Map",desc:"See which topics you have visited",keywords:"exploration map progress visited topics grid complete coverage",action:"goHome()"},{id:"_globalchat",title:"🌍 Global Chat",desc:"Live global chat room — talk with the community in real time",keywords:"global chat room live talk community message send public chatroom online users presence dm reaction gif emoji sticker emoji picker smiley face emoticon",action:"if(typeof renderChatHub==='function')renderChatHub('global');else if(typeof toggleChatOverlay==='function')toggleChatOverlay()"},{id:"_timechaintv",title:"📺 Timechain TV",desc:"Live Bitcoin television — 8 channels of curated Bitcoin videos playing 24/7",keywords:"tv television video watch live stream channel timechain tube youtube documentary tutorial mining sync broadcast cinema epg guide schedule remote couch nacho",action:"go('timechain-tv')"},{id:"_djmode",title:"🎧 DJ Mode",desc:"Go live as a DJ — broadcast music, use sound effects, crossfade, and play Bitcoin quotes",keywords:"dj mode broadcast live music stream turntable crossfade sound effects horn airhorn scratch mixer controls",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('livestream')},300)"},{id:"_upload_album",title:"📀 Upload Album/EP",desc:"Upload up to 20 songs at once — group as Album or EP with cover art",keywords:"upload album ep discography batch bulk multiple songs tracks artist release collection",action:"go('bitcoin-beats');setTimeout(function(){beatsTab('upload')},300)"},{id:"_messages",title:"💬 Messages / DMs",desc:"Direct messages — chat privately with other users",keywords:"messages dm direct message inbox chat private conversation contact send receive talk",action:"showInbox()"},{id:"_signin",title:"🔐 Sign In",desc:"Sign in or create an account",keywords:"sign in login register create account google twitter github facebook email",action:"showUsernamePrompt()"},{id:"_home",title:"🏠 Home",desc:"Return to the homepage",keywords:"home main start beginning",action:"goHome()"},{id:"_firstpurchase",title:"🛒 Your First Bitcoin Purchase",desc:"Step-by-step guide to buying your first Bitcoin — apps for 11 regions",keywords:"buy purchase first bitcoin exchange app strike river cash coinbase amber wallet region country how to start beginner dca",action:"go('first-purchase')"},{id:"_trails",title:"🦌 Nacho's Trails",desc:"Guided learning paths through Bitcoin education — Meadow, Mountain & Summit",keywords:"trails nacho guided path learning course module meadow mountain summit exam test progress curriculum education beginner intermediate advanced",action:"go('trails')"},{id:"_dashboard",title:"📊 Top Indicators",desc:"Live Bitcoin cycle top indicators — Pi Cycle, NUPL, Puell, Power Law & more",keywords:"dashboard indicators top cycle signal pi cycle nupl puell mayer multiple rsi ahr999 mstr etf power law rainbow reserve risk bitcoin metrics data analytics chart",action:"if(typeof toggleDashboard==='function')toggleDashboard()"},{id:"_meetupbox",title:"📦 Meetup-in-a-Box",desc:"Ready-made meetup templates with agendas and host tips",keywords:"meetup box template agenda host tips lightning workshop self custody mining event organize plan download",action:"go('irl-sync')"},{id:"_buddy",title:"🤝 Bitcoin Buddy",desc:"Find a learning partner — teachers matched with learners",keywords:"buddy partner match learn teach mentor mentee pair connect chat find friend study accountability group",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_certs",title:"📜 Shareable Certificates",desc:"Share your Scholar Certification with a verifiable public link",keywords:"certificate share verify link public proof scholar achievement social media url",action:"showSettings();setTimeout(function(){showSettingsPage('scholar')},100)"},{id:"_satsvbits",title:"⚡ Sats vs Bits",desc:"Live community vote — sats or bits for the Bitcoin denomination?",keywords:"sats bits vote poll denomination unit satoshi community debate live",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_newbie",title:"🟢 Brand New to Bitcoin?",desc:"Quick introduction for absolute beginners",keywords:"new beginner brand new start zero nothing know nothing introduction first time newbie noob",action:"go('one-stop-shop')"},{id:"_meetupbuilder",title:"🔨 Meetup Builder",desc:"Plan, share, and discover Bitcoin meetups — resources, venues & guides",keywords:"meetup builder create plan share venue platform resource guide community",action:"go('meetup-builder')"},{id:"_sats",title:"⚡ Claim Sats",desc:"Convert your earned points into real Bitcoin sats via Lightning",keywords:"sats claim withdraw cashout bitcoin lightning faucet earn XP convert redeem payout real btc satoshi",action:"showSettings();setTimeout(function(){showSettingsPage('sats')},100)"},{id:"_tips",title:"⚡ Lightning Tips",desc:"Tip other users with Lightning sats",keywords:"tip tips lightning send sats zap reward give appreciation",action:"if(typeof showTipOverlay==='function')showTipOverlay()"},{id:"_network",title:"📡 Bitcoin Network",desc:"Live mempool, hashrate, difficulty, fees, and block explorer",keywords:"network mempool hashrate difficulty fees block explorer transaction confirmations bitcoin network stats",action:"go('bitcoin-dashboard')"},{id:"_notifications",title:"🔔 Notifications",desc:"Enable push notifications for updates and alerts",keywords:"notifications push alerts notify bell updates permission enable disable",action:"if(typeof requestNotificationPermission==='function')requestNotificationPermission();else showSettings()"},{id:"_streakfreeze",title:"🧊 Streak Freeze",desc:"Protect your visit streak with freeze tickets",keywords:"streak freeze ticket protect miss save guard insurance ice",action:"showSettings();setTimeout(function(){showSettingsPage('data')},100)"},{id:"_cotd",title:"📅 Channel of the Day",desc:"Today's featured Bitcoin education channel",keywords:"channel of the day daily featured recommendation today pick spotlight",action:"goHome()"},{id:"_nostr",title:"🟣 Nostr Login",desc:"Sign in with Nostr — extension, nsec, or npub",keywords:"nostr login sign in nip npub nsec extension relay decentralized identity",action:"showUsernamePrompt()"},{id:"_buddyfind",title:"🤝 Find a Bitcoin Buddy",desc:"Get matched with a learning partner — teachers meet learners",keywords:"buddy partner match learn teach mentor mentee pair connect study group accountability partner friend",action:"if(typeof renderChatHub==='function')renderChatHub('global')"},{id:"_favor",title:"✨⛏️ Satoshi's Favor",desc:"Community mining game — earn points, activate mining, hash for 21,000 sats",keywords:"satoshi favor mining hash mine community points activate 21 sats game block nonce difficulty target hashing brute force proof of work",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='favor';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_raid",title:"⚔️ Raid Boss",desc:"Monthly community challenge — deal damage by earning badges and completing activities",keywords:"raid boss challenge monthly community damage badge activity quest defeat winner prize leaderboard attack",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='raid';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_charity",title:"❤️ Donate XP for Charity",desc:"Donate your XP points for charity — 1,000 XP = 1,000 sats pledged. 10× more impact than redeeming for yourself.",keywords:"charity donate donation xp points sats bitcoin giving community philanthropy pledge faction badger hornet",action:"window.showQuestHub&&window.showQuestHub();window._questHubTab='charity';setTimeout(function(){if(window._renderQuestHubTab)window._renderQuestHubTab()},50)"},{id:"_pow",title:"🚶 Proof of Walk",desc:"Connect Strava and earn XP for walking — proof of work with your feet",keywords:"proof of walk strava walking steps exercise fitness health outdoor move earn xp activity sync connect",action:"go('explore');setTimeout(function(){if(typeof renderProofOfWalk==='function')renderProofOfWalk()},300)"},{id:"_pop",title:"🕹️ Proof of Play",desc:"Bitcoin gaming hub — Timechain Arcade games + PVP trivia battles",keywords:"proof of play arcade games pvp battle timechain bitcoin gaming 1v1 trivia lightning to the moon node runner nakamoto knights block hunt",action:'if(typeof enterProofOfPlay==="function")enterProofOfPlay()'}];function te(e){const t=document.getElementById("searchResults"),o=document.getElementById("channelList");if(["searchInput","searchOverlayInput"].forEach(t=>{const o=document.getElementById(t);o&&o.value!==e&&(o.value=e)}),e&&"satoshi"===e.toLowerCase()&&("function"==typeof awardHiddenBadge&&awardHiddenBadge("discovery_satoshi","Found Satoshi! 🦢"),F("I am Satoshi. We are all Satoshi.")),e&&"deer"===e.toLowerCase()&&("function"==typeof setPose&&setPose("celebrate"),F("Fawntastic! You found the secret buck."),"function"==typeof nachoFly&&setTimeout(nachoFly,1e3)),!e||e.length<2){var n=safeJSON("btc_recent_searches",[]);if(n.length>0&&t){var i='
    🕐 Recent Searches
    ';n.forEach(function(e){i+=""}),i+="
    ",t.innerHTML=i,t.classList.add("active")}else t.classList.remove("active"),t.innerHTML="";return void(o&&(o.style.display=""))}e=e.toLowerCase(),o.style.display="none",t.classList.add("active");let a=[];for(const t of ee)(t.title.toLowerCase().includes(e)||t.keywords.includes(e)||t.desc.toLowerCase().includes(e))&&a.push({key:t.id,title:t.title,cat:"⚡ App",match:t.desc,action:t.action});let r=[];for(const[t,o]of Object.entries(CHANNELS))(o.title.toLowerCase().includes(e)||o.desc.toLowerCase().includes(e))&&r.push({key:t,title:o.title,cat:o.cat,match:"Channel match"});ie([...a,...r],t),clearTimeout(Z),Z=setTimeout(async()=>{await async function(){if(K)return;const e=Object.entries(CHANNELS).map(async([e,t])=>{if(G[e])$[e]=G[e];else try{const o=await fetch(t.file),n=await o.json();G[e]=n,$[e]=n}catch(e){}});await Promise.all(e),K=!0}();let o=[];for(const[t,n]of Object.entries($)){const i=CHANNELS[t];if(!i)continue;if(r.some(e=>e.key===t))continue;const a=n.msgs||[];for(let n=0;n0?"...":"")+r.text.substring(s,a+e.length+30).replace(/<[^>]+>/g,"")+"...";o.push({key:t,title:i.title,cat:i.cat,match:l,msgIdx:n});break}}}ie([...a,...r,...o],t)},500)}const oe=[{q:"What is Bitcoin?",icon:"💰",reason:"Most asked"},{q:"Lightning Network",icon:"⚡",reason:"Trending"},{q:"How to buy Bitcoin",icon:"🛒",reason:"Popular"},{q:"Self-custody wallets",icon:"🔐",reason:"Essential"},{q:"Bitcoin vs Ethereum",icon:"🆚",reason:"Hot topic"},{q:"Why 21 million?",icon:"🔢",reason:"Fundamental"},{q:"Mining explained",icon:"⛏️",reason:"Technical"},{q:"Bitcoin security",icon:"🛡️",reason:"Important"}];function ne(){var e=document.getElementById("searchResults");if(e){var t='
    🔥 Trending Topics
    ';oe.forEach(function(e){t+=""}),t+="
    ",e.innerHTML=t,e.classList.add("active")}}function ie(e,t){0!==e.length?t.innerHTML=e.slice(0,30).map(e=>{const t=e.key&&e.key.startsWith("_");return'
    "+e.cat+"
    "+e.title+'
    '+e.match+"
    "}).join(""):t.innerHTML='
    No results found
    Try: "Lightning Network" or "What is Bitcoin?"
    '}function ae(e,t){var o=document.getElementById("searchOverlayInput"),n=document.getElementById("searchInput"),i=o&&o.value||n&&n.value||"";!function(e){if(e&&!(e.length<2)){var t=safeJSON("btc_recent_searches",[]);(t=t.filter(function(t){return t.toLowerCase()!==e.toLowerCase()})).unshift(e.length>40?e.substring(0,40):e),t.length>10&&(t=t.slice(0,10)),localStorage.setItem("btc_recent_searches",JSON.stringify(t))}}(i),n&&(n.value=""),o&&(o.value=""),document.getElementById("searchOverlay").style.display="none",te(""),"number"==typeof t&&t>=0&&(window._searchScrollTarget={channel:e,msgIdx:t,query:i}),go(e)}window._tryScrollToSearchResult=function(){var e=window._searchScrollTarget;if(e){var t=e.msgIdx;if(e.query,window._searchScrollTarget=null,t>=(o()?20:50)&&"function"==typeof window.loadMoreMsgs)for(var n=0;!document.getElementById("msg-"+t)&&document.getElementById("loadMoreBtn")&&n<50;)window.loadMoreMsgs(),n++;var i=document.getElementById("msg-"+t);i&&setTimeout(function(){i.scrollIntoView({behavior:"smooth",block:"center"}),i.style.transition="background 0.3s, box-shadow 0.3s",i.style.background="rgba(249,115,22,0.12)",i.style.boxShadow="inset 3px 0 0 #f97316",i.style.borderRadius="8px",setTimeout(function(){i.style.background="",i.style.boxShadow="",i.style.borderRadius=""},3e3)},300)}},function(){const e=document.getElementById("visitCount");setTimeout(function(){if("undefined"==typeof firebase||!firebase.firestore)return;const t=firebase.firestore(),o=(new Date).toISOString().split("T")[0];for(var n=[screen.width,screen.height,screen.colorDepth,Intl.DateTimeFormat().resolvedOptions().timeZone,navigator.language,navigator.hardwareConcurrency||0,navigator.platform].join("|"),i=0,a=0;a{a.textContent="Submit Suggestion",a.disabled=!1},3e3)}catch(e){i.innerHTML='Error submitting. Please try again.',a.textContent="Submit Suggestion",a.disabled=!1}}else i.innerHTML='Please enter a suggestion!'},function(){const e=Object.keys(CHANNELS),t=new Date,o=e[Math.floor((t-new Date(t.getFullYear(),0,0))/864e5)%e.length],n=CHANNELS[o];if(n){const e=document.getElementById("dailyChannel");e.innerHTML='
    📅 Channel of the Day
    '+n.title+'
    '+n.desc+"
    ",e.onclick=()=>go(o)}}(),"function"==typeof renderDailyQuote&&renderDailyQuote(),"function"==typeof renderExplorationMap&&renderExplorationMap(),window.innerWidth>900&&document.getElementById("main").addEventListener("scroll",function(){const e=this;document.getElementById("backToTop").classList.toggle("visible",e.scrollTop>400);var t=e.scrollTop+e.clientHeight>=e.scrollHeight-200;document.getElementById("scrollToBottom").classList.toggle("visible",!t)}),window._launchPVP=function(){if("function"==typeof enterPVPMode)enterPVPMode();else{"function"==typeof window._loadDeferred&&window._loadDeferred(),"function"==typeof showToast&&showToast("⚔️ Loading PVP arena...");var e=0,t=setInterval(function(){e++,"function"==typeof enterPVPMode?(clearInterval(t),enterPVPMode()):e>15&&(clearInterval(t),"function"==typeof showToast&&showToast("⚠️ PVP failed to load — try refreshing the page"))},200)}},window.toggleAppsMenu=function(e){e&&e.stopPropagation();var t=document.getElementById("appsMenu");if(t&&"block"===t.style.display)t.style.display="none";else{t&&t.remove();var o=safeJSON("btc_visited_channels",[]).length,n=void 0!==currentUser&¤tUser&¤tUser.totalVisits||0,i=void 0!==auth?auth:null,a=i&&i.currentUser,r=a&&-1!==["needcreations@gmail.com","info.603btc@gmail.com"].indexOf(a.email||""),s="function"==typeof getOnboardingProfile?getOnboardingProfile():null,l=s&&("advanced"===s.level||"full"===s.level)||r||a&&!a.isAnonymous||n>=10||o>=10,c=l||n>=5||o>=5,d="padding:15px;background:var(--card-bg);border:1px solid var(--border);border-radius:16px;color:var(--text);font-size:0.85rem;font-weight:700;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:8px;transition:0.2s;",u=d+"opacity:0.45;filter:grayscale(0.8);cursor:help;",p={"Nacho Mode":"Chat with our AI Bitcoin tutor","Proof of Play":"Bitcoin gaming hub — Arcade + PVP","Pleb Talk":"Community discussion board for Bitcoin topics","Lightning Mart":"Buy and sell with Lightning sats","IRL Sync":"Find or host local Bitcoin meetups","Bitcoin Beats":"Community music player","Timechain TV":"21 channels of Bitcoin video content","Proof of Walk":"Earn XP by walking — connect Strava","Proof of Play":"Bitcoin gaming hub — Arcade + PVP"},h=!(c||n>=3||o>=3),m=!c,g=!l,f="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Bitcoin Beats!",y="🔒 Visit "+Math.max(0,3-o)+" more topics to unlock Pleb Talk!",b="🔒 Explore "+Math.max(0,5-o)+" more topics to unlock IRL Sync!",v="🔒 Explore "+Math.max(0,10-o)+" more topics or sign in to unlock Lightning Mart!",w='";document.body.insertAdjacentHTML("beforeend",w);var x=document.getElementById("appsMenu");document.addEventListener("click",function(e){"block"!==x.style.display||x.contains(e.target)||(x.style.display="none")}),x.style.display="block","function"==typeof playSound&&playSound("pop")}function k(e,t,o,n,i){var a=p[t]||t;return n?"":""}},window.showProofOfWalk=function(){var e=document.getElementById("appsMenu");e&&(e.style.display="none");var t=document.getElementById("main");t&&(t.innerHTML='
    ',window.renderProofOfWalk&&window.renderProofOfWalk())},window.toggleSidebarMenu=function(e){var t=document.getElementById(e);t&&("flex"===t.style.display||"grid"===t.style.display||"block"===t.style.display?t.style.display="none":(e.includes("Flash")?t.style.display="flex":e.includes("homeAppsMenu")?t.style.display="grid":(t.style.display="flex",t.style.flexDirection="column"),"function"==typeof playSound&&playSound("pop")))},window.onload=()=>{"true"!==localStorage.getItem("btc_nacho_mode_default")||window.location.hash||setTimeout(function(){"function"==typeof enterNachoMode&&enterNachoMode()},1500),safeJSON("btc_visited_channels",[]).forEach(e=>{document.querySelectorAll(".ch-btn").forEach(t=>{t.getAttribute("onclick")&&t.getAttribute("onclick").includes("'"+e+"'")&&t.classList.add("visited")})}),c(),R(),"function"==typeof checkPredictionResult&&setTimeout(checkPredictionResult,4e3);var e=window.location.hash||"";history.state||(history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname+e)),window.addEventListener("popstate",function(e){var t=e.state||{},o=location.hash.slice(1);if(o||"function"!=typeof _parseCleanUrl||(o=_parseCleanUrl()||""),!e.state||t.guard)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);if(!e.state&&!o)return history.replaceState({guard:!0},"",window.location.pathname),history.pushState({home:!0},"",window.location.pathname),void goHome(!0);var n=document.getElementById("notifPanel");if(n&&"translateY(0px)"===n.style.transform)"function"==typeof toggleNotifOverlay&&toggleNotifOverlay();else if(window._chatOverlayOpen)"function"==typeof toggleChatOverlay&&toggleChatOverlay();else{var i=document.getElementById("usernameModal");if(i&&i.classList.contains("open"))return i.classList.remove("open"),void("function"==typeof window._restoreSignUpForm&&window._restoreSignUpForm());var a=document.getElementById("mobileLearnMenu");if(a)a.remove();else{var r=document.getElementById("appsMenu");if(r&&"block"===r.style.display)r.style.display="none";else{var s=document.getElementById("questModal");if(s&&s.classList.contains("open"))s.classList.remove("open");else if(t.returnToGuide)"function"==typeof showGuide&&(showGuide(),setTimeout(function(){var e=document.getElementById("guideOverlay");if(e&&window._guideScrollTop){var t=e.querySelector('div[style*="border-radius:24px"]');t&&(t.scrollTop=window._guideScrollTop)}},500));else{for(var l=["guideOverlay","onboardingOverlay","pvpNameOverlay","pvpOverlay","tipOverlay","donateModal","lnAuthModal","nostrAuthOverlay","spinModal","hostEventModal","eventDetailOverlay","editEventOverlay","nachoColorPicker","articleLinkDialog","articleImageDialog","eli5Prompt","kbHelpModal","forumRulesOverlay","chatRulesOverlay","marketRulesOverlay","irlRulesOverlay"],c=0;c30&&clearInterval(o)},300)},1500)},function(){function e(){var e=window.location.hash.replace("#","");if(e||"function"!=typeof _parseCleanUrl||(e=_parseCleanUrl()||""),e){console.log("[ROUTE] Routing to:",e);var t=0;setTimeout(function o(){if(t>8e3)console.warn("[HASH] Gave up routing to:",e);else{if(!document.getElementById("msgs")||!document.getElementById("home"))return t+=200,void setTimeout(o,200);switch(e){case"nacho":if("function"==typeof enterNachoMode)return void enterNachoMode();break;case"pvp":if("function"==typeof _launchPVP)return void _launchPVP();break;case"forum":if("function"==typeof go)return void go("forum");break;case"marketplace":if("function"==typeof go)return void go("marketplace");break;case"first-purchase":case"buy":if("function"==typeof go)return void go("first-purchase");break;case"trails":case"learn":case"modules":if("function"==typeof go)return void go("trails");break;case"meetup-builder":if(window._mbRouted)return;if("function"==typeof go){window._mbRouted=!0,window._skipIRLRules=!0,localStorage.setItem("btc_irl_rules_accepted","true"),go("irl-sync"),setTimeout(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove()},100),history.replaceState({channel:"meetup-builder"},"","#meetup-builder");var n=0,i=setInterval(function(){var e=document.getElementById("irlRulesOverlay");e&&e.remove();var t=document.getElementById("meetupBuilderSection");t&&(clearInterval(i),t.scrollIntoView({behavior:"smooth",block:"start"})),++n>30&&clearInterval(i)},300);return}break;case"irl-sync":case"meet":if("function"==typeof go)return void go("irl-sync");break;case"bitcoin-beats":if("function"==typeof go)return void go("bitcoin-beats");break;case"chat":if("function"==typeof renderChatHub)return void renderChatHub("global");break;case"dms":if("function"==typeof renderChatHub)return void renderChatHub("dms");if("function"==typeof openDMInbox)return void openDMInbox();if("function"==typeof showInbox)return void showInbox();break;case"lightning":if("function"==typeof go)return void go("lightning");break;case"timechain-tv":case"tv":if("function"==typeof go)return void go("timechain-tv");break;case"pow-support":if("function"==typeof renderPOWSupport)return void renderPOWSupport();break;case"quests":if("function"==typeof showQuestHub)return void showQuestHub();break;case"dashboard":case"bitcoin-dashboard":case"metrics":case"network":if("function"==typeof toggleDashboard)return history.replaceState({home:!0},"",window.location.pathname),void toggleDashboard();break;default:if(0===e.indexOf("beats/")&&"function"==typeof go&&!window._beatsRouted){if(0===e.indexOf("beats/playlist/")){var a=e.replace("beats/playlist/","").split("/");2===a.length&&(window._beatsDeepLink={type:"playlist",ownerUid:a[0],playlistId:a[1]})}else{var r=e.replace("beats/","");r&&-1===r.indexOf("/")&&(window._beatsDeepLink={type:"track",trackId:r})}return window._beatsRouted=!0,void go("bitcoin-beats")}if(0===e.indexOf("beats/")&&window._beatsRouted)return;if(0===e.indexOf("cert/")&&"function"==typeof go)return void go(e);if("function"==typeof go&&void 0!==CHANNELS&&CHANNELS[e])return void go(e)}t+=200,setTimeout(o,200)}},500)}}e(),window.addEventListener("load",function(){setTimeout(function(){var t=window.location.hash.replace("#","");t&&document.getElementById("home")&&!document.getElementById("home").classList.contains("hidden")&&(console.log("[HASH] Post-load fallback routing to:",t),e())},800)}),window.addEventListener("hashchange",e)}(),void 0!==r&&(window.toggleCat=r),void 0!==n&&(window.toggleTheme=n),void 0!==J&&(window.toggleAudio=J),void 0!==Y&&(window.setVolume=Y),void 0!==E&&(window.handleSupportClick=E),"undefined"!=typeof showDonateModal&&(window.showDonateModal=showDonateModal),"undefined"!=typeof enterNachoMode&&(window.enterNachoMode=enterNachoMode),"undefined"!=typeof goHome&&(window.goHome=goHome),void 0!==v&&(window.goRandom=v),void 0!==k&&(window.goRandomArt=k),void 0!==x&&(window.goRandomMeme=x),void 0!==B&&(window.goRandomGraphic=B),void 0!==te&&(window.doSearch=te),void 0!==ne&&(window.showTrendingTopics=ne),void 0!==ae&&(window.selectResult=ae),void 0!==i&&(window.toggleMenu=i),void 0!==a&&(window.toggleSidebarCollapse=a),void 0!==t&&(window.openImg=t),void 0!==d&&(window.toggleFav=d),void 0!==T&&(window.shareNostr=T),void 0!==C&&(window.copyLink=C),void 0!==m&&(window.toggleGallery=m),void 0!==g&&(window.renderContent=g),"undefined"!=typeof showBeginnerGuide&&(window.showBeginnerGuide=showBeginnerGuide),void 0!==y&&(window.loadTweetEmbed=y)}(),window._spinSoundCtx=null,window.playSpinTick=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx,t=e.createOscillator(),o=e.createGain();t.connect(o),o.connect(e.destination),t.frequency.value=800+400*Math.random(),t.type="triangle",o.gain.value=.08,o.gain.exponentialRampToValueAtTime(.001,e.currentTime+.08),t.start(e.currentTime),t.stop(e.currentTime+.08)}catch(e){}},window._tctvTimer=null,window._tctvMinutesSession=0,window._tctvStartTracker=function(){if(!window._tctvTimer){window._tctvMinutesSession=0;try{var e=(new Date).toISOString().split("T")[0];localStorage.setItem("btc_tctv_visited_"+e,"true")}catch(e){}console.log("[TCTV] Watch tracker started."),window._tctvTimer=setInterval(function(){if("timechain-tv"===(window.currentChannelId||"")){if(!document.hidden){var e=parseInt(localStorage.getItem("btc_tctv_watch_time")||"0")+1;localStorage.setItem("btc_tctv_watch_time",e.toString()),window._tctvMinutesSession++;try{var t=(new Date).toISOString().split("T")[0],o=parseInt(localStorage.getItem("btc_tctv_minutes_"+t)||"0")+1;localStorage.setItem("btc_tctv_minutes_"+t,String(o))}catch(e){}console.log("[TCTV] Watch time:",e,"min (Session:",window._tctvMinutesSession,"min)");try{void 0!==db&&"undefined"!=typeof firebase&&void 0!==auth&&auth.currentUser&&!auth.currentUser.isAnonymous&&db.collection("stats").doc("global").set({watchTimeMinutes:firebase.firestore.FieldValue.increment(1)},{merge:!0}).catch(function(){})}catch(e){}e%10==0?("function"==typeof awardPoints&&awardPoints(10,"tctv_watch_10m"),"function"==typeof checkBadges&&checkBadges(),"function"==typeof showToast&&showToast("👁️ +10 Points — Thanks for watching Timechain TV!")):1===e&&"function"==typeof showToast&&showToast("📺 Watching Timechain TV — Points awarded every 10 min!")}}else window._tctvStopTracker()},6e4)}},window._tctvStopTracker=function(){window._tctvTimer&&(clearInterval(window._tctvTimer),window._tctvTimer=null,console.log("[TCTV] Watch tracker stopped. Total minutes watched:",window._tctvMinutesSession))},window._updateSEO=function(e,t,o){if(e){document.title=(t?t+" | ":"")+"Bitcoin Education Archive";var n=document.querySelector('link[rel="canonical"]');if(n){var i="home"===e||"/"===e?"":"/app/"+e;n.setAttribute("href","https://bitcoineducation.quest"+i)}var a=document.querySelector('meta[name="description"]');a&&o&&a.setAttribute("content",o.substring(0,160));var r=window._cleanUrl(e);window.location.href.includes(r)||history.replaceState({channel:e},"",r)}},window.playSpinWin=function(){if("false"!==localStorage.getItem("btc_audio")&&!document.hidden)try{window._spinSoundCtx||(window._spinSoundCtx=new(window.AudioContext||window.webkitAudioContext));var e=window._spinSoundCtx;[523,659,784,1047].forEach(function(t,o){var n=e.createOscillator(),i=e.createGain();n.connect(i),i.connect(e.destination),n.frequency.value=t,n.type="sine",i.gain.value=.1,i.gain.exponentialRampToValueAtTime(.001,e.currentTime+.15*(o+1)+.3),n.start(e.currentTime+.15*o),n.stop(e.currentTime+.15*(o+1)+.3)})}catch(e){}},window._aiToolsOpen=!1,window.toggleAITools=function(){var e=document.getElementById("aiToolsPanel");if(!e){(e=document.createElement("div")).id="aiToolsPanel",e.style.cssText="position:fixed;bottom:0;left:0;right:0;z-index:250000;background:var(--bg,#0a0a0f);border-top:2px solid var(--accent,#f7931a);border-radius:16px 16px 0 0;transform:translateY(100%);transition:transform 0.3s ease;box-shadow:0 -10px 40px rgba(0,0,0,0.6);",e.innerHTML='
    🤖AI Toolspowered by PPQ
    ',document.body.appendChild(e);var t=document.createElement("style");t.id="aiToolsPanelCSS",t.textContent="@media(min-width:901px){#aiToolsPanel{max-width:480px;right:16px;left:auto;border-radius:16px 16px 0 0;}}@media(max-width:900px){#aiToolsPanel iframe{height:calc(70vh - 56px);}}",document.head.appendChild(t)}window._aiToolsOpen=!window._aiToolsOpen,e.style.transform=window._aiToolsOpen?"translateY(0)":"translateY(100%)";var o=document.getElementById("aiToolsBtn");if(o&&(o.style.background=window._aiToolsOpen?"var(--card-bg)":"linear-gradient(135deg,#6366f1,#8b5cf6)",o.style.borderColor=window._aiToolsOpen?"var(--accent)":"transparent"),window._aiToolsOpen&&void 0!==db&&db)try{var n=auth&&auth.currentUser?auth.currentUser.uid:"anon_"+(localStorage.getItem("visitorId")||"unknown");db.collection("ai_tools_opens").add({uid:n,openedAt:firebase.firestore.FieldValue.serverTimestamp()})}catch(e){console.warn("[AI Tools] tracking error",e)}},function(){function e(){var e=document.getElementById("aiToolsBtn");e||((e=document.createElement("button")).id="aiToolsBtn",e.className="fab-btn",e.innerHTML="🤖",document.body.appendChild(e)),e.onclick=toggleAITools}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}(),function(){var e=window.renderBitcoinBeats;e&&(window.renderBitcoinBeats=function(){e(),setTimeout(function(){document.getElementById("beatsLoader");var e=document.getElementById("beatsEmbedArea");if(e){var t=e.querySelector("iframe"),o=e.querySelector(".twitter-tweet-rendered, twitter-widget");t||o||(e.innerHTML='
    🎸
    Stream Unavailable
    The live stream couldn\'t be loaded. Check out these great Bitcoin audio sources instead:
    ')}},8e3)})}(),void 0===window.contactSeller&&(window.contactSeller=function(e,t){if(!auth||!auth.currentUser||auth.currentUser.isAnonymous)return"function"==typeof showToast&&showToast("🔒 Sign in to contact sellers!"),void("function"==typeof showUsernamePrompt&&showUsernamePrompt());void 0!==db&&db.collection("marketplace").doc(e).get().then(function(e){if(e.exists){var t=e.data(),o=t.sellerUid;o!==auth.currentUser.uid?("function"==typeof openDM?openDM(o,t.sellerName||"Seller"):"function"==typeof showInbox&&(showInbox(),setTimeout(function(){"function"==typeof startNewDM&&startNewDM(o,t.sellerName||"Seller")},500)),void 0!==db&&auth.currentUser&&db.collection("users").doc(auth.currentUser.uid).update({marketMessages:firebase.firestore.FieldValue.increment(1)}).catch(function(){}),void 0!==currentUser&¤tUser&&(currentUser.marketMessages=(currentUser.marketMessages||0)+1),"function"==typeof showToast&&showToast("💬 Opening chat with "+(t.sellerName||"seller")+"...")):"function"==typeof showToast&&showToast("That's your own listing!")}})}),window.handleMktImageUploadV2=function(e){var t=e.files&&e.files[0];if(t)if(t.size>5242880)"function"==typeof showToast&&showToast("Image too large (max 5MB)");else if(auth&&auth.currentUser){var o=document.getElementById("mktImagePreview"),n=document.getElementById("mktImagePreviewImg");if(o&&(o.style.display="block",n&&(n.src=""),o.innerHTML='
    📤 Uploading...
    '),"undefined"!=typeof firebase&&firebase.storage){var i=firebase.storage().ref(),a="marketplace/"+auth.currentUser.uid+"/"+Date.now()+"_"+t.name.replace(/[^a-zA-Z0-9.]/g,"_"),r=i.child(a).put(t,{contentType:t.type});r.on("state_changed",function(e){var t=Math.round(e.bytesTransferred/e.totalBytes*100);o&&(o.innerHTML='
    📤 Uploading... '+t+"%
    ")},function(t){"function"==typeof showToast&&showToast("Upload failed: "+t.message),o&&(o.style.display="none"),handleMktImageUpload(e)},function(){r.snapshot.ref.getDownloadURL().then(function(e){window._mktUploadedImage=e,o&&n&&(o.innerHTML=''),"function"==typeof showToast&&showToast("✅ Image uploaded!")})})}else"function"==typeof handleMktImageUpload&&handleMktImageUpload(e)}else"function"==typeof showToast&&showToast("Sign in to upload images")},function(){var e=[{type:"youtube",id:"UvSnC7P-m-U",title:"What is Bitcoin? — Andreas Antonopoulos",desc:"The best intro talk ever given"},{type:"youtube",id:"l1si5ZWLgy0",title:"Bitcoin for Beginners — BTC Sessions",desc:"Step-by-step Bitcoin guide"},{type:"youtube",id:"ZKwqNgG-Sv4",title:"The Bitcoin Standard — Saifedean Ammous",desc:"Author presentation on sound money"},{type:"youtube",id:"2pDlaOGA2ac",title:"How Bitcoin Works Under the Hood",desc:"Technical deep-dive"},{type:"youtube",id:"bBC-nXj3Ng4",title:"But How Does Bitcoin Actually Work?",desc:"3Blue1Brown explains"},{type:"youtube",id:"Gc2en3nHxA4",title:"Michael Saylor on Why Bitcoin",desc:"The macro case for Bitcoin"},{type:"youtube",id:"xLYhx1z7gC4",title:"This Machine Greens — Bitcoin & Energy",desc:"Bitcoin mining documentary"},{type:"youtube",id:"HCLWDGYnAzk",title:"Running a Bitcoin Node — Ministry of Nodes",desc:"How to verify for yourself"}];window.beatsPlaylistIndex=parseInt(localStorage.getItem("btc_beats_idx")||"0")%e.length,window.renderBeatsPlaylist=function(t){if(t){var o=e[window.beatsPlaylistIndex],n=e.length,i=window.beatsPlaylistIndex,a='
    ';a+='
    ',a+='
    '+o.title+'
    '+o.desc+" • "+(i+1)+"/"+n+'
    ',t.innerHTML=a}},window.beatsNav=function(t){window.beatsPlaylistIndex=(window.beatsPlaylistIndex+t+e.length)%e.length,localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var o=document.getElementById("beatsEmbedArea");o&&renderBeatsPlaylist(o)},window.beatsNavRandom=function(){window.beatsPlaylistIndex=Math.floor(Math.random()*e.length),localStorage.setItem("btc_beats_idx",window.beatsPlaylistIndex);var t=document.getElementById("beatsEmbedArea");t&&renderBeatsPlaylist(t)};var t=8e3,o=setInterval(function(){var e=document.getElementById("beatsEmbedArea");e&&(document.getElementById("beatsLoader")?(t-=500)<=0&&(clearInterval(o),renderBeatsPlaylist(e)):clearInterval(o))},500)}(),window.fuzzyMatch=function(e,t){if(!t||!e)return!0;var o=e.toLowerCase();return t.toLowerCase().split(/\s+/).every(function(e){return-1!==o.indexOf(e)})},function(){function e(){return!(!auth||!auth.currentUser)&&"needcreations@gmail.com"===(auth.currentUser.email||"")}window.forumEditPost=function(t){auth&&auth.currentUser&&void 0!==db&&db.collection("forum_posts").doc(t).get().then(function(o){if(o.exists){var n=o.data();if(n.authorId===auth.currentUser.uid||e()){var i=n.createdAt?n.createdAt.toDate():new Date;if(Date.now()-i.getTime()>9e5&&!e())"function"==typeof showToast&&showToast("Posts can only be edited within 15 minutes of creation");else{var a='
    ✏️ Edit Post
    Edited posts will show an "edited" indicator
    ',r=document.createElement("div");r.innerHTML=a,document.body.appendChild(r.firstChild)}}else"function"==typeof showToast&&showToast("You can only edit your own posts")}})},window.forumSaveEdit=function(e){var t=(document.getElementById("editPostTitle").value||"").trim(),o=(document.getElementById("editPostBody").value||"").trim();!t||t.length<5?"function"==typeof showToast&&showToast("Title must be at least 5 characters"):"function"!=typeof isCleanText||isCleanText(t+" "+o)?db.collection("forum_posts").doc(e).update({title:t.substring(0,120),body:o.substring(0,2e3),editedAt:firebase.firestore.FieldValue.serverTimestamp(),edited:!0}).then(function(){var t=document.getElementById("forumEditOverlay");t&&t.remove(),"function"==typeof showToast&&showToast("✅ Post updated!"),"function"==typeof forumViewPost&&forumViewPost(e,!0)}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))}):"function"==typeof showToast&&showToast("Post contains inappropriate language")}}(),function(){var e=[{level:1,name:"Just Met",emoji:"🦌",threshold:1},{level:2,name:"Getting Acquainted",emoji:"👋",threshold:10},{level:3,name:"Good Friends",emoji:"😊",threshold:100},{level:4,name:"Close Friends",emoji:"🧡",threshold:350},{level:5,name:"Best Buds",emoji:"💛",threshold:750}],t=window.trackNachoInteraction;t&&(window.trackNachoInteraction=function(){for(var o=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),n=0,i=e.length-1;i>=0;i--)if(o>=e[i].threshold){n=e[i].level;break}t();for(var a=parseInt(localStorage.getItem("btc_nacho_interactions")||"0"),r=0,s=null,l=e.length-1;l>=0;l--)if(a>=e[l].threshold){r=e[l].level,s=e[l];break}if(r>n&&s){var c=JSON.parse(localStorage.getItem("btc_nacho_level_celebrated")||"[]");-1===c.indexOf(s.level)&&(c.push(s.level),localStorage.setItem("btc_nacho_level_celebrated",JSON.stringify(c)),"function"==typeof syncCelebratedState&&syncCelebratedState(),setTimeout(function(){var e="function"==typeof nachoUserName?nachoUserName():"",t=s.emoji+" "+(e?e+", w":"W")+"e just became "+s.name+"! "+(s.level>=3?"New closet items are now available! Check the Closet! 👔✨":"Keep chatting with me to unlock more! 🦌");"function"==typeof forceShowBubble?(forceShowBubble(t),s.level>=3&&setTimeout(function(){var e=document.getElementById("nacho-bubble");e&&(e.style.cursor="pointer",e.onclick=function(){e.classList.remove("show"),window._expanded_closet=!0,window._pendingClosetScroll=!0,"function"==typeof showSettings&&showSettings(),setTimeout(function(){"function"==typeof showSettingsPage&&showSettingsPage("data")},300)})},100)):"function"==typeof showToast&&showToast("🦌 Friendship Level Up: "+s.emoji+" "+s.name+"!")},1e3))}})}(),function(){var e=[],t=!1,o=0;function n(){if(!t&&0!==e.length){var i=Date.now();if(i-o<3e4)setTimeout(n,3e4-(i-o)+100);else{t=!0;var a=e.shift();o=i;try{a.show()}catch(e){console.log("Notification error:",e)}setTimeout(function(){t=!1,n()},5e3)}}}window.queueNotification=function(t,o){e.push({type:t,show:o,queued:Date.now()}),n()};var i=window.showToast;i&&(window.showToastQueued=function(e){queueNotification("toast",function(){i(e)})})}(),window.initMiniPlayer=function(){if(!document.getElementById("miniPlayer")){var e=document.createElement("div");e.id="miniPlayer",e.style.cssText="position:fixed;bottom:60px;left:0;right:0;z-index:180;background:rgba(10,10,10,0.95);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-top:1px solid rgba(247,147,26,0.3);padding:8px 16px;display:none;align-items:center;gap:12px;",e.innerHTML='
    Not playing
    Bitcoin Beats
    ',document.body.appendChild(e)}},window._miniPlayerAudio=null,window.playInMiniPlayer=function(e,t,o){initMiniPlayer();var n=document.getElementById("miniPlayer");n&&(window._miniPlayerAudio&&window._miniPlayerAudio.pause(),window._miniPlayerAudio=new Audio(e),window._miniPlayerAudio.play().catch(function(){}),document.getElementById("mpTitle").textContent=t||"Playing...",document.getElementById("mpArtist").textContent=o||"Bitcoin Beats",document.getElementById("mpPlayPause").textContent="⏸",n.style.display="flex")},window.toggleMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.paused?(window._miniPlayerAudio.play(),document.getElementById("mpPlayPause").textContent="⏸"):(window._miniPlayerAudio.pause(),document.getElementById("mpPlayPause").textContent="▶"))},window.closeMiniPlayer=function(){window._miniPlayerAudio&&(window._miniPlayerAudio.pause(),window._miniPlayerAudio=null);var e=document.getElementById("miniPlayer");e&&(e.style.display="none")},function(){var e=2592e6;window.isListingExpired=function(t){if(!t||!t.createdAt)return!1;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt);return Date.now()-o.getTime()>e},window.renewListing=function(e){auth&&auth.currentUser&&void 0!==db&&db.collection("marketplace").doc(e).update({createdAt:firebase.firestore.FieldValue.serverTimestamp(),renewed:!0,renewedAt:firebase.firestore.FieldValue.serverTimestamp()}).then(function(){"function"==typeof showToast&&showToast("✅ Listing renewed for 30 more days!"),"function"==typeof renderMarketplace&&renderMarketplace({listingId:e})}).catch(function(e){"function"==typeof showToast&&showToast("Error: "+(e.message||"Unknown"))})},window.getExpiryStatus=function(t){if(!t||!t.createdAt)return null;var o=t.createdAt.toDate?t.createdAt.toDate():new Date(t.createdAt),n=Date.now()-o.getTime(),i=Math.max(0,Math.ceil((e-n)/864e5));return i<=0?{status:"expired",text:"This listing has expired",color:"#ef4444"}:i<=5?{status:"expiring",text:"Expires in "+i+" day"+(1!==i?"s":""),color:"#eab308"}:null}}(),window.renderSellerReputation=function(e,t){e&&t&&void 0!==db&&db.collection("users").doc(e).get().then(function(e){if(e.exists){var o=e.data(),n=o.createdAt?o.createdAt.toDate?o.createdAt.toDate():new Date(o.createdAt):null,i=n?n.toLocaleDateString("en-US",{month:"short",year:"numeric"}):"Unknown",a="function"==typeof getLevel?getLevel(o.points||0):{emoji:"🟢",name:"Normie"},r='
    '+a.emoji+" "+a.name+'📅 Member since '+i+""+(o.forumPosts?'💬 '+o.forumPosts+" posts":"")+(o.marketListings?'🛒 '+o.marketListings+" listings":"")+"
    ";t.innerHTML+=r}}).catch(function(){})},function(){var e="btc_forum_draft",t="btc_forum_reply_",o=null;window.saveForumDraft=function(){var t=document.getElementById("forumNewTitle"),o=document.getElementById("forumNewBody"),n=document.getElementById("forumNewCategory");if(t||o){var i={title:t?t.value:"",body:o?o.value:"",category:n?n.value:"general",savedAt:Date.now()};localStorage.setItem(e,JSON.stringify(i))}},window.restoreForumDraft=function(){try{var t=JSON.parse(localStorage.getItem(e));return!t||Date.now()-t.savedAt>864e5?null:t}catch(e){return null}},window.clearForumDraft=function(){localStorage.removeItem(e)},window.saveReplyDraft=function(e){var o=document.getElementById("forumReplyInput");o&&o.value.trim()?localStorage.setItem(t+e,o.value):localStorage.removeItem(t+e)},window.restoreReplyDraft=function(e){return localStorage.getItem(t+e)||""},window.clearReplyDraft=function(e){localStorage.removeItem(t+e)};var n=new MutationObserver(function(){var e=document.getElementById("forumNewTitle"),t=document.getElementById("forumNewBody");if(e&&!e._draftBound){e._draftBound=!0,e.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)});var n=restoreForumDraft();n&&(n.title||n.body)&&(e.value=n.title||"",t&&(t.value=n.body||""),"function"==typeof showToast&&showToast("📝 Draft restored"))}t&&!t._draftBound&&(t._draftBound=!0,t.addEventListener("input",function(){clearTimeout(o),o=setTimeout(saveForumDraft,3e3)}));var i=document.getElementById("forumReplyInput");if(i&&!i._draftBound&&"undefined"!=typeof forumCurrentPost&&forumCurrentPost){i._draftBound=!0;var a=forumCurrentPost.id,r=restoreReplyDraft(a);r&&(i.value=r),i.addEventListener("input",function(){clearTimeout(o),o=setTimeout(function(){saveReplyDraft(a)},3e3)})}});document.body?n.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",function(){n.observe(document.body,{childList:!0,subtree:!0})})}(),window.isCleanTextV2=function(e){if(!e)return!0;for(var t=["fuck","shit","bitch","dick","cock","pussy","cunt","nigger","nigga","fag","faggot","retard","nazi","hitler","kkk","porn","hentai","rape","pedo","spic","wetback","chink","gook","kike","towelhead","raghead","beaner","coon","darkie","jap","paki","wop","slut","whore","cum","dildo","tits","nude","naked","milf","molest","suicide","terrorist","jihad","genocide","lynch","maga","trump","biden","democrat","republican","antifa","qanon","wwg1wga","supremacy","acab","blowjob","handjob","fingering","masturbat","threesome","gangbang","fetish","bondage","bdsm","kinky","horny","erection","ejaculat","deepthroat","creampie","cuckold","dominatrix","escort","prostitut","hooker","stripper","camgirl","sexting","nudes"],o=e.toLowerCase().replace(/0/g,"o").replace(/1/g,"i").replace(/3/g,"e").replace(/4/g,"a").replace(/5/g,"s").replace(/7/g,"t").replace(/\$/g,"s").replace(/@/g,"a").replace(/!/g,"i").replace(/\*/g,"").replace(/_/g,"").replace(/-/g,"").replace(/[^a-z\s]/g,"").split(/\s+/),n=0;n=4&&-1!==o[n].indexOf(t[i]))return!1}return!0},void 0!==window.isCleanText&&(window._origIsCleanText=window.isCleanText,window.isCleanText=window.isCleanTextV2),function(){var e=document.createElement("style");e.id="ux-patch-styles",e.textContent="\n /* Modal overlay */\n .modal-overlay {\n position: fixed; inset: 0;\n background: rgba(0,0,0,0.7);\n backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);\n z-index: 9999;\n display: flex; align-items: center; justify-content: center;\n padding: 16px;\n }\n /* Modal card */\n .modal-card {\n background: var(--bg-side, #1a1a2e);\n border: 1px solid rgba(255,255,255,0.1);\n border-radius: 24px;\n padding: 24px;\n max-width: 480px; width: 100%;\n max-height: 85vh; overflow-y: auto;\n box-shadow: 0 20px 60px rgba(0,0,0,0.5);\n animation: fadeSlideIn 0.3s;\n -webkit-overflow-scrolling: touch;\n }\n /* Pill button */\n .pill-btn {\n padding: 6px 14px;\n border-radius: 20px;\n border: 1px solid var(--border);\n background: var(--card-bg);\n color: var(--text-muted);\n font-size: 0.75rem;\n cursor: pointer;\n font-family: inherit;\n white-space: nowrap;\n font-weight: 600;\n transition: 0.2s;\n }\n .pill-btn.active {\n border-color: var(--accent);\n background: var(--accent);\n color: #fff;\n }\n /* scroll-top-btn removed — using #backToTop in index.html */\n /* Badge progress bar */\n .badge-progress {\n width: 100%; height: 4px;\n background: rgba(255,255,255,0.1);\n border-radius: 2px;\n margin-top: 4px;\n overflow: hidden;\n }\n .badge-progress-fill {\n height: 100%;\n background: var(--accent);\n border-radius: 2px;\n transition: width 0.5s ease;\n }\n ",document.head.appendChild(e)}(),window.renderQuestDashboard=function(){if(void 0===QUESTION_BANK)return"";var e=JSON.parse(localStorage.getItem("btc_visited_channels")||"[]"),t=parseInt(localStorage.getItem("btc_quests_completed")||"0"),o=Object.keys(QUESTION_BANK).filter(function(t){return-1!==e.indexOf(t)}),n=Object.keys(QUESTION_BANK).length;return'
    ⚔️
    Quest Progress
    '+t+' quests completed
    Channels with questions unlocked'+o.length+"/"+n+'
    Visit more topics to unlock new quests! Each topic you read adds its questions to your quest pool.
    '},window.renderBadgeWithProgress=function(e,t){var o="";if(!t&&e.progress&&"function"==typeof e.progress){var n=e.progress(),i=n.match(/(\d+)\/(\d+)/);if(i){var a=parseInt(i[1]),r=parseInt(i[2]);o='
    '+n+"
    "}}return'
    '+e.emoji+'
    '+e.name+'
    '+e.desc+"
    "+(t?'
    ✅ Earned!
    ':"")+o+"
    "},function(){function e(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;for(var o=[],n=0;n<=t.length;n++)o[n]=[n];for(var i=0;i<=e.length;i++)o[0][i]=i;for(n=1;n<=t.length;n++)for(i=1;i<=e.length;i++)t.charAt(n-1)===e.charAt(i-1)?o[n][i]=o[n-1][i-1]:o[n][i]=Math.min(o[n-1][i-1]+1,o[n][i-1]+1,o[n-1][i]+1);return o[t.length][e.length]}window.fuzzyChannelSearch=function(t,o){if(!t||!o)return[];var n=t.toLowerCase().trim().split(/\s+/),i=[];for(var a in o){var r=o[a],s=(r.name||r.title||a).toLowerCase(),l=(r.desc||"").toLowerCase(),c=s+" "+l+" "+a.replace(/-/g," "),d=0,u=0;n.forEach(function(t){if(-1!==s.indexOf(t))d+=10,u++;else if(-1!==c.indexOf(t))d+=5,u++;else if(t.length>3)for(var o=c.split(/\s+/),n=0;n0&&i.push({id:a,channel:r,score:d})}return i.sort(function(e,t){return t.score-e.score}),i}}(),console.log("✅ UX Patches loaded — 24 tasks from the UX Review Report"),new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e].concat(Array.from(e.querySelectorAll('.msg-text, .msg-body, [class*="msg"]'))):[e]).forEach(function(e){e.innerHTML&&-1!==e.innerHTML.indexOf("this Discord")&&(e.innerHTML=e.innerHTML.replace(/this Discord/g,"this App"))})})})}).observe(document.body,{childList:!0,subtree:!0}),function(){var e=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){1===e.nodeType&&(e.querySelectorAll?[e,...e.querySelectorAll("img.msg-img")]:[e]).forEach(function(e){"IMG"===e.tagName&&e.classList.contains("msg-img")&&!e.dataset.blurUp&&(e.dataset.blurUp="1",e.style.filter="blur(8px)",e.style.transition="filter 0.4s ease",e.complete&&e.naturalWidth>0?e.style.filter="none":(e.addEventListener("load",function(){e.style.filter="none"},{once:!0}),e.addEventListener("error",function(){e.style.filter="none"},{once:!0})))})})})});document.getElementById("main")&&e.observe(document.getElementById("main"),{childList:!0,subtree:!0})}(),function(){var e="btc_nacho_convo_persist",t=window.nachoRemember;"function"==typeof t&&(window.nachoRemember=function(o,n){t(o,n);try{var i=JSON.parse(localStorage.getItem(e)||"[]");i.push({q:o,a:(n||"").substring(0,200),t:Date.now()}),i.length>20&&(i=i.slice(-20)),localStorage.setItem(e,JSON.stringify(i))}catch(e){}}),setTimeout(function(){if(void 0!==window._nachoConvoHistory&&0===window._nachoConvoHistory.length)try{var t=JSON.parse(localStorage.getItem(e)||"[]");if(t.length>0)for(var o=Math.max(0,t.length-5);ot.clientHeight?Math.round(t.scrollTop/(t.scrollHeight-t.clientHeight)*100):100;try{var n=JSON.parse(localStorage.getItem(e)||"{}");o>(n[window.currentChannelId]||0)&&(n[window.currentChannelId]=o,localStorage.setItem(e,JSON.stringify(n)))}catch(e){}},500))},{passive:!0}),window.getChannelProgress=function(t){try{return JSON.parse(localStorage.getItem(e)||"{}")[t]||0}catch(e){return 0}}}}(),function(){var e=0,t=!1;window.addEventListener("unhandledrejection",function(o){if(!(++e>10)){var n=o.reason&&o.reason.message?o.reason.message:"",i=o.reason&&o.reason.code?o.reason.code:"";console.error("[Error Boundary] Unhandled promise rejection:",n||o.reason),/permission.denied|Missing or insufficient|requires an index|PERMISSION_DENIED/i.test(n+i)||!t&&/network|fetch|Failed to fetch|UNAVAILABLE|unavailable/i.test(n+i)&&(t=!0,"function"==typeof showToast&&showToast("⚠️ Connection issue — some features may not work. Try refreshing."))}}),window.addEventListener("error",function(t){++e>5||console.error("[Error Boundary]",t.message,t.filename,t.lineno)})}(),function(){var e="btc_offline_channels";"function"!=typeof window.go||window._offlineCacheHooked||(window._offlineCacheHooked=!0,setInterval(function(){if(window.currentChannelId&&void 0!==CHANNELS){var t=CHANNELS[window.currentChannelId];if(t&&t.file)try{var o=JSON.parse(localStorage.getItem(e)||"{}");if(o[window.currentChannelId]&&Date.now()-o[window.currentChannelId].ts<864e5)return;"caches"in window&&caches.open("btc-offline-channels").then(function(e){e.add(t.file).catch(function(){})}),o[window.currentChannelId]={ts:Date.now()};var n=Object.keys(o);if(n.length>10){n.sort(function(e,t){return o[e].ts-o[t].ts});for(var i=0;iwindow.innerWidth-8&&(n=window.innerWidth-240-8),t.style.left=n+"px",t.style.width="240px",window.innerWidth>900?(t.style.top=o.top-8+"px",t.style.transform="translateY(-100%)"):(t.style.top=o.bottom+8+"px",t.style.transform="none")}}document.addEventListener("mouseover",function(t){var o=t.target.closest(".badge-item");o&&e(o)}),document.addEventListener("click",function(t){var o=t.target.closest(".badge-item");o&&e(o)})}(),function(){"use strict";function e(){var e=function(){if(void 0===window.NACHO_TRAILS)return null;var e=[];try{e=JSON.parse(localStorage.getItem("btc_trail_passed")||"[]")}catch(e){}var t={};try{t=JSON.parse(localStorage.getItem("btc_trail_progress")||"{}")}catch(e){}for(var o=0;o0){var r=document.createElement("div");if(r.className="ch-progress",r.style.cssText="position:absolute;bottom:0;left:0;height:2px;background:"+(i>=100?"#22c55e":"var(--accent,#f7931a)")+";width:"+Math.min(i,100)+"%;border-radius:0 1px 0 0;transition:width 0.3s;opacity:0.7;",t.style.position="relative",t.style.overflow="hidden",t.appendChild(r),i>=100&&!t.querySelector(".ch-done")){var s=document.createElement("span");s.className="ch-done",s.style.cssText="position:absolute;right:6px;top:50%;transform:translateY(-50%);font-size:0.6rem;opacity:0.5;",s.textContent="✓",t.appendChild(s)}}}})}catch(e){}}setTimeout(e,2e3);var t=window.goHome;t&&(window.goHome=function(){var o=t.apply(this,arguments);return setTimeout(e,500),o});var o=window.go;o&&(window.go=function(){var t=o.apply(this,arguments);return setTimeout(e,1e3),t}),window.updateSidebarProgress=e}(); \ No newline at end of file +var CHANNELS = {"decentralized":{"cat":"Properties Layer 1","title":"👪decentralized-censorship-resistant-ungovernable-incorruptible-trustless-unconfiscatable-updatable","desc":"Why no single person, company, or government controls Bitcoin — and why that's the most important feature.","file":"data/D_decentralized.json"},"dominant":{"cat":"Properties Layer 1","title":"🏆dominant-recognizable-brand-legitimate-limitless-infinite-exponential-transformative-revolutionary","desc":"Bitcoin's brand recognition, network effects, and why it has maintained the #1 position since 2009.","file":"data/D_dominant.json"},"money":{"cat":"Properties Layer 1","title":"💰money-deflationary-salable-durable-anti-fragile-divisible-portable-transmittable-verifiable-fair","desc":"What money actually is, how it works, and why Bitcoin satisfies every property of sound money better than anything before it.","file":"data/D_money.json"},"organic":{"cat":"Properties Layer 1","title":"🌳organic-empowering-elegant-freedom-centric-irrefutable-unseizable-irreversible-unbreakable","desc":"How Bitcoin grew from an idea worth nothing to a trillion-dollar network — without marketing, without a company, without a leader.","file":"data/D_organic.json"},"peaceful":{"cat":"Properties Layer 1","title":"☮peaceful-neutral-voluntary-open-universal-permissionless-borderless-global-inevitable-unstoppable","desc":"Bitcoin is voluntary, permissionless, borderless, and unstoppable. No one forces you to use it — and no one can stop you.","file":"data/D_peaceful.json"},"programmable":{"cat":"Properties Layer 1","title":"🤖programable-interoperable-deflationary-pseudonymous-opt-in-resilient-adiabatic-egalitarian","desc":"Bitcoin as programmable money — interoperable, pseudonymous, resilient, and thermodynamically sound.","file":"data/D_programmable.json"},"scarce":{"cat":"Properties Layer 1","title":"🍀scarce-unforgeable-hedge-scalable-p2p-instant-open-source-auditable-inaliable","desc":"Only 21 million will ever exist. Explore what makes Bitcoin the scarcest asset humanity has ever created.","file":"data/D_scarce.json"},"secure":{"cat":"Properties Layer 1","title":"™secure-fungible-immutable-incorruptible-immalleable-infallible-reliable-predictable-irreplicable","desc":"How Bitcoin's network security makes it virtually impossible to hack — protected by more computing power than anything on Earth.","file":"data/D_secure.json"},"supranational":{"cat":"Properties Layer 1","title":"🕊supranational-lindy-inviolate-dilution-proof-frictionless-freely-accessible-settlement-finality","desc":"Bitcoin transcends nations and governments. Explore the Lindy Effect, settlement finality, and dilution-proof money.","file":"data/D_supranational.json"},"use-cases":{"cat":"Properties Layer 1","title":"✔use-cases","desc":"Real-world uses for Bitcoin: savings, payments, remittances, store of value, and more.","file":"data/D_use-cases.json"},"whitepaper":{"cat":"Properties Layer 1","title":"📄whitepaper","desc":"The 9-page document that started it all. Published October 31, 2008 by Satoshi Nakamoto — the foundation of Bitcoin.","file":"data/D_whitepaper.json"},"bitvm":{"cat":"Experienced Topics","title":"🖥bitvm","desc":"BitVM: computation on Bitcoin without changing the protocol. A new frontier for Bitcoin programmability.","file":"data/E_bitvm.json"},"blockchain-timechain":{"cat":"Experienced Topics","title":"⛓blockchain-timechain-transactions-addresses","desc":"How the Bitcoin blockchain (timechain) works — blocks, transactions, timestamps, and the immutable ledger.","file":"data/E_blockchain-timechain.json"},"chaumian-mints":{"cat":"Experienced Topics","title":"💸layer-2-chaumian-mints-ecash","desc":"Chaumian ecash, Cashu, and blinded signatures — the cutting edge of Bitcoin privacy technology.","file":"data/E_chaumian-mints.json"},"consensus":{"cat":"Additional Info","title":"🤝Consensus","desc":"How Bitcoin achieves consensus without a central authority — Nakamoto Consensus and beyond.","file":"data/H_consensus.json"},"core-source-code":{"cat":"Experienced Topics","title":"💾core-source-code-forks-testnet-future-potential-upgrades","desc":"Bitcoin Core's source code, forks, testnet, and the open-source development process.","file":"data/E_core-source-code.json"},"cryptography":{"cat":"Experienced Topics","title":"🔒cryptography-cypherpunks","desc":"The cryptographic foundations of Bitcoin — SHA-256, elliptic curves, digital signatures, and the cypherpunk legacy.","file":"data/E_cryptography.json"},"ctv-covenants":{"cat":"Experienced Topics","title":"📜ctv-bip119-covenants","desc":"BIP-119, CTV, and Bitcoin covenants — proposed upgrades and the debates around them.","file":"data/E_ctv-covenants.json"},"developers":{"cat":"Experienced Topics","title":"🖥developers","desc":"Building on Bitcoin — resources, guides, and paths for developers who want to contribute.","file":"data/E_developers.json"},"difficulty-adjustment":{"cat":"Experienced Topics","title":"😤difficulty-adjustment","desc":"The most elegant part of Bitcoin's design — how the network self-adjusts every 2,016 blocks.","file":"data/E_difficulty-adjustment.json"},"energy":{"cat":"Experienced Topics","title":"💡energy","desc":"The truth about Bitcoin's energy use: 0.1% of global energy, renewable mining, methane capture, and grid stabilization.","file":"data/E_energy.json"},"evidence-against-alts":{"cat":"Experienced Topics","title":"⚠evidence-against-ethereum-other-alt-coins-crypto-defi-nfts-web3-monero-bsv-bch-cbdcs-other-projects","desc":"Why every altcoin fails against Bitcoin — premines, centralization, broken promises, and the evidence.","file":"data/E_evidence-against-alts.json"},"extension-blocks":{"cat":"Experienced Topics","title":"🚧extension-blocks-and-other-proposed-scaling-solutions","desc":"Extension blocks and other proposed scaling solutions for Bitcoin.","file":"data/E_extension-blocks.json"},"fedi-ark":{"cat":"Experienced Topics","title":"🛡layer-2-fedi-ark","desc":"Fedimints, Ark, and Bitcoin's privacy/scaling layers — community custody with enhanced privacy.","file":"data/E_fedi-ark.json"},"investment-strategy":{"cat":"Experienced Topics","title":"🤑investment-strategy-taxes-retirement-inheritance-loans-donate-gift-consulting-remittance","desc":"DCA, HODL, lump sum strategies, taxes, retirement planning, and thinking long-term with Bitcoin.","file":"data/E_investment-strategy.json"},"layer-2-lightning":{"cat":"Experienced Topics","title":"⚡layer-2-lightning","desc":"The Lightning Network: instant, nearly-free Bitcoin payments. How Bitcoin scales without sacrificing decentralization.","file":"data/E_layer-2-lightning.json"},"layer-3-sidechains":{"cat":"Experienced Topics","title":"📱layer-3-sidechain-applications","desc":"Sidechains, Liquid Network, and layer-3 applications built on top of Bitcoin.","file":"data/E_layer-3-sidechains.json"},"maximalism":{"cat":"Experienced Topics","title":"💯maximalism","desc":"Why people who study Bitcoin the most become maximalists. The case for Bitcoin-only.","file":"data/E_maximalism.json"},"mining":{"cat":"Experienced Topics","title":"🌋mining","desc":"How Bitcoin mining actually works — nonces, SHA-256 hashing, difficulty adjustment, and the brute-force lottery.","file":"data/E_mining.json"},"nodes":{"cat":"Experienced Topics","title":"💻nodes","desc":"Run your own Bitcoin node. Don't trust, verify. How 14,000+ nodes keep the network decentralized.","file":"data/E_nodes.json"},"op-codes":{"cat":"Experienced Topics","title":"👨‍💻op-codes-simplicity","desc":"OP_CAT, Simplicity, and Bitcoin's scripting language — the building blocks of smart functionality.","file":"data/E_op-codes.json"},"pow-vs-pos":{"cat":"Experienced Topics","title":"💪proof-of-work-vs-proof-of-stake","desc":"Why Proof of Work is fundamentally superior to Proof of Stake — energy, security, fairness, and decentralization.","file":"data/E_pow-vs-pos.json"},"privacy-nonkyc":{"cat":"Experienced Topics","title":"🤫privacy-nonkyc-stacking-self-sovereignty","desc":"Financial privacy as a human right. KYC, non-KYC stacking, and protecting your sovereignty.","file":"data/E_privacy-nonkyc.json"},"problems-of-money":{"cat":"Experienced Topics","title":"📉the-problems-of-todays-money-and-freedom","desc":"The broken fiat system: inflation, money printing, the Cantillon Effect, and why today's money is failing everyone.","file":"data/E_problems-of-money.json"},"regulation":{"cat":"Experienced Topics","title":"🏛regulation-policy-legal","desc":"Bitcoin and government: bans, adoption, legal tender, ETFs, and why regulation can't stop decentralization.","file":"data/E_regulation.json"},"self-custody":{"cat":"Experienced Topics","title":"🔑personal-storage-self-custody-security","desc":"Not your keys, not your coins. Learn how to truly own your Bitcoin with wallets, seed phrases, and security.","file":"data/E_self-custody.json"},"smart-contracts":{"cat":"Experienced Topics","title":"📱smart-contracts","desc":"Smart contracts on Bitcoin — what's possible, what's coming, and why Bitcoin's approach is different.","file":"data/E_smart-contracts.json"},"stablecoins":{"cat":"Additional Info","title":"🪙Stablecoins","desc":"The role of stablecoins in the Bitcoin economy — and why they're not a threat to Bitcoin.","file":"data/H_stablecoins.json"},"0_mining__hashing":{"cat":"Additional Info","title":"0⃣Mining (Hashing)","desc":"Deep dive into Bitcoin mining and hashing — how SHA-256 works at the bit level.","file":"data/H_0_mining__hashing.json"},"100_sats":{"cat":"Additional Info","title":"💯100 sats","desc":"What can you do with just 100 satoshis? More than you think.","file":"data/H_100_sats.json"},"1_first_principles":{"cat":"Additional Info","title":"1⃣First Principles","desc":"First principles thinking applied to Bitcoin — reasoning from fundamentals, not analogies.","file":"data/H_1_first_principles.json"},"2__solved_technical_problems":{"cat":"Additional Info","title":"2⃣ Solved Technical Problems","desc":"The technical problems Bitcoin solved — digital scarcity, double-spending, and Byzantine fault tolerance.","file":"data/H_2__solved_technical_problems.json"},"analogies":{"cat":"Additional Info","title":"🔋Analogies","desc":"The best analogies for explaining Bitcoin to anyone — from trees to brains to hearts.","file":"data/H_analogies.json"},"austrian_school_of_economics":{"cat":"Additional Info","title":"🇦🇹Austrian School of Economics","desc":"Austrian Economics and Bitcoin: Mises, Hayek, sound money theory, and the intellectual foundation.","file":"data/H_austrian_school_of_economics.json"},"bip119":{"cat":"Additional Info","title":"🚧BIP119","desc":"BIP-119 (CheckTemplateVerify) — what it is, why it's controversial, and the community debate.","file":"data/H_bip119.json"},"bitcoin_exam":{"cat":"Additional Info","title":"🎓Bitcoin Exam","desc":"Test questions for a Bitcoin exam — study material and self-assessment.","file":"data/H_bitcoin_exam.json"},"bitcoin_vs_real_estate":{"cat":"Additional Info","title":"Bitcoin vs Real Estate","desc":"Bitcoin vs. real estate as an investment — comparing the two hardest assets.","file":"data/H_bitcoin_vs_real_estate.json"},"block_time-block-size":{"cat":"Additional Info","title":"⏰Block Time-Block-Size","desc":"Why Bitcoin uses 10-minute blocks and how block size affects the network.","file":"data/H_block_time-block-size.json"},"burn_bitcoin":{"cat":"Additional Info","title":"Burn bitcoin","desc":"How Bitcoin can be burned (made permanently unspendable) and why people do it.","file":"data/H_burn_bitcoin.json"},"byzantine_generals__problem":{"cat":"Additional Info","title":"⚔Byzantine Generals’ Problem","desc":"The Byzantine Generals' Problem — the computer science challenge Satoshi solved.","file":"data/H_byzantine_generals__problem.json"},"chaumian_e-cash_and_blind_signatures":{"cat":"Additional Info","title":"💲Chaumian E-cash and Blind Signatures","desc":"David Chaum's ecash, blind signatures, and the cryptographic foundations of digital privacy.","file":"data/H_chaumian_e-cash_and_blind_signatures.json"},"coin_mixing_coinjoin_coin_control_utxo":{"cat":"Additional Info","title":"🌀Coin Mixing/Coinjoin/Coin Control/UTXO Management","desc":"CoinJoin, coin mixing, UTXO management — advanced Bitcoin privacy techniques.","file":"data/H_coin_mixing_coinjoin_coin_control_utxo.json"},"cyles":{"cat":"Additional Info","title":"🚲Cyles","desc":"Bitcoin's 4-year cycles, Gartner Hype Cycles, and whether the pattern continues.","file":"data/H_cyles.json"},"derivation_path":{"cat":"Additional Info","title":"↕Derivation Path","desc":"HD wallet derivation paths — how your seed phrase generates all your addresses.","file":"data/H_derivation_path.json"},"discrete_log_contracts__dlcs":{"cat":"Additional Info","title":"📝Discrete Log Contracts (DLCs)?","desc":"DLCs (Discrete Log Contracts) — smart contracts on Bitcoin using oracle signatures.","file":"data/H_discrete_log_contracts__dlcs.json"},"dollar-bitcoin_milkshake_theory":{"cat":"Additional Info","title":"🥤Dollar-Bitcoin Milkshake Theory","desc":"The Dollar-Bitcoin Milkshake Theory — how global dollar demand and Bitcoin intersect.","file":"data/H_dollar-bitcoin_milkshake_theory.json"},"dust":{"cat":"Additional Info","title":"⏳Dust","desc":"Dust UTXOs: what they are, why they're a problem, and how to manage them.","file":"data/H_dust.json"},"elevator_pitches":{"cat":"Additional Info","title":"↕Elevator Pitches","desc":"Quick 20-30 second explanations of why Bitcoin matters — for every audience.","file":"data/H_elevator_pitches.json"},"environment___energy":{"cat":"Additional Info","title":"🌳Environment & Energy","desc":"Bitcoin and the environment: energy usage facts, renewable mining, and debunking the FUD.","file":"data/H_environment___energy.json"},"faith___religion":{"cat":"Additional Info","title":"🙏Faith & Religion","desc":"Bitcoin and faith — how sound money relates to religious and spiritual values.","file":"data/H_faith___religion.json"},"fedimints":{"cat":"Additional Info","title":"💚Fedimints","desc":"Fedimints: community custody with enhanced privacy using federated Chaumian mints.","file":"data/H_fedimints.json"},"feedback_loops":{"cat":"Additional Info","title":"➰Feedback Loops","desc":"Bitcoin's feedback loops — the self-reinforcing cycles that drive adoption and security.","file":"data/H_feedback_loops.json"},"free_and_open_source_software__foss":{"cat":"Additional Info","title":"💿Free and Open Source Software (FOSS)","desc":"Free and open source software (FOSS) projects connected to Bitcoin.","file":"data/H_free_and_open_source_software__foss.json"},"game_theory":{"cat":"Additional Info","title":"🏈Game Theory","desc":"Game theory and Bitcoin: Nash equilibrium, prisoner's dilemma, and strategic incentives.","file":"data/H_game_theory.json"},"geopolitics___macroeconomics":{"cat":"Additional Info","title":"💰Geopolitics & Macroeconomics","desc":"Bitcoin's role in geopolitics: nation-state adoption, reserve currencies, and macro trends.","file":"data/H_geopolitics___macroeconomics.json"},"governance":{"cat":"Additional Info","title":"🏛Governance","desc":"How Bitcoin is governed — consensus mechanisms, BIPs, and decentralized decision-making.","file":"data/H_governance.json"},"ham_radio":{"cat":"Additional Info","title":"Ham Radio","desc":"Using Bitcoin without internet — ham radio, mesh networks, and offline transactions.","file":"data/H_ham_radio.json"},"human_rights__social_justice_and_freedo":{"cat":"Additional Info","title":"🗽Human Rights, Social Justice and Freedom","desc":"Bitcoin as a tool for human rights, social justice, and financial freedom worldwide.","file":"data/H_human_rights__social_justice_and_freedo.json"},"improved_incentive_structure":{"cat":"Additional Info","title":"✅Improved Incentive Structure","desc":"How Bitcoin's incentive structure improves civilization — aligning individual and collective interests.","file":"data/H_improved_incentive_structure.json"},"laws_of_thermodynamics":{"cat":"Additional Info","title":"🔥Laws of Thermodynamics","desc":"How Bitcoin follows the laws of thermodynamics — energy, entropy, and proof of work.","file":"data/H_laws_of_thermodynamics.json"},"lightning_node":{"cat":"Additional Info","title":"⚡ Lightning Node","desc":"Running a Lightning Network node — setup guides, routing, and earning sats.","file":"data/H_lightning_node.json"},"lindy_effect":{"cat":"Additional Info","title":"👴Lindy Effect","desc":"The Lindy Effect: the longer Bitcoin survives, the longer it will survive.","file":"data/H_lindy_effect.json"},"market_cap":{"cat":"Additional Info","title":"🧢Market Cap","desc":"Bitcoin's market cap potential — can it reach millions per coin? The math says yes.","file":"data/H_market_cap.json"},"math":{"cat":"Additional Info","title":"➕Math","desc":"The mathematics of Bitcoin — from SHA-256 to elliptic curves to probability.","file":"data/H_math.json"},"mathematics":{"cat":"Additional Info","title":"➕Mathematics","desc":"Advanced mathematical concepts underlying Bitcoin's protocol and security.","file":"data/H_mathematics.json"},"mev":{"cat":"Additional Info","title":"⛏MEV","desc":"MEV (Miner Extractable Value) in Bitcoin — what it is and its implications.","file":"data/H_mev.json"},"network_effects":{"cat":"Additional Info","title":"🌐Network Effects","desc":"Bitcoin's network effects — why the most adopted network wins and keeps winning.","file":"data/H_network_effects.json"},"open_source":{"cat":"Additional Info","title":"⭕Open Source","desc":"What free and open source really means — and why it matters for Bitcoin.","file":"data/H_open_source.json"},"oracle":{"cat":"Additional Info","title":"🔮Oracle","desc":"Oracles in Bitcoin — how external data connects to the blockchain.","file":"data/H_oracle.json"},"orange-pilling":{"cat":"Additional Info","title":"🟠Orange-Pilling","desc":"The art of orange-pilling — strategies for explaining Bitcoin to different audiences.","file":"data/H_orange-pilling.json"},"ordinals":{"cat":"Additional Info","title":"Ordinals","desc":"Bitcoin Ordinals and inscriptions — NFTs on the world's most secure blockchain.","file":"data/H_ordinals.json"},"ordinals__nfts_on_bitcoin__and_block_spa":{"cat":"Additional Info","title":"Ordinals, NFTs on Bitcoin, and Block Space","desc":"The Ordinals debate: NFTs on Bitcoin, block space economics, and community perspectives.","file":"data/H_ordinals__nfts_on_bitcoin__and_block_spa.json"},"peace_and_anti-war":{"cat":"Additional Info","title":"☮Peace and Anti-War","desc":"Can a Bitcoin Standard end wars? The case for Bitcoin as a force for peace.","file":"data/H_peace_and_anti-war.json"},"philosophy":{"cat":"Additional Info","title":"🍎Philosophy","desc":"The philosophy of Bitcoin — from first principles to existential implications.","file":"data/H_philosophy.json"},"politics":{"cat":"Additional Info","title":"🏛Politics","desc":"Bitcoin and politics — how Bitcoin intersects with government policy and elections.","file":"data/H_politics.json"},"predictions":{"cat":"Additional Info","title":"🔮Predictions","desc":"Bitcoin predictions timestamped by the community — bold calls and their outcomes.","file":"data/H_predictions.json"},"public_key_vs_private_key":{"cat":"Additional Info","title":"🗝Public Key vs Private Key","desc":"Public keys vs. private keys — the cryptographic foundation of Bitcoin ownership.","file":"data/H_public_key_vs_private_key.json"},"rbf":{"cat":"Additional Info","title":"↔RBF","desc":"Replace-By-Fee (RBF) — how to speed up stuck Bitcoin transactions.","file":"data/H_rbf.json"},"referral-links":{"cat":"Referral Links","title":"🔗free-btc-referral-links","desc":"Curated Bitcoin referral links — earn free sats with trusted platforms like River, Fold, and Strike.","file":"data/H_referral-links.json"},"risks__threats__attack_vectors__weaknes":{"cat":"Additional Info","title":"⚔Risks, Threats, Attack Vectors, Weaknesses, Issues","desc":"Bitcoin's risks, threats, and attack vectors — what could go wrong and why it probably won't.","file":"data/H_risks__threats__attack_vectors__weaknes.json"},"rollups":{"cat":"Additional Info","title":"🥐Rollups","desc":"Rollups on Bitcoin — scaling and privacy solutions using off-chain computation.","file":"data/H_rollups.json"},"sats__or__bits":{"cat":"Additional Info","title":"\"Sats\" or \"Bits\"?","desc":"The sats vs. bits debate — which denomination should Bitcoin use?","file":"data/H_sats__or__bits.json"},"scalability":{"cat":"Additional Info","title":"🌐Scalability","desc":"Can Bitcoin scale to serve the world? Layers, Lightning, and the path forward.","file":"data/H_scalability.json"},"sidechains":{"cat":"Additional Info","title":"♻Sidechains","desc":"Bitcoin sidechains like Liquid — benefits, tradeoffs, and use cases.","file":"data/H_sidechains.json"},"simplified_payment_verification__spv":{"cat":"Additional Info","title":"✔Simplified Payment Verification (SPV)","desc":"SPV (Simplified Payment Verification) — lightweight Bitcoin verification without a full node.","file":"data/H_simplified_payment_verification__spv.json"},"soft_vs_hard_forks":{"cat":"Additional Info","title":"🍴Soft vs Hard Forks","desc":"Soft forks vs. hard forks — how Bitcoin upgrades while maintaining consensus.","file":"data/H_soft_vs_hard_forks.json"},"softwar":{"cat":"Additional Info","title":"Softwar","desc":"Jason Lowery's Softwar thesis — Bitcoin as a non-lethal alternative to physical warfare.","file":"data/H_softwar.json"},"stratum_v2":{"cat":"Additional Info","title":"🟩Stratum V2","desc":"Stratum V2 — the next-generation mining protocol for better decentralization and efficiency.","file":"data/H_stratum_v2.json"},"submarine_swap":{"cat":"Additional Info","title":"⛵Submarine Swap","desc":"Submarine swaps — trustlessly moving Bitcoin between on-chain and Lightning.","file":"data/H_submarine_swap.json"},"swaps":{"cat":"Additional Info","title":"↔Swaps","desc":"How to swap between on-chain Bitcoin and Lightning — tools, techniques, and protocols.","file":"data/H_swaps.json"},"ta_tips":{"cat":"Additional Info","title":"📈TA Tips","desc":"Technical analysis tips for Bitcoin — chart patterns, indicators, and trading education.","file":"data/H_ta_tips.json"},"tail_emission":{"cat":"Additional Info","title":"🐈Tail Emission","desc":"The tail emission debate — should Bitcoin ever have perpetual block rewards?","file":"data/H_tail_emission.json"},"taproot":{"cat":"Additional Info","title":"🧰Taproot","desc":"Taproot: Bitcoin's latest major upgrade — Schnorr signatures, script improvements, and privacy.","file":"data/H_taproot.json"},"taro":{"cat":"Additional Info","title":"🥕Taro","desc":"Taro (now Taproot Assets) — issuing assets on the Bitcoin and Lightning networks.","file":"data/H_taro.json"},"the_future":{"cat":"Additional Info","title":"🔮The Future","desc":"How Bitcoin could change the future — hyperbitcoinization, global adoption, and beyond.","file":"data/H_the_future.json"},"time":{"cat":"Additional Info","title":"⏰Time","desc":"How Bitcoin keeps time — block time, timestamps, and the decentralized clock.","file":"data/H_time.json"},"time_preference":{"cat":"Additional Info","title":"🕑Time Preference","desc":"Time preference: how sound money encourages long-term thinking and civilization building.","file":"data/H_time_preference.json"},"toxicity":{"cat":"Additional Info","title":"☣ Toxicity","desc":"Is Bitcoin community toxicity real? Or is it integrity? The debate and its meaning.","file":"data/H_toxicity.json"},"transaction_fees":{"cat":"Additional Info","title":"💲Transaction Fees","desc":"Bitcoin transaction fees — how they work, fee markets, and long-term sustainability.","file":"data/H_transaction_fees.json"},"unpopular_opinions":{"cat":"Additional Info","title":"💀Unpopular Opinions","desc":"Unpopular opinions in the Bitcoin space — controversial takes and honest debates.","file":"data/H_unpopular_opinions.json"},"utxos":{"cat":"Additional Info","title":"🕳UTXOs","desc":"UTXOs (Unspent Transaction Outputs) — the fundamental building block of Bitcoin transactions.","file":"data/H_utxos.json"},"vbyte":{"cat":"Additional Info","title":"🏋vByte","desc":"Virtual bytes (vBytes) — how Bitcoin measures transaction weight for fee calculation.","file":"data/H_vbyte.json"},"apps-tools":{"cat":"Resources","title":"🍎apps-tools-services-models","desc":"Bitcoin apps, tools, services, and platforms — everything you need to use Bitcoin daily.","file":"data/R_apps-tools.json"},"art-inspiration":{"cat":"Resources","title":"🤩art-inspiration-motivation","desc":"Bitcoin art, inspiration, and motivational content from the community.","file":"data/R_art-inspiration.json"},"articles-threads":{"cat":"Resources","title":"📃articles-threads","desc":"The best Bitcoin articles and Twitter threads — curated deep dives into every aspect of Bitcoin.","file":"data/R_articles-threads.json"},"books":{"cat":"Resources","title":"📚books","desc":"The essential Bitcoin reading list: The Bitcoin Standard, 21 Lessons, Mastering Bitcoin, and more.","file":"data/R_books.json"},"charts":{"cat":"Resources","title":"📊charts","desc":"Bitcoin price charts, on-chain analytics, stock-to-flow, and data visualizations.","file":"data/R_charts.json"},"curriculum":{"cat":"Resources","title":"🎓curriculum-presentations","desc":"Bitcoin education curriculum and presentations for teachers and students.","file":"data/R_curriculum.json"},"faq-glossary":{"cat":"Resources","title":"❓faq-glossary-search-ai-calendar","desc":"Bitcoin FAQ, glossary of terms, and quick answers to common questions.","file":"data/R_faq-glossary.json"},"fun-facts":{"cat":"Resources","title":"🎉fun-facts","desc":"Mind-blowing Bitcoin trivia: Pizza Day, Satoshi's birthday code, lost coins, and 200+ amazing facts.","file":"data/R_fun-facts.json"},"games":{"cat":"Resources","title":"🎮games","desc":"Bitcoin-themed games and gamified learning experiences.","file":"data/R_games.json"},"giga-chad":{"cat":"Resources","title":"👑giga-chad","desc":"Michael Saylor, MicroStrategy, and the corporate Bitcoin movement.","file":"data/R_giga-chad.json"},"graphics":{"cat":"Resources","title":"🎨graphics","desc":"Bitcoin infographics, charts, diagrams, and visual explanations.","file":"data/R_graphics.json"},"hardware":{"cat":"Resources","title":"💻hardware","desc":"Bitcoin hardware: mining rigs, hardware wallets, nodes, and open-source projects like Bitaxe.","file":"data/R_hardware.json"},"health":{"cat":"Resources","title":"🥩health","desc":"Bitcoin and health: low time preference living, breaking free from the system.","file":"data/R_health.json"},"history":{"cat":"Resources","title":"📆history","desc":"The complete history of Bitcoin — from the cypherpunks to today.","file":"data/R_history.json"},"informational-sites":{"cat":"Resources","title":"📃informational-sites-courses-workshops-newsletters-projects-communities-meetups-conferences","desc":"Bitcoin dashboards, tools, courses, newsletters, communities, and educational websites.","file":"data/R_informational-sites.json"},"international":{"cat":"Resources","title":"🌍international","desc":"Bitcoin resources in multiple languages and global adoption stories.","file":"data/R_international.json"},"jobs-earn":{"cat":"Resources","title":"👷job-postings-employer-info-entrepreneurship-earn-bitcoin-stack-sats","desc":"Bitcoin job boards, entrepreneurship resources, and ways to earn sats.","file":"data/R_jobs-earn.json"},"memes-funny":{"cat":"Resources","title":"😂memes-funny","desc":"The best Bitcoin memes, jokes, and humor from the community. Laugh while you learn.","file":"data/R_memes-funny.json"},"misconceptions-fud":{"cat":"Resources","title":"🤡common-misconceptions-fud-debunked","desc":"Every Bitcoin myth debunked: too volatile, wastes energy, used by criminals, no intrinsic value — all wrong.","file":"data/R_misconceptions-fud.json"},"movies-tv":{"cat":"Resources","title":"🎬movies-tv-documentaries","desc":"Bitcoin documentaries, films, and TV appearances. From The Big Short to Bitcoin-specific docs.","file":"data/R_movies-tv.json"},"music":{"cat":"Resources","title":"🎵music","desc":"Bitcoin-inspired music, songs, and audio content from the community.","file":"data/R_music.json"},"news-adoption":{"cat":"Resources","title":"📰news-adoption","desc":"Latest Bitcoin news, adoption milestones, and real-world usage stories.","file":"data/R_news-adoption.json"},"nostr":{"cat":"Resources","title":"💜nostr","desc":"Nostr: the decentralized social protocol Bitcoiners are building on. Social media you can't be censored from.","file":"data/R_nostr.json"},"one-stop-shop":{"cat":"Resources","title":"🛑one-stop-shop","desc":"The best resources to understand Bitcoin's value as fast as possible. Start here if you're new.","file":"data/R_one-stop-shop.json"},"podcasts":{"cat":"Resources","title":"🔊podcasts","desc":"Top Bitcoin podcasts: Bitcoin Audible, What Bitcoin Did, Stephan Livera, and more.","file":"data/R_podcasts.json"},"poems-stories":{"cat":"Resources","title":"📒poems-stories-jokes","desc":"Bitcoin poetry, short stories, jokes, and creative writing from the community.","file":"data/R_poems-stories.json"},"projects-diy":{"cat":"Resources","title":"🔧projects-diy","desc":"DIY Bitcoin projects: build your own node, Lightning ATM, and more.","file":"data/R_projects-diy.json"},"research-theses":{"cat":"Resources","title":"✍research-theses","desc":"Academic research papers and theses on Bitcoin, monetary policy, and cryptographic systems.","file":"data/R_research-theses.json"},"satoshi-nakamoto":{"cat":"Resources","title":"🦸satoshi-nakamoto","desc":"The mystery of Bitcoin's creator: who was Satoshi Nakamoto? The evidence, theories, and legacy.","file":"data/R_satoshi-nakamoto.json"},"social-media":{"cat":"Resources","title":"👍social-media-proponents","desc":"Bitcoin Twitter/X accounts, influencers, and social media communities to follow.","file":"data/R_social-media.json"},"swag-merch":{"cat":"Resources","title":"👕swag-merch-businesses-spend","desc":"Bitcoin merchandise, clothing, and businesses where you can spend your sats.","file":"data/R_swag-merch.json"},"videos":{"cat":"Resources","title":"📺videos","desc":"Must-watch Bitcoin lectures, talks, and presentations from Andreas Antonopoulos, Michael Saylor, and others.","file":"data/R_videos.json"},"web5":{"cat":"Resources","title":"5⃣web5","desc":"Web5 and decentralized web technologies built on Bitcoin.","file":"data/R_web5.json"}};// ============================================================ +// Bitcoin Education Archive — Shared Utilities +// [AUDIT FIX] Extracted from duplicate definitions across files. +// Load BEFORE all other local scripts in index.html. +// ============================================================ + +/** + * Safe cover image URL helper + * Returns provided URL or a placeholder if missing/invalid + * @param {string} url - image URL + * @returns {string} - sanitized or fallback URL + */ +// Safe SVG placeholder (music note icon) +var _SAFE_COVER_PLACEHOLDER = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjMWUxYTJlIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZpbGw9IiNmNzkzMWEiIGZvbnQtc2l6ZT0iMjAiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj7wnY61PC90ZXh0Pjwvc3ZnPg=='; + +function _safeCover(url) { + if (!url || typeof url !== 'string' || url.trim() === '') { + return _SAFE_COVER_PLACEHOLDER; + } + var trimmed = url.trim(); + var lower = trimmed.toLowerCase(); + + // [SECURITY FIX] Block javascript:, data:text/html:, vbscript:, blob: URIs + if (/^(javascript|data:text\/html|vbscript|blob):/i.test(lower)) { + console.warn('[XSS BLOCKED] Malicious image URL scheme rejected:', trimmed.substring(0, 50)); + return _SAFE_COVER_PLACEHOLDER; + } + + // [SECURITY FIX] Only allow https:// or data:image/ URLs + if (!/^(https:\/\/|data:image\/)/i.test(trimmed)) { + console.warn('[XSS BLOCKED] Invalid URL scheme (must be https:// or data:image/):', trimmed.substring(0, 50)); + return _SAFE_COVER_PLACEHOLDER; + } + + // [SECURITY FIX] Strip characters that could break out of HTML attributes + var sanitized = trimmed.replace(/["'<>\\]/g, ''); + + return sanitized; +} + +// ---- Safe JSON parse from localStorage ---- +// [AUDIT FIX #16] Prevents uncaught exceptions from corrupted localStorage +function safeJSON(key, fallback) { + try { + var raw = localStorage.getItem(key); + if (raw === null) return fallback; + return JSON.parse(raw); + } catch (e) { + console.warn('safeJSON: corrupted data for key "' + key + '", resetting.', e); + try { localStorage.removeItem(key); } catch (e2) {} + return fallback; + } +} + +// ---- HTML Escape ---- +// Prevents XSS in user-generated content rendered as innerHTML +function escapeHtml(str) { + if (!str) return ''; + var div = document.createElement('div'); + div.appendChild(document.createTextNode(str)); + return div.innerHTML; +} + +// ---- Safe URL (blocks javascript:, data:, vbscript:, blob: URIs) ---- +function sanitizeUrl(url) { + if (!url) return ''; + url = url.trim(); + if (/^(javascript|data|vbscript|blob):/i.test(url)) return ''; + return url; +} + +// ---- Time Ago ---- +// Converts a Firestore timestamp or Date to human-readable relative time +function timeAgo(ts) { + if (!ts) return ''; + var date; + if (ts.toDate) { + date = ts.toDate(); + } else if (ts instanceof Date) { + date = ts; + } else { + date = new Date(ts); + } + var diff = Math.floor((Date.now() - date.getTime()) / 1000); + if (diff < 60) return 'just now'; + if (diff < 3600) return Math.floor(diff / 60) + 'm ago'; + if (diff < 86400) return Math.floor(diff / 3600) + 'h ago'; + if (diff < 604800) return Math.floor(diff / 86400) + 'd ago'; + return date.toLocaleDateString(); +} + +// ---- Page Visibility: pause/resume intervals when tab is hidden ---- +// Prevents wasted CPU and API calls in background tabs +(function() { + var _registeredIntervals = []; + var _pausedIntervals = []; + + window.registerInterval = function(fn, ms, name) { + var id = setInterval(fn, ms); + _registeredIntervals.push({ id: id, fn: fn, ms: ms, name: name || 'unnamed' }); + return id; + }; + + document.addEventListener('visibilitychange', function() { + if (document.hidden) { + // Tab hidden — pause all registered intervals + _registeredIntervals.forEach(function(entry) { + clearInterval(entry.id); + }); + _pausedIntervals = _registeredIntervals.slice(); + _registeredIntervals = []; + } else { + // Tab visible — resume all paused intervals + _pausedIntervals.forEach(function(entry) { + entry.fn(); // Run immediately on resume + entry.id = setInterval(entry.fn, entry.ms); + _registeredIntervals.push(entry); + }); + _pausedIntervals = []; + } + }); +})(); + +// ============================================================ +// 🟠 Premium Tier System +// ============================================================ + +/** Check if current user has active premium */ +function isPremium() { + return typeof currentUser !== 'undefined' && currentUser && currentUser.premium && currentUser.premium.active === true; +} + +/** Get sat redemption cap based on tier */ +function getSatCap() { + return isPremium() ? 21000 : 10000; +} + +/** Premium tier constants */ +// ---- Faction Username Styling ---- +// Returns inline CSS string for faction-colored usernames. +// Cyber Hornets: yellow text, black outline +// Honey Badgers: black text, white outline +// Usage: style="' + window._factionNameStyle(faction) + '" +window._factionNameStyle = function(faction) { + if (faction === 'cyber_hornets') { + return 'color:#f7e400;text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;font-weight:700;'; + } + if (faction === 'honey_badgers') { + return 'color:#1a1a1a;text-shadow:-1px -1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,1px 1px 0 #fff;font-weight:700;'; + } + return ''; +}; + +var PREMIUM_CONFIG = { + FREE_SAT_CAP: 10000, + PREMIUM_SAT_CAP: 21000, + FREE_SPINS: 1, + PREMIUM_SPINS: 3, + MONTHLY_PRICE_USD: 4.99, + YEARLY_PRICE_USD: 42, + LIFETIME_SATS: 210000, + TIER_NAME: 'Bitcoin Maxi' +}; +// © 2024-2026 603BTC LLC. All rights reserved. +// This code is proprietary. See LICENSE file. Do not copy or redistribute. +// ============================================= +// Bitcoin Education Archive - Ranking System +// ============================================= +// FIREBASE_CONFIG is now loaded globally via firebase-config.js + +// Levels +const LEVELS = [ + { name: 'Normie', emoji: '🟢', min: 0 }, + { name: 'Curious', emoji: '🔵', min: 10 }, + { name: 'Pleb', emoji: '🟠', min: 144 }, + { name: 'Pleb II', emoji: '🟠🟠', min: 170 }, + { name: 'Pleb III', emoji: '🟠🟠🟠', min: 256 }, + { name: 'Stacker', emoji: '📦', min: 500 }, + { name: 'Stacker II', emoji: '📦📦', min: 1913 }, + { name: 'Stacker III', emoji: '📦📦📦', min: 2016 }, + { name: 'Maxi', emoji: '🔥', min: 2140 }, + { name: 'Maxi II', emoji: '🔥🔥', min: 6102 }, + { name: 'Maxi III', emoji: '🔥🔥🔥', min: 8888 }, + { name: 'Papa John', emoji: '🍕', min: 10000 }, + { name: 'Full Node', emoji: '🖥️', min: 18333 }, + { name: 'Whale', emoji: '🐋', min: 50000 }, + { name: 'Sovereign', emoji: '🏴', min: 100000 }, + { name: 'Cypherpunk', emoji: '🔒', min: 133337 }, + { name: 'Satoshi', emoji: '👑', min: 210000 }, +]; + +// Client-side QR code generation (avoids leaking data to external API) +function _renderQRCode(container, data, size) { + if (window.qrcode && typeof window.qrcode === 'function') { _drawQR(container, data, size); return; } + var script = document.createElement('script'); + script.src = 'https://cdnjs.cloudflare.com/ajax/libs/qrcode-generator/1.4.4/qrcode.min.js'; + script.integrity = 'sha384-mZT2gIty7ZDdOGkxfP6joZcYdMW1Jvj9dRlfpTmaJAKKXTqzygtB22k7FLe+KZC1'; + script.crossOrigin = 'anonymous'; + script.onload = function() { _drawQR(container, data, size); }; + script.onerror = function() { container.innerHTML = '
    ' + data + '
    '; }; + document.head.appendChild(script); +} +function _drawQR(container, data, size) { + try { + var qr = qrcode(0, 'M'); qr.addData(data); qr.make(); + var img = document.createElement('img'); + img.src = qr.createDataURL(6, 4); img.width = size; img.height = size; + img.alt = 'QR Code'; img.style.cssText = 'border-radius:8px;image-rendering:pixelated;'; + container.innerHTML = ''; container.appendChild(img); + } catch(e) { container.innerHTML = '
    QR generation failed
    '; } +} + +// Points config +const POINTS = { + visit: 5, + openChannel: 10, + readTime: 15, // per 30 seconds + explore10: 50, // 10+ channels in a session + streak: 100, // daily streak bonus +}; + +let db, auth, currentUser = null; +let signInAttempts = 0; +let signInLockout = 0; +let redirectResultResolved = false; // Track whether getRedirectResult has resolved +let redirectResultPromise = Promise.resolve(null); // Resolves when getRedirectResult completes +// Session timeout removed — users stay signed in via Firebase LOCAL persistence +let sessionChannels = new Set(); +let readTimer = null; +let readSeconds = 0; +let lastReadAward = 0; +let rankingReady = false; +let allTimeChannels = new Set(); // tracks channels already awarded across all sessions +let lastLevelName = ''; +let lastLevelMin = 0; +let levelUpReady = false; // Don't celebrate until initial load completes + +// Initialize Firebase +function initRanking() { + try { + firebase.initializeApp(FIREBASE_CONFIG); + + // Firebase App Check — temporarily disabled to fix Cloud Functions auth + // Firebase App Check — temporarily disabled until key is verified + // App Check DISABLED — not enforced, and reCAPTCHA adds 724KB to page load + // Re-enable when Firebase App Check is enforced in the console + // if (typeof firebase.appCheck === 'function') { + // firebase.appCheck().activate('6LcTlnYsAAAAAMR0KkaRoCrIlvceClMGkWXr9ahv', true); + // } + + db = firebase.firestore(); + // Enable offline persistence — data survives connection loss + db.enablePersistence({ synchronizeTabs: true }).catch(function(err) { + // multi-tab or unimplemented — not critical + if (err.code !== 'failed-precondition' && err.code !== 'unimplemented') { + console.log('Persistence error:', err.code); + } + }); + auth = firebase.auth(); + // Ensure auth persists across refreshes, tab closes, and app restarts + auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).catch(function() {}); + + // Check if returning from email magic link + if (auth.isSignInWithEmailLink(window.location.href)) { + handleEmailSignIn(); + // Still set up auth listener for future state changes + } + + // Check if returning from provider redirect (in-app browser flow) + // IMPORTANT: must resolve before we allow anonymous sign-in to avoid + // clobbering the redirect auth state on mobile + redirectResultPromise = auth.getRedirectResult().then(async function(result) { + redirectResultResolved = true; + console.log('[Auth] getRedirectResult:', result ? (result.user ? result.user.uid : 'no user') : 'null'); + if (!result || !result.user) return null; + const user = result.user; + // Mark that we came from a redirect — prevent anonymous sign-in from overwriting + sessionStorage.setItem('btc_redirect_auth', '1'); + const existingDoc = await db.collection('users').doc(user.uid).get(); + + // Recover anonymous data from before redirect + const anonUid = localStorage.getItem('btc_anon_uid'); + let anonData = null; + try { anonData = JSON.parse(localStorage.getItem('btc_anon_data')); } catch(e) {} + localStorage.removeItem('btc_anon_uid'); + localStorage.removeItem('btc_anon_data'); + + if (!existingDoc.exists) { + if (anonData) { + anonData.email = user.email || ''; + if (!anonData.username) anonData.username = user.displayName || 'Bitcoiner'; + await db.collection('users').doc(user.uid).set(anonData); + } else { + await db.collection('users').doc(user.uid).set({ + username: user.displayName || 'Bitcoiner', + email: user.email || '', + points: 0, channelsVisited: 0, totalVisits: 1, streak: 1, + lastVisit: new Date().toISOString().split('T')[0], + created: firebase.firestore.FieldValue.serverTimestamp() + }); + } + try { db.collection('stats').doc('global').set({ userCount: firebase.firestore.FieldValue.increment(1) }, { merge: true }).catch(function() {}); } catch(e) {} + if (typeof attachReferral === 'function') attachReferral(user.uid); + } else if (anonData) { + const existData = existingDoc.data(); + // Anti-abuse: only merge anonymous data once per account + // Anonymous data merge now handled minimally (points/visits are server-managed) + if (!existData.mergedAnon) { + await existingDoc.ref.update({ + mergedAnon: true, + }); + // Award any anonymous points through the server-side Cloud Function + var _mergedPts = Math.min(anonData.points || 0, 500); + if (_mergedPts > 0 && typeof awardPoints === 'function') { + await awardPoints(_mergedPts, '🔗 Anonymous progress merged'); + } + } + } + + // Clean up old anonymous doc + if (anonUid && anonUid !== user.uid) { + try { await db.collection('users').doc(anonUid).delete(); } catch(e) {} + } + + loadUser(user.uid); + updateAuthButton(); + if (typeof hideUsernamePrompt === 'function') hideUsernamePrompt(); + showToast('✅ Signed in as ' + escapeHtml(user.displayName || user.email || 'Bitcoiner')); + return user; + }).catch(function(e) { + redirectResultResolved = true; + if (e.code !== 'auth/popup-closed-by-user') { + console.log('Redirect result error:', e); + } + return null; + }); + + // Wait for auth to fully resolve before doing anything + // This prevents the race condition where anonymous user loads before Google auth restores + let firstAuthEvent = true; + let emailLinkHandled = auth.isSignInWithEmailLink(window.location.href); + // Detect if we're returning from a social login redirect + var _pwaAuthPending = localStorage.getItem('btc_pwa_auth_pending'); + var _pendingRedirect = !!localStorage.getItem('btc_anon_uid') || sessionStorage.getItem('btc_redirect_pending') === '1' || !!_pwaAuthPending; + if (_pwaAuthPending) { localStorage.removeItem('btc_pwa_auth_pending'); console.log('[Auth] PWA auth pending detected'); } + if (_pendingRedirect) console.log('[Auth] Detected pending redirect return'); + + auth.onAuthStateChanged(user => { + console.log('[Auth] onAuthStateChanged:', user ? (user.isAnonymous ? 'anon:' + user.uid : 'real:' + user.uid) : 'null', 'firstEvent:', firstAuthEvent, 'pendingRedirect:', _pendingRedirect); + // Detect account switch: if a real user signs in and it's a different UID, clear old data + if (user && !user.isAnonymous) { + var prevUid = localStorage.getItem('btc_last_auth_uid'); + if (prevUid && prevUid !== user.uid) { + console.log('[Auth] Account switch detected:', prevUid, '->', user.uid, '— clearing localStorage'); + clearUserLocalStorage(); + } + localStorage.setItem('btc_last_auth_uid', user.uid); + } + if (firstAuthEvent) { + firstAuthEvent = false; + // If email link sign-in is being handled, skip — handleEmailSignIn manages it + if (emailLinkHandled) return; + if (user && !user.isAnonymous) { + // Real user restored immediately — load them + console.log('[Auth] Real user on first event:', user.uid); + sessionStorage.removeItem('btc_redirect_auth'); + loadUser(user.uid).then(function() { + if (currentUser && currentUser.username) { + setTimeout(function() { + if (typeof showToast === 'function') showToast('👋 Welcome back, ' + escapeHtml(currentUser.username || '') + '!'); + }, 2000); + } + }).catch(function() {}); + } else if (user && user.isAnonymous) { + // If we're pending a redirect, DON'T load anon yet — wait longer for auth to resolve + if (_pendingRedirect) { + console.log('[Auth] Anon user but pending redirect — waiting 8s for real auth...'); + // Give Firebase extra time to restore the redirect session + // (mobile redirects can be slow due to cross-origin ITP/partitioning) + var _redirectTimeout = setTimeout(function() { + // Check one more time if a real user appeared + if (auth.currentUser && !auth.currentUser.isAnonymous) { + console.log('[Auth] Real user appeared after wait:', auth.currentUser.uid); + loadUser(auth.currentUser.uid); + } else { + console.log('[Auth] No real user after 8s — loading anon'); + loadUserLocal(user.uid); + } + localStorage.removeItem('btc_anon_uid'); + localStorage.removeItem('btc_anon_data'); + localStorage.removeItem('btc_pwa_auth_pending'); + sessionStorage.removeItem('btc_redirect_pending'); + }, 8000); + // But if getRedirectResult resolves with a user, use that immediately + redirectResultPromise.then(function(redirectUser) { + if (redirectUser) { clearTimeout(_redirectTimeout); return; } + }); + } else { + loadUserLocal(user.uid); + } + } else { + // null user — WAIT for getRedirectResult before signing in anonymously + // Otherwise we clobber the redirect auth state on mobile + if (redirectResultResolved && !_pendingRedirect) { + // Redirect already resolved (no redirect happened) — safe to go anonymous + auth.signInAnonymously().then(() => {}); + } else { + // Wait for redirect result to resolve first, with extra timeout for mobile + var _nullUserTimeout = setTimeout(function() { + // After 10s if still no user, go anonymous + if (!auth.currentUser) { + console.log('[Auth] 10s timeout with no user — going anonymous'); + localStorage.removeItem('btc_pwa_auth_pending'); + auth.signInAnonymously().then(() => {}); + } + }, 10000); + redirectResultPromise.then(function(redirectUser) { + clearTimeout(_nullUserTimeout); + // If redirect gave us a real user, onAuthStateChanged already fired for them + if (!redirectUser && !auth.currentUser) { + auth.signInAnonymously().then(() => {}); + } + }); + } + } + return; + } + // Subsequent auth changes (sign in, sign out, etc.) + if (user) { + if (currentUser && currentUser.uid === user.uid) { + updateAuthButton(); + return; + } + if (user.isAnonymous) { + loadUserLocal(user.uid); + } else { + loadUser(user.uid); + } + } else { + currentUser = null; + // Only sign in anonymously if redirect has already resolved + if (redirectResultResolved) { + auth.signInAnonymously().then(() => {}); + } else { + redirectResultPromise.then(function(redirectUser) { + if (!redirectUser && !auth.currentUser) { + auth.signInAnonymously().then(() => {}); + } + }); + } + } + }); + } catch(e) { + console.error('Ranking init error:', e); + // Show visible error for debugging + setTimeout(function() { if (typeof showToast === 'function') showToast('⚠️ Init error: ' + (e.message || e)); }, 2000); + } +} + +// Handle email magic link return +async function handleEmailSignIn() { + // Save the full URL before any modifications — needed for signInWithEmailLink + var _signInUrl = window.location.href; + + // Try to get email from: 1) URL param (works cross-device), 2) localStorage (same device), 3) prompt (last resort) + let email = null; + // Check URL parameter first — this is embedded in the magic link + var urlParams = new URLSearchParams(window.location.search); + if (urlParams.get('signin_email')) { + email = decodeURIComponent(urlParams.get('signin_email')); + } + // Fallback to localStorage (same device/browser) + if (!email) { + email = localStorage.getItem('btc_signin_email'); + } + // Last resort: show a friendly inline prompt (cross-device scenario) + if (!email) { + return new Promise(function(resolve) { + var ov = document.createElement('div'); + ov.id = 'emailConfirmOverlay'; + ov.style.cssText = 'position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:20px;'; + ov.innerHTML = '
    ' + + '
    📧
    ' + + '
    Confirm Your Email
    ' + + '
    It looks like you opened this link on a different device. Enter the email you used to sign up:
    ' + + '' + + '' + + '
    Cancel
    ' + + '
    '; + document.body.appendChild(ov); + var inp = document.getElementById('crossDeviceEmail'); + var btn = document.getElementById('crossDeviceSubmit'); + function submit() { + var val = inp.value.trim().toLowerCase(); + if (!val || !val.includes('@')) { if (typeof showToast === 'function') showToast('Please enter a valid email'); return; } + ov.remove(); + email = val; + resolve(finishEmailSignIn(email, _signInUrl)); + } + btn.onclick = submit; + inp.addEventListener('keydown', function(e) { if (e.key === 'Enter') submit(); }); + setTimeout(function() { inp.focus(); }, 100); + }); + } + return finishEmailSignIn(email, _signInUrl); +} + +async function finishEmailSignIn(email, _signInUrl) { + if (!email) { + showToast('⚠️ Could not determine your email. Please sign in again from the app.'); + return; + } + + try { + // Save anonymous user info BEFORE sign-in changes auth state + const anonUser = auth.currentUser; + let anonUid = null; + let anonData = null; + if (anonUser && anonUser.isAnonymous) { + anonUid = anonUser.uid; + console.log('[Email Sign-In] Anon user found:', anonUid); + try { + const anonDoc = await db.collection('users').doc(anonUid).get(); + if (anonDoc.exists) anonData = anonDoc.data(); + console.log('[Email Sign-In] Anon data loaded:', !!anonData); + } catch(e) { + console.log('[Email Sign-In] Anon data load failed (non-fatal):', e.code); + } + } + + // Sign in with email link (use saved URL that still has Firebase params) + console.log('[Email Sign-In] Starting signInWithEmailLink for:', email); + const result = await auth.signInWithEmailLink(email, _signInUrl); + console.log('[Email Sign-In] Sign-in result:', result.user ? result.user.uid : 'no user'); + localStorage.removeItem('btc_signin_email'); + + // Check if this email user already has data + const emailUid = result.user.uid; + + // Wait for auth state to fully stabilize and db to get fresh token + console.log('[Email Sign-In] Waiting for auth token propagation...'); + for (var _retry = 0; _retry < 5; _retry++) { + await new Promise(r => setTimeout(r, 200)); + try { + var _testDoc = await db.collection('users').doc(emailUid).get(); + console.log('[Email Sign-In] Firestore auth ready after', (_retry + 1) * 200, 'ms'); + break; + } catch(_testErr) { + if (_testErr.code === 'permission-denied') { + console.log('[Email Sign-In] Permission denied on retry ' + (_retry + 1) + ', waiting for token propagation...'); + continue; + } + throw _testErr; + } + } + console.log('[Email Sign-In] Fetching existing user doc:', emailUid); + const existingDoc = await db.collection('users').doc(emailUid).get(); + console.log('[Email Sign-In] Existing doc exists:', existingDoc.exists); + + if (!existingDoc.exists && anonData) { + // Migrate anonymous data to email account + anonData.email = email; + await db.collection('users').doc(emailUid).set(anonData); + } else if (existingDoc.exists && anonData) { + // Existing email user — merge points if anon had more (one-time only) + const existData = existingDoc.data(); + var _mergedPts = Math.min(anonData.points || 0, 500); + if (!existData.mergedAnon && _mergedPts > (existData.points || 0)) { + await existingDoc.ref.update({ + points: Math.max(_mergedPts, existData.points || 0), + channelsVisited: Math.max(anonData.channelsVisited || 0, existData.channelsVisited || 0), + totalVisits: (existData.totalVisits || 0) + (anonData.totalVisits || 0), + mergedAnon: true, + }); + } + } + + // Delete the old anonymous user document to prevent duplicates on leaderboard + if (anonUid && anonUid !== emailUid) { + try { await db.collection('users').doc(anonUid).delete(); } catch(e) {} + } + + // Clean URL + window.history.replaceState(null, '', window.location.pathname + window.location.hash); + + // Check if this was a new registration (pending username from signup form) + const pendingUsername = localStorage.getItem('btc_pending_username'); + const pendingEmail = localStorage.getItem('btc_pending_email'); + const pendingLnAddress = localStorage.getItem('btc_pending_ln_address') || ''; + if (pendingUsername && !existingDoc.exists) { + // New user verifying their email — create their full account now + const userData = { + username: pendingUsername, + email: email, + points: 0, + channelsVisited: 0, + totalVisits: 1, + streak: 1, + lastVisit: new Date().toISOString().split('T')[0], + created: firebase.firestore.FieldValue.serverTimestamp() + }; + if (pendingLnAddress) { userData.lightning = pendingLnAddress; userData.lightningAddress = pendingLnAddress; } + await db.collection('users').doc(emailUid).set(userData); + try { db.collection('stats').doc('global').set({ userCount: firebase.firestore.FieldValue.increment(1) }, { merge: true }).catch(function() {}); } catch(e) {} + + // Attach referral if they came via referral link + if (typeof attachReferral === 'function') attachReferral(emailUid); + } + + // Clean up pending data + localStorage.removeItem('btc_pending_username'); + localStorage.removeItem('btc_pending_email'); + localStorage.removeItem('btc_pending_ln_address'); + // 🗑️ SECURITY HARDENING (C-NEW-13): Wipe ghost on-chain wallet data + localStorage.removeItem('btc_wallet_enc'); + localStorage.removeItem('btc_wallet_addrs'); + + loadUser(emailUid); + showToast('✅ Email verified! Signed in as ' + escapeHtml(pendingUsername || email)); + } catch(e) { + console.error('[Email Sign-In] Full error:', e.code, e.message, e.stack); + // Check if this is a Firestore permission error + if (e.code === 'permission-denied') { + showToast('⚠️ Permission denied. Try refreshing the page or clearing cache.'); + console.error('[Email Sign-In] Firestore permission denied - auth state may not be ready'); + } else if (e.code === 'auth/invalid-action-code' || e.code === 'auth/expired-action-code') { + showToast('⚠️ This sign-in link has expired. Please request a new one.'); + } else if (e.code === 'auth/invalid-email') { + showToast('⚠️ Email mismatch. Make sure you enter the same email you signed up with.'); + } else { + showToast('Sign-in error (' + (e.code || 'unknown') + '). Please try again.'); + } + // Clean URL so the broken link doesn't keep retrying + window.history.replaceState(null, '', window.location.pathname + window.location.hash); + auth.signInAnonymously(); + } +} + +// Google Sign-In — uses Google Identity Services (GIS) for PWA compatibility +var GOOGLE_CLIENT_ID = '1055248200518-jcn5efjp7vhk0vm8cbmj4mfsgc0edkga.apps.googleusercontent.com'; + +window.signInWithGoogle = async function() { + var isMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent || ''); + // On desktop, try GIS One Tap (fast if available) + // On mobile, skip GIS entirely — go straight to Firebase popup (faster, more reliable) + if (!isMobile && typeof google !== 'undefined' && google.accounts && google.accounts.id) { + try { + await signInWithGIS(); + return; + } catch(gisErr) { + console.warn('[Auth] GIS failed, falling back to Firebase popup:', gisErr); + try { google.accounts.id.cancel(); } catch(e) {} + document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(el) { el.remove(); }); + } + } + // Firebase popup/redirect + await signInWithProvider(new firebase.auth.GoogleAuthProvider()); +}; + +async function signInWithGIS() { + var saved = await _saveAnonDataGlobal(); + return new Promise(function(resolve, reject) { + var anonUid = saved.anonUid; + var anonData = saved.anonData; + + google.accounts.id.initialize({ + client_id: GOOGLE_CLIENT_ID, + callback: async function(response) { + if (!response || !response.credential) { + reject(new Error('No credential received')); + return; + } + try { + var credential = firebase.auth.GoogleAuthProvider.credential(response.credential); + var result = await auth.signInWithCredential(credential); + // Clean up ALL GIS UI elements + try { google.accounts.id.cancel(); } catch(e) {} + var _gsiBtn = document.getElementById('gsi-temp-btn'); + if (_gsiBtn) { var _bd = _gsiBtn.closest('div[style*="position:fixed"]'); if (_bd) _bd.remove(); else _gsiBtn.remove(); } + document.querySelectorAll('[id*="credential_picker"], [id*="g_id_"], iframe[src*="accounts.google.com"]').forEach(function(el) { el.remove(); }); + await _handleSignInResultGlobal(result.user, anonUid, anonData); + resolve(result.user); + } catch(e) { + reject(e); + } + }, + auto_select: false, + cancel_on_tap_outside: true, + context: 'signin', + ux_mode: 'popup' + }); + + // Try One Tap first + google.accounts.id.prompt(function(notification) { + if (notification.isNotDisplayed() || notification.isSkippedMoment()) { + // One Tap not available — fall back to Firebase popup immediately (no second button) + console.log('[Auth] One Tap not shown, falling back to Firebase popup'); + reject(new Error('One Tap unavailable')); + } + }); + }); +} + +// Twitter/X Sign-In — no client SDK, must use Firebase popup/redirect +window.signInWithTwitter = async function() { + var isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone; + if (isStandalone) { + try { + var _ad = await _saveAnonDataGlobal(); + var result = await auth.signInWithPopup(new firebase.auth.TwitterAuthProvider()); + await _handleSignInResultGlobal(result.user, _ad.anonUid, _ad.anonData); + return; + } catch(e) { + if (e.code === 'auth/popup-closed-by-user') return; + showPWAAuthFallback('Twitter'); + return; + } + } + await signInWithProvider(new firebase.auth.TwitterAuthProvider()); +} + +// GitHub Sign-In +window.signInWithGithub = async function() { + var isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone; + if (isStandalone) { + try { + var _ad = await _saveAnonDataGlobal(); + var result = await auth.signInWithPopup(new firebase.auth.GithubAuthProvider()); + await _handleSignInResultGlobal(result.user, _ad.anonUid, _ad.anonData); + return; + } catch(e) { + if (e.code === 'auth/popup-closed-by-user') return; + showPWAAuthFallback('GitHub'); + return; + } + } + await signInWithProvider(new firebase.auth.GithubAuthProvider()); +} + +// PWA auth fallback for providers without client SDKs +function showPWAAuthFallback(providerName) { + var msg = document.createElement('div'); + msg.style.cssText = 'position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;padding:20px;'; + msg.onclick = function(e) { if (e.target === msg) msg.remove(); }; + msg.innerHTML = '
    ' + + '
    🔐
    ' + + '
    ' + providerName + ' Sign-In
    ' + + '
    ' + providerName + ' sign-in requires a browser window. Open the site in your browser to sign in.
    ' + + '' + + '' + + '
    '; + document.body.appendChild(msg); +} + +// Facebook Sign-In — uses FB SDK for PWA compatibility +var FB_APP_ID = '1400842698021858'; + +window.fbAsyncInit = function() { + FB.init({ appId: FB_APP_ID, cookie: true, xfbml: false, version: 'v19.0' }); +}; + +window.signInWithFacebook = async function() { + if (typeof FB !== 'undefined') { + try { + await signInWithFBSDK(); + return; + } catch(fbErr) { + if (fbErr.message === 'Facebook login cancelled') return; + console.warn('[Auth] FB SDK failed:', fbErr); + } + } + await signInWithProvider(new firebase.auth.FacebookAuthProvider()); +} + +async function signInWithFBSDK() { + var saved = await _saveAnonDataGlobal(); + return new Promise(function(resolve, reject) { + FB.login(function(response) { + if (!response.authResponse) { reject(new Error('Facebook login cancelled')); return; } + var credential = firebase.auth.FacebookAuthProvider.credential(response.authResponse.accessToken); + auth.signInWithCredential(credential).then(async function(result) { + await _handleSignInResultGlobal(result.user, saved.anonUid, saved.anonData); + resolve(result.user); + }).catch(reject); + }, { scope: 'email,public_profile' }); + }); +} + +// Nostr sign-in — full modal with extension/nsec/npub options +// Uses nostr-tools CDN for nsec decoding, signing, and key derivation +window.signInWithNostr = async function() { + if (!checkRateLimit()) return; + var hasExtension = !!window.nostr; + var overlay = document.createElement('div'); + overlay.id = 'nostrAuthOverlay'; + overlay.style.cssText = 'position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;padding:16px;overflow-y:auto;'; + overlay.onclick = function(e) { if (e.target === overlay) overlay.remove(); }; + overlay.innerHTML = + '
    ' + + '
    ' + + '

    🟣 Sign in with Nostr

    ' + + '' + + '
    ' + + (hasExtension ? + '' + : '
    🔌
    No Extension Detected
    Install Alby or nos2x for one-click login
    ') + + '
    or
    ' + + '
    🔒 Your nsec is used only in your browser to sign a one-time login event. It is never sent to our servers or stored anywhere.
    ' + + '' + + '
    ' + + '
    or
    ' + + '
    ' + + '' + + '
    '; + document.body.appendChild(overlay); +}; + +// NIP-07 extension sign-in +window.nostrSignInWithExtension = async function() { + if (!window.nostr) { showToast('Extension not found'); return; } + var statusEl = document.getElementById('nostrAuthStatus'); + if (statusEl) statusEl.innerHTML = 'Requesting key from extension...'; + try { + var pubkey = await window.nostr.getPublicKey(); + if (!pubkey || !/^[a-f0-9]{64}$/.test(pubkey)) { if (statusEl) statusEl.innerHTML = 'Could not get public key'; return; } + if (statusEl) statusEl.innerHTML = 'Signing auth event...'; + var signed = await window.nostr.signEvent({ kind: 22242, created_at: Math.floor(Date.now() / 1000), tags: [['challenge', 'btc-edu-' + Date.now()]], content: 'Sign in to Bitcoin Education Archive', pubkey: pubkey }); + if (!signed || !signed.sig) { if (statusEl) statusEl.innerHTML = 'Signing cancelled'; return; } + await nostrCompleteAuth(pubkey, signed.sig, signed); + } catch(e) { console.error('Nostr extension error:', e); if (statusEl) statusEl.innerHTML = 'Extension error: ' + (e.message || 'Unknown') + ''; } +}; + +// nsec sign-in — uses nostr-tools CDN for key derivation and signing +window.nostrSignInWithNsec = async function() { + var nsec = (document.getElementById('nostrNsecInput').value || '').trim(); + var statusEl = document.getElementById('nostrAuthStatus'); + var btn = document.getElementById('nostrNsecBtn'); + if (!nsec) { showToast('Please paste your nsec'); return; } + if (!nsec.startsWith('nsec1')) { if (statusEl) statusEl.innerHTML = 'Invalid nsec format. Must start with nsec1'; return; } + btn.disabled = true; btn.textContent = 'Loading crypto library...'; + if (statusEl) statusEl.innerHTML = 'Loading...'; + try { + // Load nostr-tools from CDN if not already loaded + if (!window.NostrTools) { + await new Promise(function(resolve, reject) { + var script = document.createElement('script'); + script.src = 'https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js'; + script.integrity = 'sha384-GwmNxV/GnZt+zRBR/Hhtu5D4MKfbxeJSApW44ARryGYtj3MFheHMFgiEZ7tVnrln'; + script.crossOrigin = 'anonymous'; + script.onload = resolve; + script.onerror = function() { reject(new Error('Failed to load nostr-tools')); }; + document.head.appendChild(script); + }); + } + var NT = window.NostrTools; + if (statusEl) statusEl.innerHTML = 'Decoding nsec...'; + btn.textContent = 'Signing...'; + var decoded = NT.nip19.decode(nsec); + if (!decoded || decoded.type !== 'nsec') { if (statusEl) statusEl.innerHTML = 'Invalid nsec'; btn.disabled = false; btn.textContent = 'Sign In with nsec'; return; } + var privkeyHex = decoded.data; + if (typeof privkeyHex !== 'string') { privkeyHex = Array.from(new Uint8Array(privkeyHex)).map(function(b) { return b.toString(16).padStart(2, '0'); }).join(''); } + var pubkey = NT.getPublicKey(privkeyHex); + var event = { kind: 22242, created_at: Math.floor(Date.now() / 1000), tags: [['challenge', 'btc-edu-' + Date.now()]], content: 'Sign in to Bitcoin Education Archive', pubkey: pubkey }; + event.id = NT.getEventHash(event); + event.sig = NT.signEvent(event, privkeyHex); + document.getElementById('nostrNsecInput').value = ''; + if (statusEl) statusEl.innerHTML = 'Verifying signature...'; + await nostrCompleteAuth(pubkey, event.sig, event); + } catch(e) { + console.error('Nostr nsec error:', e); + if (statusEl) statusEl.innerHTML = 'Error: ' + (e.message || 'Failed to sign') + ''; + btn.disabled = false; btn.textContent = 'Sign In with nsec'; + } +}; + +// npub linking (read-only — links pubkey to current account) +window.nostrSignInWithNpub = async function() { + var npub = (document.getElementById('nostrNpubInput').value || '').trim(); + var statusEl = document.getElementById('nostrAuthStatus'); + if (!npub) { showToast('Please paste your npub'); return; } + var pubkey = npub; + if (npub.startsWith('npub1')) { + try { + if (!window.NostrTools) { + await new Promise(function(resolve, reject) { + var script = document.createElement('script'); + script.src = 'https://cdn.jsdelivr.net/npm/nostr-tools@1.17.0/lib/nostr.bundle.js'; + script.onload = resolve; + script.onerror = function() { reject(new Error('Failed to load nostr-tools')); }; + document.head.appendChild(script); + }); + } + var decoded = window.NostrTools.nip19.decode(npub); + if (decoded && decoded.type === 'npub') { + pubkey = decoded.data; + if (typeof pubkey !== 'string') { pubkey = Array.from(new Uint8Array(pubkey)).map(function(b) { return b.toString(16).padStart(2, '0'); }).join(''); } + } + } catch(e) { if (statusEl) statusEl.innerHTML = 'Invalid npub format'; return; } + } + if (!/^[a-f0-9]{64}$/.test(pubkey)) { if (statusEl) statusEl.innerHTML = 'Invalid public key'; return; } + if (statusEl) statusEl.innerHTML = 'Linking Nostr identity...'; + try { + if (!auth.currentUser) await auth.signInAnonymously(); + var uid = auth.currentUser.uid; + await db.collection('users').doc(uid).set({ nostr: pubkey, lastLogin: firebase.firestore.FieldValue.serverTimestamp() }, { merge: true }); + if (currentUser) currentUser.nostr = pubkey; + var overlay = document.getElementById('nostrAuthOverlay'); if (overlay) overlay.remove(); + showToast('🟣 Nostr identity linked! (npub)'); + } catch(e) { if (statusEl) statusEl.innerHTML = 'Error: ' + (e.message || 'Unknown') + ''; } +}; + +// Complete Nostr auth — send signed event to Cloud Function for verification +window.nostrCompleteAuth = async function(pubkey, sig, event) { + var statusEl = document.getElementById('nostrAuthStatus'); + try { + var nostrAuth = firebase.functions().httpsCallable('nostrAuth'); + var result = await nostrAuth({ pubkey: pubkey, sig: sig, event: event }); + if (result.data && result.data.token) { + await auth.signInWithCustomToken(result.data.token); + var uid = result.data.uid; + var userDoc = await db.collection('users').doc(uid).get(); + if (!userDoc.exists || !userDoc.data().username) { + var npubShort = 'npub...' + pubkey.substring(0, 8); + var _nostrUserData = { username: npubShort, nostr: pubkey, totalVisits: 1, streak: 1, lastVisit: new Date().toISOString().split('T')[0] }; + if (!userDoc.exists) { _nostrUserData.points = 0; _nostrUserData.channelsVisited = 0; _nostrUserData.created = firebase.firestore.FieldValue.serverTimestamp(); } + await db.collection('users').doc(uid).set(_nostrUserData, { merge: true }); + try { db.collection('stats').doc('global').set({ userCount: firebase.firestore.FieldValue.increment(1) }, { merge: true }).catch(function() {}); } catch(e) {} + } + loadUser(uid); hideUsernamePrompt(); + var overlay = document.getElementById('nostrAuthOverlay'); if (overlay) overlay.remove(); + showToast('🟣 Signed in with Nostr!'); + } else { if (statusEl) statusEl.innerHTML = 'Auth failed — no token received'; } + } catch(e) { console.error('Nostr auth error:', e); if (statusEl) statusEl.innerHTML = 'Verification failed: ' + (e.message || 'Unknown') + ''; } +}; + +// Apple Sign-In removed + +// Lightning (LNURL-auth) Sign-In +window.signInWithLightning = async function() { + if (!checkRateLimit()) return; + + // Show modal immediately with loading skeleton (Cloud Function can be slow on cold start) + var qrModal = document.createElement('div'); + qrModal.id = 'lnAuthModal'; + qrModal.style.cssText = 'position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.8);'; + qrModal.onclick = function(e) { if (e.target === qrModal) qrModal.remove(); }; + qrModal.innerHTML = + '
    ' + + '
    ' + + '

    Lightning Login

    ' + + '

    Scan this QR code with your Lightning wallet (Alby, Zeus, Phoenix, BlueWallet, etc.)

    ' + + '
    ' + + '
    Generating challenge...
    ' + + '
    ' + + '' + + '

    Connecting to server...

    ' + + '' + + '
    '; + document.body.appendChild(qrModal); + + try { + // Request challenge from Cloud Function + var lnAuthChallenge = firebase.functions().httpsCallable('lnAuthChallenge'); + var challengeResult = await lnAuthChallenge(); + + // Check modal still exists (user might have cancelled) + if (!document.getElementById('lnAuthModal')) return; + + if (!challengeResult.data || !challengeResult.data.k1 || !challengeResult.data.lnurl) { + if (typeof showToast === 'function') showToast('Failed to generate login challenge'); + qrModal.remove(); + return; + } + + var k1 = challengeResult.data.k1; + var lnurlEncoded = challengeResult.data.lnurl; + + // Replace loading skeleton with actual QR code + var qrContainer = document.getElementById('lnAuthQR'); + if (qrContainer) { + qrContainer.innerHTML = ''; + qrContainer.style.display = 'inline-block'; + if (typeof _renderQRCode === 'function') { + _renderQRCode(qrContainer, 'lightning:' + lnurlEncoded, 220); + } else { + var qrImg = document.createElement('img'); + qrImg.src = 'https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=' + encodeURIComponent('lightning:' + lnurlEncoded); + qrImg.width = 220; qrImg.height = 220; qrImg.alt = 'Lightning Auth QR'; + qrImg.style.cssText = 'border-radius:8px;'; + qrContainer.appendChild(qrImg); + } + } + + // Show copy button now that we have the LNURL + var copyWrap = document.getElementById('lnAuthCopyWrap'); + if (copyWrap) { + copyWrap.style.display = 'block'; + copyWrap.innerHTML = ''; + } + + // Update status + var statusEl = document.getElementById('lnAuthStatus'); + if (statusEl) { statusEl.textContent = 'Waiting for wallet...'; statusEl.style.color = 'var(--accent)'; } + + // Poll for completion + var lnAuthVerify = firebase.functions().httpsCallable('lnAuthVerify'); + var pollCount = 0; + var maxPolls = 60; // 2 minutes at 2-second intervals + var pollInterval = setInterval(async function() { + pollCount++; + if (pollCount > maxPolls || !document.getElementById('lnAuthModal')) { + clearInterval(pollInterval); + return; + } + try { + var verifyResult = await lnAuthVerify({ k1: k1 }); + if (verifyResult.data && verifyResult.data.token) { + clearInterval(pollInterval); + var statusEl = document.getElementById('lnAuthStatus'); + if (statusEl) statusEl.textContent = '✅ Authenticated!'; + + await auth.signInWithCustomToken(verifyResult.data.token); + + // Set up user doc if needed + var uid = verifyResult.data.uid; + var userDoc = await db.collection('users').doc(uid).get(); + if (!userDoc.exists || !userDoc.data().username) { + var lnName = '⚡anon-' + k1.substring(0, 8); + var _lnUserData = { username: lnName, authMethod: 'lightning', totalVisits: 1, streak: 1, lastVisit: new Date().toISOString().split('T')[0] }; + if (!userDoc.exists) { _lnUserData.points = 0; _lnUserData.channelsVisited = 0; _lnUserData.created = firebase.firestore.FieldValue.serverTimestamp(); } + await db.collection('users').doc(uid).set(_lnUserData, { merge: true }); + try { db.collection('stats').doc('global').set({ userCount: firebase.firestore.FieldValue.increment(1) }, { merge: true }).catch(function() {}); } catch(e) {} + } + + loadUser(uid); + hideUsernamePrompt(); + setTimeout(function() { + var modal = document.getElementById('lnAuthModal'); + if (modal) modal.remove(); + }, 1000); + if (typeof showToast === 'function') showToast('⚡ Signed in with Lightning!'); + } + } catch(e) { + // Not ready yet, keep polling + if (e.code !== 'not-found') console.log('LN auth poll:', e.message); + } + }, 2000); + + } catch(e) { + console.error('Lightning auth error:', e); + if (typeof showToast === 'function') showToast('Lightning sign-in failed. Try again.'); + var modal = document.getElementById('lnAuthModal'); + if (modal) modal.remove(); + } +}; + +// Rate limiting check +function checkRateLimit() { + const now = Date.now(); + if (now < signInLockout) { + const secs = Math.ceil((signInLockout - now) / 1000); + showToast('⏳ Too many attempts. Wait ' + secs + 's'); + return false; + } + signInAttempts++; + if (signInAttempts > 5) { + signInLockout = now + 60000; // 1 minute lockout + signInAttempts = 0; + showToast('⏳ Too many attempts. Please wait 60 seconds.'); + return false; + } + return true; +} + +// Session timeout — sign out after 30 min inactivity +// Session timer removed — users stay signed in indefinitely via Firebase LOCAL persistence + +// Generic provider sign-in (reused by Google, Twitter, GitHub) +function isInAppBrowser() { + var ua = navigator.userAgent || ''; + return /FBAN|FBAV|Instagram|Twitter|Line\/|Snapchat|BytedanceWebview|musical_ly|TikTok|Weibo|MicroMessenger|LinkedInApp|Telegram/i.test(ua); +} + +// Module-scope auth helpers (accessible from GIS, FB SDK, and signInWithProvider) +async function _saveAnonDataGlobal() { + var anonUser = auth.currentUser; + var anonUid = null, anonData = null; + if (anonUser && anonUser.isAnonymous) { + anonUid = anonUser.uid; + try { + var anonDoc = await db.collection('users').doc(anonUid).get(); + if (anonDoc.exists) anonData = anonDoc.data(); + } catch(e) {} + } + return { anonUid: anonUid, anonData: anonData }; +} + +async function _handleSignInResultGlobal(user, anonUid, anonData) { + // Pick up Lightning address typed in the sign-up form before provider auth + var _pendingLn = localStorage.getItem('btc_pending_ln_address') || ''; + localStorage.removeItem('btc_pending_ln_address'); + + var existingDoc = await db.collection('users').doc(user.uid).get(); + if (!existingDoc.exists) { + if (anonData) { + anonData.email = user.email || ''; + if (!anonData.username) anonData.username = user.displayName || 'Bitcoiner'; + if (_pendingLn) { anonData.lightning = _pendingLn; anonData.lightningAddress = _pendingLn; } + await db.collection('users').doc(user.uid).set(anonData); + } else { + var _newProviderDoc = { + username: user.displayName || 'Bitcoiner', + email: user.email || '', + points: 0, channelsVisited: 0, totalVisits: 1, streak: 1, + lastVisit: new Date().toISOString().split('T')[0], + created: firebase.firestore.FieldValue.serverTimestamp() + }; + if (_pendingLn) { _newProviderDoc.lightning = _pendingLn; _newProviderDoc.lightningAddress = _pendingLn; } + await db.collection('users').doc(user.uid).set(_newProviderDoc); + } + } else { + // Returning user — save LN if they typed one and don't already have one + if (_pendingLn && !existingDoc.data().lightningAddress && !existingDoc.data().lightning) { + try { await existingDoc.ref.update({ lightning: _pendingLn, lightningAddress: _pendingLn }); } catch(e) {} + } + if (anonData) { + var existData = existingDoc.data(); + var _mergedPts = Math.min(anonData.points || 0, 500); + if (!existData.mergedAnon && _mergedPts > (existData.points || 0)) { + await existingDoc.ref.update({ + points: Math.max(_mergedPts, existData.points || 0), + channelsVisited: Math.max(anonData.channelsVisited || 0, existData.channelsVisited || 0), + totalVisits: (existData.totalVisits || 0) + (anonData.totalVisits || 0), + mergedAnon: true, + }); + } + } + if (!existingDoc.data().email && user.email) { + await existingDoc.ref.update({ email: user.email }); + } + } + if (anonUid && anonUid !== user.uid) { + try { await db.collection('users').doc(anonUid).delete(); } catch(e) {} + } + loadUser(user.uid); + if (!existingDoc.exists) { + if (typeof attachReferral === 'function') attachReferral(user.uid); + hideUsernamePrompt(); + showToast('✅ Welcome, ' + escapeHtml(user.displayName || user.email || 'Bitcoiner') + '!'); + // Show Quest Guide for brand new provider sign-ups + try { + localStorage.removeItem('guide_dismissed'); + localStorage.removeItem('guide_seen'); + if (typeof showGuide === 'function') { + setTimeout(function() { showGuide(); }, 1500); + } + } catch(e) {} + } else { + hideUsernamePrompt(); + showToast('✅ Signed in as ' + escapeHtml(user.displayName || user.email || 'Bitcoiner')); + } +} + +async function signInWithProvider(provider) { + if (!checkRateLimit()) return; + + // In-app browsers can't do popups or redirects reliably — open in system browser + if (isInAppBrowser()) { + var _ua = navigator.userAgent || ''; + var _hint = /iPhone|iPad/i.test(_ua) ? 'Tap the share icon (↑) → "Open in Safari"' + : /Android/i.test(_ua) ? 'Tap ⋮ (menu) → "Open in Browser"' + : 'Open this page in your default browser'; + var _iab = document.createElement('div'); + _iab.style.cssText = 'position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.9);padding:20px;'; + _iab.innerHTML = '
    ' + + '
    🌐
    ' + + '

    Open in Browser

    ' + + '

    Sign-in doesn\'t work inside apps. ' + _hint + '

    ' + + '' + + '' + + '
    '; + document.body.appendChild(_iab); + return; + } + + // Delegate to module-scope helper + async function handleSignInResult(user, anonUid, anonData) { + return _handleSignInResultGlobal(user, anonUid, anonData); + } + async function saveAnonData() { + return _saveAnonDataGlobal(); + } + + // Strategy: Use popup on desktop (reliable), redirect on mobile/PWA. + // Redirect loses session cross-domain but at least shows the Google sign-in page. + // Popup on Android PWA causes redirect_uri_mismatch errors. + var isMobileDevice = /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent || ''); + var isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone; + + if (isMobileDevice || isStandalone) { + // Mobile: try popup first (works on most modern mobile browsers), + // fall back to redirect if popup fails. + try { + showToast('⏳ Opening sign-in...'); + // Save anon data BEFORE anything async (non-blocking fire-and-forget) + const anonUser = auth.currentUser; + if (anonUser && anonUser.isAnonymous) { + localStorage.setItem('btc_anon_uid', anonUser.uid); + db.collection('users').doc(anonUser.uid).get().then(function(doc) { + if (doc.exists) localStorage.setItem('btc_anon_data', JSON.stringify(doc.data())); + }).catch(function() {}); + } + // Try popup first (faster, doesn't lose page context) + try { + const result = await auth.signInWithPopup(provider); + if (result && result.user) { + const { anonUid, anonData } = await saveAnonData(); + await handleSignInResult(result.user, anonUid, anonData); + return; + } + } catch(popupErr) { + console.log('[Auth] Mobile popup failed, falling back to redirect:', popupErr.code); + // Popup failed — use redirect + sessionStorage.setItem('btc_redirect_pending', '1'); + localStorage.setItem('btc_pwa_auth_pending', '1'); + await auth.signInWithRedirect(provider); + return; + } + } catch(e) { + console.error('Mobile sign-in error:', e); + showToast('Sign-in failed: ' + (e.message || 'Unknown error')); + return; + } + } + + // Desktop: try popup first + try { + const { anonUid, anonData } = await saveAnonData(); + + const result = await auth.signInWithPopup(provider); + await handleSignInResult(result.user, anonUid, anonData); + } catch(e) { + console.error('Provider sign-in error:', e.code, e.message, e); + + // Popup blocked, closed, or failed — fallback to redirect + if (e.code === 'auth/popup-blocked' || + e.code === 'auth/cancelled-popup-request' || + e.code === 'auth/popup-closed-by-user' || + e.code === 'auth/internal-error') { + try { + showToast('⏳ Opening sign-in page...'); + // Save anon data to localStorage so redirect return can recover it + const anonUser = auth.currentUser; + if (anonUser && anonUser.isAnonymous) { + localStorage.setItem('btc_anon_uid', anonUser.uid); + try { + const anonDoc = await db.collection('users').doc(anonUser.uid).get(); + if (anonDoc.exists) { + localStorage.setItem('btc_anon_data', JSON.stringify(anonDoc.data())); + } + } catch(e2) {} + } + localStorage.setItem('btc_pwa_auth_pending', '1'); + await auth.signInWithRedirect(provider); + return; + } catch(redirectErr) { + console.error('Redirect fallback also failed:', redirectErr); + showToast('Sign-in failed. Please try a different browser.'); + } + return; + } + + // User intentionally closed popup — do nothing + if (e.code === 'auth/popup-closed-by-user') return; + + // Actionable error messages + if (e.code === 'auth/unauthorized-domain') { + showToast('⚠️ This domain is not authorized for sign-in. Please contact support.'); + } else if (e.code === 'auth/operation-not-allowed') { + showToast('⚠️ This sign-in method is not enabled. Try a different option.'); + } else if (e.code === 'auth/account-exists-with-different-credential') { + showToast('⚠️ An account with this email exists using a different sign-in method. Try another option.'); + } else if (e.code === 'auth/network-request-failed') { + showToast('⚠️ Network error. Check your connection and try again.'); + } else { + showToast('Sign-in error (' + (e.code || 'unknown') + '). Please try again.'); + } + } +} + +// Returning user: send magic link to sign back in +window.sendReturningMagicLink = async function() { + var input = document.getElementById('returningEmailInput'); + if (!input) return; + var email = input.value.trim(); + if (!email || !email.includes('@')) { + showToast('📧 Please enter a valid email address'); + if (input) input.style.borderColor = '#ef4444'; + return; + } + input.disabled = true; + var btn = input.nextElementSibling; + if (btn) { btn.disabled = true; btn.textContent = 'Sending...'; } + var sent = await sendMagicLink(email); + if (sent) { + showToast('📧 Magic link sent! Check your email to sign in.'); + if (btn) btn.textContent = '✅ Sent!'; + hideUsernamePrompt(); + } else { + showToast('❌ Could not send magic link. Try again.'); + input.disabled = false; + if (btn) { btn.disabled = false; btn.textContent = 'Send Link'; } + } +}; + +// Send magic link email +async function sendMagicLink(email) { + const actionCodeSettings = { + // Embed email in URL so it works even when opened on a different device/browser + url: window.location.origin + window.location.pathname + '?signin_email=' + encodeURIComponent(email), + handleCodeInApp: true, + }; + try { + await auth.sendSignInLinkToEmail(email, actionCodeSettings); + localStorage.setItem('btc_signin_email', email); + return true; + } catch(e) { + console.log('Magic link error:', e); + return false; + } +} + +// Load anonymous user from localStorage only — no Firestore reads +function loadUserLocal(uid) { + var localPoints = parseInt(localStorage.getItem('btc_points') || '0'); + var localChannels = JSON.parse(localStorage.getItem('btc_visited_channels') || '[]'); + currentUser = { + uid: uid, + points: localPoints, + channelsVisited: localChannels.length, + readChannels: localChannels, + totalVisits: parseInt(localStorage.getItem('btc_total_visits') || '1'), + streak: parseInt(localStorage.getItem('btc_streak') || '0'), + lastVisit: localStorage.getItem('btc_last_visit') || '', + _isLocal: true // Flag: this user has no Firestore doc yet + }; + rankingReady = true; + window._badgesReady = true; + if (typeof markVisibleBadgesReady === 'function') markVisibleBadgesReady(); window._hiddenBadgesReady = true; + restoreVisitedUI(); + updateRankUI(); + _checkCapOnLoad(); + updateAuthButton(); + if (typeof renderProgressRings === 'function') renderProgressRings(); + if (typeof renderExplorationMap === 'function') renderExplorationMap(); + startReadTimer(); +} + +async function loadUser(uid, prefetchedDoc) { + const doc = prefetchedDoc || await db.collection('users').doc(uid).get(); + if (doc.exists) { + currentUser = { uid, ...doc.data() }; + // Restore visited channels so we don't re-award + if (currentUser.visitedChannelsList) { + currentUser.visitedChannelsList.forEach(ch => allTimeChannels.add(ch)); + } + + const isRealUser = auth.currentUser && !auth.currentUser.isAnonymous; + + // Sync read checkmarks: for real users, use Firebase as source of truth + // visitedChannelsList is the authoritative field (written by awardPoints CF via arrayUnion) + // readChannels is the legacy field — union both for backward compat + var _fbRead = [...new Set([ + ...(Array.isArray(currentUser.visitedChannelsList) ? currentUser.visitedChannelsList : []), + ...(Array.isArray(currentUser.readChannels) ? currentUser.readChannels : []) + ])]; + if (_fbRead.length > 0) { + if (isRealUser) { + localStorage.setItem('btc_visited_channels', JSON.stringify(_fbRead)); + } else { + let local = JSON.parse(localStorage.getItem('btc_visited_channels') || '[]'); + let merged = [...new Set([...local, ..._fbRead])]; + localStorage.setItem('btc_visited_channels', JSON.stringify(merged)); + } + restoreVisitedUI(); + } else if (isRealUser) { + // Real user with nothing in Firebase yet — clear local + localStorage.setItem('btc_visited_channels', '[]'); + restoreVisitedUI(); + } + + // Sync favorites: for real users, use Firebase as source of truth + if (currentUser.favorites) { + if (isRealUser) { + localStorage.setItem('btc_favs', JSON.stringify(currentUser.favorites)); + } else { + let localFavs = JSON.parse(localStorage.getItem('btc_favs') || '[]'); + let mergedFavs = [...new Set([...localFavs, ...currentUser.favorites])]; + localStorage.setItem('btc_favs', JSON.stringify(mergedFavs)); + } + if (typeof renderFavs === 'function') renderFavs(); + } else if (isRealUser) { + localStorage.setItem('btc_favs', '[]'); + if (typeof renderFavs === 'function') renderFavs(); + } + // Sync bookmarks: for real users, use Firebase as source of truth + if (currentUser.bookmarks) { + if (isRealUser) { + localStorage.setItem('btc_bookmarks', JSON.stringify(currentUser.bookmarks)); + } else { + let localBm = JSON.parse(localStorage.getItem('btc_bookmarks') || '[]'); + let mergedBm = currentUser.bookmarks.concat(localBm.filter(function(b) { + return !currentUser.bookmarks.some(function(fb) { return fb.channel === b.channel && fb.idx === b.idx; }); + })); + localStorage.setItem('btc_bookmarks', JSON.stringify(mergedBm)); + } + if (typeof renderFavs === 'function') renderFavs(); + } else if (isRealUser) { + // No bookmarks in Firebase yet — push local ones up if any exist + var _localBm = JSON.parse(localStorage.getItem('btc_bookmarks') || '[]'); + if (_localBm.length > 0 && db && auth.currentUser) { + db.collection('users').doc(auth.currentUser.uid).update({ bookmarks: _localBm }).catch(function() {}); + } + } + + // Cache username in localStorage for PVP and other modules + if (currentUser.username) { + localStorage.setItem('btc_username', currentUser.username); + } + + // One-time migration: set bestStreak if not present (now handled by recordDailyVisit CF) + if (currentUser.streak > 0 && !currentUser.bestStreak) { + currentUser.bestStreak = currentUser.streak; + } + + rankingReady = true; + updateRankUI(); + if (typeof renderProgressRings === 'function') renderProgressRings(); + awardVisitPoints(); + startReadTimer(); + + // Update high-res lastActive timestamp for DAU tracking + if (!auth.currentUser.isAnonymous) { + db.collection('users').doc(uid).update({ + lastActive: firebase.firestore.FieldValue.serverTimestamp() + }).catch(function() {}); + } + + // Restore badges and scholar status from Firebase + if (isRealUser) { + if (currentUser.hiddenBadges) { + // Merge Firebase hidden badges into localStorage (don't replace — avoids losing locally-earned badges) + var existingHidden = JSON.parse(localStorage.getItem('btc_hidden_badges') || '[]'); + var mergedHidden = [...new Set([...existingHidden, ...currentUser.hiddenBadges])]; + localStorage.setItem('btc_hidden_badges', JSON.stringify(mergedHidden)); + } + // Merge donation badges (awarded server-side by donatePoints CF) + if (currentUser.donationBadges && currentUser.donationBadges.length > 0) { + var existingHidden2 = JSON.parse(localStorage.getItem('btc_hidden_badges') || '[]'); + var mergedHidden2 = [...new Set([...existingHidden2, ...currentUser.donationBadges])]; + localStorage.setItem('btc_hidden_badges', JSON.stringify(mergedHidden2)); + } + if (currentUser.visibleBadges) { + // Merge Firebase badges into localStorage + var existing = JSON.parse(localStorage.getItem('btc_badges') || '[]'); + var merged = [...new Set([...existing, ...currentUser.visibleBadges])]; + localStorage.setItem('btc_badges', JSON.stringify(merged)); + } + if (currentUser.spinClosetItems) { + var existingItems = JSON.parse(localStorage.getItem('btc_spin_closet_items') || '[]'); + var mergedItems = [...new Set([...existingItems, ...currentUser.spinClosetItems])]; + localStorage.setItem('btc_spin_closet_items', JSON.stringify(mergedItems)); + } + if (currentUser.scholarPassed) { + localStorage.setItem('btc_scholar_passed', 'true'); + } + // Restore milestone/celebration state from Firestore (prevents re-triggering) + if (currentUser.nachoMilestones) { + localStorage.setItem('btc_nacho_q_milestones', JSON.stringify(currentUser.nachoMilestones)); + } + if (currentUser.celebratedState) { + var cs = currentUser.celebratedState; + if (cs.nachoMilestones) localStorage.setItem('btc_nacho_milestones', JSON.stringify(cs.nachoMilestones)); + if (cs.nachoCatComplete) localStorage.setItem('btc_nacho_cat_complete', JSON.stringify(cs.nachoCatComplete)); + if (cs.nachoLevelCelebrated) localStorage.setItem('btc_nacho_level_celebrated', JSON.stringify(cs.nachoLevelCelebrated)); + if (cs.nachoItemsNotified) localStorage.setItem('btc_nacho_items_notified', JSON.stringify(cs.nachoItemsNotified)); + } + // Restore Nacho interaction counts — use max of Firebase vs localStorage + if (currentUser.nachoInteractions) { + var localInteractions = parseInt(localStorage.getItem('btc_nacho_interactions') || '0'); + var fbInteractions = currentUser.nachoInteractions || 0; + localStorage.setItem('btc_nacho_interactions', Math.max(localInteractions, fbInteractions).toString()); + } + if (currentUser.nachoQuestions) { + var localQuestions = parseInt(localStorage.getItem('btc_nacho_questions') || '0'); + var fbQuestions = currentUser.nachoQuestions || 0; + localStorage.setItem('btc_nacho_questions', Math.max(localQuestions, fbQuestions).toString()); + } + } + + // Sync PVP stats: Firestore is always source of truth (prevents cross-account bleed on same device) + localStorage.setItem('btc_pvp_wins', String(currentUser.pvpWins || 0)); + localStorage.setItem('btc_pvp_losses', String(currentUser.pvpLosses || 0)); + + // Restore Nacho nickname from Firestore + if (currentUser.nachoNickname) { + localStorage.setItem('btc_nacho_nickname', currentUser.nachoNickname); + if (typeof updateNachoNameUI === 'function') updateNachoNameUI(currentUser.nachoNickname); + } + + // Restore engagement data from Firebase (cross-device sync) + if (isRealUser) { + if (currentUser.lastSpinDate) { + var localSpin = localStorage.getItem('btc_last_spin') || ''; + if (currentUser.lastSpinDate > localSpin) { + localStorage.setItem('btc_last_spin', currentUser.lastSpinDate); + } + if (typeof updateSpinBanner === 'function') updateSpinBanner(); + } + if (currentUser.prediction) { + var localPred = localStorage.getItem('btc_prediction'); + if (!localPred) { + localStorage.setItem('btc_prediction', JSON.stringify(currentUser.prediction)); + } + } + if (currentUser.nachoStoryDays && Array.isArray(currentUser.nachoStoryDays)) { + // Restore the days array (source of truth for chapter unlocks) + var localDays = safeJSON('btc_nacho_story_days', []); + // Merge: take the longer array (more days = more chapters unlocked) + if (currentUser.nachoStoryDays.length > localDays.length) { + localStorage.setItem('btc_nacho_story_days', JSON.stringify(currentUser.nachoStoryDays)); + } + } + if (currentUser.nachoStoryProgress) { + var localStory = parseInt(localStorage.getItem('btc_nacho_story_highest') || '0'); + if (currentUser.nachoStoryProgress > localStory) { + localStorage.setItem('btc_nacho_story_highest', currentUser.nachoStoryProgress.toString()); + } + } + if (currentUser.nachoStoryDate) { + var localStoryDate = localStorage.getItem('btc_nacho_story_date') || ''; + if (currentUser.nachoStoryDate > localStoryDate) { + localStorage.setItem('btc_nacho_story_date', currentUser.nachoStoryDate); + } + } + } + + // Badges are now safe to check — Firebase data has been restored + window._badgesReady = true; + if (typeof markVisibleBadgesReady === 'function') markVisibleBadgesReady(); window._hiddenBadgesReady = true; + + // Set current level BEFORE enabling level-up detection + // This prevents false level-ups from 0→current on first load + var initLv = getLevel(currentUser.points || 0); + lastLevelName = initLv.name; + lastLevelMin = initLv.min; + if (!localStorage.getItem('btc_highest_level_seen')) { + localStorage.setItem('btc_highest_level_seen', initLv.min.toString()); + } + // Now safe to detect level-ups (initial data loaded) + setTimeout(function() { levelUpReady = true; }, 3000); + + // Refresh exploration map and home page elements + if (typeof renderExplorationMap === 'function') renderExplorationMap(); + if (typeof showContinueReading === 'function') showContinueReading(); + + // Update auth button text if signed in with a provider + updateAuthButton(); + + // Initialize Orange Tickets system + if (typeof onUserLoadedTickets === 'function') onUserLoadedTickets(); + // Initialize messaging (presence + unread polling) + if (typeof initMessaging === 'function') initMessaging(); + + } else { + // User exists in auth but not in Firestore — recreate their doc + const user = auth.currentUser; + if (user && !user.isAnonymous) { + const newData = { + username: user.displayName || 'Bitcoiner', + email: user.email || '', + points: 0, + channelsVisited: 0, + totalVisits: 1, + streak: 1, + lastVisit: new Date().toISOString().split('T')[0], + created: firebase.firestore.FieldValue.serverTimestamp() + }; + await db.collection('users').doc(uid).set(newData); + currentUser = { uid, ...newData }; + rankingReady = true; + window._badgesReady = true; + if (typeof markVisibleBadgesReady === "function") markVisibleBadgesReady(); window._hiddenBadgesReady = true; + updateRankUI(); + updateAuthButton(); + } + } +} + +// Track if button was ever set to "signed in" state — never downgrade once set +var _authBtnSignedIn = false; + +function updateAuthButton() { + const btn = document.getElementById('authBtn'); + if (!btn) return; + // Check all possible ways a user can be "signed in": + var firebaseUser = auth && auth.currentUser; + var isRealAuth = firebaseUser && !firebaseUser.isAnonymous; + var fsUsername = currentUser && currentUser.username; + var localUsername = localStorage.getItem('btc_username'); + var displayName = fsUsername || localUsername || (firebaseUser && firebaseUser.displayName) || ''; + var isNostrOrLn = firebaseUser && firebaseUser.uid && (firebaseUser.uid.startsWith('nostr:') || firebaseUser.uid.startsWith('ln:')); + + var shouldShowSignedIn = isRealAuth || isNostrOrLn || displayName; + + // Once signed in, NEVER go back to "Create Account" unless explicitly signed out (firebaseUser is null) + if (shouldShowSignedIn) { + _authBtnSignedIn = true; + } else if (_authBtnSignedIn && firebaseUser) { + // Auth still exists but Firestore temporarily lost — don't downgrade + return; + } else if (!firebaseUser) { + // Actually signed out + _authBtnSignedIn = false; + } + + if (_authBtnSignedIn) { + var name = displayName || 'My Account'; + btn.innerHTML = '⚙️ ' + (typeof escapeHtml === 'function' ? escapeHtml(name) : name) + ' — Settings'; + btn.onclick = function() { showSettings(); }; + // Hide on mobile — mobile top bar already shows username + Topics + btn.style.display = (window.innerWidth <= 900) ? 'none' : 'block'; + btn.style.background = 'none'; + btn.style.border = '2px solid #3b82f6'; + btn.style.color = '#3b82f6'; + btn.onmouseover = function() { this.style.background='#3b82f6'; this.style.color='#fff'; }; + btn.onmouseout = function() { this.style.background='none'; this.style.color='#3b82f6'; }; + } else if (!firebaseUser || (firebaseUser && firebaseUser.isAnonymous)) { + // Only show "Create Account" for truly anonymous/no-auth users + btn.textContent = 'Create Free Account / Sign In'; + btn.style.display = 'block'; + btn.style.background = 'var(--accent)'; + btn.style.border = 'none'; + btn.style.color = '#000'; + btn.onmouseover = function() { this.style.transform='scale(1.02)'; }; + btn.onmouseout = function() { this.style.transform='scale(1)'; }; + } + // If auth hasn't resolved yet (firebaseUser exists but not anonymous and not identified), keep button hidden + + // Also hide guest banner for signed-in users + var guestBanner = document.getElementById('guestPointsBanner'); + if (guestBanner && _authBtnSignedIn) { + guestBanner.style.display = 'none'; + } + + +} + +// Sanitize user input — strip HTML tags and dangerous chars +function sanitizeInput(str) { + return str.replace(/<[^>]*>/g, '').replace(/[<>"'&]/g, '').trim(); +} +window.sanitizeInput = sanitizeInput; + +// Sync all celebration/milestone state to Firestore (prevents re-triggering on re-login) +window.syncCelebratedState = function() { + if (typeof db === 'undefined' || !auth || !auth.currentUser) return; + var state = { + nachoMilestones: safeJSON('btc_nacho_milestones', []), + nachoCatComplete: safeJSON('btc_nacho_cat_complete', []), + nachoLevelCelebrated: safeJSON('btc_nacho_level_celebrated', []), + nachoItemsNotified: safeJSON('btc_nacho_items_notified', []) + }; + db.collection('users').doc(auth.currentUser.uid).update({ celebratedState: state }).catch(function() {}); +}; + +// Profanity filter +const PROFANITY_LIST = [ + // Profanity + 'fuck','shit','ass','bitch','dick','cock','pussy','cunt','damn','hell', + 'bastard','slut','whore','fag','faggot','nigger','nigga','retard','retarded','penis','vagina', + 'porn','sex','anal','cum','jizz','dildo','tits','boob','nude','naked', + 'hentai','milf','orgasm','erect','molest','rape','pedo','nazi','hitler', + 'kkk','jihad','terrorist','kill','murder','suicide','die','stfu','gtfo', + 'wank','twat','bollocks','arse','shag','piss','crap','douche','skank', + 'thot','incel','simp','onlyfans','xnxx','pornhub','xvideos', + // Sexual content + 'blowjob','handjob','fingering','masturbat','threesome','gangbang','fetish','bondage','bdsm','kinky','horny','aroused','erection','erectile','climax','ejaculat','deepthroat','rimjob','creampie','cuckold','dominatrix','escort','prostitut','hooker','stripper','camgirl','sexting','nudes','twerk', + // Racial slurs + 'spic','wetback','chink','gook','kike','towelhead','raghead','beaner','coon','darkie','zipperhead','jap','paki','wop','dago', + // Hate/political (blocked in usernames too) + 'maga','trump','biden','democrat','republican','antifa','qanon','wwg1wga','acab', + 'supremacy','genocide','lynch' +]; + +function containsProfanity(str) { + // Normalize leet speak and special chars + const lower = str.toLowerCase() + .replace(/0/g, 'o').replace(/1/g, 'i').replace(/3/g, 'e') + .replace(/4/g, 'a').replace(/5/g, 's').replace(/7/g, 't') + .replace(/\$/g, 's').replace(/@/g, 'a').replace(/!/g, 'i') + .replace(/\*/g, '').replace(/_/g, '').replace(/-/g, '') + .replace(/[^a-z\s]/g, ' '); + const words = lower.split(/\s+/); + for (const word of words) { + if (PROFANITY_LIST.includes(word)) return true; + } + // Also check for profanity embedded in the string (no spaces) + const compressed = lower.replace(/\s/g, ''); + for (const bad of PROFANITY_LIST) { + if (bad.length >= 4 && compressed.includes(bad)) return true; + } + return false; +} + +async function createUser(username, email, enteredGiveaway, giveawayLnAddress, country) { // giveaway params kept for call-site compat; giveawayLnAddress now used as lightningAddress + // Wait for auth to be ready if not yet + if (typeof auth === 'undefined' || !auth) { + showToast('⏳ Loading... please try again in a moment.'); + // Try to init if it hasn't happened + if (typeof initRanking === 'function') initRanking(); + return; + } + if (!auth.currentUser) { + try { + const cred = await auth.signInAnonymously(); + // Wait a moment for auth.currentUser to update + if (!auth.currentUser) { + await new Promise(resolve => { + const unsub = auth.onAuthStateChanged(user => { + if (user) { unsub(); resolve(); } + }); + setTimeout(() => { resolve(); }, 3000); // timeout fallback + }); + } + } catch(e) { + console.log('Anonymous sign-in error:', e); + showToast('Error creating account. Please try again.'); + return; + } + } + if (!auth.currentUser) { + showToast('Error: Could not authenticate. Please refresh and try again.'); + return; + } + const uid = auth.currentUser.uid; + // Clear any leftover data from previous users on this browser + clearUserData(); + username = sanitizeInput(username); + // Strip non-ASCII characters (prevents Unicode/homoglyph bypass) + username = username.replace(/[^\x20-\x7E]/g, '').replace(/[\\'"<>]/g, '').trim(); + if (!username || username.length < 2) { + showToast('⚠️ Username must be at least 2 characters (letters, numbers, basic symbols only).'); + return; + } + if (containsProfanity(username)) { + showToast('⚠️ That username is not allowed. Please choose another.'); + return; + } + if (email) email = sanitizeInput(email); + const userData = { + username: username, + points: 0, + channelsVisited: 0, + totalVisits: 1, + streak: 1, + lastVisit: new Date().toISOString().split('T')[0], + created: firebase.firestore.FieldValue.serverTimestamp() + }; + if (email) userData.email = email; + if (country) userData.country = country; + // Lightning address from signup field + var _signupLn = giveawayLnAddress || ''; + if (!_signupLn) { + // Also check localStorage in case it was set for email-flow users + _signupLn = localStorage.getItem('btc_pending_ln_address') || ''; + localStorage.removeItem('btc_pending_ln_address'); + } + if (_signupLn) userData.lightningAddress = _signupLn; + // Faction choice from signup + if (window._signupFaction) { userData.faction = window._signupFaction; window._signupFaction = null; } + + await db.collection('users').doc(uid).set(userData); + // Increment global registered user count + try { db.collection('stats').doc('global').set({ userCount: firebase.firestore.FieldValue.increment(1) }, { merge: true }).catch(function() {}); } catch(e) {} + currentUser = { uid, ...userData }; + rankingReady = true; + window._badgesReady = true; + if (typeof markVisibleBadgesReady === "function") markVisibleBadgesReady(); window._hiddenBadgesReady = true; + updateRankUI(); + updateAuthButton(); + awardPoints(POINTS.visit, 'Welcome bonus!'); + startReadTimer(); + hideUsernamePrompt(); + // Confirm LN address was saved + if (_signupLn) setTimeout(function() { showToast('⚡ Lightning address saved to your profile!'); }, 1200); + // Show Quest Guide for new accounts (reset dismiss so they see it fresh) + try { + localStorage.removeItem('guide_dismissed'); + localStorage.removeItem('guide_seen'); + if (typeof showGuide === 'function') { + setTimeout(function() { showGuide(); }, 800); + } + } catch(e) {} + + + // Attach referral if user came via referral link + if (typeof attachReferral === 'function') attachReferral(uid); + // Initialize Orange Tickets for new user + if (typeof onUserLoadedTickets === 'function') onUserLoadedTickets(); + // Initialize messaging + if (typeof initMessaging === 'function') initMessaging(); + // Process pending buddy match from anonymous onboarding + try { + var _pendingBuddy = JSON.parse(localStorage.getItem('btc_buddy_pending') || 'null'); + if (_pendingBuddy && _pendingBuddy.goal) { + localStorage.removeItem('btc_buddy_pending'); + if (typeof _submitBuddyFromOnboarding === 'function') { + setTimeout(function() { _submitBuddyFromOnboarding(_pendingBuddy.level || 'beginner', _pendingBuddy.goal); }, 2000); + } + } + } catch(e) {} +} + +async function awardVisitPoints() { + if (!currentUser) return; + const today = new Date().toISOString().split('T')[0]; + const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0]; + + // Only award once per day — no refresh exploits + if (currentUser.lastVisit === today) return; + + let streakBonus = false; + let bonusTickets = 0; + let pointsToAdd = POINTS.visit; + let newStreak = 1; + + if (currentUser.lastVisit === yesterday) { + newStreak = (currentUser.streak || 0) + 1; + // Streak milestones: every 7 days = bonus tickets + if (newStreak % 7 === 0) { + bonusTickets = Math.min(25, Math.floor(newStreak / 7) * 5); + streakBonus = true; + } else if (newStreak % 5 === 0) { + pointsToAdd += POINTS.streak; + streakBonus = true; + } + } else if (currentUser.lastVisit !== today) { + // Streak broken! Check for STREAK FREEZE + var oldStreak = currentUser.streak || 0; + if (currentUser.streakFreezes > 0) { + // AUTO-USE a freeze to save the streak + newStreak = oldStreak + 1; + currentUser.streakFreezes--; + streakBonus = true; + setTimeout(function() { + showToast('🧊 STREAK FROZEN! A freeze ticket was used to save your ' + newStreak + '-day streak! (' + (currentUser.streakFreezes || 0) + ' freezes remaining)'); + }, 3000); + // Streak freeze is now deducted server-side in recordDailyVisit Cloud Function + } else if (oldStreak > 1) { + // No freeze available — streak is broken + setTimeout(function() { + showToast('💔 Your ' + oldStreak + '-day streak was broken! Earn 🧊 Freeze Tickets from the Daily Spin to protect your streak next time.'); + }, 3000); + } + } + + if (currentUser._isLocal) { + // ... update logic + } else { + // Record visit server-side (streak, totalVisits, bestStreak, tickets all handled atomically) + try { + var recordVisitFn = firebase.functions().httpsCallable('recordDailyVisit'); + var visitResult = await recordVisitFn({}); + if (visitResult.data && visitResult.data.success && !visitResult.data.alreadyVisited) { + newStreak = visitResult.data.streak || 1; + bonusTickets = visitResult.data.bonusTickets || 0; + var newBest = visitResult.data.bestStreak || newStreak; + currentUser.streak = newStreak; + currentUser.bestStreak = newBest; + currentUser.lastVisit = today; + currentUser.totalVisits = visitResult.data.totalVisits || (currentUser.totalVisits || 0) + 1; + if (bonusTickets > 0) currentUser.orangeTickets = (currentUser.orangeTickets || 0) + bonusTickets; + if (visitResult.data.usedFreeze) { + currentUser.streakFreezes = Math.max(0, (currentUser.streakFreezes || 0) - 1); + setTimeout(function() { showToast('🧊 STREAK FROZEN! A freeze was used to save your ' + newStreak + '-day streak!'); }, 3000); + } + } + } catch (e) { + console.warn('[VISIT] Cloud Function failed:', e.message); + } + // Award points through Cloud Function (daily cap enforced server-side) + var _visitPts = pointsToAdd + (bonusTickets * 5); + if (_visitPts > 0) await awardPoints(_visitPts, '✅ Daily visit' + (newStreak > 1 ? ' (' + newStreak + '-day streak!)' : '')); + } + + if (bonusTickets > 0) { + if (typeof notifySelfStreak === 'function') notifySelfStreak(newStreak); + setTimeout(function() { + showToast('🔥 STREAK MILESTONE! Day ' + newStreak + ': Earned +' + bonusTickets + ' Bonus Tickets! 🎟️'); + }, 3500); + } else if (streakBonus) { + showToast('🔥 Day ' + currentUser.streak + ' streak! +' + (POINTS.visit + POINTS.streak) + ' XP'); + } + // Silent for non-streak daily visits — ticket toast covers it + updateRankUI(); + if (typeof renderProgressRings === 'function') renderProgressRings(); + refreshLeaderboardIfOpen(); +} + +async function awardPoints(pts, reason, channelId, tickets, streakFreezes, badgeId) { + if (!currentUser || !rankingReady) return; + + // Anti-abuse: validate pts is a reasonable number + pts = parseInt(pts); + if (isNaN(pts) || pts < 0 || pts > 2200) return; + // Allow 0 pts if tickets or streakFreezes are being awarded + if (pts === 0 && !tickets && !streakFreezes) return; + + // Anti-abuse: rate limit — max 20 point awards per minute + window._pointAwardTimes = window._pointAwardTimes || []; + var _now = Date.now(); + window._pointAwardTimes = window._pointAwardTimes.filter(function(t) { return _now - t < 60000; }); + if (window._pointAwardTimes.length >= 20) return; + window._pointAwardTimes.push(_now); + + if (currentUser._isLocal) { + // ── Anonymous / local-only user ── + // Track points in localStorage. Daily cap 500. Server-side validation happens + // later if they ever sign in (via anon_merge), so this is purely UX reward. + var DAILY_CAP = 500; + var _today = new Date().toISOString().split('T')[0]; + var _capKey = 'btc_daily_pts_' + _today; + var _dailyUsed = parseInt(localStorage.getItem(_capKey) || '0', 10); + if (isNaN(_dailyUsed)) _dailyUsed = 0; + + // ── Action cooldown (anon-local mirror of server cooldowns) ── + // Prevents spam e.g. tctv_watch_10m firing faster than every 10 min. + var LOCAL_COOLDOWNS = { + 'tctv_watch_10m': 10 * 60 * 1000, + 'daily_spin': 24 * 60 * 60 * 1000, + 'daily_visit': 20 * 60 * 60 * 1000 + }; + var cdMs = LOCAL_COOLDOWNS[reason]; + if (cdMs) { + var cdKey = 'btc_cd_' + reason; + var last = parseInt(localStorage.getItem(cdKey) || '0', 10); + if (last && (Date.now() - last) < cdMs) { + if (typeof showToast === 'function') showToast('⏳ Slow down — cooldown still active'); + return; + } + try { localStorage.setItem(cdKey, String(Date.now())); } catch(e) {} + } + + // Anon overflow mirror: redeem yesterday's overflow first, then award today's pts. + var _overflowKey = 'btc_pts_overflow'; + var _overflowDateKey = 'btc_pts_overflow_date'; + var _overflow = parseInt(localStorage.getItem(_overflowKey) || '0', 10) || 0; + var _overflowDate = localStorage.getItem(_overflowDateKey) || ''; + var overflowRedeemed = 0; + if (_overflow > 0 && _overflowDate && _overflowDate !== _today) { + overflowRedeemed = Math.min(_overflow, DAILY_CAP); + _overflow -= overflowRedeemed; + try { localStorage.setItem(_overflowKey, String(_overflow)); } catch(e) {} + } + + var awarded = pts; + var overflowAdded = 0; + if (_dailyUsed >= DAILY_CAP) { + awarded = 0; + overflowAdded = pts; + } else if (_dailyUsed + pts > DAILY_CAP) { + awarded = DAILY_CAP - _dailyUsed; + overflowAdded = pts - awarded; + } + + var totalAdded = awarded + overflowRedeemed; + if (totalAdded > 0) { + var newPoints = (parseInt(localStorage.getItem('btc_points') || '0', 10) || 0) + totalAdded; + try { + localStorage.setItem('btc_points', String(newPoints)); + if (awarded > 0) localStorage.setItem(_capKey, String(_dailyUsed + awarded)); + } catch(e) {} + currentUser.points = newPoints; + _showPointsToast(awarded, reason); + if (typeof notifySelfPoints === 'function') notifySelfPoints(awarded, reason); + if (overflowRedeemed > 0 && typeof showToast === 'function') { + setTimeout(function() { + showToast('♻️ +' + overflowRedeemed + ' overflow pts redeemed from prior day!', 4000); + }, 1200); + } + } + + if (overflowAdded > 0) { + _overflow += overflowAdded; + try { + localStorage.setItem(_overflowKey, String(_overflow)); + localStorage.setItem(_overflowDateKey, _today); + } catch(e) {} + var _overflowNotifKey = 'btc_overflow_notified_' + _today; + if (!localStorage.getItem(_overflowNotifKey)) { + try { localStorage.setItem(_overflowNotifKey, '1'); } catch(e) {} + if (typeof showToast === 'function') showToast('🎯 Daily cap reached (500)! +' + overflowAdded + ' XP banked as overflow — they roll over tomorrow. Sign in to convert to sats.', 8000); + if (typeof _updateCapIndicator === 'function') _updateCapIndicator(true); + } + } else if (_dailyUsed + awarded >= DAILY_CAP) { + // Daily cap notification (once per day) + var _capNotifKey = 'btc_daily_cap_notified_' + _today; + if (!localStorage.getItem(_capNotifKey)) { + try { localStorage.setItem(_capNotifKey, '1'); } catch(e) {} + if (typeof showToast === 'function') showToast('🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow. Sign in to convert to sats.', 8000); + if (typeof _updateCapIndicator === 'function') _updateCapIndicator(true); + } + } + + updateRankUI(); + if (typeof renderProgressRings === 'function') renderProgressRings(); + refreshLeaderboardIfOpen(); + if (typeof nachoOnPoints === 'function') nachoOnPoints(pts); + return; + } + + // Update lastActive timestamp on heartbeat + if (!auth.currentUser.isAnonymous) { + db.collection('users').doc(auth.currentUser.uid).update({ + lastActive: firebase.firestore.FieldValue.serverTimestamp() + }).catch(function() {}); + } + + // ── Signed-in users: Cloud Function enforces daily cap server-side ── + // Eagerly log to notification tracker so it always appears in 🔔 Alerts + // (CF is async — user may navigate away before it returns) + if (pts > 0 && reason && typeof notifySelfPoints === 'function') { + notifySelfPoints(pts, reason); + } + try { + var awardPointsFn = firebase.functions().httpsCallable('awardPoints'); + var payload = { pts: pts, action: reason || '', reason: reason || '' }; + if (channelId) payload.channelId = channelId; + if (tickets) payload.tickets = tickets; + if (streakFreezes) payload.streakFreezes = streakFreezes; + if (badgeId) payload.badgeId = badgeId; + var result = await awardPointsFn(payload); + if (result.data && result.data.dailyActionCapped) { + if (typeof showToast === 'function') showToast('⏳ ' + (result.data.error || 'Daily limit reached for this action.'), 6000); + } + if (result.data && result.data.cooldown) { + if (typeof showToast === 'function') showToast('⏳ ' + (result.data.error || 'Slow down a bit.'), 4000); + } + if (result.data && result.data.success) { + var awarded = result.data.awarded || 0; + var overflowRedeemed = result.data.overflowRedeemed || 0; + var overflowAdded = result.data.overflowAdded || 0; + var pendingOverflow = result.data.pendingOverflow || 0; + var totalAdded = awarded + overflowRedeemed; + if (totalAdded > 0) { + currentUser.points = (currentUser.points || 0) + totalAdded; + _showPointsToast(awarded, reason); + // Notification already logged eagerly before CF call + if (overflowRedeemed > 0) { + setTimeout(function() { + showToast('♻️ +' + overflowRedeemed + ' overflow pts redeemed from prior day!', 4000); + }, 1200); + } + } + if (overflowAdded > 0) { + var _overflowKey = 'btc_overflow_notified_' + new Date().toISOString().split('T')[0]; + if (!localStorage.getItem(_overflowKey)) { + localStorage.setItem(_overflowKey, '1'); + showToast('🎯 Daily cap reached (500)! +' + overflowAdded + ' XP banked as overflow — they roll over tomorrow.', 8000); + _updateCapIndicator(true); + } + // Cache pendingOverflow locally for the CAP indicator tooltip + try { localStorage.setItem('btc_pts_overflow', String(pendingOverflow)); } catch(e) {} + } else if (result.data.capped) { + var _capNotifKey = 'btc_daily_cap_notified_' + new Date().toISOString().split('T')[0]; + if (!localStorage.getItem(_capNotifKey)) { + localStorage.setItem(_capNotifKey, '1'); + showToast('🎯 Daily cap hit (500)! Further XP today rolls over to tomorrow.', 8000); + _updateCapIndicator(true); + } + } + } + } catch (e) { + // [SECURITY] No local fallback — server is the only source of truth for points + console.warn('[POINTS] Cloud Function failed:', e.message); + if (typeof showToast === 'function') showToast('⏳ XP will sync when connection restores'); + } + updateRankUI(); + if (typeof renderProgressRings === 'function') renderProgressRings(); + refreshLeaderboardIfOpen(); + if (typeof nachoOnPoints === 'function') nachoOnPoints(pts); +} + +// Helper: smart toast throttling for point awards +function _showPointsToast(pts, reason) { + var _show = false; + if (pts >= 25) { + _show = true; + } else if (reason && reason.length > 0) { + window._lastPtsToast = window._lastPtsToast || 0; + if (Date.now() - window._lastPtsToast > 30000) _show = true; + } + if (_show && reason) { + window._lastPtsToast = Date.now(); + showToast('+' + pts + ' XP — ' + reason, 2500); + } +} + +// Points notification log — stored in localStorage for the bell panel +// Defined here (in bundle) so it's available before lazy-loaded notifications.js +window.notifySelfPoints = function(pts, reason) { + if (!pts || pts < 1) return; + if (!reason || reason === '') return; + var entry = { pts: pts, reason: reason, ts: Date.now(), read: false }; + try { + var log = JSON.parse(localStorage.getItem('btc_points_log') || '[]'); + log.push(entry); + if (log.length > 100) log = log.slice(log.length - 100); + localStorage.setItem('btc_points_log', JSON.stringify(log)); + } catch(e) {} + // Badge update (if notifications.js has loaded) + if (typeof _updatePointsBadge === 'function') _updatePointsBadge(); +}; + +// Auto-refresh leaderboard if it's currently open +function refreshLeaderboardIfOpen() { + var lb = document.getElementById('leaderboard'); + if (lb && lb.classList.contains('open') && !lb.classList.contains('minimized')) { + // Clear cache so next open fetches fresh data + window._lbCache = null; + window._lbCacheTime = null; + // In-place update: find the current user's row and update score + var meRow = lb.querySelector('.lb-me .lb-score'); + if (meRow && currentUser) { + meRow.textContent = (currentUser.points || 0).toLocaleString() + ' XP'; + } + } +} + +// Called from go() when user opens a channel +async function onChannelOpen(channelId) { + if (typeof nachoOnChannel === 'function') nachoOnChannel(channelId); + if (!currentUser || !rankingReady) return; + + // Only award points for channels NEVER visited before (persisted) + if (!allTimeChannels.has(channelId)) { + allTimeChannels.add(channelId); + sessionChannels.add(channelId); + + let ptsAwarded = POINTS.openChannel; + // Apply daily 2X boost + if (window._dailyBoosts && window._dailyBoosts.includes(channelId)) { + ptsAwarded *= 2; + setTimeout(() => { showToast('⚡ 2X XP! Daily boost applied! +' + ptsAwarded + ' XP'); }, 2000); + } + + // Update local tracking + if (currentUser._isLocal) { + currentUser.channelsVisited = (currentUser.channelsVisited || 0) + 1; + } else { + currentUser.channelsVisited = (currentUser.channelsVisited || 0) + 1; + } + if (currentUser.readChannels) { + if (currentUser.readChannels.indexOf(channelId) === -1) currentUser.readChannels.push(channelId); + } else { + currentUser.readChannels = [channelId]; + } + // Also mirror to visitedChannelsList so the Sats requirements checklist + // updates immediately (the Cloud Function will add it server-side too, + // but we don't want the UI to lag by a round-trip). + if (!Array.isArray(currentUser.visitedChannelsList)) currentUser.visitedChannelsList = []; + if (currentUser.visitedChannelsList.indexOf(channelId) === -1) currentUser.visitedChannelsList.push(channelId); + // Award points + track channel visit server-side (Cloud Function handles both atomically) + await awardPoints(ptsAwarded, '📖 New channel explored', channelId); + + // Show leaderboard only if forced or during specific onboarding by Nacho + // (Removed auto-show on every new channel visit) + // if (typeof showLeaderboardAuto === 'function') showLeaderboardAuto(); + + // Update exploration map + toast + if (typeof renderExplorationMap === 'function') renderExplorationMap(); + if (typeof showToast === 'function') { + const totalCh = typeof CHANNELS !== 'undefined' ? Object.keys(CHANNELS).length : 146; + const pct = Math.round((allTimeChannels.size / totalCh) * 100); + showToast('🗺️ Exploration Map: ' + allTimeChannels.size + ' channels reached (' + pct + '%)'); + } + + // Bonus for exploring 10+ unique channels total + if (allTimeChannels.size === 10) { + await awardPoints(POINTS.explore10, 'Explorer bonus! 10 topics 🎉'); + } + } + + // Reset read timer for new channel + readSeconds = 0; + lastReadAward = 0; + + // Sync read channel to Firebase + syncReadToFirebase(channelId); + + // Notify quest system + if (typeof onChannelVisitForQuest === 'function') onChannelVisitForQuest(channelId); +} + +// Sync read checkmarks to Firebase +async function syncReadToFirebase(channelId) { + // readChannels is now blocked in Firestore rules — channel tracking goes through awardPoints CF + // This function is kept as a no-op for backward compatibility +} + +// Sync favorites to Firebase (called from index.html) +async function syncFavsToFirebase() { + if (!currentUser || !db || !auth.currentUser || currentUser._isLocal) return; + try { + const favs = JSON.parse(localStorage.getItem('btc_favs') || '[]'); + await db.collection('users').doc(auth.currentUser.uid).update({ + favorites: favs + }); + } catch(e) {} +} + +// Sync bookmarks to Firebase +async function syncBookmarksToFirebase() { + if (!currentUser || !db || !auth.currentUser || currentUser._isLocal) return; + try { + const bm = JSON.parse(localStorage.getItem('btc_bookmarks') || '[]'); + await db.collection('users').doc(auth.currentUser.uid).update({ + bookmarks: bm + }); + } catch(e) {} +} +window.syncBookmarksToFirebase = syncBookmarksToFirebase; + +// Sync badges and scholar status to Firebase +// syncProgressToFirebase removed — badges and scholar status are synced inline at award time + +// Restore visited UI checkmarks +function restoreVisitedUI() { + const visited = JSON.parse(localStorage.getItem('btc_visited_channels') || '[]'); + visited.forEach(id => { + document.querySelectorAll('.ch-btn').forEach(b => { + if (b.getAttribute('onclick') && b.getAttribute('onclick').includes("'" + id + "'")) { + b.classList.add('visited'); + } + }); + }); +} + +let lastActivityTime = Date.now(); +let lastScrollPos = 0; +let hasScrolledSinceLastAward = false; + +// Track user activity +function trackActivity() { + lastActivityTime = Date.now(); +} +function trackScroll() { + const main = document.getElementById('main'); + if (main && Math.abs(main.scrollTop - lastScrollPos) > 30) { + lastScrollPos = main.scrollTop; + hasScrolledSinceLastAward = true; + lastActivityTime = Date.now(); + } +} + +// Listen for real user activity +document.addEventListener('mousemove', trackActivity); +document.addEventListener('keydown', trackActivity); +document.addEventListener('touchstart', trackActivity, { passive: true }); +document.addEventListener('click', trackActivity); +setInterval(trackScroll, 2000); + +function startReadTimer() { + if (readTimer) clearInterval(readTimer); + readTimer = setInterval(async () => { + if (!currentUser || !rankingReady) return; + if (document.hidden) return; // Tab not focused + + // Must have been active in last 45 seconds AND scrolled since last award + const idleSeconds = (Date.now() - lastActivityTime) / 1000; + if (idleSeconds > 45) return; // AFK + if (!hasScrolledSinceLastAward) return; // No scrolling + + readSeconds++; + // Track for Nacho bubble quiz trigger + sessionStorage.setItem('btc_channel_read_seconds', readSeconds.toString()); + if (readSeconds - lastReadAward >= 30) { + lastReadAward = readSeconds; + hasScrolledSinceLastAward = false; + + // Anti-abuse: max 5 read rewards per channel per day + var _chId = window.currentChannelId || 'unknown'; + var _readCapKey = 'btc_read_cap_' + _chId + '_' + new Date().toISOString().split('T')[0]; + var _readCount = parseInt(localStorage.getItem(_readCapKey) || '0'); + if (_readCount >= 5) return; // capped for this channel today + localStorage.setItem(_readCapKey, (_readCount + 1).toString()); + + // Use awardPoints for global daily cap enforcement + await awardPoints(POINTS.readTime, ''); + } + }, 1000); +} + +function getLevel(points) { + let level = LEVELS[0]; + for (const l of LEVELS) { + if (points >= l.min) level = l; + } + const nextIdx = LEVELS.indexOf(level) + 1; + const next = nextIdx < LEVELS.length ? LEVELS[nextIdx] : null; + return { ...level, next }; +} + +function updateGuestPointsBanner() { + var banner = document.getElementById('guestPointsBanner'); + if (!currentUser || !auth || !auth.currentUser) { + if (banner) banner.style.display = 'none'; + return; + } + var isAnon = auth.currentUser.isAnonymous; + if (!isAnon) { + if (banner) banner.style.display = 'none'; + return; + } + // Mobile: don't show old guest banner — user info is in the mobile top bar + if (window.innerWidth <= 900) { + if (banner) banner.style.display = 'none'; + return; + } + var pts = currentUser.points || 0; + if (pts < 1) { + if (banner) banner.style.display = 'none'; + return; + } + if (!banner) { + banner = document.createElement('div'); + banner.id = 'guestPointsBanner'; + banner.style.cssText = 'position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:10px;padding:10px 16px;background:linear-gradient(135deg,#1a1a2e,#2d1f4e);border:2px solid #f7931a;border-radius:14px;box-shadow:0 4px 20px rgba(247,147,26,0.3);font-size:0.85rem;cursor:pointer;transition:0.3s;max-width:320px;'; + banner.onclick = function(e) { + // Don't trigger sign-in if the click was on the minimize toggle + if (e && e.target && e.target.closest && e.target.closest('.banner-toggle')) return; + showSignInPrompt(); + }; + document.body.appendChild(banner); + } + // Restore previous minimized state so users don't have to re-minimize on every page nav + try { + if (localStorage.getItem('btc_signin_banner_min') === '1') banner.classList.add('banner-min'); + else banner.classList.remove('banner-min'); + } catch(e) {} + var lv = getLevel(pts); + var isMin = banner.classList.contains('banner-min'); + banner.innerHTML = + '
    ' + + '
    ' + + '' + lv.emoji + '' + + '' + pts.toLocaleString() + ' XP' + + '
    ' + + '
    Sign in to keep your XP & get on the leaderboard!
    ' + + '
    ' + + '
    Sign Up Free →
    ' + + ''; + banner.style.display = 'flex'; +} + +window.toggleGuestPointsBanner = function() { + var banner = document.getElementById('guestPointsBanner'); + if (!banner) return; + var willMin = !banner.classList.contains('banner-min'); + banner.classList.toggle('banner-min', willMin); + try { localStorage.setItem('btc_signin_banner_min', willMin ? '1' : '0'); } catch(e) {} + updateGuestPointsBanner(); +}; + +// ── Daily Cap Visual Indicator ── +function _updateCapIndicator(atCap) { + var el = document.getElementById('userDisplay'); + if (!el) return; + var _today = new Date().toISOString().split('T')[0]; + var _dailyKey = 'btc_daily_pts_' + _today; + var _dailyPts = parseInt(localStorage.getItem(_dailyKey) || '0'); + var _overflow = parseInt(localStorage.getItem('btc_pts_overflow') || '0'); + if (atCap || _dailyPts >= 500) { + el.style.borderColor = '#ef4444'; + el.style.boxShadow = '0 0 12px rgba(239,68,68,0.3)'; + el.title = '🎯 Daily XP cap reached (500/500)' + (_overflow > 0 ? '\n💫 Overflow: ' + _overflow + ' pts (rolls over tomorrow)' : ''); + // Add cap badge if not present + if (!document.getElementById('dailyCapBadge')) { + var badge = document.createElement('span'); + badge.id = 'dailyCapBadge'; + badge.style.cssText = 'position:absolute;top:-6px;left:-6px;background:#ef4444;color:#fff;font-size:0.55rem;font-weight:800;padding:2px 6px;border-radius:8px;z-index:2;pointer-events:none;'; + badge.textContent = 'CAP'; + el.style.position = 'fixed'; // ensure positioned + el.appendChild(badge); + } + } else { + el.style.borderColor = 'var(--border)'; + el.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)'; + el.title = ''; + var badge = document.getElementById('dailyCapBadge'); + if (badge) badge.remove(); + } +} + +function _checkCapOnLoad() { + var _today = new Date().toISOString().split('T')[0]; + var _dailyKey = 'btc_daily_pts_' + _today; + var _dailyPts = parseInt(localStorage.getItem(_dailyKey) || '0'); + if (_dailyPts >= 500) { + setTimeout(function() { _updateCapIndicator(true); }, 2000); + } +} + +function updateRankUI() { + if (!currentUser) return; + + const lv = getLevel(currentUser.points || 0); + + // PERSISTENCE FIX: Ensure we don't celebrate 0 -> current on load + // Initialize if this is the first ever run of updateRankUI + if (!lastLevelName && lv.name) { + lastLevelName = lv.name; + lastLevelMin = lv.min; + } + + // Always update the top-right user display, even if rankBar doesn't exist + updateGuestPointsBanner(); + updateUserDisplay(lv); + + // Detect level-up — only celebrate going UP, never on initial load + const highestLevelSeen = parseInt(localStorage.getItem('btc_highest_level_seen') || '0'); + if (levelUpReady && lastLevelName && lastLevelName !== lv.name && lv.min > lastLevelMin && lv.min > highestLevelSeen) { + showLevelUpCelebration(lv); + localStorage.setItem('btc_highest_level_seen', lv.min.toString()); + if (typeof notifySelfLevelUp === 'function') notifySelfLevelUp(lv.min, lv.name, lv.emoji); + // Announce level-up in Global Chat + var _luName = (currentUser && currentUser.username) ? currentUser.username : null; + var _luUid = (typeof auth !== 'undefined' && auth && auth.currentUser) ? auth.currentUser.uid : ''; + if (_luName && typeof window.nachoGlobalAnnounce === 'function') { + window.nachoGlobalAnnounce(lv.emoji + ' @' + _luName + ' just leveled up to ' + lv.emoji + ' ' + lv.name + '! Congrats! \uD83C\uDF89', _luUid); + } + + // Satoshi's Favor contribution for level-ups + if (typeof window.contributeSatoshiFavor === 'function') { + var levelName = lv.name || ''; + var source = null; + // Check rank tier + if (['Pleb','Pleb II','Pleb III','Stacker','Stacker II','Stacker III'].includes(levelName)) { + source = 'level_up'; + } else if (['Maxi','Maxi II','Maxi III'].includes(levelName)) { + source = 'level_up_5'; + } else if (['Papa John','Full Node','Whale','Sovereign','Cypherpunk','Satoshi'].includes(levelName)) { + source = 'level_up_10'; + } + if (source) { + // contributeSatoshiFavor handles all Nacho announcements internally + window.contributeSatoshiFavor(source, levelName); + } + } + } + lastLevelName = lv.name; + lastLevelMin = lv.min; + + const bar = document.getElementById('rankBar'); + if (!bar) return; + + let progressHtml = ''; + if (lv.next) { + const pct = Math.min(100, ((currentUser.points - lv.min) / (lv.next.min - lv.min)) * 100); + progressHtml = '
    ' + + '
    ' + (lv.next.min - currentUser.points) + ' XP to ' + lv.next.emoji + ' ' + lv.next.name + '
    '; + } + + const isAnon = auth.currentUser && auth.currentUser.isAnonymous; + const signInLink = isAnon && currentUser.username ? '' : ''; + + const streak = currentUser.streak || 0; + const isMilestone = streak > 0 && (streak % 7 === 0 || streak === 30 || streak === 100 || streak === 365); + const bestStreakVal = currentUser.bestStreak || 0; + const streakHtml = (streak > 0 || bestStreakVal > 0) ? '🔥 ' + streak + (bestStreakVal > 0 ? '(' + bestStreakVal + ')' : '') + ' day streak' + (isMilestone ? ' ✨' : '') + '' : ''; + const ticketHtml = (currentUser.orangeTickets || 0) > 0 ? '' + currentUser.orangeTickets + '' : ''; + + bar.innerHTML = + '
    ' + + '' + lv.emoji + ' ' + lv.name + '' + + '' + escapeHtml(currentUser.username || 'Anon') + '' + + '' + (currentUser.points || 0).toLocaleString() + ' XP' + + streakHtml + ticketHtml + + '
    ' + progressHtml + signInLink; + bar.style.display = 'flex'; + +} + +// Get user's display emoji — chosen badge or default level emoji +function getUserDisplayEmoji(lv) { + var chosenBadge = (typeof currentUser !== 'undefined' && currentUser) ? currentUser.displayBadge : null; + if (chosenBadge) { + // Look in BADGE_DEFS + if (typeof BADGE_DEFS !== 'undefined') { + for (var i = 0; i < BADGE_DEFS.length; i++) { + if (BADGE_DEFS[i].id === chosenBadge) return BADGE_DEFS[i].emoji; + } + } + // Look in HIDDEN_BADGES + if (typeof HIDDEN_BADGES !== 'undefined') { + for (var j = 0; j < HIDDEN_BADGES.length; j++) { + if (HIDDEN_BADGES[j].id === chosenBadge) { + return HIDDEN_BADGES[j].hidden ? (HIDDEN_BADGES[j].revealEmoji || HIDDEN_BADGES[j].emoji) : HIDDEN_BADGES[j].emoji; + } + } + } + } + return lv ? lv.emoji : '🌱'; +} + +function updateUserDisplay(lv) { + // Suppress user display during direct link cooldown + if (window._directLinkMode) { + var _ud = document.getElementById('userDisplay'); + if (_ud) _ud.style.display = 'none'; + return; + } + // Hide old guest banner — we now use unified display + var guestBanner = document.getElementById('guestPointsBanner'); + if (guestBanner) guestBanner.style.display = 'none'; + + var isAnon = auth && auth.currentUser && auth.currentUser.isAnonymous && !currentUser.username; + var hasUsername = currentUser && currentUser.username; + var pts = (currentUser.points || 0); + var streakBit = (currentUser.streak || 0) > 0 ? '🔥' + currentUser.streak + '' : ''; + var displayEmoji = getUserDisplayEmoji(lv); + + let el = document.getElementById('userDisplay'); + if (!el) { + el = document.createElement('div'); + el.id = 'userDisplay'; + document.body.appendChild(el); + } + + if (isAnon || (auth.currentUser && auth.currentUser.isAnonymous && !hasUsername)) { + // Mobile: hide the fixed overlay — user info already lives in the mobile top bar. + // Anonymous users on mobile see their stats in #mobileUserInfo, no need for the + // intrusive bottom sign-up banner. + var _isMob = window.innerWidth <= 900; + if (_isMob) { + el.setAttribute('data-mob-hidden', '1'); + el.style.display = 'none'; + return; + } + // If user dismissed the banner this session, keep it hidden. + // Use a CSS class (which also has !important) so the "display:flex !important" + // mobile rule can't resurrect it. + if (sessionStorage.getItem('btc_signin_banner_dismissed') === '1') { + el.classList.add('user-hidden'); + el.style.display = 'none'; + return; + } + // Otherwise ensure the hide class is removed (re-expanded state) + el.classList.remove('user-hidden'); + // Consolidated Metric Dashboard + Guest Sign-in + el.setAttribute('data-anon', '1'); + + // NEW POSITIONING: Under sidebar branding for tablet/laptop + if (!_isMob) { + var sidebarHeader = document.querySelector('.sidebar-header'); + if (sidebarHeader && !document.getElementById('userDisplayContainer')) { + var container = document.createElement('div'); + container.id = 'userDisplayContainer'; + container.style.padding = '0 20px 16px'; + container.style.borderBottom = '1px solid var(--border)'; + sidebarHeader.parentNode.insertBefore(container, sidebarHeader.nextSibling); + container.appendChild(el); + } + // Add horizontal row for Dashboard + Notifications + el.style.cssText = 'position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:12px;background:rgba(247,147,26,0.05);border:1px solid rgba(247,147,26,0.2);border-radius:12px;cursor:default;transition:0.3s;width:100%;'; + } else { + el.style.cssText = 'position:fixed;bottom:70px;left:12px;right:12px;z-index:200;display:flex;align-items:center;gap:10px;padding:10px 16px;background:linear-gradient(135deg,#1a1a2e,#2d1f4e);border:2px solid #f7931a;border-radius:14px;box-shadow:0 4px 20px rgba(247,147,26,0.3);font-size:0.85rem;cursor:pointer;'; + } + + el.onclick = function(e) { if(!_isMob && e.target.closest('button')) return; showSettingsPage('account'); }; + + el.innerHTML = + (_isMob ? '' : '') + + '
    ' + + '
    ' + + '
    ' + + '' + lv.emoji + '' + + 'GUEST' + + '' + pts.toLocaleString() + ' XP' + + '
    ' + + '
    ' + + (function() { + var cp = parseFloat(localStorage.getItem('btc_last_price')) || 0; + var ch = parseInt(localStorage.getItem('btc_last_height')) || 0; + if (typeof nachoLiveData !== 'undefined' && nachoLiveData.price) cp = nachoLiveData.price; + if (typeof nachoLiveData !== 'undefined' && nachoLiveData.blockHeight) ch = nachoLiveData.blockHeight; + + var s = '
    '; + if (cp) s += '
    $' + Math.round(cp).toLocaleString() + '
    '; + if (ch) s += '⛓️ ' + ch.toLocaleString() + ''; + return s + '
    '; + })() + + (_isMob ? '
    Sign in to keep your XP!
    ' : '') + + '
    ' + + (!_isMob ? '
    ' : '') + + (!_isMob ? '
    SIGN UP
    ' : '') + + (_isMob ? '
    Sign Up →
    ' : ''); + } else { + // Signed in user + el.removeAttribute('data-anon'); + el.removeAttribute('data-mob-hidden'); + var _isMob = window.innerWidth <= 900; + + // dashboardFloatBtn is static HTML — just ensure onclick is wired + var dashBtn = document.getElementById('dashboardFloatBtn'); + if (!dashBtn) { + dashBtn = document.createElement('div'); + dashBtn.id = 'dashboardFloatBtn'; + dashBtn.className = 'fab-btn'; + dashBtn.innerHTML = '📊'; + dashBtn.title = 'Bitcoin Metrics'; + document.body.appendChild(dashBtn); + } + dashBtn.onclick = function() { if (typeof toggleDashboard === 'function') toggleDashboard(); }; + + // Mobile: hide the fixed overlay entirely — user info lives in the mobile-bar instead + if (_isMob) { + el.style.display = 'none'; + // updateRankUI will populate #mobileUserInfo in the mobile-bar + return; + } + + if (!_isMob) { + var sidebarHeader = document.querySelector('.sidebar-header'); + if (sidebarHeader && !document.getElementById('userDisplayContainer')) { + var container = document.createElement('div'); + container.id = 'userDisplayContainer'; + container.style.padding = '0 20px 16px'; + container.style.borderBottom = '1px solid var(--border)'; + sidebarHeader.parentNode.insertBefore(container, sidebarHeader.nextSibling); + container.appendChild(el); + } + el.style.cssText = 'position:relative;top:auto;right:auto;z-index:10;display:flex;flex-direction:row;align-items:center;gap:10px;padding:10px;background:rgba(255,255,255,0.03);border:1px solid var(--border);border-radius:10px;cursor:pointer;width:100%;'; + } else { + el.style.cssText = 'position:fixed;top:12px;right:20px;z-index:200;display:flex;align-items:center;gap:8px;padding:8px 14px;background:var(--bg-side);border:1px solid var(--border);border-radius:10px;font-size:0.8rem;cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,0.2);'; + } + + // Clicking the user display opens settings (except block height link) + el.onclick = function(e) { if (e.target.closest('a')) return; showSettings(); }; + + var displayName = currentUser.username || (auth.currentUser && auth.currentUser.displayName) || 'Anon'; + + // Show BOTH display badge and rank emoji if a badge is selected + var chosenBadge = currentUser.displayBadge; + var iconsHtml = ''; + if (chosenBadge) { + iconsHtml = '' + displayEmoji + ' ' + + '' + lv.emoji + ''; + } else { + iconsHtml = '' + lv.emoji + ''; + } + + el.innerHTML = + '
    ' + + '
    ' + + iconsHtml + + '' + escapeHtml(displayName) + '' + + (streakBit ? '' + streakBit + '' : '') + + '
    ' + + (function() { + var cp = parseFloat(localStorage.getItem('btc_last_price')) || 0; + var ch = parseInt(localStorage.getItem('btc_last_height')) || 0; + if (typeof nachoLiveData !== 'undefined' && nachoLiveData.price) cp = nachoLiveData.price; + if (typeof nachoLiveData !== 'undefined' && nachoLiveData.blockHeight) ch = nachoLiveData.blockHeight; + var s = '
    '; + if (cp) s += '
    $' + Math.round(cp).toLocaleString() + '
    '; + if (ch) s += '⛓️ ' + ch.toLocaleString() + ''; + s += '' + pts.toLocaleString() + ' XP'; + return s + '
    '; + })() + + '
    ' + + (!_isMob ? '
    ' : ''); + } + el.style.display = 'flex'; + + // dashboardFloatBtn is now created earlier (before mobile early-return) to ensure it shows on mobile too + + // Update mobile top bar user info (username + price + block height + pts) + const mobileInfo = document.getElementById('mobileUserInfo'); + if (mobileInfo && window.innerWidth <= 900) { + var chosenBadge = currentUser.displayBadge; + var mobileIcons = displayEmoji; + if (chosenBadge) mobileIcons += ' ' + lv.emoji; + var pts = (currentUser.points || 0); + var _cp = parseFloat(localStorage.getItem('btc_last_price')) || 0; + var _ch = parseInt(localStorage.getItem('btc_last_height')) || 0; + if (typeof nachoLiveData !== 'undefined' && nachoLiveData.price) _cp = nachoLiveData.price; + if (typeof nachoLiveData !== 'undefined' && nachoLiveData.blockHeight) _ch = nachoLiveData.blockHeight; + var nameStr = escapeHtml(currentUser.username || (isAnon ? 'Anonymous' : 'Anon')); + var s = '' + mobileIcons + ' ' + nameStr + ''; + if (_cp) s += ' $' + Math.round(_cp).toLocaleString() + ''; + if (_ch) s += ' ⛓️ ' + _ch.toLocaleString() + ''; + s += ' ' + pts.toLocaleString() + ' XP'; + mobileInfo.innerHTML = s; + mobileInfo.style.display = 'inline'; + mobileInfo.style.maxWidth = 'none'; + } + + // Update home page welcome banner + const wb = document.getElementById('welcomeBanner'); + if (wb && currentUser.username) { + // Sync auth button whenever we update the welcome banner to ensure identity consistency + updateAuthButton(); + + const streak = currentUser.streak || 0; + const wbBestStreak = currentUser.bestStreak || 0; + const streakText = (streak > 0 || wbBestStreak > 0) ? ' · 🔥 ' + streak + (wbBestStreak > 0 ? '(' + wbBestStreak + ')' : '') + ' day streak' : ''; + wb.innerHTML = '' + lv.emoji + ' ' + + 'Welcome back, ' + escapeHtml(currentUser.username || 'Anon') + '!' + + ' · ' + lv.name + ' · ' + (currentUser.points || 0).toLocaleString() + ' XP' + + streakText + + '
    ⚙️ Tap here for Account & Settings
    '; + wb.style.display = 'block'; + wb.removeAttribute('data-simplified-hidden'); + } +} +let lbAutoShown = false; + +function showLeaderboardAuto() { + if (lbAutoShown) return; + lbAutoShown = true; + const lb = document.getElementById('leaderboard'); + if (lb.classList.contains('open')) return; + toggleLeaderboard(); +} + +function expandLeaderboard(e) { + if (e) e.stopPropagation(); + document.querySelectorAll('.lb-extra').forEach(el => el.style.display = 'flex'); + const btn = document.getElementById('lbShowMore'); + if (btn) btn.remove(); +} + +function minimizeLeaderboard() { + const lb = document.getElementById('leaderboard'); + const fab = document.getElementById('lbFloatBtn'); + lb.classList.remove('open'); + lb.classList.remove('minimized'); + if (fab) fab.style.display = 'flex'; +} + +function hideLeaderboard() { + const lb = document.getElementById('leaderboard'); + const fab = document.getElementById('lbFloatBtn'); + lb.classList.remove('open'); + lb.classList.remove('minimized'); + if (fab) fab.style.display = 'flex'; +} + +// Leaderboard username search +var _lbSearchTimer = null; +var _lbSearchQuery = ''; +var _lbSearchLastRank = 0; +var _lbSearchHasMore = false; +var _lbSearchLoading = false; + +function _lbBuildResultRow(u) { + var pts = (u.points || 0).toLocaleString(); + var lv = typeof getLevel === 'function' ? getLevel(u.points || 0) : { emoji: '' }; + var factionStyle = u.faction && typeof window._factionNameStyle === 'function' ? ' style="' + window._factionNameStyle(u.faction) + '"' : ''; + return '
    ' + + '' + lv.emoji + '' + + '' + escapeHtml(u.username || 'Anon') + '' + + '' + pts + ' XP · #' + u.rank + '' + + '
    '; +} + +async function _lbSearchLoad(query, afterRank, append) { + if (_lbSearchLoading) return; + _lbSearchLoading = true; + var resultEl = document.getElementById('lbSearchResult'); + if (!resultEl) { _lbSearchLoading = false; return; } + + // Remove old load-more button if present + var oldBtn = document.getElementById('lbSearchMoreBtn'); + if (oldBtn) oldBtn.remove(); + + if (!append) { + resultEl.innerHTML = '
    Searching...
    '; + } else { + var loadingRow = document.createElement('div'); + loadingRow.id = 'lbSearchLoadingRow'; + loadingRow.className = 'lb-search-none'; + loadingRow.textContent = 'Loading more...'; + resultEl.appendChild(loadingRow); + } + + try { + var searchFn = firebase.functions().httpsCallable('searchUsers'); + var res = await searchFn({ query: query, pageSize: 10, afterRank: afterRank }); + var users = (res.data && res.data.users) || []; + var hasMore = !!(res.data && res.data.hasMore); + + // Remove loading indicator + var lr = document.getElementById('lbSearchLoadingRow'); + if (lr) lr.remove(); + + if (!append && !users.length) { + resultEl.innerHTML = '
    No users found matching "' + escapeHtml(query) + '"
    '; + _lbSearchLoading = false; + return; + } + + if (!append) resultEl.innerHTML = ''; + users.forEach(function(u) { resultEl.insertAdjacentHTML('beforeend', _lbBuildResultRow(u)); }); + + _lbSearchLastRank = users.length ? users[users.length - 1].rank : afterRank; + _lbSearchHasMore = hasMore; + + if (hasMore) { + var btn = document.createElement('button'); + btn.id = 'lbSearchMoreBtn'; + btn.style.cssText = 'width:100%;padding:8px;background:none;border:1px solid var(--border);border-radius:8px;color:var(--text-muted);font-size:0.8rem;cursor:pointer;font-family:inherit;margin:4px 0 2px;'; + btn.textContent = 'Show more results ▼'; + btn.onclick = function() { _lbSearchLoad(_lbSearchQuery, _lbSearchLastRank, true); }; + resultEl.appendChild(btn); + } + } catch(e) { + console.warn('[lbSearch]', e); + var lr2 = document.getElementById('lbSearchLoadingRow'); + if (lr2) lr2.remove(); + if (!append) resultEl.innerHTML = '
    Search error — try again
    '; + } + _lbSearchLoading = false; +} + +window.lbSearchUser = function(val) { + var resultEl = document.getElementById('lbSearchResult'); + if (!resultEl) return; + val = (val || '').trim(); + if (!val || val.length < 2) { resultEl.innerHTML = ''; _lbSearchQuery = ''; return; } + + clearTimeout(_lbSearchTimer); + _lbSearchTimer = setTimeout(function() { + _lbSearchQuery = val; + _lbSearchLastRank = 0; + _lbSearchHasMore = false; + _lbSearchLoading = false; + _lbSearchLoad(val, 0, false); + }, 350); +}; + +// Close leaderboard when clicking/tapping outside. +// Uses capture phase + both mousedown and touchstart so it fires BEFORE +// any inner handler can call stopPropagation() and swallow the event. +function _lbOutsideClose(e) { + var lb = document.getElementById('leaderboard'); + if (!lb || !lb.classList.contains('open') || lb.classList.contains('minimized')) return; + if (lb.contains(e.target)) return; + // Don't close if clicking the rank bar or leaderboard button (those toggle the LB themselves) + var rankBar = document.getElementById('rankBar'); + if (rankBar && rankBar.contains(e.target)) return; + var fab = document.getElementById('lbFloatBtn'); + if (fab && fab.contains(e.target)) return; + // Don't close if a profile modal is open (clicking in the modal shouldn't close the LB behind it) + var profileModal = document.getElementById('userProfileModal'); + if (profileModal) return; + // Close it + lb.classList.remove('open'); + lb.classList.remove('minimized'); + if (fab) fab.style.display = 'flex'; +} +document.addEventListener('mousedown', _lbOutsideClose, true); +document.addEventListener('touchstart', _lbOutsideClose, true); + +window.toggleOLEDTheme = function() { + const isOLED = localStorage.getItem('btc_theme_oled') === 'true'; + localStorage.setItem('btc_theme_oled', !isOLED); + applyOLEDTheme(); + showSettingsPage('prefs'); + showToast(!isOLED ? '🖤 Midnight OLED enabled!' : 'Deep sea mode disabled'); +}; + +function applyOLEDTheme() { + const isOLED = localStorage.getItem('btc_theme_oled') === 'true'; + const isDark = document.body.getAttribute('data-theme') !== 'light'; + if (isOLED && isDark) { + document.body.classList.add('oled-theme'); + } else { + document.body.classList.remove('oled-theme'); + } +} + +// Initial apply +document.addEventListener('DOMContentLoaded', applyOLEDTheme); + +// ---- Delete Account ---- +window.showDeleteAccountConfirm = function() { + var overlay = document.createElement('div'); + overlay.id = 'deleteAccountOverlay'; + overlay.style.cssText = 'position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,0.92);display:flex;align-items:center;justify-content:center;padding:20px;'; + overlay.onclick = function(e) { if (e.target === overlay) overlay.remove(); }; + + var username = (currentUser && currentUser.username) ? currentUser.username : 'your account'; + var pts = currentUser ? (currentUser.points || 0) : 0; + var streak = currentUser ? (currentUser.streak || 0) : 0; + + overlay.innerHTML = + '
    ' + + '
    ⚠️
    ' + + '

    Delete Your Account?

    ' + + '
    ' + + 'This will permanently delete everything associated with ' + escapeHtml(username) + ':' + + '
    ' + + '
    ' + + '
    ' + + '
    ' + pts.toLocaleString() + ' XP and all badges
    ' + + (streak > 0 ? '
    ' + streak + '-day streak
    ' : '') + + '
    ❌ All forum posts and replies
    ' + + '
    ❌ Marketplace listings
    ' + + '
    ❌ DM conversations
    ' + + '
    ❌ Nacho chat history
    ' + + '
    ❌ Leaderboard ranking
    ' + + '
    ❌ Orange Tickets and quest progress
    ' + + '
    ' + + '
    ' + + '
    ⚠️ This action is IRREVERSIBLE. There is no undo.
    ' + + '
    ' + + '' + + '' + + '
    ' + + '
    ' + + '' + + '' + + '
    ' + + '
    '; + + document.body.appendChild(overlay); +}; + +window.confirmDeleteAccount = async function() { + var input = document.getElementById('deleteConfirmInput'); + if (!input || input.value !== 'DELETE') return; + + var btn = document.getElementById('deleteConfirmBtn'); + if (btn) { btn.disabled = true; btn.textContent = 'Deleting...'; } + + try { + var user = auth.currentUser; + if (!user) throw new Error('Not signed in'); + var uid = user.uid; + + // 1. Delete Firestore user document + try { await db.collection('users').doc(uid).delete(); } catch(e) { console.warn('User doc delete failed:', e); } + + // 2. Delete forum posts by this user + try { + var posts = await db.collection('forum_posts').where('authorId', '==', uid).get(); + var batch1 = db.batch(); + posts.forEach(function(doc) { batch1.delete(doc.ref); }); + if (!posts.empty) await batch1.commit(); + } catch(e) { console.warn('Forum posts delete failed:', e); } + + // 3. Delete forum replies by this user + try { + var replies = await db.collection('forum_replies').where('authorId', '==', uid).get(); + var batch2 = db.batch(); + replies.forEach(function(doc) { batch2.delete(doc.ref); }); + if (!replies.empty) await batch2.commit(); + } catch(e) { console.warn('Forum replies delete failed:', e); } + + // 4. Delete marketplace listings + try { + var listings = await db.collection('marketplace').where('sellerUid', '==', uid).get(); + var batch3 = db.batch(); + listings.forEach(function(doc) { batch3.delete(doc.ref); }); + if (!listings.empty) await batch3.commit(); + } catch(e) { console.warn('Marketplace delete failed:', e); } + + // 5. Delete DM conversations + try { + var convos = await db.collection('conversations').where('participants', 'array-contains', uid).get(); + var batch4 = db.batch(); + convos.forEach(function(doc) { batch4.delete(doc.ref); }); + if (!convos.empty) await batch4.commit(); + } catch(e) { console.warn('DM delete failed:', e); } + + // 6. Delete suggestions + try { + var suggestions = await db.collection('suggestions').where('uid', '==', uid).get(); + var batch5 = db.batch(); + suggestions.forEach(function(doc) { batch5.delete(doc.ref); }); + if (!suggestions.empty) await batch5.commit(); + } catch(e) { console.warn('Suggestions delete failed:', e); } + + // 7. Clear all localStorage + var keysToRemove = []; + for (var i = 0; i < localStorage.length; i++) { + var key = localStorage.key(i); + if (key && key.startsWith('btc_')) keysToRemove.push(key); + } + keysToRemove.forEach(function(k) { localStorage.removeItem(k); }); + sessionStorage.clear(); + // [AUDIT FIX M5] Clear SW caches on account deletion + if ('caches' in window) { try { var _ck = await caches.keys(); _ck.forEach(function(k) { caches.delete(k); }); } catch(e) {} } + + // 8. Delete Firebase Auth account + await user.delete(); + + // 9. Close overlay and show confirmation + var overlay = document.getElementById('deleteAccountOverlay'); + if (overlay) overlay.remove(); + + // Close settings + var settingsEl = document.getElementById('settings-overlay') || document.querySelector('[id*="settings"]'); + if (settingsEl) settingsEl.remove(); + + showToast('👋 Account deleted. We\'re sorry to see you go.'); + + // Reload after brief delay + setTimeout(function() { window.location.reload(); }, 2000); + + } catch(e) { + console.error('Account deletion error:', e); + if (e.code === 'auth/requires-recent-login') { + showToast('🔒 For security, please sign out and sign back in, then try again.'); + } else { + showToast('Error deleting account: ' + (e.message || 'Unknown error')); + } + if (btn) { btn.disabled = false; btn.textContent = '🗑️ Delete Forever'; btn.style.opacity = '1'; } + } +}; + +window.toggleGhostMode = async function() { + if (!currentUser) return; + const isGhost = !currentUser.ghostMode; + currentUser.ghostMode = isGhost; + + // Update local state and UI + showSettingsPage('security'); + + // Update Firestore + try { + await db.collection('users').doc(auth.currentUser.uid).update({ ghostMode: isGhost }); + showToast(isGhost ? '👻 Ghost Mode enabled!' : 'Visible mode enabled'); + } catch(e) { console.log("Ghost mode update failed:", e); } +}; + +// Stubs for upcoming features +window.setNachoNickname = function(val) { + var nick = (val || '').trim(); + if (!nick) return; + // Save to localStorage (used everywhere) + localStorage.setItem('btc_nacho_nickname', nick); + // Save to currentUser object + if (currentUser) currentUser.nachoNickname = nick; + // Save to Firestore + if (typeof db !== 'undefined' && auth && auth.currentUser && !auth.currentUser.isAnonymous) { + db.collection('users').doc(auth.currentUser.uid).update({ nachoNickname: nick }).catch(function(e) { console.error('[ranking] Error:', e); }); + } + // Update Nacho's name throughout the app + if (typeof updateNachoNameUI === 'function') updateNachoNameUI(nick); + // Update Nacho Mode title if open + var nmTitle = document.querySelector('.nm-hero-title'); + if (nmTitle) nmTitle.textContent = nick.toUpperCase() + ' MODE'; + // Update bubble header + var bubbleHeader = document.querySelector('#nacho-bubble .nacho-name, #nacho-name'); + if (bubbleHeader) bubbleHeader.textContent = nick; + showToast('🦌 Your deer is now named "' + nick + '"!'); + showSettingsPage('data'); +}; + +// Update Nacho's name across all UI elements +window.updateNachoNameUI = function(name) { + if (!name) return; + // Nacho Mode title + var nmTitle = document.querySelector('.nm-hero-title'); + if (nmTitle) nmTitle.textContent = name.toUpperCase() + ' MODE'; + // Sidebar Nacho button + var sidebarBtn = document.getElementById('sidebarNachoBtn'); + if (sidebarBtn) sidebarBtn.innerHTML = '🦌 ' + name + ' Mode'; + // Bottom nav + var bnavNacho = document.getElementById('bnavNacho'); + if (bnavNacho) { + var label = bnavNacho.querySelector('.bnav-label'); + if (label) label.textContent = name; + } + // Nacho bubble header + var bubbleName = document.getElementById('nacho-bubble-name'); + if (bubbleName) bubbleName.textContent = name; + // Nacho avatar name label + var avatarName = document.querySelector('.nacho-name'); + if (avatarName) { + avatarName.innerHTML = name.toUpperCase() + '
    click to ask!'; + } + // Closet header + var closetHeaders = document.querySelectorAll('[id*="nachoCloset"]'); + closetHeaders.forEach(function(el) { + var header = el.querySelector('[style*="letter-spacing"]'); + if (header && header.textContent.indexOf("'s Closet") !== -1) { + header.textContent = '🦌 ' + name + "'s Closet"; + } + }); + // Story header + var storyHeaders = document.querySelectorAll('[style*="font-weight:800"]'); + storyHeaders.forEach(function(el) { + if (el.textContent.indexOf("'s Story") !== -1) { + el.textContent = name + "'s Story"; + } + }); +}; + +// Render leaderboard badge emoji — compact multi-emoji into a fixed-size cell +function _lbBadgeEmoji(emoji) { + // Split emoji string into individual emoji characters (handles multi-byte emoji) + var chars = []; + var segs = typeof Intl !== 'undefined' && Intl.Segmenter + ? Array.from(new Intl.Segmenter('en', { granularity: 'grapheme' }).segment(emoji)).map(function(s) { return s.segment; }) + : null; + if (segs) { chars = segs; } + else { + // Fallback: split on emoji boundaries (regex for surrogate pairs + variation selectors + ZWJ) + var m = emoji.match(/\p{Emoji_Presentation}(\u200d\p{Emoji_Presentation})*/gu); + chars = m ? m : [emoji]; + } + if (chars.length <= 1) return emoji; + // 2-3 emoji: render as a compact grid + var size = chars.length === 2 ? '0.6rem' : '0.5rem'; + var gap = chars.length === 2 ? '0px' : '0px'; + return '' + + chars.map(function(c) { return '' + c + ''; }).join('') + ''; +} + +async function toggleLeaderboard() { + const lb = document.getElementById('leaderboard'); + if (!lb) return; + const fab = document.getElementById('lbFloatBtn'); + if (lb.classList.contains('open') && !lb.classList.contains('minimized')) { + lb.classList.remove('open'); + lb.classList.remove('minimized'); + if (fab) fab.style.display = 'flex'; + return; + } + + lb.classList.remove('minimized'); + lb.innerHTML = '
    Loading leaderboard...
    '; + lb.classList.add('open'); + if (fab) fab.style.display = 'none'; + + // Leaderboard open sound — dramatic reveal + if ((typeof canPlaySound !== 'function' || canPlaySound()) && (typeof audioEnabled === 'undefined' || audioEnabled)) { + try { + if (!window._sharedAudioCtx) window._sharedAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); var ctx = window._sharedAudioCtx; if (ctx.state === "suspended") ctx.resume(); + const vol = typeof audioVolume !== 'undefined' ? audioVolume : 0.5; + // Rising whoosh + chime + const now = ctx.currentTime; + // Whoosh sweep + const osc1 = ctx.createOscillator(); + const g1 = ctx.createGain(); + osc1.connect(g1); g1.connect(ctx.destination); + osc1.type = 'sine'; + osc1.frequency.setValueAtTime(200, now); + osc1.frequency.exponentialRampToValueAtTime(800, now + 0.15); + g1.gain.setValueAtTime(0.08 * vol, now); + g1.gain.exponentialRampToValueAtTime(0.001, now + 0.2); + osc1.start(now); osc1.stop(now + 0.2); + // Trophy chime — two bright notes + [880, 1175].forEach((freq, i) => { + const osc = ctx.createOscillator(); + const g = ctx.createGain(); + osc.connect(g); g.connect(ctx.destination); + osc.type = 'triangle'; + osc.frequency.value = freq; + g.gain.setValueAtTime(0.1 * vol, now + 0.1 + i * 0.08); + g.gain.exponentialRampToValueAtTime(0.001, now + 0.1 + i * 0.08 + 0.3); + osc.start(now + 0.1 + i * 0.08); + osc.stop(now + 0.1 + i * 0.08 + 0.3); + }); + } catch(e) {} + } + + try { + // Cache leaderboard data for 5 minutes to reduce Firestore reads + var now = Date.now(); + var useCache = window._lbCache && window._lbCacheTime && (now - window._lbCacheTime < 120000); + let allUsers = []; + if (useCache) { + allUsers = window._lbCache; + } else { + const snap = await db.collection('users').orderBy('points', 'desc').limit(150).get(); + snap.forEach(doc => { + const d = doc.data(); + // Ghost Mode: only show if user is visible OR is the current user themselves + const isMe = auth.currentUser && doc.id === auth.currentUser.uid; + if (d.points > 0 && (!d.ghostMode || isMe)) { + allUsers.push({ id: doc.id, ...d }); + } + }); + window._lbCache = allUsers; + window._lbCacheTime = now; + } + + let html = '
    🏆 Leaderboard — tap to expand
    '; + html += '

    🏆 Leaderboard

    '; + html += '
    '; + html += '
    '; + html += '
    '; + + const showInitial = Math.min(10, allUsers.length); + allUsers.forEach((d, i) => { + const rank = i + 1; + const lv = getLevel(d.points || 0); + const isMe = auth.currentUser && d.id === auth.currentUser.uid; + // Sync local points with Firestore if leaderboard has newer data + if (isMe && currentUser && (d.points || 0) > (currentUser.points || 0)) { + currentUser.points = d.points; + updateRankUI(); + } + const medal = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : '#' + rank; + const hidden = rank > 10 ? ' style="display:none;" class="lb-row lb-extra' + (isMe ? ' lb-me' : '') + '"' : ' class="lb-row' + (isMe ? ' lb-me' : '') + '"'; + var statusDot = typeof onlineStatusDot === 'function' ? onlineStatusDot(d.lastSeen) : ''; + + // Certifications display + let certIcons = ''; + if (d.earnedHidden && d.earnedHidden.includes('cert_scholar')) certIcons += ' 🎓'; + if (d.earnedHidden && d.earnedHidden.includes('cert_tech')) certIcons += ' 🛠️'; + + var _rowPfp = d.profilePic + ? '' + : ''; + var _lbTipData = JSON.stringify({recipientName: d.username || 'Anon', recipientUid: d.id, lightningAddress: d.lightningAddress || d.lightning || '', context: 'leaderboard', label: 'Tip ' + (d.username || 'Anon')}).replace(/'/g, ''').replace(/"/g, '"'); + var _lbNameStyle = d.faction ? window._factionNameStyle(d.faction) : ''; + html += '
    '; + }); + + if (allUsers.length > 10) { + html += ''; + } + html += ''; + + // Badges section + if (typeof getBadgeHTML === 'function') { + html += '

    Your Badges

    ' + getBadgeHTML() + '
    '; + } + + // Level guide + // PVP LEADERBOARD + html += '
    ' + + '
    ' + + '

    ⚔️ PVP Leaderboard

    ' + + '' + + '
    ' + + '
    Loading PVP rankings...
    ' + + '
    '; + + html += '

    Levels

    '; + for (const l of LEVELS) { + html += '
    ' + l.emoji + ' ' + l.name + '' + (l.min === 0 ? '0 XP' : l.min + '+ XP') + '
    '; + } + html += '
    '; + + lb.innerHTML = html; + + // Load PVP leaderboard data asynchronously (must be after innerHTML so DOM element exists) + _loadPVPLeaderboard(); + } catch(e) { + console.error('[Leaderboard] Error:', e); + lb.innerHTML = '
    Error loading leaderboard: ' + (e.message || 'Unknown error') + '
    '; + } +} + +// PVP Leaderboard — loaded after main leaderboard renders, sorted by win % +async function _loadPVPLeaderboard() { + var container = document.getElementById('pvpLeaderboardList'); + if (!container) return; + try { + // Cache PVP leaderboard for 5 minutes + var _pvpNow = Date.now(); + var _pvpCached = window._pvpLbCache && window._pvpLbCacheTime && (_pvpNow - window._pvpLbCacheTime < 300000); + var winsSnap, lossSnap; + if (_pvpCached) { + winsSnap = window._pvpLbCache.wins; + lossSnap = window._pvpLbCache.losses; + } else { + [winsSnap, lossSnap] = await Promise.all([ + db.collection('users').where('pvpWins', '>', 0).orderBy('pvpWins', 'desc').limit(50).get(), + db.collection('users').where('pvpLosses', '>', 0).orderBy('pvpLosses', 'desc').limit(50).get() + ]); + window._pvpLbCache = { wins: winsSnap, losses: lossSnap }; + window._pvpLbCacheTime = _pvpNow; + } + var playerMap = {}; + var myUid = auth.currentUser ? auth.currentUser.uid : null; + function addPlayer(doc) { + if (playerMap[doc.id]) return; + var d = doc.data(); + if (d.ghostMode && doc.id !== myUid) return; + var wins = d.pvpWins || 0; + var losses = d.pvpLosses || 0; + var total = wins + losses; + if (total === 0) return; + var winRate = total > 0 ? (wins / total) * 100 : 0; + playerMap[doc.id] = { id: doc.id, username: escapeHtml(d.username || 'Anon'), wins: wins, losses: losses, total: total, winRate: winRate, isMe: doc.id === myUid, lightningAddress: d.lightningAddress || d.lightning || '' }; + } + winsSnap.forEach(addPlayer); + lossSnap.forEach(addPlayer); + var players = Object.values(playerMap); + if (players.length === 0) { + container.innerHTML = '
    No PVP battles yet — be the first to compete!
    '; + return; + } + players.sort(function(a, b) { return b.winRate - a.winRate || b.wins - a.wins; }); + + var pvpHtml = ''; + players.forEach(function(p, idx) { + var rank = idx + 1; + var medal = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : '#' + rank; + var pvpIcon = p.wins >= 100 ? '👑' : p.wins >= 50 ? '🏆' : p.wins >= 25 ? '🏟️' : p.wins >= 5 ? '🥊' : '⚔️'; + var hidden = rank > 10 ? ' style="display:none;" class="lb-row pvp-lb-extra' + (p.isMe ? ' lb-me' : '') + '"' : ' class="lb-row' + (p.isMe ? ' lb-me' : '') + '"'; + var _pvpTipData = JSON.stringify({recipientName: p.username, recipientUid: p.id, lightningAddress: p.lightningAddress, context: 'pvp', label: 'Tip ' + p.username}).replace(/'/g, ''').replace(/"/g, '"'); + pvpHtml += '