// RESET method — intro + 5 step phases
const RESET_STEPS = [
  { key: "recognise", letter: "R", title: "Recognise" },
  { key: "exhale", letter: "E", title: "Exhale" },
  { key: "simplify", letter: "S", title: "Simplify" },
  { key: "establish", letter: "E", title: "Establish" },
  { key: "take", letter: "T", title: "Take" },
];

function ResetProgress({ current }) {
  return (
    <div className="reset-progress">
      {RESET_STEPS.map((s) => (
        <div
          key={s.key}
          className={`reset-dot ${s.key === current ? "current" : (RESET_STEPS.findIndex(x => x.key === current) > RESET_STEPS.findIndex(x => x.key === s.key) ? "done" : "")}`}
        />
      ))}
    </div>
  );
}

function ResetIntroPhase({ go }) {
  return (
    <div className="phase">
      <Eyebrow>The RESET Method</Eyebrow>
      <h1 className="display">Five steps to interrupt a stress spiral.</h1>
      <p className="lede">
        You don't need to solve everything at once. You need to interrupt the pattern and choose the next right action.
      </p>

      <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 20 }}>
        {RESET_STEPS.map((s, i) => (
          <div key={s.key} style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 0", borderBottom: i < 4 ? "1px solid var(--line)" : "none" }}>
            <div style={{
              width: 40, height: 40, borderRadius: 99,
              background: "var(--terra-soft)", color: "var(--terra-deep)",
              fontFamily: "var(--serif)", fontSize: 22, fontWeight: 500,
              display: "flex", alignItems: "center", justifyContent: "center",
              flexShrink: 0,
            }}>{s.letter}</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 19 }}>{s.title}</div>
          </div>
        ))}
      </div>

      <div className="actions">
        <PrimaryButton onClick={() => go("recognise")}>Begin with R</PrimaryButton>
      </div>
    </div>
  );
}

// R = Recognise — body diagram / signal selector
const SIGNALS = [
  { id: "jaw", area: "Jaw", sub: "Clenched, tight, grinding" },
  { id: "shoulders", area: "Shoulders & neck", sub: "Raised, tight, knotted" },
  { id: "chest", area: "Chest", sub: "Tight, shallow breath, racing heart" },
  { id: "gut", area: "Gut", sub: "Knotted, churning, no appetite" },
  { id: "head", area: "Head", sub: "Headache, foggy, hard to focus" },
  { id: "energy", area: "Energy", sub: "Drained, heavy, exhausted" },
  { id: "mood", area: "Mood", sub: "Irritable, snappy, on edge" },
  { id: "behaviour", area: "Behaviour", sub: "Rushing, withdrawing, procrastinating" },
];

function RecognisePhase({ state, update, go }) {
  const { signals, custom } = state.recognise;

  const toggle = (id) => {
    update("recognise", (r) => ({
      ...r,
      signals: r.signals.includes(id) ? r.signals.filter(s => s !== id) : [...r.signals, id],
    }));
  };

  const saveAndContinue = () => {
    // pick first signal as the plan signal
    if (signals.length > 0 && !state.plan.signal) {
      const first = SIGNALS.find(s => s.id === signals[0]);
      update("plan", { signal: first ? first.area : "" });
    } else if (custom.trim() && !state.plan.signal) {
      update("plan", { signal: custom.trim() });
    }
    go("exhale");
  };

  return (
    <div className="phase">
      <ResetProgress current="recognise" />

      <Eyebrow>R &middot; Recognise</Eyebrow>
      <h2 className="display">Where does stress show up in you first?</h2>
      <p className="lede">
        Stress sends signals before it takes over. The earlier you notice yours, the more options you have. Tap every signal you recognise.
      </p>

      <div className="body-zones">
        {SIGNALS.map((s) => (
          <div
            key={s.id}
            className={`zone-row ${signals.includes(s.id) ? "on" : ""}`}
            onClick={() => toggle(s.id)}
          >
            <div className="zone-icon">{s.area.charAt(0)}</div>
            <div style={{ flex: 1 }}>
              <div className="zone-name">{s.area}</div>
              <div className="zone-sub">{s.sub}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 16 }}>
        <div className="caption" style={{ marginBottom: 6 }}>My earliest signal is usually…</div>
        <input
          className="input"
          placeholder="e.g. I go quiet, my jaw tightens, I start rushing"
          value={custom}
          onChange={(e) => update("recognise", { custom: e.target.value })}
        />
      </div>

      <div className="pullquote">
        Your body often tells the truth before your mouth does.
      </div>

      <window.Sketchnote
        src="assets/sketchnotes/reset-method.jpg"
        alt="The RESET Method sketchnote — all five steps"
        caption="The full RESET sketchnote"
        defaultOpen={true}
      />

      <div className="actions">
        <PrimaryButton onClick={saveAndContinue}>Continue to Exhale</PrimaryButton>
      </div>
    </div>
  );
}

// E = Exhale — breathing orb
function ExhalePhase({ state, update, go }) {
  const [phase, setPhase] = useState("idle"); // idle | inhale | hold | exhale | rest | done
  const [round, setRound] = useState(0);
  const [label, setLabel] = useState("Tap to begin");
  const timerRef = useRef(null);
  const TOTAL_ROUNDS = 3;

  useEffect(() => {
    return () => { if (timerRef.current) clearTimeout(timerRef.current); };
  }, []);

  const runCycle = (r) => {
    if (r >= TOTAL_ROUNDS) {
      setPhase("done");
      setLabel("Well done.");
      update("exhale", { completed: true });
      return;
    }
    setRound(r);
    setPhase("inhale");
    setLabel("Breathe in… 4");
    timerRef.current = setTimeout(() => {
      setPhase("hold");
      setLabel("Hold…");
      timerRef.current = setTimeout(() => {
        setPhase("exhale");
        setLabel("Breathe out… 6");
        timerRef.current = setTimeout(() => {
          setPhase("rest");
          setLabel("Rest…");
          timerRef.current = setTimeout(() => runCycle(r + 1), 1000);
        }, 6000);
      }, 1500);
    }, 4000);
  };

  const start = () => {
    setPhase("inhale");
    runCycle(0);
  };

  // Orb scale based on phase
  let scale = 1;
  let transitionMs = 4000;
  if (phase === "inhale") { scale = 2.2; transitionMs = 4000; }
  else if (phase === "hold") { scale = 2.2; transitionMs = 1500; }
  else if (phase === "exhale") { scale = 1; transitionMs = 6000; }
  else if (phase === "rest") { scale = 1; transitionMs = 1000; }
  else if (phase === "done") { scale = 1.3; transitionMs = 800; }

  return (
    <div className="phase">
      <ResetProgress current="exhale" />
      <Eyebrow>E &middot; Exhale</Eyebrow>
      <h2 className="display">Calm the body before you respond.</h2>
      <p className="lede">
        You cannot think clearly while your body is still in alarm mode. Three rounds. Follow the orb.
      </p>

      <div className="orb-stage">
        <div className="orb-frame">
          <div className="orb-ring"></div>
          <div className="orb" style={{ transform: `scale(${scale})`, transition: `transform ${transitionMs}ms cubic-bezier(.4,0,.2,1)` }}></div>
        </div>
        <div className="breath-label">{label}</div>
        <div className="breath-count">
          {phase !== "idle" && phase !== "done" ? `Round ${round + 1} of ${TOTAL_ROUNDS}` : phase === "done" ? "3 rounds complete" : ""}
        </div>
      </div>

      <div className="actions">
        {phase === "idle" && (
          <PrimaryButton onClick={start}>Start breathing</PrimaryButton>
        )}
        {phase !== "idle" && phase !== "done" && (
          <GhostButton onClick={() => { if (timerRef.current) clearTimeout(timerRef.current); setPhase("idle"); setLabel("Tap to begin"); }}>
            Stop
          </GhostButton>
        )}
        {phase === "done" && (
          <PrimaryButton onClick={() => go("simplify")}>Continue to Simplify</PrimaryButton>
        )}
        {phase === "idle" && state.exhale.completed && (
          <GhostButton onClick={() => go("simplify")}>Skip — I've done this before</GhostButton>
        )}
      </div>
    </div>
  );
}

// S = Simplify — load sort
const LOAD_LABELS = [
  { id: "today", label: "Do today", cls: "l-today" },
  { id: "schedule", label: "Schedule", cls: "l-sched" },
  { id: "simplify", label: "Simplify", cls: "l-simp" },
  { id: "release", label: "Release", cls: "l-rel" },
];

function SimplifyPhase({ state, update, go }) {
  const { tasks } = state.simplify;

  const setTask = (id, patch) => {
    update("simplify", (s) => ({
      ...s,
      tasks: s.tasks.map((t) => t.id === id ? { ...t, ...patch } : t),
    }));
  };

  const allLabeled = tasks.every((t) => !t.text.trim() || t.label);
  const hasAtLeastOne = tasks.some((t) => t.text.trim() && t.label);

  return (
    <div className="phase">
      <ResetProgress current="simplify" />
      <Eyebrow>S &middot; Simplify</Eyebrow>
      <h2 className="display">Sort the load before it crushes you.</h2>
      <p className="lede">
        Not everything screaming for attention is genuinely urgent. List three things on your plate and label each.
      </p>

      <div style={{ marginTop: 8 }}>
        {tasks.map((t, i) => (
          <div key={t.id} className="task-row">
            <input
              className="input"
              placeholder={`Task ${i + 1}`}
              value={t.text}
              onChange={(e) => setTask(t.id, { text: e.target.value })}
            />
            {t.text.trim() && (
              <div className="label-pills">
                {LOAD_LABELS.map((l) => (
                  <div
                    key={l.id}
                    className={`label-pill ${t.label === l.id ? `on ${l.cls}` : ""}`}
                    onClick={() => setTask(t.id, { label: l.id })}
                  >
                    {l.label}
                  </div>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>

      <div className="pullquote">
        Simplifying is not lowering your standards. It is protecting your capacity for what matters most.
      </div>

      <div className="actions">
        <PrimaryButton onClick={() => go("establish")} disabled={!hasAtLeastOne}>
          Continue to Establish
        </PrimaryButton>
      </div>
    </div>
  );
}

// E = Establish — boundary phrases
const BOUNDARIES = [
  { context: "When asked to take on more", phrase: "I can assist with this, but I need clarity on what should be deprioritised." },
  { context: "When something can't be done today", phrase: "I cannot complete this today, but I can schedule it for…" },
  { context: "When pressured to reply immediately", phrase: "I need time to review this properly before responding." },
  { context: "When asked to absorb someone else's crisis", phrase: "I can support, but I cannot carry responsibility that does not belong to me." },
  { context: "When the conversation is spiralling", phrase: "Let us agree on the next practical step." },
  { context: "When work creeps past your hours", phrase: "I'll respond to this during work hours tomorrow." },
];

function EstablishPhase({ state, update, go }) {
  const { saved } = state.establish;

  const toggle = (i) => {
    update("establish", (e) => ({
      ...e,
      saved: e.saved.includes(i) ? e.saved.filter(x => x !== i) : [...e.saved, i],
    }));
  };

  const saveAndContinue = () => {
    if (saved.length > 0 && !state.plan.boundary) {
      update("plan", { boundary: BOUNDARIES[saved[0]].phrase });
    }
    go("take");
  };

  return (
    <div className="phase">
      <ResetProgress current="establish" />
      <Eyebrow>E &middot; Establish a boundary</Eyebrow>
      <h2 className="display">Protect your capacity.</h2>
      <p className="lede">
        A boundary is not a wall. It's a gate. Tap the phrases you could actually use this week.
      </p>

      <div className="boundary-list">
        {BOUNDARIES.map((b, i) => (
          <div
            key={i}
            className={`boundary-card ${saved.includes(i) ? "saved" : ""}`}
            onClick={() => toggle(i)}
          >
            <div className="b-context">{b.context}</div>
            <div className="b-phrase">"{b.phrase}"</div>
            <div className="b-check">{saved.includes(i) ? "✓ Saved to my plan" : "Tap to save"}</div>
          </div>
        ))}
      </div>

      <div className="pullquote">
        Many people burn out not because they don't care, but because they care without limits.
      </div>

      <div className="actions">
        <PrimaryButton onClick={saveAndContinue} disabled={saved.length === 0}>
          Continue to Take
        </PrimaryButton>
      </div>
    </div>
  );
}

// T = Take one next step
function TakePhase({ state, update, go }) {
  const { next } = state.take;

  const saveAndContinue = () => {
    if (next.trim()) {
      update("plan", { nextStep: next.trim() });
    }
    go("guided");
  };

  return (
    <div className="phase">
      <ResetProgress current="take" />
      <Eyebrow>T &middot; Take one next step</Eyebrow>

      <h2 className="display">Move forward without spiralling.</h2>
      <p className="lede">
        Stress wants you to solve everything at once. Wisdom asks you to choose the next right action.
      </p>

      <div className="card">
        <div className="caption" style={{ marginBottom: 8 }}>The next right action for me is…</div>
        <textarea
          className="input text-display"
          placeholder="One small, doable thing. Not a plan. An action."
          value={next}
          onChange={(e) => update("take", { next: e.target.value })}
          rows={3}
        />
        <div className="caption" style={{ marginTop: 12, fontSize: 12 }}>
          Examples: reply to one email, drink water, take three breaths, close the laptop at 5pm, ask for clarification.
        </div>
      </div>

      <div className="pullquote">
        One next step is how you take back movement when stress has made you feel stuck.
      </div>

      <div className="actions">
        <PrimaryButton onClick={saveAndContinue} disabled={!next.trim()}>
          Continue to Guided Reset
        </PrimaryButton>
      </div>
    </div>
  );
}

Object.assign(window, {
  ResetIntroPhase, RecognisePhase, ExhalePhase, SimplifyPhase, EstablishPhase, TakePhase,
});
