/* scope guard: file-scoped IIFE — see index.html */
(function () {
/* Stoic+ — Journey: composite trend + streak calendar.
   Handles cold-start (day1/sparse), streak break + freeze, and day detail. */

const { Icons, SectionLabel, ScoreNumber, Card, LinkButton, PrimaryButton,
        DIMENSIONS, monitorOf, feelingFor, ReadOnlyMetric } = window;

function MiniTrend({ data }) {
  const lo = 3, hi = 9.5, H = 52, W = 100;
  const n = data.length;
  const xy = data.map((v, i) => [ n === 1 ? W : (i / (n - 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`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: "100%", height: 96, display: "block", overflow: "visible" }}>
      <defs>
        <linearGradient id="jFill" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#BBB065" stopOpacity="0.28" /><stop offset="100%" stopColor="#BBB065" stopOpacity="0" /></linearGradient>
      </defs>
      <path d={area} fill="url(#jFill)" />
      <path d={line} fill="none" stroke="#BBB065" strokeWidth="2" vectorEffect="non-scaling-stroke" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={xy[xy.length - 1][0]} cy={xy[xy.length - 1][1]} r="3.2" fill="#BBB065" vectorEffect="non-scaling-stroke" />
    </svg>
  );
}

/* states: 'on' logged · 'miss' missed · 'freeze' protected · 'off' future/empty.
   NOTE: cells are simple colored tiles — only the *card* is a glass surface.
   Stacking 35 backdrop-filter blurs over the ambient glow blew out into a
   neon artifact, so the glass blur lives on the card, not each cell. */
function Calendar({ cells, onPick }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 8 }}>
      {cells.map((c, i) => {
        const base = { aspectRatio: "1", borderRadius: 9, display: "flex", alignItems: "center", justifyContent: "center", cursor: c === "off" ? "default" : "pointer", border: "1px solid transparent" };
        let st = { ...base }, inner = null, cls = c === "off" ? "" : "press";
        if (c === "on") { st.background = "linear-gradient(150deg, rgba(224,214,150,0.52) 0%, rgba(187,176,101,0.34) 55%, rgba(200,189,118,0.44) 100%)"; st.borderColor = "rgba(224,214,150,0.6)"; st.boxShadow = "inset 0 1px 0 rgba(255,255,255,0.4), 0 6px 16px -6px rgba(187,176,101,0.55)"; }
        else if (c === "miss") { st.background = "rgba(255,255,255,0.03)"; st.borderColor = "var(--color-border)"; inner = <span style={{ width: 4, height: 4, borderRadius: 9999, background: "var(--color-text-faint)" }} />; }
        else if (c === "freeze") { st.background = "var(--glass-tint-amber)"; st.borderColor = "rgba(187,176,101,0.3)"; st.color = "var(--color-amber)"; inner = <Icons.Snow size={13} />; }
        else { st.background = "rgba(255,255,255,0.04)"; }
        return <div key={i} className={cls.trim()} style={st} onClick={() => c !== "off" && onPick && onPick(i)}>{inner}</div>;
      })}
    </div>
  );
}

function JourneyScreen({ scenario, openSheet }) {
  if (scenario === "day1") {
    return (
      <div className="screen">
        <SectionLabel style={{ marginBottom: 6 }}>Your journey</SectionLabel>
        <h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: "-0.025em", margin: "0 0 24px", color: "var(--color-text)" }}>Starts today.</h1>
        <Card glass style={{ borderRadius: 24, padding: 30, textAlign: "center" }}>
          <div style={{ width: 56, height: 56, borderRadius: 9999, background: "var(--color-surface-3)", color: "var(--color-amber)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 16px" }}><Icons.Trend size={26} /></div>
          <p style={{ fontSize: 17, fontWeight: 500, color: "var(--color-text)", margin: "0 0 6px" }}>No trend yet.</p>
          <p style={{ fontSize: 14, color: "var(--color-text-faint)", margin: 0, lineHeight: 1.5 }}>Log a few days and your composite line, streak, and patterns appear here.</p>
        </Card>
      </div>
    );
  }

  const sparse = scenario === "sparse";
  const data = sparse ? [6.1, 5.7, monitorOf({ energy: 7, sleep: 6, focus: 7, mood: 7, drive: 6 })] : window.__HIST.slice(-12);
  // calendar
  let cells;
  if (sparse) cells = ["on", "on", "on", "off", "off", "off", "off"].concat(Array(28).fill("off"));
  else if (scenario === "streakbreak") cells = ["on","on","on","on","on","on","on","on","on","on","on","on","on","on","on","on","on","miss","freeze","on","on","off","off","off","off","off","off","off","off","off","off","off","off","off","off"];
  else if (window.__BOOT && Array.isArray(window.__BOOT.calendar) && window.__BOOT.calendar.length) cells = window.__BOOT.calendar;
  else cells = Array.from({ length: 35 }, (_, i) => (i > 1 && i < 33 && i % 9 !== 4 ? "on" : (i >= 33 ? "off" : "miss"))).map((c, i) => (i >= 33 ? "off" : c));

  return (
    <div className="screen">
      <SectionLabel style={{ marginBottom: 6 }}>Your journey</SectionLabel>
      <h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: "-0.025em", margin: "0 0 22px", color: "var(--color-text)" }}>{sparse ? "3 days in." : (scenario === "streakbreak" || (window.__BOOT && window.__BOOT.streak && window.__BOOT.streak.broke)) ? "Climbing back." : `${(window.__BOOT && window.__BOOT.streak && window.__BOOT.streak.day) || 13} days in.`}</h1>

      <Card glass style={{ borderRadius: 24, marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16 }}>
          <SectionLabel>Composite trend</SectionLabel>
          {!sparse && <span style={{ color: "var(--color-amber)", fontSize: 13, fontWeight: 600 }}>+0.8 this week</span>}
        </div>
        {sparse ? <div style={{ position: "relative" }}><MiniTrend data={data} /><div style={{ fontSize: 12, color: "var(--color-text-faint)", textAlign: "center", marginTop: 8 }}>Building — 2 more days for weekly patterns.</div></div> : <MiniTrend data={data} />}
      </Card>

      <Card glass style={{ borderRadius: 24 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16 }}>
          <SectionLabel>Streak calendar</SectionLabel>
          <span style={{ color: "var(--color-text-muted)", fontSize: 13, fontWeight: 500 }}>{(() => { const fz = cells.filter((c) => c === "freeze").length; if (scenario === "streakbreak") return "incl. 1 freeze"; if (fz > 0) return `incl. ${fz} freeze${fz === 1 ? "" : "s"}`; return new Date().toLocaleDateString("en-US", { month: "long" }); })()}</span>
        </div>
        <Calendar cells={cells} onPick={() => openSheet("day")} />
        {(scenario === "streakbreak" || cells.indexOf("freeze") >= 0 || cells.indexOf("miss") >= 0) && (
          <div style={{ display: "flex", gap: 16, marginTop: 16, fontSize: 12, color: "var(--color-text-muted)" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 12, height: 12, borderRadius: 4, background: "var(--grad-amber)" }} /> Logged</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 12, height: 12, borderRadius: 4, border: "1px solid var(--color-border)" }} /> Missed</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icons.Snow size={13} /> Freeze</span>
          </div>
        )}
      </Card>
    </div>
  );
}

/* Day detail (sheet body) — a logged day's dimensions + monitor + edit */
function DayDetailBody({ onEdit }) {
  const vals = { energy: 7, sleep: 6, focus: 8, mood: 7, drive: 6 };
  const c = monitorOf(vals);
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
        <div>
          <div style={{ fontSize: 15, fontWeight: 500, color: "var(--color-text-muted)" }}>Tuesday, March 18</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 4 }}>
            <ScoreNumber value={c.toFixed(1)} size={40} />
            <span style={{ fontSize: 15, color: "var(--color-text)", fontWeight: 500 }}>· {feelingFor(c)}</span>
          </div>
        </div>
        <button onClick={onEdit} className="glass glass-lit press" style={{ display: "inline-flex", alignItems: "center", gap: 7, borderRadius: 9999, padding: "9px 14px", color: "var(--color-text)", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, cursor: "pointer" }}><Icons.Pencil size={15} />Edit</button>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {DIMENSIONS.map((d) => <ReadOnlyMetric key={d.key} d={d} value={vals[d.key]} />)}
      </div>
    </div>
  );
}

Object.assign(window, { JourneyScreen, DayDetailBody });
})();
