/* scope guard: file-scoped IIFE — see index.html */
(function () {
/* Stoic+ — Coach: one daily read, a single committable action, cold-start.
   Subscriber-only product → no upsell here. */

const { useState } = React;
const { Icons, SectionLabel, Card, PrimaryButton, GlassButton } = window;

const ACTIONS = ["Protect bedtime — lights out by 11", "Train before noon", "No screens after 10pm"];

function CoachScreen({ scenario, committedAction, onCommit, onAsk }) {
  if (scenario === "day1" || scenario === "sparse" || (scenario === "normal" && window.isColdStart())) {
    const sparse = scenario === "sparse";
    return (
      <div className="screen">
        <SectionLabel style={{ marginBottom: 6 }}>Coach</SectionLabel>
        <h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: "-0.025em", margin: "0 0 22px", color: "var(--color-text)" }}>{sparse ? "Almost there." : "Day one."}</h1>
        <Card glass style={{ borderRadius: 24, padding: 26, textAlign: "center" }}>
          <div style={{ width: 52, height: 52, borderRadius: 9999, background: "var(--grad-amber)", boxShadow: "var(--glow-amber)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 16px" }}><Icons.Message size={24} /></div>
          <p style={{ fontSize: 17, fontWeight: 500, color: "var(--color-text)", margin: "0 0 6px" }}>{sparse ? "Two more check-ins." : "Your Coach is listening."}</p>
          <p style={{ fontSize: 14, color: "var(--color-text-faint)", margin: 0, lineHeight: 1.5 }}>{sparse ? "A few more days and the Coach can read your patterns and name the one thing to fix." : "Log a few days and the Coach gives you a daily read — one clear thing to act on."}</p>
        </Card>
      </div>
    );
  }

  return (
    <div className="screen">
      <SectionLabel style={{ marginBottom: 6 }}>Coach</SectionLabel>
      <h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: "-0.025em", margin: "0 0 22px", color: "var(--color-text)" }}>One thing.</h1>

      <Card glass style={{ borderRadius: 24, marginBottom: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
          <div className="glass glass-lit glass-amber" style={{ width: 40, height: 40, borderRadius: 9999, color: "var(--color-amber)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icons.Message size={19} /></div>
          <SectionLabel>Today's read</SectionLabel>
        </div>
        <p style={{ fontSize: 19, fontWeight: 500, lineHeight: 1.45, margin: 0, color: "var(--color-text)" }}>{(window.__BOOT && window.__BOOT.coach && window.__BOOT.coach.read) || "Your monitor climbs on the days you sleep seven hours. Last night you got five. Protect the next bedtime — everything else follows it."}</p>
      </Card>

      {committedAction ? (
        <Card glass style={{ borderRadius: 20, marginBottom: 16 }}>
          <SectionLabel style={{ marginBottom: 10 }}>Committed for today</SectionLabel>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ width: 34, height: 34, borderRadius: 9999, background: "var(--grad-amber)", color: "#1a1206", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icons.Check size={18} sw={2.6} /></span>
            <span style={{ flex: 1, fontSize: 15, fontWeight: 600, color: "var(--color-text)" }}>{committedAction}</span>
          </div>
          <p style={{ fontSize: 13, color: "var(--color-text-faint)", margin: "12px 0 0", lineHeight: 1.5 }}>We'll check tomorrow whether it moved your Monitor.</p>
        </Card>
      ) : (
        <div style={{ marginBottom: 16 }}>
          <SectionLabel style={{ marginBottom: 12 }}>Commit to one action</SectionLabel>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {((window.__BOOT && window.__BOOT.coach && window.__BOOT.coach.actions) || ACTIONS).map((a) => (
              <button key={a} onClick={() => onCommit(a)} className="glass glass-lit press" style={{ display: "flex", alignItems: "center", gap: 12, borderRadius: 16, padding: "15px 16px", cursor: "pointer", fontFamily: "var(--font-sans)", textAlign: "left", border: "1px solid var(--glass-border)" }}>
                <span style={{ width: 22, height: 22, borderRadius: 9999, border: "2px solid var(--color-text-faint)", flex: "none" }} />
                <span style={{ flex: 1, fontSize: 15, fontWeight: 600, color: "var(--color-text)" }}>{a}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      <GlassButton icon={false} onClick={onAsk}>Ask the Coach</GlassButton>
    </div>
  );
}

/* Ask the Coach — one question a day, a straight answer grounded in the
   member's history. Posts through Store.api.askCoach → /api/coach/ask (the
   server uses the LLM when configured, a stub otherwise) and renders the
   reply in place.

   The one-a-day limit is held client-side: a real (non-offline) answer is
   persisted to Store under `coachAsk` keyed by the local day, so reopening
   the sheet — or reloading — shows today's answer locked instead of a fresh
   input. It resets when the day rolls over (Store.todayKey changes). An
   offline reply is shown but NOT persisted, so the member can retry once
   back online. Server-side enforcement (one CoachMessage per member/day) is
   the durable guard and a clean follow-up; this covers the UX + most cost. */
function AskCoachBody() {
  const today = window.Store.todayKey();
  const prior = (window.Store.load() || {}).coachAsk;
  const askedToday = !!(prior && prior.date === today);

  const [question, setQuestion] = useState(askedToday ? prior.question : "");
  const [answer, setAnswer] = useState(askedToday ? prior.answer : null);
  const [offline, setOffline] = useState(false);
  const [loading, setLoading] = useState(false);
  const [locked, setLocked] = useState(askedToday); // today's question used up

  const send = function () {
    const q = question.trim();
    if (!q || loading || locked) return;
    setLoading(true);
    window.Store.api.askCoach(q).then(function (r) {
      r = r || {};
      const text = r.answer || "No answer came back. Try again.";
      setAnswer(text);
      setOffline(!!r.offline);
      setLoading(false);
      if (!r.offline) {
        setLocked(true);
        window.Store.save({ coachAsk: { date: today, question: q, answer: text } });
      }
    });
  };

  if (answer) {
    return (
      <div>
        <SectionLabel style={{ marginBottom: 8 }}>You asked</SectionLabel>
        <p style={{ fontSize: 15, color: "var(--color-text-muted)", margin: "0 0 16px", lineHeight: 1.5 }}>{question}</p>
        <Card glass style={{ borderRadius: 18, marginBottom: 18 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
            <div className="glass glass-lit glass-amber" style={{ width: 34, height: 34, borderRadius: 9999, color: "var(--color-amber)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icons.Message size={17} /></div>
            <SectionLabel>{offline ? "Saved" : "Coach"}</SectionLabel>
          </div>
          <p style={{ fontSize: 17, fontWeight: 500, lineHeight: 1.5, margin: 0, color: "var(--color-text)" }}>{answer}</p>
        </Card>
        {locked && (
          <p style={{ fontSize: 13, color: "var(--color-text-faint)", textAlign: "center", margin: 0, lineHeight: 1.5 }}>One question a day. Come back tomorrow.</p>
        )}
      </div>
    );
  }

  const canSend = !!question.trim() && !loading;
  return (
    <div>
      <p style={{ fontSize: 15, color: "var(--color-text-muted)", margin: "0 0 16px", lineHeight: 1.5 }}>One question a day. A straight answer, grounded in your history.</p>
      <textarea
        value={question}
        onChange={function (e) { setQuestion(e.target.value); }}
        onKeyDown={function (e) { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
        placeholder="Why does my focus drop midweek?"
        rows={3}
        autoFocus
        disabled={loading}
        className="glass glass-lit"
        style={{ width: "100%", boxSizing: "border-box", borderRadius: 16, padding: "14px 16px", marginBottom: 16, color: "var(--color-text)", fontSize: 15, fontFamily: "var(--font-sans)", lineHeight: 1.5, resize: "none", border: "1px solid var(--glass-border)", outline: "none" }}
      />
      <div style={{ opacity: canSend ? 1 : 0.5, pointerEvents: canSend ? "auto" : "none", transition: "opacity 150ms var(--ease-out)" }}>
        <PrimaryButton icon={false} onClick={send}>{loading ? "Thinking…" : "Send"}</PrimaryButton>
      </div>
    </div>
  );
}

Object.assign(window, { CoachScreen, AskCoachBody });
})();
