/* scope guard: file-scoped IIFE — see index.html */
(function () {
/* Stoic+ — Daily loop: Today (empty / logged / cold-start), the slider
   check-in flow with confirmation, and the Live Monitor breakdown. */

const { Icons, SectionLabel, ScoreNumber, CheckBadge, PrimaryButton, GlassButton, GhostButton, LinkButton, Card, StepProgress,
        DIMENSIONS, DEFAULT_VALUES, monitorOf, feelingFor, ReadOnlyMetric, Banner, TopBar } = window;

/* Per-scenario shape for cold-start / streak demos.
   In production these counts derive from the member's real history;
   here they are stubbed (CLAUDE.md §10). `scenario` is 'normal' unless
   the dev Prototype-states menu switches it. */
function scen(s) {
  switch (s) {
    case "day1":       return { day: 1,  streak: 0,  freezes: 0, hist: [] };
    case "sparse":     return { day: 3,  streak: 2,  freezes: 0, hist: [6.1, 5.7] };
    case "streakbreak":return { day: 21, streak: 0,  freezes: 1, broke: true, hist: window.__HIST };
    default: {
      // 'normal' = real member data once hydrated (window.__BOOT); seeded until then.
      const B = (window.__BOOT && window.__BOOT.streak) || {};
      return {
        day: B.day != null ? B.day : 13,
        streak: B.current != null ? B.current : 12,
        freezes: B.freezesRemaining != null ? B.freezesRemaining : 2,
        hist: window.__HIST,
      };
    }
  }
}

const RANGES = [
  { key: "today", n: 1, word: "Today" },
  { key: "7D", n: 7, word: "7 days" },
  { key: "30D", n: 30, word: "30 days" },
  { key: "90D", n: 90, word: "90 days" },
];

/* ---------- Live Monitor dashboard ---------- */
function Dashboard({ values, logged, scenario, rangeIdx, setRangeIdx, onTapMonitor }) {
  const s = scen(scenario);
  const composite = monitorOf(values);
  const full = scenario === "normal" || scenario === "streakbreak";
  const range = full ? RANGES[rangeIdx] : null;
  const lo = 3, hi = 9.5, H = 52, W = 100;

  // Day-1: nothing to chart yet
  if (!logged && s.hist.length === 0) {
    return (
      <Card glass style={{ borderRadius: 26, padding: 20, marginBottom: 22 }}>
        <SectionLabel>Live monitor</SectionLabel>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10, margin: "8px 0 16px" }}>
          <span style={{ fontSize: 44, fontWeight: 700, color: "var(--color-text-faint)", letterSpacing: "-0.03em" }}>—</span>
        </div>
        <div style={{ height: 80, borderRadius: 14, border: "1px dashed var(--color-border)", display: "flex", alignItems: "center", justifyContent: "center", textAlign: "center", padding: "0 24px" }}>
          <span style={{ fontSize: 13, color: "var(--color-text-faint)", lineHeight: 1.5 }}>Log your first check-in to start your Monitor. The trend builds from here.</span>
        </div>
      </Card>
    );
  }

  // Build the value series
  let series, leftLabel;
  if (full && range && range.key === "today") {
    const start = window.__HIST[window.__HIST.length - 1];
    series = Array.from({ length: 8 }, (_, i) => { const t = i / 7; return start + ((logged ? composite : start) - start) * t + Math.sin(i * 1.25) * 0.22 * (1 - t); });
    if (logged) series[series.length - 1] = composite;
    leftLabel = "This morning";
  } else {
    const base = full ? window.__HIST.slice(window.__HIST.length - range.n) : s.hist;
    series = logged ? [...base, composite] : [...base];
    leftLabel = full ? `${range.n} days ago` : "Day 1";
  }
  const len = series.length;
  const xy = series.map((v, i) => [ len === 1 ? W : (i / (len - 1)) * W, H - ((v - lo) / (hi - lo)) * H ]);
  const line = xy.map((p, i) => (i ? "L" : "M") + p[0].toFixed(2) + " " + p[1].toFixed(2)).join(" ");
  const area = line + ` L ${W} ${H} L 0 ${H} Z`;
  const last = xy[xy.length - 1];
  const big = logged ? composite : series[series.length - 1];
  const delta = logged ? composite - series[0] : null;

  return (
    <Card glass style={{ borderRadius: 26, padding: 20, marginBottom: 22 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
        {full ? (
          <button onClick={() => setRangeIdx((rangeIdx + 1) % RANGES.length)} className="glass glass-lit press"
            style={{ display: "inline-flex", alignItems: "center", gap: 6, borderRadius: 9999, padding: "8px 13px", color: "var(--color-text)", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, cursor: "pointer", whiteSpace: "nowrap" }}>
            {range.word}<Icons.ChevronDown size={15} sw={2.2} />
          </button>
        ) : <span className="glass glass-lit" style={{ borderRadius: 9999, padding: "8px 13px", fontSize: 14, fontWeight: 600, color: "var(--color-text-muted)" }}>Day {s.day}</span>}
        <button onClick={logged ? onTapMonitor : undefined} className={logged ? "press" : ""} style={{ background: "none", border: "none", padding: 0, textAlign: "right", cursor: logged ? "pointer" : "default", fontFamily: "var(--font-sans)" }}>
          <SectionLabel style={{ display: "flex", gap: 6, justifyContent: "flex-end", alignItems: "center" }}>Live monitor {logged && <Icons.ChevronRight size={13} sw={2.4} />}</SectionLabel>
          <div style={{ display: "flex", alignItems: "baseline", gap: 8, justifyContent: "flex-end", marginTop: 6 }}>
            <span style={{ fontSize: 44, fontWeight: 700, letterSpacing: "-0.03em", color: logged ? "var(--color-text)" : "var(--color-text-muted)", lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{big.toFixed(1)}</span>
            {delta != null && <span style={{ color: delta >= 0 ? "var(--color-amber)" : "var(--color-text-muted)", fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{delta >= 0 ? "+" : ""}{delta.toFixed(1)}</span>}
          </div>
        </button>
      </div>

      <div style={{ position: "relative", height: 116, overflow: "visible" }}>
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: "100%", height: "100%", display: "block", overflow: "visible" }}>
          <defs>
            <linearGradient id="dashFill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#BBB065" stopOpacity="0.30" />
              <stop offset="100%" stopColor="#BBB065" stopOpacity="0" />
            </linearGradient>
          </defs>
          {len > 1 && <path d={area} fill="url(#dashFill)" />}
          {len > 1 && <path d={line} fill="none" stroke="#BBB065" strokeWidth="2" vectorEffect="non-scaling-stroke" strokeLinecap="round" strokeLinejoin="round" />}
        </svg>
        {(logged || len > 1) && <div className="live-dot" style={{ left: len === 1 ? "50%" : "100%", top: `${(last[1] / H) * 100}%` }} />}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
        <span style={{ fontSize: 11, color: "var(--color-text-faint)" }}>{leftLabel}</span>
        <span style={{ fontSize: 11, color: "var(--color-text-faint)" }}>{logged ? "Now" : "Yesterday"}</span>
      </div>
      {!logged && s.hist.length > 0 && <div style={{ fontSize: 12, color: "var(--color-text-faint)", marginTop: 10, textAlign: "center" }}>Not logged today · check in to update</div>}
    </Card>
  );
}

/* ---------- Live Monitor breakdown (sheet body) ---------- */
function MonitorBreakdownBody({ values }) {
  const composite = monitorOf(values);
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 4 }}>
        <ScoreNumber value={composite.toFixed(1)} size={52} />
        <span style={{ fontSize: 18, color: "var(--color-text-faint)", fontWeight: 600 }}>/ 10</span>
      </div>
      <p style={{ fontSize: 14, color: "var(--color-text-muted)", margin: "0 0 18px", lineHeight: 1.5 }}>A weighted average of today's five dimensions. Sleep and energy carry the most.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        {DIMENSIONS.map((d, i) => {
          const Icon = Icons[d.icon];
          return (
            <div key={d.key} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 2px", borderBottom: i < DIMENSIONS.length - 1 ? "1px solid var(--color-border)" : "none" }}>
              <span style={{ color: "var(--color-text-muted)", display: "flex", flex: "none" }}><Icon size={18} /></span>
              <span style={{ flex: 1, fontSize: 15, fontWeight: 500, color: "var(--color-text)" }}>{d.label}</span>
              <span style={{ fontSize: 12, color: "var(--color-text-faint)", fontWeight: 600, width: 44, textAlign: "right" }}>{Math.round(d.weight * 100)}%</span>
              <span style={{ color: "var(--color-amber)", fontSize: 16, fontWeight: 700, fontVariantNumeric: "tabular-nums", width: 26, textAlign: "right" }}>{values[d.key]}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Slider-based sequential check-in ---------- */
function Checkin({ initial, onSubmit, onCancel }) {
  const dims = DIMENSIONS;
  const [vals, setVals] = React.useState(initial || { energy: 5, sleep: 5, focus: 5, mood: 5, drive: 5 });
  const [step, setStep] = React.useState(0);
  const [phase, setPhase] = React.useState("form"); // form | done
  const d = dims[step];
  const Icon = Icons[d.icon];
  const isLast = step === dims.length - 1;
  const v = vals[d.key];
  const pct = ((v - 1) / 9) * 100;

  const back = () => (step === 0 ? onCancel() : setStep(step - 1));
  const next = () => (isLast ? setPhase("done") : setStep(step + 1));

  if (phase === "done") {
    const c = monitorOf(vals);
    return (
      <div className="screen" style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", paddingTop: 36 }}>
        <div className="pop"><CheckBadge size={76} /></div>
        <SectionLabel style={{ marginTop: 22 }}>Logged · today's monitor</SectionLabel>
        <div style={{ margin: "8px 0 4px" }}><ScoreNumber value={c.toFixed(1)} /></div>
        <p style={{ fontSize: 19, fontWeight: 500, color: "var(--color-text)", margin: "8px 0 0" }}>Today you feel <span style={{ color: "var(--color-amber)" }}>{feelingFor(c)}</span>.</p>
        <p style={{ fontSize: 15, color: "var(--color-text-faint)", margin: "10px 0 30px", maxWidth: "30ch", lineHeight: 1.5 }}>Your Coach read is ready. Keep the streak alive.</p>
        <GlassButton icon={false} onClick={() => onSubmit(vals)}>See today</GlassButton>
      </div>
    );
  }

  return (
    <div className="screen">
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 30 }}>
        <button onClick={back} className="glass glass-lit press" style={{ color: "var(--color-text)", width: 42, height: 42, borderRadius: 9999, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flex: "none" }}><Icons.ArrowLeft size={18} /></button>
        <StepProgress total={dims.length} current={step + 1} />
        <span style={{ fontSize: 13, fontWeight: 500, color: "var(--color-text-muted)", whiteSpace: "nowrap" }}>{step + 1} of {dims.length}</span>
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
        <span className="glass glass-lit glass-amber" style={{ width: 44, height: 44, borderRadius: 9999, color: "var(--color-amber)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon size={22} sw={2.2} /></span>
        <SectionLabel style={{ whiteSpace: "nowrap" }}>Check-in</SectionLabel>
      </div>
      <h1 style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.025em", margin: "0 0 4px", color: "var(--color-text)" }}>{d.label}</h1>
      <p style={{ fontSize: 15, color: "var(--color-text-faint)", margin: "0 0 40px" }}>Drag to rate today, 1 to 10.</p>

      <div style={{ textAlign: "center", marginBottom: 18 }}>
        <span style={{ fontSize: 64, fontWeight: 700, letterSpacing: "-0.03em", color: "var(--color-text)", fontVariantNumeric: "tabular-nums" }}>{v}</span>
      </div>
      <input type="range" min="1" max="10" step="1" value={v} className="metric-range" aria-label={`${d.label}, 1 to 10`}
        style={{ "--pct": pct + "%", height: 12 }} onChange={(e) => setVals({ ...vals, [d.key]: +e.target.value })} />
      <div style={{ display: "flex", justifyContent: "space-between", margin: "12px 4px 40px" }}>
        <span style={{ fontSize: 12, color: "var(--color-text-faint)" }}>Poor</span>
        <span style={{ fontSize: 12, color: "var(--color-text-faint)" }}>Excellent</span>
      </div>

      <GlassButton onClick={next} icon={!isLast}>{isLast ? "Submit check-in" : "Continue"}</GlassButton>
    </div>
  );
}

/* ---------- Today ---------- */
function TodayScreen({ values, logged, scenario, offline, committedAction, rangeIdx, setRangeIdx, onStartCheckin, onEditCheckin, openSheet }) {
  const s = scen(scenario);
  const composite = monitorOf(values);
  const today = new Date();
  const dateStr = today.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" });

  return (
    <div className="screen">
      {offline && <Banner icon="CloudOff">Offline — showing your saved data. Changes sync when you reconnect.</Banner>}
      <TopBar day={s.day} streak={!window.__BOOT && logged && scenario === "normal" ? s.streak + 1 : s.streak} />

      {(scenario === "streakbreak" || (window.__BOOT && window.__BOOT.streak && window.__BOOT.streak.broke)) && (
        <Card glass style={{ borderRadius: 18, padding: 16, marginBottom: 16, display: "flex", gap: 13, alignItems: "center" }}>
          <span style={{ width: 40, height: 40, borderRadius: 9999, background: "var(--color-surface-3)", color: "var(--color-amber)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icons.Snow size={20} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: "var(--color-text)" }}>Streak reset — not a failure.</div>
            <div style={{ fontSize: 13, color: "var(--color-text-muted)", lineHeight: 1.4 }}>{s.freezes > 0 ? `${s.freezes} freeze${s.freezes === 1 ? "" : "s"} left — log today to start the climb back.` : "Log today to start the climb back."}</div>
          </div>
        </Card>
      )}

      <Dashboard values={values} logged={logged} scenario={scenario} rangeIdx={rangeIdx} setRangeIdx={setRangeIdx} onTapMonitor={() => openSheet("monitor")} />

      <div style={{ marginBottom: 22 }}>
        <div style={{ fontSize: 15, fontWeight: 500, color: "var(--color-text-muted)", marginBottom: 6 }}>{dateStr}</div>
        {logged
          ? <h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: "-0.025em", margin: 0, color: "var(--color-text)" }}>Today you feel <span style={{ color: "var(--color-amber)" }}>{feelingFor(composite)}</span>.</h1>
          : <h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: "-0.025em", margin: 0, color: "var(--color-text)" }}>How are you today?</h1>}
      </div>

      {committedAction && logged && (
        <Card glass style={{ borderRadius: 18, padding: 16, marginBottom: 16 }}>
          <SectionLabel style={{ marginBottom: 8 }}>Yesterday's commitment</SectionLabel>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ flex: 1, fontSize: 15, fontWeight: 500, color: "var(--color-text)" }}>{committedAction}</span>
            <span className="glass glass-lit" style={{ borderRadius: 9999, padding: "5px 11px", color: "var(--color-amber)", fontSize: 13, fontWeight: 700, flex: "none" }}>+0.4 Monitor</span>
          </div>
        </Card>
      )}

      {logged ? (
        <div>
          <SectionLabel style={{ marginBottom: 12 }}>Today's check-in</SectionLabel>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 16 }}>
            {DIMENSIONS.map((d) => <ReadOnlyMetric key={d.key} d={d} value={values[d.key]} />)}
          </div>
          <div style={{ textAlign: "center" }}><LinkButton onClick={onEditCheckin}>Edit today's check-in</LinkButton></div>
        </div>
      ) : (
        <div>
          <GlassButton onClick={onStartCheckin}>{scenario === "day1" ? "Log your first check-in" : "Start today's check-in"}</GlassButton>
          <p style={{ fontSize: 13, color: "var(--color-text-faint)", textAlign: "center", margin: "14px 0 0", lineHeight: 1.5 }}>{scenario === "day1" ? "Five quick dimensions. Takes under a minute." : "Five dimensions feed today's Live Monitor."}</p>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Dashboard, MonitorBreakdownBody, Checkin, TodayScreen });
})();
