// ----- Home (active + past trials), Past results, Explore, Profile -----
(() => {
const { Icon, Ring, Spark, TrendChart, Toggle, Avvy } = window.UI;

// Shared results renderer: works for the active trial (interim) and past trials (complete)
function ResultsSection({ trial, stage }) {
  const R = trial[stage];
  const values = stage === "complete" ? trial.valuesComplete : trial.valuesInterim;
  const ins = trial.insights[stage];
  return (
    <div>
      {R.callable === false ? (
        <div className="callout muted" style={{ marginBottom: 12 }}>
          <div className="big">Too early to call</div>
          <div style={{ fontSize: 13.5, color: "var(--text-2)", marginTop: 8, lineHeight: 1.55 }}>{R.note}</div>
        </div>
      ) : (
        <div className="callout" style={{ marginBottom: 12 }}>
          <div className="big">{R.effect}<span className="u">{R.effectUnit}</span></div>
          <div style={{ fontSize: 14, fontWeight: 600, margin: "8px 0 3px" }}>{R.headline}</div>
          <div className="tiny">{R.detail}</div>
        </div>
      )}

      <div className="chart-tile" style={{ marginBottom: 12 }}>
        <div className="row" style={{ marginBottom: 10 }}>
          <span className="eyebrow">{trial.chartLabel}</span>
          <span className="tiny mono">{trial.unit}</span>
        </div>
        <TrendChart values={values} phases={trial.phases} cfg={trial.chart} />
        {trial.chart.type === "line-roll" && (
          <p className="tiny" style={{ margin: "8px 0 0" }}>Dots are single nights; the line is a {trial.chart.roll}-night rolling average. Single nights are noisy by nature.</p>
        )}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {ins.map((c) => (
          <div className="insight" key={c.lab}>
            <div className="lab"><Icon name="spark" size={13} /> {c.lab}</div>
            <div className="tx">{c.tx}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// -------------------- Home: active trial + past trials --------------------
function Home({ nav, toast, logged, cfg }) {
  const T = cfg.trial;
  const pastTrials = cfg.pastIds.map((id) => window.PAST_LIB[id]);
  const [protoOpen, setProtoOpen] = useState(false);

  return (
    <div>
      <div style={{ marginBottom: 18 }}>
        <span className="pill b"><span className="dot" /> Day {T.currentDay} of {T.duration} · {T.phaseNow}</span>
        <h1 className="hero-t" style={{ fontSize: 26, margin: "12px 0 4px" }}>{T.title}</h1>
        <p className="tiny">{T.q}</p>
      </div>

      {/* Today */}
      <div className="tile">
        <div className="today">
          <Ring value={T.currentDay} max={T.duration} label={`${T.currentDay}`} sub={`of ${T.duration}`} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 650, marginBottom: 3 }}>{T.today.task}</div>
            <div className="tiny" style={{ marginBottom: 10 }}>{T.today.sub}</div>
            <div className="tiny"><span className="good">{T.today.streak}</span></div>
          </div>
        </div>
        <button className={`btnP ${logged ? "done" : ""}`} style={{ marginTop: 14 }} onClick={() => !logged && nav("checkin")}>
          {logged ? "Logged for tonight" : T.today.cta}
        </button>
      </div>

      {/* Outcome metric */}
      <div className="sec">
        <div className="sec-head">
          <h2 className="sec-t">{T.metricTitle}</h2>
          <span className="tiny">{T.sourceLine}</span>
        </div>
        <div className="tile" style={{ display: "flex", gap: 18 }}>
          <div style={{ flex: 1 }}>
            <div className="eyebrow" style={{ marginBottom: 6 }}>{T.tiles.aLabel}</div>
            <div className="metric"><span className="n" style={{ color: "var(--text-2)" }}>{T.tiles.aVal}</span><span className="u">{T.tiles.unit}</span></div>
          </div>
          <div style={{ width: 1, background: "var(--line)" }} />
          <div style={{ flex: 1 }}>
            <div className="eyebrow" style={{ marginBottom: 6 }}>{T.tiles.bLabel}</div>
            <div className="metric"><span className="n blue">{T.tiles.bVal}</span><span className="u">{T.tiles.unit}</span></div>
          </div>
        </div>
      </div>

      {/* Schedule */}
      <div className="sec">
        <div className="sec-head">
          <h2 className="sec-t">Schedule</h2>
          <span className="tiny">{T.design}</span>
        </div>
        <div className="tile">
          <div className="cal">
            {Array.from({ length: T.duration }, (_, i) => {
              const d = i + 1;
              const ph = T.phases.find((p) => d >= p.s && d <= p.e);
              const isWash = ph.washUntil && d <= ph.washUntil;
              const isLogged = T.valuesInterim[i] != null;
              const isToday = d === T.currentDay;
              return (
                <div key={d} className={`c ${ph.type} ${isLogged ? "logged" : ""} ${isWash ? "wash" : ""} ${isToday ? "today" : ""}`}>
                  {d}<span className="ph">{ph.type}</span>
                </div>
              );
            })}
          </div>
          <div className="legend">
            <span><span className="sw" style={{ background: "#2b2b31" }} />{T.legendA}</span>
            <span><span className="sw" style={{ background: "var(--blue-dim)", borderColor: "var(--blue-line)" }} />{T.legendB}</span>
            <span><span className="sw" style={{ borderStyle: "dashed" }} />transition</span>
          </div>
        </div>
      </div>

      {/* Protocol */}
      <div className="sec">
        <div className={`acc ${protoOpen ? "open" : ""}`}>
          <button className="acc-h" onClick={() => setProtoOpen(!protoOpen)}>
            Protocol <Icon name="chev" size={17} />
          </button>
          {protoOpen && (
            <div className="acc-b">
              {[
                ["Intervention", T.intervention],
                ["Primary outcome", T.outcome],
                ["Design", T.design],
              ].map(([k, v]) => (
                <div key={k} className="p-row"><div className="k">{k}</div><div className="v">{v}</div></div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Interim results */}
      <div className="sec">
        <div className="sec-head">
          <h2 className="sec-t">Interim read</h2>
          <span className="tiny">day {T.currentDay} of {T.duration}</span>
        </div>
        <ResultsSection trial={T} stage="interim" />
        <p className="tiny" style={{ marginTop: 12, lineHeight: 1.6 }}>
          Your data, your reading. The app reports what the numbers show, and never tells you what to take.
        </p>
      </div>

      {/* Past trials */}
      <div className="sec">
        <div className="sec-head">
          <h2 className="sec-t">Past trials</h2>
          <span className="tiny">{pastTrials.length} completed</span>
        </div>
        {pastTrials.map((p) => (
          <button key={p.id} className="past-card" onClick={() => nav("past/" + p.id)}>
            <div style={{ minWidth: 0 }}>
              <div className="t">{p.title}</div>
              <div className="m">{p.completedLine}</div>
            </div>
            <div style={{ textAlign: "right", flex: "none" }}>
              <div className={`e ${p.effCol === "good" ? "good" : ""}`} style={p.effCol === "muted" ? { color: "var(--text-3)" } : {}}>{p.effShort}</div>
              <div className="tiny blue" style={{ marginTop: 3 }}>View results →</div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// -------------------- Past trial results --------------------
function PastResults({ id, nav }) {
  const p = window.PAST_LIB[id] || window.PAST_LIB.magnesium;
  const [protoOpen, setProtoOpen] = useState(false);
  return (
    <div>
      <div className="back-row">
        <button onClick={() => nav("home")}><Icon name="left" size={16} /> Home</button>
      </div>
      <span className="pill g"><span className="dot" /> Complete · {p.duration} days</span>
      <h1 className="hero-t" style={{ fontSize: 26, margin: "12px 0 4px" }}>{p.title}</h1>
      <p className="tiny" style={{ marginBottom: 20 }}>{p.q}</p>

      <ResultsSection trial={p} stage="complete" />

      <div style={{ display: "flex", gap: 8, marginTop: 16 }}>
        <button className="btnG" style={{ flex: 1, justifyContent: "center" }} onClick={() => nav("designer")}>Run a follow-up</button>
        <button className="btnG" style={{ flex: 1, justifyContent: "center", color: "var(--blue)", borderColor: "var(--blue-line)" }} onClick={() => nav("explore")}>See community version</button>
      </div>

      <div className="sec">
        <div className={`acc ${protoOpen ? "open" : ""}`}>
          <button className="acc-h" onClick={() => setProtoOpen(!protoOpen)}>
            Protocol <Icon name="chev" size={17} />
          </button>
          {protoOpen && (
            <div className="acc-b">
              {[
                ["Intervention", p.intervention],
                ["Primary outcome", p.outcome],
                ["Design", p.design],
              ].map(([k, v]) => (
                <div key={k} className="p-row"><div className="k">{k}</div><div className="v">{v}</div></div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// -------------------- Explore (search + working sort) --------------------
function Explore({ nav, toast }) {
  const [sort, setSort] = useState("Popular");
  const [q, setQ] = useState("");

  const cards = useMemo(() => {
    const needle = q.trim().toLowerCase();
    let list = window.COMMUNITY.filter((c) =>
      !needle || c.q.toLowerCase().includes(needle) || c.tags.some((t) => t.toLowerCase().includes(needle)));
    if (sort === "Popular") list = [...list].sort((a, b) => b.runsN - a.runsN);
    if (sort === "Effect size") list = [...list].sort((a, b) => b.effVal - a.effVal);
    if (sort === "Newest") list = [...list].sort((a, b) => a.days - b.days);
    return list;
  }, [sort, q]);

  return (
    <div>
      <h1 className="sec-t" style={{ fontSize: 22 }}>Explore</h1>
      <p className="tiny" style={{ marginTop: 4 }}>2,400+ community trials, anonymised. Clone one and make it yours.</p>

      <div className="search-bar">
        <Icon name="search" size={16} />
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search sleep, energy, HRV…" />
        {q && <button onClick={() => setQ("")} style={{ color: "var(--text-4)" }}><Icon name="x" size={15} /></button>}
      </div>

      <div className="sort">
        {["Popular", "Effect size", "Newest"].map((s) => (
          <button key={s} className={sort === s ? "on" : ""} onClick={() => setSort(s)}>{s}</button>
        ))}
      </div>

      {cards.length === 0 && <div className="no-results">Nothing matches "{q}" yet. Start that trial yourself?</div>}

      {cards.map((c) => (
        <div key={c.who} className="feed-card">
          <div className="feed-head">
            <Avvy init={c.init} col={c.col} />
            <div>
              <div className="who">{c.who}</div>
              <div className="meta">{c.status} · {c.days}d ago · {c.runsN} runs</div>
            </div>
          </div>
          <div className="feed-q">{c.q}</div>
          <div className="tagrow">
            {c.tags.map((t) => <span key={t} className="t">{t}</span>)}
          </div>
          <div className="feed-mid">
            <div className={`eff ${c.effCol === "good" ? "good" : ""}`} style={c.effCol === "muted" ? { color: "var(--text-3)" } : {}}>
              {c.eff}
              <span className="runs">{c.runsN} runs · pooled result</span>
            </div>
            <Spark data={c.spark} color={c.effCol === "muted" ? "var(--text-4)" : "var(--blue)"} />
          </div>
          <div className="feed-actions">
            <button className="hot" onClick={() => { toast("Protocol copied. The collaborator personalises it for you."); nav("designer"); }}>
              <Icon name="copy" size={15} /> Clone
            </button>
            <button onClick={() => toast("Saved for later")}><Icon name="save" size={15} /> Save</button>
            <button onClick={() => toast("Mock: pooled results + method details")}>Details</button>
          </div>
        </div>
      ))}
      <p className="tiny" style={{ textAlign: "center", margin: "8px 0 4px" }}>
        Pooled community results are context, not medical evidence. Your trial is the test that counts.
      </p>
    </div>
  );
}

// -------------------- Profile --------------------
function Profile({ nav, toast, cfg }) {
  const [consents, setConsents] = useState({ wear: cfg.trial.source === "wear", ai: true, pin: false });
  const [lang, setLang] = useState("EN");
  return (
    <div>
      <div className="prof-head">
        <Avvy init="PF" col="#39566e" size={56} />
        <div>
          <div style={{ fontSize: 17, fontWeight: 650 }}>Peter F.</div>
          <div className="tiny">community alias: quietowl</div>
        </div>
      </div>

      <div className="eyebrow" style={{ marginBottom: 8 }}>Data sources</div>
      <div className="list" style={{ marginBottom: 22 }}>
        <div className="it">
          <div className="l" style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <span style={{ color: "var(--blue)" }}><Icon name="watch" size={20} /></span>
            <div>
              <div className="t">{cfg.profile.deviceTitle}</div>
              <div className="d">{cfg.profile.deviceSub}</div>
            </div>
          </div>
          <button className="btnL" onClick={() => toast("Mock: wearable management")}>{cfg.profile.deviceAction}</button>
        </div>
        <div className="it">
          <div className="l">
            <div className="t">Blood tests & genetics</div>
            <div className="d">Coming later. Import lab history or order new panels.</div>
          </div>
          <span className="pill">Soon</span>
        </div>
      </div>

      <div className="eyebrow" style={{ marginBottom: 8 }}>Consents</div>
      <div className="list" style={{ marginBottom: 22 }}>
        {[
          { k: "wear", t: "Import wearable data", d: "Nightly, encrypted, EU-hosted" },
          { k: "ai", t: "AI processing of health data", d: "Protocol design and analysis" },
          { k: "pin", t: "Publish results to community", d: "Anonymised · off by default" },
        ].map((c) => (
          <div key={c.k} className="it">
            <div className="l">
              <div className="t">{c.t}</div>
              <div className="d">{c.d}</div>
            </div>
            <Toggle on={consents[c.k]} onTap={() => setConsents({ ...consents, [c.k]: !consents[c.k] })} />
          </div>
        ))}
      </div>

      <div className="eyebrow" style={{ marginBottom: 8 }}>Language</div>
      <div className="seg" style={{ marginBottom: 22 }}>
        {["EN", "DA"].map((l) => (
          <button key={l} className={lang === l ? "on" : ""} onClick={() => setLang(l)}>{l === "EN" ? "English" : "Dansk"}</button>
        ))}
      </div>

      <div className="eyebrow" style={{ marginBottom: 8 }}>Your data</div>
      <div className="list">
        <div className="it">
          <div className="l"><div className="t">Export everything</div><div className="d">CSV + JSON, within minutes</div></div>
          <button className="btnL" onClick={() => toast("Mock: export queued")}>Export</button>
        </div>
        <div className="it">
          <div className="l"><div className="t" style={{ color: "var(--danger)" }}>Delete everything</div><div className="d">Full erasure, no residue</div></div>
          <button className="btnL" style={{ color: "var(--danger)" }} onClick={() => toast("Mock: erasure flow with confirmation")}>Delete</button>
        </div>
      </div>

      <p className="tiny" style={{ marginTop: 20, textAlign: "center" }}>mock · {cfg.tag} · all data simulated</p>
    </div>
  );
}

window.Screens2 = { Home, PastResults, Explore, Profile };
})();
