// ----- Shared React helpers + example pool + community data (all simulated) -----
const { useState, useEffect, useMemo, useRef } = React;

// 12 designer-ready example trials. `expect` is the effect range the generator
// states at the end (based on "similar trials"); no user-facing power slider.
window.EXAMPLES = [
  { id: "curfew", q: "Does a screen curfew after 22:00 shorten my time to fall asleep?", m: "Sleep · any wearable · 4 weeks",
    outcomeLabel: "Minutes to fall asleep", unit: "min", source: "wear", days: 28,
    expect: "5 to 15 minutes faster sleep onset" },
  { id: "daylight", q: "Does 10 minutes of morning daylight increase my energy?", m: "Energy · self-report · 4 weeks",
    outcomeLabel: "Daily energy (1–10, evening rating)", unit: "pts", source: "self", days: 28,
    expect: "0.5 to 2 points higher daily energy" },
  { id: "dinner", q: "Does finishing dinner before 18:30 improve my overnight HRV?", m: "Recovery · Whoop / Oura · 4 weeks",
    outcomeLabel: "Overnight HRV (rMSSD)", unit: "ms", source: "wear", days: 28,
    expect: "2 to 8 ms higher overnight HRV" },
  { id: "magnesium", q: "Does 200 mg magnesium before bed increase my deep sleep?", m: "Sleep · Oura / Apple Watch · 4 weeks",
    outcomeLabel: "Minutes of deep sleep", unit: "min", source: "wear", days: 28,
    expect: "8 to 20 minutes more deep sleep" },
  { id: "caffeine", q: "Does caffeine after 14:00 delay my sleep onset?", m: "Sleep · any wearable · 3 weeks",
    outcomeLabel: "Minutes to fall asleep", unit: "min", source: "wear", days: 28,
    expect: "6 to 14 minutes faster sleep onset with a cutoff" },
  { id: "walk", q: "Does a 20-minute walk after dinner lower my resting heart rate?", m: "Heart · any wearable · 4 weeks",
    outcomeLabel: "Resting heart rate", unit: "bpm", source: "wear", days: 28,
    expect: "2 to 6 bpm lower resting heart rate" },
  { id: "creatine", q: "Does creatine increase my weekly training volume?", m: "Fitness · self-report · 6 weeks",
    outcomeLabel: "Weekly training volume", unit: "kg", source: "self", days: 42,
    expect: "5 to 12% more weekly volume" },
  { id: "dairy", q: "Does cutting dairy reduce my bloating?", m: "Gut · self-report · 4 weeks",
    outcomeLabel: "Bloating episodes per week", unit: "days", source: "self", days: 28,
    expect: "1 to 4 fewer episodes per week" },
  { id: "meditation", q: "Does 10 minutes of morning meditation lower my stress?", m: "Mood · self-report · 4 weeks",
    outcomeLabel: "Perceived stress (1–10)", unit: "pts", source: "self", days: 28,
    expect: "0.5 to 2 points lower perceived stress" },
  { id: "coldshower", q: "Do cold showers improve my morning mood?", m: "Mood · self-report · 3 weeks",
    outcomeLabel: "Morning mood (1–10)", unit: "pts", source: "self", days: 28,
    expect: "anywhere from no effect to +1.5 points; many find nothing" },
  { id: "breathwork", q: "Does 5 minutes of slow breathing before bed shorten my sleep onset?", m: "Sleep · any wearable · 3 weeks",
    outcomeLabel: "Minutes to fall asleep", unit: "min", source: "wear", days: 28,
    expect: "4 to 10 minutes faster sleep onset" },
  { id: "nap", q: "Do afternoon naps hurt my sleep quality that night?", m: "Sleep · any wearable · 4 weeks",
    outcomeLabel: "Sleep efficiency", unit: "%", source: "wear", days: 28,
    expect: "0 to 5 percentage points lower sleep efficiency" },
];

window.DEVICES = ["Oura Ring", "Apple Watch", "Fitbit", "Garmin", "Whoop", "Samsung Galaxy Watch", "Polar", "Withings ScanWatch", "Google Pixel Watch", "Coros", "Amazfit", "Self-report only"];

// Community feed: 12 pooled trials. runsN/effVal/days drive working sort + search.
window.COMMUNITY = [
  { who: "quietowl", init: "QO", col: "#39566e", days: 2, status: "recruiting", runsN: 412, effVal: 18,
    q: "Does 200 mg magnesium before bed increase deep sleep?", tags: ["Sleep", "ABAB", "4 weeks"],
    eff: "+18% deep sleep", effCol: "good", spark: [58, 60, 59, 62, 71, 73, 72, 75] },
  { who: "sentigern", init: "SG", col: "#5e4a6e", days: 5, status: "complete", runsN: 208, effVal: 34,
    q: "Does caffeine after 14:00 delay sleep onset?", tags: ["Sleep", "Alternating days", "3 weeks"],
    eff: "−34% sleep onset", effCol: "good", spark: [34, 33, 31, 30, 24, 22, 23, 21] },
  { who: "skaermfri", init: "SF", col: "#3f5e6e", days: 1, status: "recruiting", runsN: 389, effVal: 38,
    q: "Does a screen curfew after 22:00 shorten time to fall asleep?", tags: ["Sleep", "ABAB", "4 weeks"],
    eff: "−38% sleep onset", effCol: "good", spark: [29, 28, 30, 27, 19, 17, 18, 16] },
  { who: "morgenlys", init: "ML", col: "#6e5a3f", days: 3, status: "recruiting", runsN: 271, effVal: 24,
    q: "Does 10 minutes of morning daylight increase daily energy?", tags: ["Energy", "ABAB", "4 weeks"],
    eff: "+1.4 pts energy", effCol: "good", spark: [5.7, 5.9, 5.6, 6.0, 7.0, 7.2, 6.9, 7.3] },
  { who: "tidligmad", init: "TM", col: "#4a6e5a", days: 4, status: "complete", runsN: 143, effVal: 12,
    q: "Does finishing dinner before 18:30 improve overnight HRV?", tags: ["Recovery", "ABAB", "4 weeks"],
    eff: "+12% HRV", effCol: "good", spark: [45, 47, 44, 46, 50, 52, 49, 53] },
  { who: "stillgaard", init: "ST", col: "#3f6152", days: 7, status: "recruiting", runsN: 156, effVal: 6,
    q: "Does a 20-minute evening walk lower resting heart rate?", tags: ["Heart", "ABA", "4 weeks"],
    eff: "−4 bpm resting HR", effCol: "good", spark: [64, 63, 64, 62, 61, 60, 60, 59] },
  { who: "nordlys22", init: "N2", col: "#5a3f6e", days: 9, status: "complete", runsN: 89, effVal: 12,
    q: "Does 10 min of morning meditation improve HRV?", tags: ["Recovery", "ABAB", "4 weeks"],
    eff: "+12% overnight HRV", effCol: "good", spark: [42, 44, 43, 45, 47, 49, 48, 50] },
  { who: "koldbad", init: "KB", col: "#575760", days: 12, status: "complete", runsN: 134, effVal: 0,
    q: "Do cold showers improve morning mood?", tags: ["Mood", "Alternating days", "3 weeks"],
    eff: "No clear effect", effCol: "muted", spark: [6, 7, 6, 7, 6, 7, 7, 6] },
  { who: "pusterum", init: "PU", col: "#6e3f4a", days: 6, status: "recruiting", runsN: 197, effVal: 31,
    q: "Does slow breathing before bed shorten sleep onset?", tags: ["Sleep", "ABAB", "3 weeks"],
    eff: "−8 min sleep onset", effCol: "good", spark: [27, 26, 28, 25, 20, 19, 21, 18] },
  { who: "mavefred", init: "MF", col: "#3f6e6a", days: 8, status: "complete", runsN: 76, effVal: 55,
    q: "Does cutting dairy reduce bloating?", tags: ["Gut", "ABAB", "4 weeks"],
    eff: "2 vs 9 episodes / 2 wks", effCol: "good", spark: [5, 4, 5, 4, 2, 1, 2, 1] },
  { who: "jernhjerte", init: "JH", col: "#6e6a3f", days: 10, status: "recruiting", runsN: 118, effVal: 9,
    q: "Does creatine increase weekly training volume?", tags: ["Fitness", "ABAB", "6 weeks"],
    eff: "+9% training volume", effCol: "good", spark: [12.1, 12.4, 12.2, 12.6, 13.3, 13.5, 13.2, 13.6] },
  { who: "luremus", init: "LU", col: "#4a5a6e", days: 14, status: "complete", runsN: 64, effVal: 3,
    q: "Do afternoon naps hurt sleep quality that night?", tags: ["Sleep", "Alternating days", "4 weeks"],
    eff: "−3% sleep efficiency", effCol: "muted", spark: [89, 88, 90, 87, 86, 85, 87, 85] },
];

// Map any designed example onto one of the three fully-built runnable trials.
window.startableId = (exId, source) => {
  if (window.TRIALS[exId]) return exId;
  return source === "self" ? "daylight" : "curfew";
};

// Completed trials, shared across builds. Trials reference these by id.
window.PAST_LIB = {
  magnesium: {
    id: "magnesium", title: "Magnesium & deep sleep",
    q: "Does 200 mg magnesium before bed increase my deep sleep?",
    intervention: "200 mg magnesium glycinate, 30 min before bed",
    outcome: "Minutes of deep sleep per night (Oura)",
    design: "ABAB crossover · 4 × 7-day blocks", duration: 28, unit: "min",
    completedLine: "Completed in May · 28 nights · Oura", effShort: "+19% deep sleep", effCol: "good",
    chartLabel: "Deep sleep by night",
    chart: { type: "bars", yMin: 0, yMax: 95, yTicks: [0, 30, 60, 90] },
    phases: [
      { s: 1, e: 7, type: "A", short: "A" }, { s: 8, e: 14, type: "B", short: "B · mag" },
      { s: 15, e: 21, type: "A", short: "A", washUntil: 17 }, { s: 22, e: 28, type: "B", short: "B · mag" },
    ],
    valuesComplete: [61, 58, 64, 61, 59, 63, 60, 68, 74, 72, 77, 73, 79, 75, 60, 62, 59, 61, 58, 62, 60, 73, 76, 71, 78, 74, 77, 75],
    complete: { callable: true, effect: "+19", effectUnit: "%", headline: "more deep sleep on magnesium nights", detail: "95% CI +12 to +26 · 28 nights · 60 → 74 min average" },
    insights: { complete: [
      { lab: "Signal", tx: "Both magnesium blocks beat both baseline blocks, and every single B-phase night exceeded the A-phase average. Consistent direction, stable size: very unlikely to be noise." },
      { lab: "Confounders checked", tx: "Bedtime drifted slightly later in baseline weeks, the opposite of what would fake this effect. Caffeine and alcohol were near zero throughout." },
      { lab: "Suggested next", tx: "A dose-response follow-up: 100 vs 200 vs 400 mg in one-week blocks would show whether less gives the same effect." },
    ] },
  },
  caffeine: {
    id: "caffeine", title: "Caffeine cutoff & sleep onset",
    q: "Does caffeine after 14:00 delay my sleep onset?",
    intervention: "No caffeine after 14:00 on cutoff weeks",
    outcome: "Minutes to fall asleep (Apple Watch)",
    design: "ABAB crossover · 4 × 7-day blocks", duration: 28, unit: "min",
    completedLine: "Completed in April · 28 nights · Apple Watch", effShort: "−35% sleep onset", effCol: "good",
    chartLabel: "Sleep onset by night",
    chart: { type: "bars", yMin: 0, yMax: 45, yTicks: [0, 15, 30, 45] },
    phases: [
      { s: 1, e: 7, type: "A", short: "A" }, { s: 8, e: 14, type: "B", short: "B · cutoff" },
      { s: 15, e: 21, type: "A", short: "A" }, { s: 22, e: 28, type: "B", short: "B · cutoff" },
    ],
    valuesComplete: [32, 36, 31, 35, 33, 37, 30, 21, 24, 20, 23, 22, 25, 21, 33, 35, 31, 34, 36, 30, 32, 22, 20, 23, 21, 24, 22, 19],
    complete: { callable: true, effect: "−12", effectUnit: " min", headline: "faster sleep onset without afternoon caffeine", detail: "95% CI −8 to −16 min (−35%) · 28 nights · 33 → 22 min average" },
    insights: { complete: [
      { lab: "Signal", tx: "Cutoff weeks were faster on 13 of 14 nights. The one exception was a flagged late-stress evening." },
      { lab: "Confounders checked", tx: "Total daily caffeine stayed constant; only timing moved. Bedtime and naps held steady across all four blocks." },
      { lab: "Suggested next", tx: "Find your personal cutoff: 12:00 vs 14:00 vs 16:00 in one-week blocks." },
    ] },
  },
  walk: {
    id: "walk", title: "Evening walk & resting HR",
    q: "Does a 20-minute walk after dinner lower my resting heart rate?",
    intervention: "20-minute walk after dinner, conversational pace",
    outcome: "Resting heart rate (Garmin)",
    design: "ABAB crossover · 4 × 7-day blocks", duration: 28, unit: "bpm",
    completedLine: "Completed in March · 28 days · Garmin", effShort: "−4 bpm resting HR", effCol: "good",
    chartLabel: "Resting HR by day",
    chart: { type: "line", yMin: 50, yMax: 70, yTicks: [55, 60, 65] },
    phases: [
      { s: 1, e: 7, type: "A", short: "A" }, { s: 8, e: 14, type: "B", short: "B · walk" },
      { s: 15, e: 21, type: "A", short: "A" }, { s: 22, e: 28, type: "B", short: "B · walk" },
    ],
    valuesComplete: [63, 62, 64, 61, 63, 62, 64, 60, 59, 61, 58, 60, 59, 60, 63, 64, 62, 63, 61, 64, 63, 59, 58, 60, 57, 59, 58, 59],
    complete: { callable: true, effect: "−4", effectUnit: " bpm", headline: "lower resting heart rate on walking weeks", detail: "95% CI −2.5 to −5.5 · 28 days · 63 → 59 bpm average" },
    insights: { complete: [
      { lab: "Signal", tx: "Resting HR dropped within 3 to 4 days of each walking block starting, and rebounded in baseline weeks. That on-off-on-off tracking is the signature of a real effect." },
      { lab: "Confounders checked", tx: "Other training stayed level, and sleep duration did not change between blocks. The walk itself is the best remaining explanation." },
      { lab: "Suggested next", tx: "Dose: does 10 minutes give most of the benefit? Or timing: morning vs evening walk." },
    ] },
  },
};

