// Discernment training widget — the page that argues for the skill
// gives you a place to practice it.
//
// Each round: 6 statements drawn randomly from a pool. For each, the
// reader picks "Truth" or "Inversion." Immediate feedback with a short
// reason. Final score and a button to play again.
//
// All statement text + reasons are i18n keys so the pool translates
// cleanly with the rest of the site.

(function () {
  const root = document.getElementById("discern");
  if (!root) return;

  const stmtEl  = root.querySelector(".dc-statement");
  const truthBtn = root.querySelector('[data-pick="truth"]');
  const invBtn   = root.querySelector('[data-pick="inversion"]');
  const fbEl     = root.querySelector(".dc-feedback");
  const nextBtn  = root.querySelector(".dc-next");
  const scoreEl  = root.querySelector(".dc-score");
  const replayEl = root.querySelector(".dc-replay");

  // Pool: each item is { id, isTruth, reasonId }.
  // 6 truths + 6 inversions = 12 total. The translation file holds the
  // actual statement + reason text under page.discernment.dc_<id>_stmt /
  // page.discernment.dc_<id>_why.
  const POOL = [
    { id: "t1", isTruth: true,  fallback: "The body knows truth before the mind can analyze it.",
      whyFallback: "Sensed, not reasoned. Recognized in every contemplative tradition." },
    { id: "t2", isTruth: true,  fallback: "Comparison is the engine of dissatisfaction — manufactured, amplified, and sold back to you as ambition.",
      whyFallback: "Without the comparison you would not have noticed you were lacking anything." },
    { id: "t3", isTruth: true,  fallback: "Capture the children and you do not need to capture the adults.",
      whyFallback: "The adults grow up inside the capture and call it normal." },
    { id: "t4", isTruth: true,  fallback: "The Federal Reserve is a privately-owned bank.",
      whyFallback: "Created 1913 on Jekyll Island by representatives of Rothschild, Morgan, Rockefeller. Not federal." },
    { id: "t5", isTruth: true,  fallback: "Antarctica is governed by a treaty that suspends ordinary national sovereignty.",
      whyFallback: "1959 Antarctic Treaty. Independent civilian access to the interior is effectively impossible." },
    { id: "t6", isTruth: true,  fallback: "Operation Mockingbird — CIA-run media coordination of journalists — was officially admitted in 1975.",
      whyFallback: "Church Committee hearings. Names are public. The infrastructure was never dismantled." },

    { id: "f1", isTruth: false, fallback: "The news tells you what is actually happening, accurately and in full.",
      whyFallback: "It tells you what someone wants you to look at — and, just as importantly, what they want you not to." },
    { id: "f2", isTruth: false, fallback: "Authority knows better than you about what is right for your own body.",
      whyFallback: "Authority has its own incentives. Your knowing is yours alone, and no one can knock on the door of your soul but you." },
    { id: "f3", isTruth: false, fallback: "Higher education is primarily about teaching how to think.",
      whyFallback: "Modelled on the Prussian industrial school: rows, bells, age-grading, standardized testing. Produces manageable workers." },
    { id: "f4", isTruth: false, fallback: "Modern processed food is engineered for nourishment.",
      whyFallback: "Engineered to override the body's satiety signals — exact ratios of salt, fat, sugar, texture designed to maximize consumption." },
    { id: "f5", isTruth: false, fallback: "If a treatment is approved by the FDA, it must be safe.",
      whyFallback: "The agency is staffed and steered by the industry it regulates — regulatory capture is the documented norm, not the exception." },
    { id: "f6", isTruth: false, fallback: "If you have nothing to hide, you have nothing to fear from mass surveillance.",
      whyFallback: "The framing was authored by surveillance states to disarm dissent. What you hide is your sovereignty." },

    { id: "t7", isTruth: true,  fallback: "The Tuskegee experiment ran for 40 years on rural Black men told they were being treated, while syphilis was deliberately left untreated.",
      whyFallback: "1932–1972, US Public Health Service. Disclosed by AP reporter Jean Heller in 1972 after a whistleblower — not after the program ended on its own." },
    { id: "t8", isTruth: true,  fallback: "MKUltra used psychiatric patients, prisoners, and unwitting civilians as subjects in CIA mind-control experiments.",
      whyFallback: "1953–1973. Most files destroyed in 1973 on Richard Helms's order. Senate testimony and FOIA-recovered fragments confirm the program." },
    { id: "t9", isTruth: true,  fallback: "Nestlé marketed infant formula to mothers in poor countries by dressing sales reps as nurses.",
      whyFallback: "1970s. Free samples lasted just long enough for the mother's milk to dry up — then she had to keep buying. Babies died from formula mixed with unsafe water." },
    { id: "t10", isTruth: true, fallback: "In the 1960s, sugar industry-funded researchers paid Harvard scientists to shift dietary blame from sugar to fat.",
      whyFallback: "Sugar Research Foundation internal correspondence, recovered in JAMA Internal Medicine 2016. The Harvard papers reshaped US dietary policy for decades." },
    { id: "t11", isTruth: true, fallback: "In the US, vaccine manufacturers cannot be sued for injuries caused by their products.",
      whyFallback: "1986 National Childhood Vaccine Injury Act removed liability and routed claims to a federal program funded by an excise tax on the vaccines themselves." },
    { id: "t12", isTruth: true, fallback: "Silence is a form of communication. Refusing to answer says something the other person reads precisely.",
      whyFallback: "There is no neutral position in a relationship — only choices about what to send." },
    { id: "t13", isTruth: true, fallback: "Most adult opinions were installed before age 12 and never reconsidered.",
      whyFallback: "The mind defends its early frames as if they were the self. Revisiting them feels like a threat to identity, not to a belief." },
    { id: "t14", isTruth: true, fallback: "The same substance can be medicine or poison depending on dose, timing, and the body receiving it.",
      whyFallback: "Paracelsus, 1538: \"The dose makes the poison.\" Standardized dosing is a marketing convenience, not a biological reality." },
    { id: "t15", isTruth: true, fallback: "Forgiveness is a release of debt for your benefit, not the other person's.",
      whyFallback: "It stops the rent the wound was charging your nervous system. The other person rarely notices." },
    { id: "t16", isTruth: true, fallback: "Most pharmaceutical trials are paid for by the company that profits from a positive result.",
      whyFallback: "When the publisher of the science is also the seller of the cure, the science is no longer disinterested." },

    { id: "f7", isTruth: false, fallback: "Voting is the primary way ordinary people influence policy in modern democracies.",
      whyFallback: "Gilens & Page, Princeton 2014: policy outcomes track the preferences of economic elites and organized interests, not ordinary voters." },
    { id: "f8", isTruth: false, fallback: "Mental illness is fundamentally a chemical imbalance in the brain.",
      whyFallback: "Moncrieff et al., Molecular Psychiatry 2022 — the serotonin hypothesis of depression was retired. The chemistry framing was popularized by drug marketing, not proven by data." },
    { id: "f9", isTruth: false, fallback: "Standardized IQ tests measure intelligence in a culture-neutral way.",
      whyFallback: "IQ tests were designed around Western verbal-mathematical reasoning. They reliably measure how well you perform on IQ tests." },
    { id: "f10", isTruth: false, fallback: "If something is illegal, it must be morally wrong.",
      whyFallback: "Slavery was legal. Helping Jews escape Germany was illegal. Law and morality occupy different rooms." },
    { id: "f11", isTruth: false, fallback: "Wars are caused by ideologies clashing.",
      whyFallback: "Wars are caused by who profits from them. The ideologies are recruiting posters." },
    { id: "f12", isTruth: false, fallback: "Mainstream nutrition science is settled and reliable.",
      whyFallback: "Dietary guidelines have inverted multiple times in 60 years — fat, eggs, salt, butter, cholesterol. The constant is funding, not findings." },
    { id: "f13", isTruth: false, fallback: "Children behave badly because they need stricter discipline.",
      whyFallback: "Children behave badly when the adults around them are dysregulated. Discipline imposed by an unsettled adult teaches obedience, not regulation." },
    { id: "f14", isTruth: false, fallback: "Therapy is a neutral, evidence-based process.",
      whyFallback: "The therapist's worldview becomes the implicit frame. \"Evidence-based\" usually means \"easy to measure\" — which excludes most of what matters." },
    { id: "f15", isTruth: false, fallback: "The internet has democratized information.",
      whyFallback: "It has also centralized attention. Five platforms decide what most people see, and the algorithm — not the truth — chooses the order." },
    { id: "f16", isTruth: false, fallback: "The market is free — it rewards the best products.",
      whyFallback: "It rewards what survives the regulatory + advertising + capital filter. The 'best product' rarely makes it through; the most-funded one usually does." },

    { id: "t17", isTruth: true, fallback: "In 1962, the Joint Chiefs of Staff proposed staging attacks on Americans to justify a war with Cuba.",
      whyFallback: "Operation Northwoods, signed by Chairman Lyman Lemnitzer. President Kennedy rejected it. Declassified in 1997 — the plan was real and approved at the top of the military." },
    { id: "t18", isTruth: true, fallback: "The CIA helped funnel cocaine into Los Angeles to fund the Nicaraguan Contras.",
      whyFallback: "Investigative series \"Dark Alliance\" by Gary Webb, San Jose Mercury News 1996. The CIA Inspector General report (1998) confirmed agency knowledge of trafficking ties." },
    { id: "t19", isTruth: true, fallback: "Major tax-exempt foundations shape education and public policy from outside democratic accountability.",
      whyFallback: "Reece Committee, US Congress 1953: documented that Ford, Rockefeller, Carnegie and others steer curriculum and research toward agendas no one voted for." },
    { id: "t20", isTruth: true, fallback: "The most-decorated US Marine of his era publicly admitted: \"I was a high-class muscle man for Big Business, Wall Street, and the bankers.\"",
      whyFallback: "Major General Smedley Butler, War Is a Racket, 1935. Two Medals of Honor. Spoke openly about who actually profits from the wars he was sent to fight." },
    { id: "t21", isTruth: true, fallback: "Pharmaceutical companies are one of the largest categories of US TV advertising.",
      whyFallback: "An outlet that depends on pharma ad revenue cannot run editorially honest pharma criticism. The funder shapes the silence." },
    { id: "t22", isTruth: true, fallback: "Lithium has been proposed and studied for addition to public water supplies for \"population mental health\".",
      whyFallback: "Multiple papers and editorials since Schrauzer & Shrestha (1990) and JAMA Psychiatry commentary (2018) explore municipal water dosing of psychoactive minerals." },
    { id: "t23", isTruth: true, fallback: "You are not your thoughts. Most thoughts are reactive, repetitive, and never chosen.",
      whyFallback: "Awareness can watch a thought arise without being it. The contemplative traditions point at the same thing modern cognitive science calls metacognition." },
    { id: "t24", isTruth: true, fallback: "Boundaries are loving. Saying no to what depletes you is how the relationship survives.",
      whyFallback: "Without a no, the yes means nothing — and resentment quietly replaces care. The boundary protects both people." },
    { id: "t25", isTruth: true, fallback: "Continuous news consumption produces chronic stress-hormone elevation and fragmented attention.",
      whyFallback: "The format — endless urgency, no resolution — keeps the nervous system in low-grade fight-or-flight. The body cannot tell breaking news from a real threat." },
    { id: "t26", isTruth: true, fallback: "Most adults fear being seen more than they fear failing.",
      whyFallback: "The hidden belief: \"if you really saw me you would not love me.\" Most performance is camouflage built around it." },
    { id: "t27", isTruth: true, fallback: "Chronic loneliness affects mortality on the same order as smoking roughly 15 cigarettes a day.",
      whyFallback: "Holt-Lunstad et al. meta-analyses (2010, 2015). Lacking secure connection is not a mood problem — it is a physiological one." },
    { id: "t28", isTruth: true, fallback: "The body stores trauma physiologically, not only psychologically.",
      whyFallback: "Bessel van der Kolk, The Body Keeps the Score, 2014. Talk therapy alone often cannot reach what is held in muscle, breath, and posture." },
    { id: "t29", isTruth: true, fallback: "When a government borrows, future generations pay it back through inflation and taxes.",
      whyFallback: "The debt does not vanish. The cost is shifted onto people who could not vote on the deal, and onto the purchasing power of every saver." },
    { id: "t30", isTruth: true, fallback: "Anger directed accurately at the actual source of harm is healthy. Anger sprayed at proxies is sickness.",
      whyFallback: "Misdirected anger is what abuses spouses and shouts at children. Accurate anger ends an injustice — your own or someone else's." },
    { id: "t31", isTruth: true, fallback: "Gratitude practiced over weeks physically changes what the nervous system notices first.",
      whyFallback: "Repeated attention reshapes neural priors. You see more of whatever you train yourself to look for — by design, not metaphor." },

    { id: "f17", isTruth: false, fallback: "Doctors prescribe independently, based on what is medically best for the patient.",
      whyFallback: "Drug rep visits, sponsored \"continuing education,\" free samples, and ghostwritten guidelines all shape prescribing. The doctor is rarely told they are inside an influence channel." },
    { id: "f18", isTruth: false, fallback: "If you cannot measure it, it is not real.",
      whyFallback: "Love, meaning, beauty, conscience, and grief have all run human lives without ever fitting on an instrument. The ruler is not the only judge of what exists." },
    { id: "f19", isTruth: false, fallback: "The wealthy got there by working harder than everyone else.",
      whyFallback: "The largest determinant of adult wealth is the wealth of the parents, not hours worked. The single mother on two jobs works harder than most heirs." },
    { id: "f20", isTruth: false, fallback: "Your trauma defines you. The past is your identity.",
      whyFallback: "Trauma shaped you; it is not you. Identifying with the wound is one of the most durable ways to keep it." },
    { id: "f21", isTruth: false, fallback: "Anger is always bad. Forgive and move on quickly.",
      whyFallback: "Forgiveness that skips the anger is suppression in a robe. The anger carries information — about a violated boundary or value — that must be heard before it can be released." },
    { id: "f22", isTruth: false, fallback: "Major charities exist to solve problems their own funders had nothing to do with creating.",
      whyFallback: "Many large foundations were endowed by the same industries — food, pharma, finance, fossil — whose externalities the charities now treat. The cycle launders reputation." },
    { id: "f23", isTruth: false, fallback: "The official story of any major event is the complete story.",
      whyFallback: "The official story is the one that survives the editing of multiple stakeholders. Survival is not the same as truth." },
    { id: "f24", isTruth: false, fallback: "Sex is just biology. Nothing energetic or soul-level happens.",
      whyFallback: "Every contemplative tradition disagrees, and people who pay attention to their own bodies disagree. The \"just biology\" frame is a relatively recent — and convenient — flattening." },
    { id: "f25", isTruth: false, fallback: "The afterlife is a comforting story for people afraid of death.",
      whyFallback: "Cross-cultural near-death-experience reports converge on details the dying could not have known — including verifiable ones. The phenomenon is at least more interesting than the dismissal allows." },
    { id: "f26", isTruth: false, fallback: "Aging is purely biological. Mindset has nothing to do with it.",
      whyFallback: "Langer's counterclockwise study (Harvard, 1979) and decades of follow-on research show that perceived age, social role, and environment measurably move biomarkers." },
    { id: "f27", isTruth: false, fallback: "Privacy is dead. Get used to it.",
      whyFallback: "This line was popularized by executives who profit from your data. \"Inevitable\" is what the powerful tell you when they want resistance to feel naive." },
    { id: "f28", isTruth: false, fallback: "Your genes are your destiny.",
      whyFallback: "Epigenetics: which genes express depends on environment, stress, nutrition, and behavior. Identical twins age differently. The blueprint is a draft, not a verdict." },
    { id: "f29", isTruth: false, fallback: "Death is the end. Nothing continues.",
      whyFallback: "Reincarnation cases documented across decades (Stevenson, Tucker, Univ. of Virginia) include verifiable specifics no child could plausibly know. Whether or not you accept the conclusion, the data is not nothing." },
    { id: "f30", isTruth: false, fallback: "Suffering is meaningless. Bear it stoically and shut up.",
      whyFallback: "Suffering felt all the way through reorganizes a person — sometimes into something the comfortable version could never become. Refusing the feeling is what makes it pointless." },
    { id: "f31", isTruth: false, fallback: "Your purpose comes from your job.",
      whyFallback: "Your job is one expression of contribution. Most lives change the world through how they parent, love, attend, and refuse — none of which sit on a payroll." },

    { id: "t32", isTruth: true, fallback: "Banks lend money they do not have. New money is created when a loan is issued and destroyed when it is repaid.",
      whyFallback: "This is how the money supply expands and contracts. \"Putting your money in the bank\" puts most of it into circulation, lent on at interest, while you receive a fraction." },
    { id: "t33", isTruth: true, fallback: "Nixon ended the gold standard in 1971. The US dollar has been pure fiat ever since.",
      whyFallback: "Before 1971, dollars were convertible to gold. After 1971, the dollar's value rests on confidence and military reach, not on any underlying asset." },
    { id: "t34", isTruth: true, fallback: "The Bank for International Settlements is the central bank of central banks, immune from national law.",
      whyFallback: "Headquartered in Basel since 1930. Its premises, archives, and officials are protected by treaty from search, seizure, taxation, and prosecution in the host country." },
    { id: "t35", isTruth: true, fallback: "After WWII, the US secretly imported Nazi scientists into NASA, biological-weapons programs, and intelligence services.",
      whyFallback: "Operation Paperclip, declassified piece by piece since the 1970s. Wernher von Braun (V-2, then Saturn V) was the most public; many others were embedded quietly." },
    { id: "t36", isTruth: true, fallback: "The 1921 Tulsa race massacre — an entire prosperous Black neighborhood burned to the ground by armed white mobs — was systematically left out of US textbooks until the 2000s.",
      whyFallback: "Greenwood district, also known as \"Black Wall Street\". Aerial firebombing was used. Records were sealed, survivors silenced. The official story only began arriving in classrooms about 80 years late." },
    { id: "t37", isTruth: true, fallback: "Peer review filters for conformity with the existing paradigm, not necessarily for truth.",
      whyFallback: "Reviewers are anonymous gatekeepers from the same field with their own funded interests. Papers that overturn the consensus are routinely rejected — sometimes for being right." },
    { id: "t38", isTruth: true, fallback: "Most published findings in psychology, biology, and medicine cannot be replicated.",
      whyFallback: "Ioannidis 2005, \"Why Most Published Research Findings Are False\". Open Science Collaboration 2015: only about a third of psychology results held up. The crisis is named, ongoing, and largely unfixed." },
    { id: "t39", isTruth: true, fallback: "The tobacco industry pioneered the \"doubt science\" playbook. Sugar, oil, and pharma reused the same template.",
      whyFallback: "Manufacture studies, fund \"independent\" experts, attack inconvenient researchers, demand impossible certainty. Documented in Oreskes & Conway, Merchants of Doubt, 2010." },
    { id: "t40", isTruth: true, fallback: "Many men were taught that feeling disqualifies them from being men. The suppression is what breaks them later.",
      whyFallback: "\"Boys cry, men do not\" is not biology, it is conditioning. The cost shows up as numbness, addiction, rage, or suicide statistics no one wants to look at." },
    { id: "t41", isTruth: true, fallback: "Children mirror what is unprocessed in the parent. The \"problem behavior\" often points exactly at the parent's blind spot.",
      whyFallback: "Children pick up the felt sense of the household, not the words. They act out what the adults will not look at." },
    { id: "t42", isTruth: true, fallback: "Sunlight is essential for hormonal regulation, sleep cycles, and vitamin D synthesis.",
      whyFallback: "\"Avoid the sun at all costs\" ignores systemic cost. Indoor lives plus chronic sunblock equal vitamin D deficiency, circadian disruption, and lower mood. The body evolved outside." },
    { id: "t43", isTruth: true, fallback: "About 90% of the body's serotonin is produced in the gut, not the brain.",
      whyFallback: "Mental state and gut health are not separate systems. \"It's all in your head\" gets the geography wrong." },
    { id: "t44", isTruth: true, fallback: "Sleep deprivation has been used both as a torture technique and as a productivity ideal in modern work culture.",
      whyFallback: "The CIA's enhanced interrogation manuals and the modern hustle ethos rely on the same physiology — broken cognition, suppressed emotion, compliance." },
    { id: "t45", isTruth: true, fallback: "Mainstream nutrition orthodoxy on saturated fat, salt, and cholesterol has been reversed in the last 15 years — after decades of being \"settled\".",
      whyFallback: "Butter, eggs, and salt were villains; newer meta-analyses moved them back into the safe column. The pattern is the inversion: certainty, then quiet retraction." },
    { id: "t46", isTruth: true, fallback: "The placebo effect is robust enough that every serious drug trial is designed to control for it.",
      whyFallback: "Belief, expectation, ritual, and care measurably move biological outcomes. That medicine treats this as a nuisance to be cancelled, instead of a phenomenon to be studied, is itself revealing." },

    { id: "f32", isTruth: false, fallback: "Inflation is bad luck. It is just how the economy works.",
      whyFallback: "Inflation is the predictable result of expanding the money supply faster than the goods supply. Someone always benefits — typically whoever spends the new money first, before prices rise." },
    { id: "f33", isTruth: false, fallback: "Central banks are independent of political pressure.",
      whyFallback: "Their boards are appointed by governments and staffed largely by alumni of the institutions they regulate. \"Independent\" describes the brand, not the personnel." },
    { id: "f34", isTruth: false, fallback: "Cash is dirty and inefficient. Digital money is pure progress.",
      whyFallback: "Digital money is also surveilled, programmable, and revocable. Cash has no permission layer. The convenience case is real; the loss is rarely named in the same conversation." },
    { id: "f35", isTruth: false, fallback: "History is a settled, neutral record of what happened.",
      whyFallback: "History is the editing of survivors. What you find in textbooks is what survived political pressure, archive control, and several centuries of revision." },
    { id: "f36", isTruth: false, fallback: "Modern medicine saved more lives than sanitation, nutrition, and clean water did.",
      whyFallback: "Most of the gain in life expectancy from 1800 to 1950 came before antibiotics or vaccines were widespread — from sewers, soap, food, and housing. The credit was reassigned later." },
    { id: "f37", isTruth: false, fallback: "Science is self-correcting and free of institutional bias.",
      whyFallback: "Self-correcting is the ideal. The actual institution selects for funding, careerism, and consensus. Self-correction happens, eventually, after the careers built on the error retire." },
    { id: "f38", isTruth: false, fallback: "Skepticism of an official scientific position automatically makes you anti-science.",
      whyFallback: "Skepticism is science. The label \"anti-science\" is a political tool, not a description of method — it short-circuits the questioning that science requires to function." },
    { id: "f39", isTruth: false, fallback: "Strength means not feeling.",
      whyFallback: "Not feeling is dissociation. Real strength is the capacity to feel everything fully and still act with care." },
    { id: "f40", isTruth: false, fallback: "Children are blank slates. Their problems come from outside the home.",
      whyFallback: "The home is the first \"outside\" the child knows. What is unprocessed there is exactly what gets carried out into school, peers, and adulthood." },
    { id: "f41", isTruth: false, fallback: "\"I had it worse and turned out fine\" is good parenting wisdom.",
      whyFallback: "\"Turned out fine\" usually means \"learned to suppress the cost\". Repeating an inheritance because you survived it is not wisdom — it is the inheritance." },
    { id: "f42", isTruth: false, fallback: "Cholesterol is the cause of heart disease. Lower it at all costs.",
      whyFallback: "The diet-heart hypothesis was always thinner than its certainty. Newer reviews (BMJ, Lancet) find inflammation and insulin resistance are larger drivers — and aggressive statin use has its own costs." },
    { id: "f43", isTruth: false, fallback: "Pain is something to suppress quickly with medication.",
      whyFallback: "Pain is a signal. Suppressing the signal without listening to it is how the underlying problem becomes chronic — and how an opioid crisis becomes possible." },
    { id: "f44", isTruth: false, fallback: "Sunscreen at all doses is universally healthy.",
      whyFallback: "Some sunscreens block the wavelengths required for vitamin D synthesis. Many contain compounds (oxybenzone, octinoxate) under active scrutiny. \"Healthy\" depends on dose, skin, and formulation." },
    { id: "f45", isTruth: false, fallback: "Hard work is the main route to financial security.",
      whyFallback: "It is one route, and rarely the dominant one. Inheritance, capital ownership, networks, and proximity to power produce more wealth than effort does in most economies." },
    { id: "f46", isTruth: false, fallback: "Being busy is the same as being productive.",
      whyFallback: "Most modern work optimizes for the appearance of motion. Productivity is output, not the visible exhaustion that proves you tried." },

    // History +10
    { id: "t47", isTruth: true, fallback: "The FBI ran COINTELPRO — a covert program to discredit, infiltrate, and sabotage civil-rights organizers, including Martin Luther King Jr.",
      whyFallback: "1956–1971. Exposed by the 1971 Citizens' Commission burglary; later confirmed by the Senate Church Committee (1975). MLK was sent an anonymous letter urging him to commit suicide." },
    { id: "t48", isTruth: true, fallback: "US courts legally authorized the forced sterilization of poor, disabled, and \"undesirable\" Americans well into the 1970s.",
      whyFallback: "Buck v. Bell (1927) — Supreme Court ruling never overturned. ~60,000 Americans sterilized under state programs. North Carolina ran its program until 1974." },
    { id: "t49", isTruth: true, fallback: "Japan's Unit 731 ran biowarfare experiments on Chinese, Korean, and Allied prisoners. After the war, the US gave the lead researchers immunity in exchange for their data.",
      whyFallback: "Vivisection, frostbite tests, plague-bomb development. General MacArthur's deal: prosecution dropped in exchange for the data being handed to US Army labs at Fort Detrick." },
    { id: "t50", isTruth: true, fallback: "The British East India Company had its own private army and ran an entire subcontinent as a corporate franchise.",
      whyFallback: "Founded 1600. At peak: 260,000 soldiers — twice the size of the British Army. Ran most of India until 1858. The first corporation to discover that the colour of empire is balance sheet." },
    { id: "t51", isTruth: true, fallback: "King Leopold II of Belgium ran the Congo as personal property; millions died in rubber-extraction atrocities, marketed as a civilizing mission.",
      whyFallback: "1885–1908. Severed hands as a quota-enforcement tool. Estimated 10 million Congolese killed. Edmund Morel and Roger Casement broke the story to a Europe that did not want to hear it." },
    { id: "f47", isTruth: false, fallback: "America's wars are fundamentally about spreading democracy and human rights.",
      whyFallback: "The pattern that actually correlates with intervention is access to resources, currency arrangements, or strategic geography. Smedley Butler said it plainly in 1935 — the staffing has changed, the script has not." },
    { id: "f48", isTruth: false, fallback: "Christopher Columbus discovered America and brought civilization to a barren continent.",
      whyFallback: "Tens of millions of people already lived there, in cities larger than any in Europe at the time. \"Discovered\" means \"first reached by someone whose flag your textbook flies\"." },
    { id: "f49", isTruth: false, fallback: "World War II ended cleanly. The good side won and the bad ideologies were defeated.",
      whyFallback: "Nazi industrialists kept their fortunes. Allied firebombing of Dresden, Tokyo, and Hiroshima killed hundreds of thousands of civilians. The eugenics agenda continued under new names. \"Clean\" is the picture-book version." },
    { id: "f50", isTruth: false, fallback: "Communism just collapsed on its own in 1989–91.",
      whyFallback: "Decades of covert economic and intelligence pressure (Reagan/Casey/CIA, papal channels, Saudi oil flooding, defense-spending arms race) helped collapse the Soviet bloc. Internal rot was real; external help was deliberate." },
    { id: "f51", isTruth: false, fallback: "All major hidden events of the 20th century have been declassified by now.",
      whyFallback: "Most US classified material from before 1970 has never been reviewed for release. Many post-WWII intelligence operations remain sealed beyond declassification deadlines. We know fragments because they leak, not because they release." },

    // Money +4
    { id: "t52", isTruth: true, fallback: "SWIFT — the global payment messaging system — can cut any country off from the international banking system at the behest of the US and EU.",
      whyFallback: "~11,000 financial institutions in 200+ countries. Used as a sanctions weapon against Iran (2012), Russia (2022). When the rails are controlled by one side, the rails are not neutral." },
    { id: "t53", isTruth: true, fallback: "BlackRock, Vanguard, and State Street together hold significant stakes in nearly every major US public company.",
      whyFallback: "\"The Big Three\" combined manage ~$22 trillion. They appear on the top-10 shareholder list of essentially every S&P 500 firm — including each other. Concentration of ownership at this scale has no precedent." },
    { id: "f52", isTruth: false, fallback: "Your taxes pay for government services.",
      whyFallback: "In a fiat system the government issues currency first, then taxes drain it. Tax is more like a thermostat (managing the money supply) than a funding source. \"We can't afford it\" usually means \"we choose not to print for that\"." },
    { id: "f53", isTruth: false, fallback: "Cryptocurrency is just speculation. Nothing real backs it.",
      whyFallback: "Cryptocurrencies are flawed and full of scams; that's true of every emerging asset class. They are also a parallel monetary rail outside central-bank control, which is the actual reason regulators speak about them so urgently." },

    // Body +7
    { id: "t54", isTruth: true, fallback: "Deliberate cold exposure activates brown adipose tissue and reliably shifts metabolic, immune, and mood markers.",
      whyFallback: "Wim Hof's protocols have been peer-reviewed (Kox et al., PNAS 2014) — voluntary cold + breath training measurably influenced inflammation and autonomic responses long assumed to be involuntary." },
    { id: "t55", isTruth: true, fallback: "Habitual mouth breathing in childhood reshapes facial bone structure for life.",
      whyFallback: "Orthotropic research, John Mew and others. Tongue posture against the palate is what shapes the upper jaw outward; mouth breathing during growth produces the long-face/narrow-jaw pattern increasingly common in modern populations." },
    { id: "t56", isTruth: true, fallback: "The skin absorbs what you put on it. Many cosmetic ingredients reach the bloodstream within minutes.",
      whyFallback: "Nicotine patches and hormone creams work because of this. The \"apply only externally\" framing relies on people not noticing the same physics works for parabens, phthalates, oxybenzone, and a long list of common additives." },
    { id: "t57", isTruth: true, fallback: "Fascia is a single continuous web of tissue running through the body. It conducts force, information, and tension from one region to another.",
      whyFallback: "Tom Myers, Anatomy Trains, 2001+. A tight hip can show up as a stiff jaw because the fascia connects them. \"It's all connected\" is a literal anatomical fact, not a metaphor." },
    { id: "f54", isTruth: false, fallback: "Heart disease is purely genetic. There is nothing you can do about it.",
      whyFallback: "Genetics load the gun; environment and behavior pull the trigger. Dean Ornish and Caldwell Esselstyn have both shown angiographic reversal in patients written off as genetically destined for surgery." },
    { id: "f55", isTruth: false, fallback: "More sanitization is always healthier.",
      whyFallback: "Hygiene hypothesis: immune systems calibrate by exposure to microbes. Children raised in sterile environments show higher rates of allergy, asthma, and autoimmune disease. The cost is real and quiet." },
    { id: "f56", isTruth: false, fallback: "All grains are good for you.",
      whyFallback: "Modern wheat (dwarf hybrids since the 1960s) is not the wheat humans co-evolved with. Many people who think they have a gluten issue have a glyphosate issue, a modern-industrial-bread issue, or a hybrid-wheat issue." },

    // Media +11
    { id: "t58", isTruth: true, fallback: "Reuters, AP, and AFP write most of the international news that the world's outlets reprint.",
      whyFallback: "Three wire services. They source 80%+ of \"international coverage\" in most national papers. When three agencies decide a story matters, every outlet downstream agrees." },
    { id: "t59", isTruth: true, fallback: "Six conglomerates own roughly 90% of US media.",
      whyFallback: "Disney, Comcast/NBCU, Warner Bros Discovery, Paramount, Fox, Sony. Down from ~50 companies in 1983 (Bagdikian, The Media Monopoly). Editorial \"diversity\" is a product brand, not a structural reality." },
    { id: "t60", isTruth: true, fallback: "Social-media algorithms are tuned to maximize engagement — typically anger, fear, and outrage — not truth.",
      whyFallback: "Internal Meta documents leaked by Frances Haugen (2021) confirm engagement ranking elevates the most enraging content. The platform reflects whichever emotion holds your scroll longest." },
    { id: "t61", isTruth: true, fallback: "Television uses specific frame rates, edit cadences, and sound design that nudge viewers into mild dissociative states.",
      whyFallback: "Alpha-wave dominance during TV viewing is well documented in EEG literature since the 1970s. The medium is not neutral about your nervous system — it is designed to capture and hold it." },
    { id: "t62", isTruth: true, fallback: "\"Native advertising\" — paid content styled to look like editorial — is now indistinguishable from real reporting in many major outlets.",
      whyFallback: "The disclosures are visually minimal by design. The reader cannot tell what was bought from what was investigated, which is the entire business case for the format." },
    { id: "f57", isTruth: false, fallback: "Fact-checkers are neutral arbiters of truth.",
      whyFallback: "Many \"fact-checking\" operations are funded by the same governments, foundations, or platforms whose narratives they are checking. The label is editorial; the funding is the actual filter." },
    { id: "f58", isTruth: false, fallback: "Big tech defends free speech.",
      whyFallback: "Big tech defends the speech it monetizes, on the platform whose rules it writes, with deplatforming as a routine business decision. The freedom in question is the platform's, not yours." },
    { id: "f59", isTruth: false, fallback: "If it's not in the news, it's not happening.",
      whyFallback: "There are roughly 8 billion people on Earth. Coverage is selection. What's not on the front page is sometimes more important than what is, especially when no one is making money from telling you about it." },
    { id: "f60", isTruth: false, fallback: "Documentaries are objective.",
      whyFallback: "Every documentary is a sequence of edits. The choice of who speaks, what footage to cut, what music to lay underneath — that is the argument. \"Documentary\" is a genre claim about format, not a guarantee of neutrality." },
    { id: "f61", isTruth: false, fallback: "Public broadcasting is the people's voice.",
      whyFallback: "Public broadcasters' boards are appointed by governments or political parties. Editorial direction sits with those appointments. \"Public\" describes the funding mechanism, not editorial independence." },
    { id: "f62", isTruth: false, fallback: "Trust in journalism is high among the public.",
      whyFallback: "US trust in mass media: Gallup tracking shows it at historic lows (~30%). \"Journalist\" routinely ranks at the bottom of trusted-profession polls. The public knows. The institutions know they know." },

    // Pharma +11
    { id: "t63", isTruth: true, fallback: "Antidepressant withdrawal can take months or years and is routinely mislabeled as \"relapse of the original illness\".",
      whyFallback: "Davies & Read 2019 systematic review. Withdrawal symptoms occur in 50–60%+ of long-term users; many last over a year. Mislabeling as relapse keeps people on the drug; the system has no incentive to call it withdrawal." },
    { id: "t64", isTruth: true, fallback: "Statins reduce absolute heart-attack risk by roughly 1–2% over 5 years in most patients.",
      whyFallback: "The famous \"50% reduction\" is relative risk. Absolute numbers from large trials: NNT often 50–100 to prevent one event in primary prevention. The headline number sells; the absolute number tells." },
    { id: "t65", isTruth: true, fallback: "Vioxx (Merck, 1999–2004) killed an estimated 38,000–55,000 Americans before withdrawal. Internal Merck documents show the company knew of cardiac risks years earlier.",
      whyFallback: "Eric Topol, FDA's David Graham. The Lancet called the affair \"one of the worst medical disasters of recent decades\". Merck paid $4.85 billion in settlements. No executive went to prison." },
    { id: "t66", isTruth: true, fallback: "Purdue Pharma and the Sackler family admitted misleading marketing of OxyContin. Settlements have exceeded $8 billion.",
      whyFallback: "The family extracted ~$11 billion from Purdue before bankruptcy. The opioid crisis killed over 500,000 Americans. The Sacklers' personal liability was structured to shield future wealth." },
    { id: "t67", isTruth: true, fallback: "Direct-to-consumer prescription-drug advertising is legal only in the United States and New Zealand.",
      whyFallback: "Every other developed country prohibits it. There is a structural reason every American TV ad break contains pharmaceutical pitches and every European break does not." },
    { id: "f63", isTruth: false, fallback: "The doctor always knows what is best for you.",
      whyFallback: "Doctors know averages, pathologies, and the protocols they were trained in — under heavy pharma influence on the curriculum itself. They do not know you. You live in your body 24/7; they meet it for 12 minutes." },
    { id: "f64", isTruth: false, fallback: "Side effects of most drugs are rare and minor.",
      whyFallback: "Drug adverse events are a leading cause of hospitalization and death in developed countries (BMJ, NEJM analyses). The framing \"side effect\" demotes a primary effect of the drug into a footnote." },
    { id: "f65", isTruth: false, fallback: "Generic drugs are identical to brand-name drugs.",
      whyFallback: "Generics must contain the same active ingredient. They are not required to be identical in fillers, dissolution rate, or bioavailability. For some narrow-therapeutic-index drugs, the difference is clinically significant." },
    { id: "f66", isTruth: false, fallback: "If a pill makes you feel better, it is curing the underlying problem.",
      whyFallback: "Symptom suppression is not cure. Painkillers, antidepressants, and antacids mostly mask. The thing causing the symptom is still doing whatever it was doing. Most chronic disease is managed, not solved, by the pharmaceutical model." },
    { id: "f67", isTruth: false, fallback: "Long approval timelines guarantee a drug is safe.",
      whyFallback: "Vioxx was approved. Thalidomide was approved. The approval timeline reflects an industrial process, not a guarantee. Many drugs are pulled within years of approval — the trial population is rarely the real-world population." },
    { id: "f68", isTruth: false, fallback: "More medicine means more health.",
      whyFallback: "Polypharmacy interactions are now one of the largest categories of iatrogenic harm. Patients on 5+ drugs frequently have symptoms caused by the drug interactions themselves. Adding a drug for the side effect of a drug is a structural pattern, not an exception." },

    // Inner +4
    { id: "t68", isTruth: true, fallback: "You can love someone and still need to leave them.",
      whyFallback: "Staying is not the same as loving. Sometimes leaving is the most loving choice — for them, for you, for the truth of what was actually there." },
    { id: "t69", isTruth: true, fallback: "Most adult \"personality\" is a defensive structure built in childhood to survive what could not be processed.",
      whyFallback: "Personality and character are not the same. Personality is the costume of survival. Character is what is left when the costume is allowed to come off." },
    { id: "f69", isTruth: false, fallback: "Self-improvement will fix the wound.",
      whyFallback: "Many \"self-improvement\" projects are sophisticated avoidance. The wound is not improved away — it is felt, witnessed, and integrated. Optimization is sometimes a way of staying just busy enough to not feel." },
    { id: "f70", isTruth: false, fallback: "If you really loved yourself, you wouldn't feel this.",
      whyFallback: "This is spiritual bypassing in a kind voice. Real self-love does not require you to not feel painful things — it requires you to be there for yourself while you do." },

    // Parenting +15
    { id: "t70", isTruth: true, fallback: "A tantrum is a nervous-system overflow, not manipulation.",
      whyFallback: "A small body cannot hold large emotion. \"Misbehavior\" is usually a regulation crisis. Punishment shames the overflow without teaching the regulation." },
    { id: "t71", isTruth: true, fallback: "A baby cannot be \"spoiled\" by being held.",
      whyFallback: "Held babies develop more secure attachment, lower stress markers, and better self-regulation later. The \"don't pick them up too much\" advice is a cultural fashion (Behaviorism, 1920s–40s), not a developmental finding." },
    { id: "t72", isTruth: true, fallback: "A child's nervous system co-regulates from the adult's. You cannot teach calm from a state of chaos.",
      whyFallback: "The adult brain is what stabilizes the child brain through proximity, voice, breath, and presence. If the adult is dysregulated, the child has no anchor. Self-regulation is downstream of co-regulation." },
    { id: "t73", isTruth: true, fallback: "Screens in the first years of life interrupt brain development.",
      whyFallback: "AAP and WHO both recommend zero screen time before 18–24 months. Real-time face-to-face interaction is what builds the early neural architecture for language, attention, and bonding. Screens do not provide it." },
    { id: "t74", isTruth: true, fallback: "The mother's nervous system regulates the infant's nervous system long before any words.",
      whyFallback: "Heart rate, breath, hormones, gaze, and tone — all synchronized through proximity. Maternal stress is felt by the baby directly, not abstractly. This is biology, not metaphor." },
    { id: "t75", isTruth: true, fallback: "Children copy what they see, not what they're told.",
      whyFallback: "Mirror neurons. Children inherit the adults' nervous-system patterns long before they parse the adults' words. \"Do as I say, not as I do\" is an instruction the brain has no machinery to follow." },
    { id: "t76", isTruth: true, fallback: "A father's presence is irreplaceable — not the same as the mother's, but essential differently.",
      whyFallback: "Different role, different chemistry, different signaling. Boys without engaged fathers face higher rates of every adverse outcome measured; girls without engaged fathers carry different costs. \"Two parents are the same\" flattens the data." },
    { id: "f71", isTruth: false, fallback: "Babies should be left to cry it out so they learn to self-soothe.",
      whyFallback: "Infants left to cry alone have measurably elevated cortisol that persists after they fall silent. \"Self-soothed\" usually means \"gave up trying to be answered\". The lesson learned is that calling for help does not work." },
    { id: "f72", isTruth: false, fallback: "Children need to learn the world is harsh early.",
      whyFallback: "The world will deliver enough harshness on its own. The home is supposed to be the calibration baseline, not a preview of the worst the world has to offer. Premature exposure produces dysregulation, not resilience." },
    { id: "f73", isTruth: false, fallback: "Modern parenting is too soft.",
      whyFallback: "What looks like \"soft\" is usually responsive parenting. The previous default — distant fathers, shaming, beatings — produced the generations now in therapy. \"Hard\" did not make stable adults. It made people who hide it well." },
    { id: "f74", isTruth: false, fallback: "Schools know how to raise your child better than you do.",
      whyFallback: "Schools are institutions optimized for batch processing, behavior management, and curriculum compliance. They produce credentialed workers; they were not designed to grow soul. Schools have a role; that role is not parent." },
    { id: "f75", isTruth: false, fallback: "Too much affection makes a child weak.",
      whyFallback: "Affection is the regulation system that lets a child develop strength. The opposite of affection is not strength — it is brittleness, performance, and a lifetime spent looking for what was withheld." },
    { id: "f76", isTruth: false, fallback: "Spanking builds character.",
      whyFallback: "Decades of longitudinal data: corporal punishment correlates with worse impulse control, more aggression, weaker bonding, and higher anxiety. The \"character\" the spanking produced is usually compliance, not character." },
    { id: "f77", isTruth: false, fallback: "Children misbehave because they are naughty.",
      whyFallback: "Children behave the way their nervous systems can manage given their developmental stage and their environment. \"Naughty\" is a moral judgment applied to what is usually a regulatory event." },
    { id: "f78", isTruth: false, fallback: "Boys and girls are blank slates with no innate differences.",
      whyFallback: "Even controlled cross-cultural studies show consistent average differences in preference, attention, and play patterns from infancy onward. Recognizing this is not the same as enforcing rigid roles — but pretending there is no difference is a different kind of denial." },

    // Mind +6
    { id: "t77", isTruth: true, fallback: "Belief shapes perception. You literally see more of what you expect.",
      whyFallback: "Predictive-coding models of the brain: perception is partly hallucination constrained by sensory input. The brain shows you a version of the world consistent with its priors. This is not failure of perception — it is how perception works." },
    { id: "t78", isTruth: true, fallback: "Memory is reconstructive, not a recording. It rewrites every time you recall.",
      whyFallback: "Reconsolidation research, Karim Nader 2000+. Each recall makes the memory editable. Eyewitness testimony has been the basis of countless wrongful convictions; the \"replay\" framing is not how memory works." },
    { id: "t79", isTruth: true, fallback: "Language shapes thought. The words you don't have constrain the thoughts you can hold.",
      whyFallback: "Sapir–Whorf in mild form is well-supported. People who do not have a word for a concept (\"saudade\", \"hygge\", \"emergence\") tend to have less access to the experience itself. Vocabulary is not decoration. It is scaffolding." },
    { id: "f79", isTruth: false, fallback: "Consciousness is purely a product of the brain.",
      whyFallback: "This is metaphysics, not science. The \"hard problem of consciousness\" (Chalmers 1995) is not solved. Several reasonable positions exist; calling one of them the settled answer is a philosophy choice masquerading as a finding." },
    { id: "f80", isTruth: false, fallback: "Critical thinking and skepticism are the same thing.",
      whyFallback: "Critical thinking weighs evidence in every direction. Skepticism only doubts the position you have decided to doubt. They look identical from outside; they are different operations." },
    { id: "f81", isTruth: false, fallback: "If something lacks scientific consensus, it isn't real.",
      whyFallback: "Continental drift, hand-washing, ulcers from bacteria, gut microbiome — all sat outside consensus for decades while being entirely real. Consensus is the lagging indicator, not the verification." },
  ];

  // Per-statement primary category. Each statement gets one. "all" pool is
  // synthesized at runtime (every entry).
  const STATEMENT_CAT = {
    t1: "inner",  t2: "media",   t3: "parenting", t4: "money",   t5: "history", t6: "media",
    f1: "media",  f2: "inner",   f3: "history",   f4: "body",    f5: "pharma",  f6: "media",
    t7: "history", t8: "history", t9: "history",  t10: "pharma", t11: "pharma", t12: "inner",
    t13: "inner", t14: "mind",   t15: "inner",    t16: "pharma",
    f7: "money",  f8: "pharma",  f9: "mind",      f10: "mind",   f11: "money",  f12: "body",
    f13: "parenting", f14: "mind", f15: "media",  f16: "money",
    t17: "history", t18: "history", t19: "money", t20: "money",  t21: "media",  t22: "pharma",
    t23: "mind",  t24: "inner",  t25: "media",    t26: "inner",  t27: "inner",  t28: "body",
    t29: "money", t30: "inner",  t31: "mind",
    f17: "pharma", f18: "mind",  f19: "money",    f20: "inner",  f21: "inner",  f22: "money",
    f23: "media", f24: "body",   f25: "mind",     f26: "body",   f27: "media",  f28: "body",
    f29: "mind",  f30: "inner",  f31: "inner",
    t32: "money", t33: "money",  t34: "money",    t35: "history", t36: "history",
    t37: "mind",  t38: "mind",   t39: "pharma",   t40: "inner",  t41: "parenting",
    t42: "body",  t43: "body",   t44: "body",     t45: "body",   t46: "mind",
    f32: "money", f33: "money",  f34: "money",    f35: "history", f36: "pharma",
    f37: "mind",  f38: "mind",   f39: "inner",    f40: "parenting", f41: "parenting",
    f42: "body",  f43: "body",   f44: "body",     f45: "money",  f46: "inner",
    // History +10
    t47: "history", t48: "history", t49: "history", t50: "history", t51: "history",
    f47: "history", f48: "history", f49: "history", f50: "history", f51: "history",
    // Money +4
    t52: "money", t53: "money", f52: "money", f53: "money",
    // Body +7
    t54: "body", t55: "body", t56: "body", t57: "body",
    f54: "body", f55: "body", f56: "body",
    // Media +11
    t58: "media", t59: "media", t60: "media", t61: "media", t62: "media",
    f57: "media", f58: "media", f59: "media", f60: "media", f61: "media", f62: "media",
    // Pharma +11
    t63: "pharma", t64: "pharma", t65: "pharma", t66: "pharma", t67: "pharma",
    f63: "pharma", f64: "pharma", f65: "pharma", f66: "pharma", f67: "pharma", f68: "pharma",
    // Inner +4
    t68: "inner", t69: "inner", f69: "inner", f70: "inner",
    // Parenting +15
    t70: "parenting", t71: "parenting", t72: "parenting", t73: "parenting",
    t74: "parenting", t75: "parenting", t76: "parenting",
    f71: "parenting", f72: "parenting", f73: "parenting", f74: "parenting",
    f75: "parenting", f76: "parenting", f77: "parenting", f78: "parenting",
    // Mind +6
    t77: "mind", t78: "mind", t79: "mind",
    f79: "mind", f80: "mind", f81: "mind",
  };

  // Category metadata (visible labels come from i18n).
  const CATEGORIES = [
    { id: "all",       icon: "✦" },
    { id: "history",   icon: "⌖" },
    { id: "money",     icon: "◈" },
    { id: "body",      icon: "✺" },
    { id: "media",     icon: "◉" },
    { id: "pharma",    icon: "✚" },
    { id: "inner",     icon: "❤" },
    { id: "parenting", icon: "✿" },
    { id: "mind",      icon: "✧" },
  ];

  const CAT_STORAGE_KEY = "wuys-dc-cat";
  function loadCat() {
    try {
      const v = localStorage.getItem(CAT_STORAGE_KEY);
      if (v && CATEGORIES.some(c => c.id === v)) return v;
    } catch (e) {}
    return null;
  }
  function saveCat(v) {
    try {
      if (v) localStorage.setItem(CAT_STORAGE_KEY, v);
      else localStorage.removeItem(CAT_STORAGE_KEY);
    } catch (e) {}
  }

  let activeCategory = null; // null = hub view, non-null = inside a category

  // Token substitution for dynamic counts in i18n strings.
  // {n} = pool size, {c} = number of real categories (excluding "all").
  function substituteTokens(str) {
    if (!str) return str;
    const catN = CATEGORIES.filter(c => c.id !== "all").length;
    return String(str).replace(/\{n\}/g, POOL.length).replace(/\{c\}/g, catN);
  }
  function applyDcTokens() {
    document.querySelectorAll(".dc-tokens").forEach(el => {
      el.textContent = substituteTokens(el.textContent);
    });
  }

  function poolForCategory(catId) {
    if (!catId || catId === "all") return POOL.slice();
    return POOL.filter(p => STATEMENT_CAT[p.id] === catId);
  }

  function countForCategory(catId) {
    return catId === "all" ? POOL.length : poolForCategory(catId).length;
  }

  const SIZE_STORAGE_KEY = "wuys-dc-size";
  const DEFAULT_SIZE = 6;

  function loadSize() {
    try {
      const raw = localStorage.getItem(SIZE_STORAGE_KEY);
      if (raw === "all") return "all";
      const n = parseInt(raw, 10);
      if (n === 6 || n === 12 || n === 20) return n;
    } catch (e) {}
    return DEFAULT_SIZE;
  }
  function saveSize(v) {
    try { localStorage.setItem(SIZE_STORAGE_KEY, String(v)); } catch (e) {}
  }

  let roundSize = loadSize();
  function effectiveRoundSize() {
    const cap = activeCategory ? countForCategory(activeCategory) : POOL.length;
    return roundSize === "all" ? cap : Math.min(roundSize, cap);
  }

  let queue = [];
  let cur = null;
  let correct = 0;
  let answered = 0;
  let awaiting = true;

  function t(key, fallback) {
    return (window.i18n && window.i18n.t) ? window.i18n.t(key, fallback) : fallback;
  }

  function shuffle(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
  }

  let activeSize = effectiveRoundSize();

  // Tier system: maps a 0..1 score ratio to a named tier with a one-liner.
  // Order matters — first match wins.
  const TIERS = [
    { min: 0.96, key: "witness",        nameKey: "page.discernment.tier_witness_name",  descKey: "page.discernment.tier_witness_desc",
      nameFallback: "Witness",         descFallback: "Almost nothing fools you. Even the elegant inversions show their seam." },
    { min: 0.86, key: "sovereign",      nameKey: "page.discernment.tier_sovereign_name", descKey: "page.discernment.tier_sovereign_desc",
      nameFallback: "Sovereign Sight", descFallback: "Very little slips past you. You see the architecture of the lie." },
    { min: 0.71, key: "discerning",     nameKey: "page.discernment.tier_discerning_name", descKey: "page.discernment.tier_discerning_desc",
      nameFallback: "Discerning",      descFallback: "You can tell true from inverted reliably. The cage is visible from here." },
    { min: 0.51, key: "awakening",      nameKey: "page.discernment.tier_awakening_name", descKey: "page.discernment.tier_awakening_desc",
      nameFallback: "Awakening",       descFallback: "Discernment is forming. The body is starting to know before the mind does." },
    { min: 0.31, key: "stirring",       nameKey: "page.discernment.tier_stirring_name", descKey: "page.discernment.tier_stirring_desc",
      nameFallback: "Stirring",        descFallback: "Something is waking. The signal is faint, but you heard it." },
    { min: 0.00, key: "asleep",         nameKey: "page.discernment.tier_asleep_name",   descKey: "page.discernment.tier_asleep_desc",
      nameFallback: "Asleep",          descFallback: "Most of the lies still feel like truth. Almost everyone starts here. Start with the books." },
  ];

  function tierFor(ratio) {
    for (const tier of TIERS) {
      if (ratio >= tier.min) return tier;
    }
    return TIERS[TIERS.length - 1];
  }

  function bestKeyFor(catId) {
    return "wuys-dc-best-" + (catId || "all");
  }
  function loadBest(catId) {
    try {
      const raw = localStorage.getItem(bestKeyFor(catId));
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      if (typeof parsed.ratio === "number" && typeof parsed.size === "number") return parsed;
    } catch (e) {}
    return null;
  }
  function saveBest(catId, ratio, size) {
    try { localStorage.setItem(bestKeyFor(catId), JSON.stringify({ ratio, size })); } catch (e) {}
  }
  function maybeUpdateBest(catId, ratio, size) {
    const prev = loadBest(catId);
    if (!prev || ratio > prev.ratio) saveBest(catId, ratio, size);
  }

  function renderTier(correct, total) {
    const tierEl = document.getElementById("dc-tier");
    if (!tierEl) return;
    const ratio = total > 0 ? correct / total : 0;
    const tier = tierFor(ratio);
    const labelEl = document.getElementById("dc-tier-label");
    const nameEl = document.getElementById("dc-tier-name");
    const descEl = document.getElementById("dc-tier-desc");
    const bestEl = document.getElementById("dc-tier-best");
    if (labelEl) labelEl.textContent = t("page.discernment.tier_label", "Your reading");
    if (nameEl) {
      nameEl.textContent = t(tier.nameKey, tier.nameFallback);
      nameEl.dataset.tier = tier.key;
    }
    if (descEl) descEl.textContent = t(tier.descKey, tier.descFallback);

    const catKey = activeCategory || "all";
    maybeUpdateBest(catKey, ratio, total);
    const best = loadBest(catKey);
    if (bestEl && best) {
      const pct = Math.round(best.ratio * 100);
      bestEl.textContent = t("page.discernment.tier_best_prefix", "Best so far: ") + pct + "%";
    } else if (bestEl) {
      bestEl.textContent = "";
    }
    tierEl.hidden = false;
  }
  function hideTier() {
    const tierEl = document.getElementById("dc-tier");
    if (tierEl) tierEl.hidden = true;
  }

  function nextRound() {
    activeSize = effectiveRoundSize();
    const pool = poolForCategory(activeCategory);
    queue = shuffle(pool).slice(0, activeSize);
    correct = 0;
    answered = 0;
    replayEl.classList.remove("visible");
    hideTier();
    updateProgress(0);
    pickNext();
  }

  function updateProgress(done) {
    const fill = document.getElementById("dc-progress-fill");
    if (!fill) return;
    const pct = activeSize > 0 ? Math.round((done / activeSize) * 100) : 0;
    fill.style.width = pct + "%";
  }

  function pickNext() {
    if (queue.length === 0) {
      const total = activeSize;
      const passThreshold = Math.ceil(total * 0.83);
      const okThreshold = Math.ceil(total * 0.5);
      stmtEl.textContent = t("page.discernment.dc_round_done", "Round complete.");
      fbEl.textContent = correct + " / " + total + " " + t("page.discernment.dc_correct_n", "correct");
      fbEl.className = "dc-feedback show " + (correct >= passThreshold ? "good" : (correct >= okThreshold ? "ok" : "bad"));
      truthBtn.disabled = invBtn.disabled = true;
      nextBtn.classList.remove("visible");
      replayEl.classList.add("visible");
      updateScore(true);
      renderTier(correct, total);
      return;
    }
    cur = queue.shift();
    awaiting = true;
    stmtEl.textContent = t("page.discernment.dc_" + cur.id + "_stmt", cur.fallback);
    fbEl.textContent = "";
    fbEl.className = "dc-feedback";
    truthBtn.disabled = invBtn.disabled = false;
    nextBtn.classList.remove("visible");
    truthBtn.classList.remove("right", "wrong");
    invBtn.classList.remove("right", "wrong");
    updateScore(false);
  }

  function updateScore(final) {
    const idxOfCur = activeSize - queue.length; // 1..activeSize while answering
    if (final) {
      scoreEl.textContent = "";
      updateProgress(activeSize);
    } else {
      scoreEl.textContent = idxOfCur + " / " + activeSize + "   ·   " + correct + " " + t("page.discernment.dc_right", "right");
      // idxOfCur reflects the statement now being asked; progress fills as
      // they're completed, so subtract 1 (or use answered count).
      updateProgress(answered);
    }
  }

  function answer(pickedTruth) {
    if (!awaiting || !cur) return;
    awaiting = false;
    answered++;
    const isCorrect = pickedTruth === cur.isTruth;
    if (isCorrect) correct++;

    const pickedBtn = pickedTruth ? truthBtn : invBtn;
    const otherBtn  = pickedTruth ? invBtn   : truthBtn;
    pickedBtn.classList.add(isCorrect ? "right" : "wrong");
    if (!isCorrect) {
      (cur.isTruth ? truthBtn : invBtn).classList.add("right");
    }
    truthBtn.disabled = invBtn.disabled = true;

    const why = t("page.discernment.dc_" + cur.id + "_why", cur.whyFallback);
    const verdict = isCorrect
      ? t("page.discernment.dc_correct", "Correct.")
      : (cur.isTruth
          ? t("page.discernment.dc_was_truth", "That one was truth.")
          : t("page.discernment.dc_was_inversion", "That one was an inversion."));
    fbEl.innerHTML = '<strong>' + verdict + '</strong> ' + why;
    fbEl.className = "dc-feedback show " + (isCorrect ? "good" : "bad");
    nextBtn.classList.add("visible");
  }

  // ==========================================================================
  // Quiz Hub — category landing
  // ==========================================================================

  const hubEl = document.getElementById("quiz-hub");
  const stageEl = document.getElementById("quiz-stage");
  const stageCatEl = document.getElementById("quiz-stage-cat");
  const backBtn = document.getElementById("quiz-back");

  function renderHubCards() {
    const grid = document.getElementById("quiz-hub-grid");
    if (!grid) return;
    grid.innerHTML = CATEGORIES.map((cat) => {
      const count = countForCategory(cat.id);
      const best = loadBest(cat.id);
      const bestStr = best
        ? t("quiz.hub.best_pct", "Best: ") + Math.round(best.ratio * 100) + "%"
        : t("quiz.hub.best_none", "Best: —");
      const countStr = count + " " + t("quiz.hub.statements_n", "statements");
      const name = t("quiz.cat." + cat.id + ".name", cat.id);
      const desc = substituteTokens(t("quiz.cat." + cat.id + ".desc", ""));
      return ''
        + '<button class="quiz-cat-card" data-quiz-cat="' + cat.id + '" data-cat-tone="' + cat.id + '" type="button">'
        + '  <div class="quiz-cat-icon" aria-hidden="true">' + cat.icon + '</div>'
        + '  <div class="quiz-cat-body">'
        + '    <div class="quiz-cat-name">' + name + '</div>'
        + '    <div class="quiz-cat-desc">' + desc + '</div>'
        + '  </div>'
        + '  <div class="quiz-cat-meta">'
        + '    <span class="quiz-cat-count">' + countStr + '</span>'
        + '    <span class="quiz-cat-best">' + bestStr + '</span>'
        + '  </div>'
        + '</button>';
    }).join("");
  }

  function showHub() {
    activeCategory = null;
    saveCat(null);
    if (hubEl) hubEl.hidden = false;
    if (stageEl) stageEl.hidden = true;
    renderHubCards();
  }

  function showStage(catId) {
    activeCategory = catId;
    saveCat(catId);
    if (hubEl) hubEl.hidden = true;
    if (stageEl) stageEl.hidden = false;
    if (stageCatEl) {
      const cat = CATEGORIES.find(c => c.id === catId);
      stageCatEl.dataset.catTone = catId;
      stageCatEl.innerHTML = '<span class="quiz-stage-icon">' + (cat ? cat.icon : '✦') + '</span><span>' + t("quiz.cat." + catId + ".name", catId) + '</span>';
    }
    // Refresh "All · N" label to category's actual count when filtered.
    const allBtn = root.querySelector('.dc-size-btn[data-size="all"]');
    if (allBtn) {
      const count = countForCategory(catId);
      allBtn.textContent = t("page.discernment.dc_size_all_prefix", "All · ") + count;
    }
    nextRound();
  }

  if (hubEl) {
    hubEl.addEventListener("click", (ev) => {
      const card = ev.target.closest("[data-quiz-cat]");
      if (!card) return;
      showStage(card.dataset.quizCat);
    });
  }
  if (backBtn) {
    backBtn.addEventListener("click", showHub);
  }

  // Wire.
  truthBtn.addEventListener("click", () => answer(true));
  invBtn  .addEventListener("click", () => answer(false));
  nextBtn .addEventListener("click", pickNext);
  replayEl.addEventListener("click", nextRound);

  // Round-size selector
  const sizeButtons = root.querySelectorAll(".dc-size-btn");
  function paintSizeButtons() {
    sizeButtons.forEach((btn) => {
      const v = btn.dataset.size === "all" ? "all" : parseInt(btn.dataset.size, 10);
      btn.classList.toggle("active", v === roundSize);
      btn.setAttribute("aria-pressed", v === roundSize ? "true" : "false");
    });
  }
  paintSizeButtons();
  sizeButtons.forEach((btn) => {
    btn.addEventListener("click", () => {
      const v = btn.dataset.size === "all" ? "all" : parseInt(btn.dataset.size, 10);
      if (v === roundSize) return;
      roundSize = v;
      saveSize(v);
      paintSizeButtons();
      nextRound();
    });
  });

  // Background music: opt-in, off by default. Volume persisted, not auto-played.
  (function setupAudio() {
    const audio = document.getElementById("dc-audio");
    const toggle = document.getElementById("dc-audio-toggle");
    const slider = document.getElementById("dc-audio-volume");
    if (!audio || !toggle || !slider) return;

    const VOL_KEY = "wuys-dc-music-vol";
    const ON_KEY = "wuys-dc-music-on";

    function loadVol() {
      try { const v = parseInt(localStorage.getItem(VOL_KEY), 10); if (v >= 0 && v <= 100) return v; } catch (e) {}
      return 50;
    }
    function loadOn() {
      try { return localStorage.getItem(ON_KEY) === "1"; } catch (e) {}
      return false;
    }
    function saveVol(v) { try { localStorage.setItem(VOL_KEY, String(v)); } catch (e) {} }
    function saveOn(on) { try { localStorage.setItem(ON_KEY, on ? "1" : "0"); } catch (e) {} }

    let vol = loadVol();
    let on = loadOn();
    slider.value = vol;
    audio.volume = vol / 100;
    slider.disabled = !on;
    toggle.classList.toggle("active", on);
    toggle.setAttribute("aria-pressed", on ? "true" : "false");

    // Only resume playback on enter if user has explicitly turned it on AND
    // the tab is currently on the discernment view. Browsers also require a
    // user gesture before play(); the first toggle click provides that.
    function isDiscernActive() {
      const v = document.querySelector('[data-view="quiz"]');
      return v && v.classList.contains("active");
    }

    function play() {
      if (audio.paused) {
        const p = audio.play();
        if (p && typeof p.catch === "function") p.catch(() => {});
      }
    }
    function pause() {
      if (!audio.paused) audio.pause();
    }

    toggle.addEventListener("click", () => {
      on = !on;
      saveOn(on);
      toggle.classList.toggle("active", on);
      toggle.setAttribute("aria-pressed", on ? "true" : "false");
      slider.disabled = !on;
      if (on) play(); else pause();
    });

    slider.addEventListener("input", () => {
      vol = parseInt(slider.value, 10) || 0;
      audio.volume = vol / 100;
      saveVol(vol);
    });

    // Pause when the user leaves the discernment view; resume only if they
    // explicitly had it on.
    window.addEventListener("hashchange", () => {
      if (!isDiscernActive()) pause();
      else if (on) play();
    });
    // Also re-check after nav-link clicks that don't change the hash.
    document.body.addEventListener("click", (ev) => {
      if (ev.target.closest('[data-view]')) {
        setTimeout(() => {
          if (!isDiscernActive()) pause();
          else if (on) play();
        }, 50);
      }
    });
  })();

  window.addEventListener("langchange", () => {
    // Re-render the active statement + feedback in new language.
    if (cur && awaiting) {
      stmtEl.textContent = t("page.discernment.dc_" + cur.id + "_stmt", cur.fallback);
    }
    // Re-paint hub cards (category names + counts use t()).
    if (hubEl && !hubEl.hidden) renderHubCards();
    // Re-paint stage header if visible.
    if (stageEl && !stageEl.hidden && activeCategory && stageCatEl) {
      const cat = CATEGORIES.find(c => c.id === activeCategory);
      stageCatEl.innerHTML = '<span class="quiz-stage-icon">' + (cat ? cat.icon : '✦') + '</span><span>' + t("quiz.cat." + activeCategory + ".name", activeCategory) + '</span>';
    }
    // After i18n has rewritten textContent in lang-switch, substitute {n}/{c}.
    applyDcTokens();
  });

  // Default: show the Hub. (No auto-start of a round — user picks a category.)
  showHub();
  // Initial token substitution (i18n applies its strings on DOMContentLoaded,
  // we run after to swap {n}/{c} for the live numbers).
  applyDcTokens();
})();
