// ----- Landing, Designer (no slider, no control-variable step), Check-in -----
(() => {
const { Icon, Sheet, Toggle } = window.UI;

// -------------------- Landing --------------------
// The first three cards are the fully-built trials; picking one shapes the app.
function Landing({ nav }) {
  const runnable = ["curfew", "daylight", "dinner"].map((id) => window.EXAMPLES.find((e) => e.id === id));
  const [seed, setSeed] = useState(0);
  const extra = useMemo(() => {
    const rest = window.EXAMPLES.filter((e) => !window.TRIALS[e.id]);
    for (let i = rest.length - 1; i > 0; i--) { const j = (i * 7 + seed * 13 + 3) % (i + 1); [rest[i], rest[j]] = [rest[j], rest[i]]; }
    return rest.slice(0, 2);
  }, [seed]);

  return (
    <div>
      <div className="brand">
        <div className="mark">n1</div>
        <div className="name">N1Trials</div>
      </div>

      <h1 className="hero-t">Run a trial on yourself.</h1>
      <p className="sub" style={{ margin: "12px 0 24px" }}>
        Turn a hunch into a structured experiment. Design it with an AI collaborator, run it for a few weeks, and see what actually works for you.
      </p>

      <div className="row" style={{ marginBottom: 10 }}>
        <span className="eyebrow">What do you want to test?</span>
        <button className="btnL" onClick={() => setSeed(seed + 1)} style={{ display: "flex", alignItems: "center", gap: 5 }}>
          <Icon name="shuffle" size={14} /> more
        </button>
      </div>
      {[...runnable, ...extra].map((e) => (
        <button key={e.id} className="ex-card" onClick={() => nav("designer/" + e.id)}>
          <div>
            <div className="q">{e.q}</div>
            <div className="m">{e.m}</div>
          </div>
          <Icon name="right" size={18} />
        </button>
      ))}

      <button className="btnP" style={{ marginTop: 14 }} onClick={() => nav("designer")}>
        Design your own trial <Icon name="right" size={17} />
      </button>
      <p className="tiny" style={{ textAlign: "center", marginTop: 10 }}>
        No account needed until your trial is designed.
      </p>

      <div className="sec">
        <div className="sec-head">
          <h2 className="sec-t">What others found</h2>
          <button className="btnL" onClick={() => nav("explore")}>Explore all</button>
        </div>
        <div className="mini-strip">
          {window.COMMUNITY.slice(0, 6).map((c) => (
            <button key={c.who} className="mini-card" onClick={() => nav("explore")}>
              <div className="q">{c.q}</div>
              <div className={`e ${c.effCol === "good" ? "good" : "tiny"}`}>{c.eff}</div>
              <div className="tiny">{c.runsN} runs</div>
            </button>
          ))}
        </div>
        <p className="tiny" style={{ marginTop: 14, lineHeight: 1.6 }}>
          2,400+ community trials. Every result is one person's answer about their own body, shared anonymously. EU-hosted.
        </p>
      </div>
    </div>
  );
}

// -------------------- Designer --------------------
// Flow: question → measurement → design rationale → expected effect range → summary → account.
function Designer({ nav, toast, exampleId, onStartTrial }) {
  const preEx = exampleId ? window.EXAMPLES.find((e) => e.id === exampleId) : null;
  const [ex, setEx] = useState(preEx);
  const [msgs, setMsgs] = useState(() => {
    const opening = { from: "ai", text: "What would you like to find out about yourself? Pick an example, or just describe it in your own words below." };
    return preEx ? [opening, { from: "me", text: preEx.q }] : [opening];
  });
  const [input, setInput] = useState(preEx ? { type: "none" } : { type: "chips", options: null });
  const [typing, setTyping] = useState(false);
  const [composerOn, setComposerOn] = useState(!preEx);
  const [draft, setDraft] = useState("");
  const [state, setState] = useState({ q: !!preEx, device: null, design: false, expect: false });
  const [showProto, setShowProto] = useState(false);
  const [showAccount, setShowAccount] = useState(false);
  const [consents, setConsents] = useState({ wear: true, ai: true, pin: false });
  const endRef = useRef(null);
  const booted = useRef(false);

  useEffect(() => { endRef.current && endRef.current.scrollIntoView({ block: "end", behavior: "smooth" }); }, [msgs, typing, showAccount]);

  const pushAI = (newMsgs, nextInput) => {
    setTyping(true);
    setInput({ type: "none" });
    setTimeout(() => {
      setTyping(false);
      setMsgs((m) => [...m, ...newMsgs]);
      setInput(nextInput);
    }, 600);
  };

  const measureStep = (theEx) =>
    theEx.source === "wear"
      ? [{ from: "ai", text: `Good self-trial: one clear intervention, one measurable outcome (${theEx.outcomeLabel.toLowerCase()}). Which device should supply the data?` },
         { type: "chips", options: window.DEVICES.map((d) => ({ t: d, act: "device" })) }]
      : [{ from: "ai", text: `Good self-trial. ${theEx.outcomeLabel.split(" (")[0]} is something you sense better than any sensor, so we capture it as a quick daily rating at a fixed time. Deal?` },
         { type: "chips", options: [{ t: "Deal — daily rating", act: "device" }, { t: "Can a wearable measure this?", act: "whySelf" }] }];

  // If we arrived from a landing card, the question is already asked.
  useEffect(() => {
    if (preEx && !booted.current) {
      booted.current = true;
      const [m, inp] = measureStep(preEx);
      pushAI([m], inp);
    }
  }, []);

  const startQuestion = (text, chosenEx) => {
    setComposerOn(false);
    const typed = !chosenEx;
    const theEx = chosenEx || window.EXAMPLES[(text.length * 7 + 3) % window.EXAMPLES.length];
    setEx(theEx);
    setState((s) => ({ ...s, q: true }));
    const intro = typed ? [{ from: "ai", text: `Nice one. I'll structure it as a formal self-trial: "${theEx.q}"`, note: "Mock note: free text maps to a random example in this prototype." }] : [];
    const [m, inp] = measureStep(theEx);
    pushAI([{ from: "me", text }, ...intro, m], inp);
  };

  const actions = {
    device: (t) => {
      setState((s) => ({ ...s, device: t }));
      pushAI([
        { from: "me", text: t },
        { from: "ai", text: "I suggest an ABAB design: one week as usual, one week with the change, then repeat. Alternating blocks separate the real effect from weekly rhythms, stress cycles and slow drift. Live your life as normal otherwise; the design handles the rest.",
          note: "The first days after each switch count as transition days in the analysis." },
      ], { type: "chips", options: [{ t: "Sounds good", act: "designOk" }, { t: "Why not just before/after?", act: "whyNot" }] });
    },
    whySelf: (t) => {
      pushAI([
        { from: "me", text: t },
        { from: "ai", text: "Wearables estimate stress and energy from heart-rate proxies, but for how you actually feel, your own 10-second rating is the more direct instrument. We can add a wearable later as a second opinion." },
      ], { type: "chips", options: [{ t: "Deal — daily rating", act: "device" }] });
    },
    whyNot: (t) => {
      pushAI([
        { from: "me", text: t },
        { from: "ai", text: "A simple before/after can't tell your change apart from everything else that shifted in the same weeks: season, work stress, a new mattress. Alternating blocks put the comparison inside the same month, so those factors hit both conditions equally." },
      ], { type: "chips", options: [{ t: "Makes sense, use ABAB", act: "designOk" }] });
    },
    designOk: (t) => {
      setState((s) => ({ ...s, design: true, expect: true }));
      pushAI([
        { from: "me", text: t },
        { from: "ai", text: `One expectation to set: in similar trials, people who respond typically see ${ex.expect}. Some see nothing, and that is a real answer too. ${ex.days} days in four blocks is enough to tell which group you are in.` },
        { from: "ai", text: "Your protocol is ready. Create an account to save it and start tonight. You choose exactly what the app may store and process.", widget: "summary" },
      ], { type: "none" });
    },
  };

  const questionChips = useMemo(() => {
    return ["curfew", "daylight", "dinner"].map((id) => {
      const e = window.EXAMPLES.find((x) => x.id === id);
      return { t: e.q, act: "q", ex: e };
    });
  }, []);

  const onChip = (opt) => {
    if (opt.act === "q") startQuestion(opt.t, opt.ex);
    else actions[opt.act](opt.t);
  };

  const onSend = () => {
    const t = draft.trim();
    if (!t) return;
    setDraft("");
    startQuestion(t, null);
  };

  const startTrial = () => {
    const targetId = window.startableId(ex.id, ex.source);
    setShowAccount(false);
    onStartTrial(targetId);
    nav("home");
    toast(window.TRIALS[ex.id] ? "Trial started. First check-in tonight." : `Mock: entering the ${window.TRIALS[targetId].trial.title} trial.`);
  };

  const protoCount = [state.q, state.device, state.design, state.expect].filter(Boolean).length;

  return (
    <div>
      <button className="proto-fab pill b" onClick={() => setShowProto(true)}>Protocol · {protoCount}/4</button>

      <div style={{ marginBottom: 18 }}>
        <h1 className="sec-t" style={{ fontSize: 22 }}>Design your trial</h1>
        <p className="tiny" style={{ marginTop: 4 }}>with your research collaborator</p>
      </div>

      <div className="chat">
        {msgs.map((m, i) => {
          if (m.from === "me") return <div key={i} className="msg-me"><div className="bub-me">{m.text}</div></div>;
          return (
            <div key={i} className="msg-ai">
              <div className="av"><Icon name="spark" size={14} /></div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div className="bub-ai">
                  {m.text}
                  {m.note && <div className="note">{m.note}</div>}
                </div>
                {m.widget === "summary" && (
                  <div className="tile" style={{ marginTop: 10 }}>
                    <div className="eyebrow" style={{ marginBottom: 10 }}>Your protocol</div>
                    <ProtoRows ex={ex} state={state} />
                    <button className="btnP" style={{ marginTop: 14 }} onClick={() => setShowAccount(true)}>
                      Create account & start tonight
                    </button>
                  </div>
                )}
              </div>
            </div>
          );
        })}

        {typing && (
          <div className="msg-ai">
            <div className="av"><Icon name="spark" size={14} /></div>
            <div className="bub-ai"><div className="typing"><i /><i /><i /></div></div>
          </div>
        )}

        {!typing && input.type === "chips" && (
          <div className="chiprow" style={{ paddingLeft: 38 }}>
            {(input.options || questionChips).map((o) => (
              <button key={o.t} className="chip" onClick={() => onChip(o)}>{o.t}</button>
            ))}
          </div>
        )}
        <div ref={endRef} />
      </div>

      {composerOn && !typing && (
        <div className="composer">
          <div className="composer-inner">
            <input value={draft} onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") onSend(); }}
              placeholder="Describe what you want to test…" />
            <button onClick={onSend} disabled={!draft.trim()} aria-label="Send"><Icon name="send" size={17} /></button>
          </div>
        </div>
      )}

      {showProto && (
        <Sheet onClose={() => setShowProto(false)}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Protocol · building live</div>
          {ex ? <ProtoRows ex={ex} state={state} /> : <p className="tiny">Pick or write a question to begin.</p>}
          <p className="tiny" style={{ marginTop: 14 }}>
            Live as you normally would during the trial. The alternating design keeps everyday variation from masquerading as the effect, and your daily note flags anything unusual for the analysis.
          </p>
        </Sheet>
      )}

      {showAccount && (
        <Sheet onClose={() => setShowAccount(false)}>
          <h2 className="sec-t" style={{ marginBottom: 4 }}>Save your trial</h2>
          <p className="tiny" style={{ marginBottom: 16 }}>Granular consent. Each permission is separate, and reversible in Profile.</p>
          <input className="inp" placeholder="Email" style={{ marginBottom: 14 }} />
          {[
            { k: "wear", t: "Import wearable data", d: ex && ex.source === "wear" ? `${ex.outcomeLabel} from your device, nightly` : "Not needed for this trial" },
            { k: "ai", t: "AI processing of health data", d: "Protocol design and analysis. EU-hosted." },
            { k: "pin", t: "Publish results to community", d: "Anonymised, opt-in per trial. Off by default." },
          ].map((c) => (
            <div key={c.k} className="row" style={{ padding: "11px 2px" }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 550 }}>{c.t}</div>
                <div className="tiny">{c.d}</div>
              </div>
              <Toggle on={consents[c.k]} onTap={() => setConsents({ ...consents, [c.k]: !consents[c.k] })} />
            </div>
          ))}
          <button className="btnP" style={{ marginTop: 14 }} onClick={startTrial}>
            Start my trial
          </button>
        </Sheet>
      )}
    </div>
  );
}

function ProtoRows({ ex, state }) {
  const rows = [
    { k: "Question", v: ex.q, on: state.q },
    { k: "Outcome", v: `${ex.outcomeLabel}${state.device && state.device !== "Self-report only" && ex.source === "wear" ? ` (${state.device})` : ""}`, on: !!state.device || state.q },
    { k: "Design", v: `ABAB crossover · ${ex.days} days · transition-aware`, on: state.design },
    { k: "Expected range", v: `If it works for you: ${ex.expect}`, on: state.expect },
  ];
  return (
    <div>
      {rows.map((r) => (
        <div key={r.k} className="p-row">
          <div className="k">{r.k}</div>
          <div className={`v ${r.on ? "" : "off"}`}>{r.on ? r.v : "pending"}</div>
        </div>
      ))}
    </div>
  );
}

// -------------------- Check-in --------------------
function CheckIn({ nav, toast, onLogged, cfg }) {
  const C = cfg;
  const [compliance, setCompliance] = useState(null);
  const [vals, setVals] = useState({});
  const [done, setDone] = useState(false);

  if (done) return (
    <div style={{ paddingTop: 90, textAlign: "center" }}>
      <div style={{ color: "var(--good)", margin: "0 auto 14px", width: 54, height: 54, borderRadius: "50%", background: "var(--good-dim)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Icon name="check" size={26} />
      </div>
      <h2 className="sec-t">Logged.</h2>
      <p className="sub" style={{ margin: "8px auto 24px", maxWidth: 270 }}>{C.successNote}</p>
      <button className="btnG" onClick={() => nav("home")}>Back to trial</button>
    </div>
  );

  return (
    <div>
      <div style={{ marginBottom: 20 }}>
        <span className="pill b" style={{ marginBottom: 10 }}><span className="dot" /> {C.pill}</span>
        <h1 className="sec-t" style={{ fontSize: 22, marginTop: 10 }}>{C.title}</h1>
        <p className="tiny" style={{ marginTop: 4 }}>{C.sub}</p>
      </div>

      <div className="field">
        <div className="lab"><span>{C.compliance.label}</span><span className="h">{C.compliance.hint}</span></div>
        <div className="seg">
          {C.compliance.options.map((o) => (
            <button key={o} className={compliance === o ? "on" : ""} onClick={() => setCompliance(o)}>{o}</button>
          ))}
        </div>
      </div>

      {C.fields.map((f, i) => {
        if (f.type === "rate10") return (
          <div className="field" key={i}>
            <div className="lab"><span>{f.label}</span>{f.hint && <span className="h">{f.hint}</span>}</div>
            <div className="rate">
              {[1,2,3,4,5,6,7,8,9,10].map((n) => (
                <button key={n} className={vals[i] === n ? "on" : ""} onClick={() => setVals({ ...vals, [i]: n })}>{n}</button>
              ))}
            </div>
          </div>
        );
        if (f.type === "notes") return (
          <div className="field" key={i}>
            <div className="lab"><span>Anything unusual?</span><span className="h">optional</span></div>
            <textarea className="inp" rows="2" placeholder={f.placeholder} />
          </div>
        );
        return null;
      })}

      <button className="btnP" onClick={() => { setDone(true); onLogged(); }}>Save tonight's log</button>
      <p className="tiny" style={{ textAlign: "center", marginTop: 12 }}>{C.footer}</p>
    </div>
  );
}

window.Screens1 = { Landing, Designer, CheckIn };
})();
