// Guided Reset — anchor word + constellation
const SEED_WORDS = [
  "calm", "clarity", "strength", "courage", "boundaries", "patience",
  "recovery", "peace", "gentle", "steady", "rest", "permission",
  "softness", "spacious", "kind", "enough", "breathe", "anchor",
  "slow", "trust", "grace", "release", "still", "hope",
  "lighter", "present", "okay", "rooted", "open", "whole",
];

function GuidedPhase({ state, update, go }) {
  const [stage, setStage] = useState("intro"); // intro | breathing | prompt | reveal
  const [word, setWord] = useState(state.guided.anchorWord || "");
  const [stars, setStars] = useState([]);
  const [breathPhase, setBreathPhase] = useState("hold");
  const [breathLabel, setBreathLabel] = useState("Find a comfortable position.");
  const breathRef = useRef(null);
  const starIdRef = useRef(0);
  const containerRef = useRef(null);

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

  // Breathing loop
  const breatheLoop = (label, scaleTarget, ms, nextCb) => {
    setBreathLabel(label);
    setBreathPhase(scaleTarget === 2.2 ? "inhale" : "exhale");
    breathRef.current = setTimeout(nextCb, ms);
  };

  const startBreathing = () => {
    setStage("breathing");
    const cycle = () => {
      breatheLoop("Breathe in…", 2.2, 4000, () => {
        breatheLoop("Hold…", 2.2, 1500, () => {
          breatheLoop("Breathe out…", 1, 6000, () => {
            breatheLoop("Rest…", 1, 1500, cycle);
          });
        });
      });
    };
    cycle();
  };

  const moveToPrompt = () => {
    if (breathRef.current) clearTimeout(breathRef.current);
    setStage("prompt");
    setBreathLabel("What word do you need this week?");
    setBreathPhase("exhale");
  };

  const submitWord = () => {
    if (!word.trim()) return;
    update("guided", { anchorWord: word.trim() });
    update("plan", (p) => ({ ...p, commitment: p.commitment || `Anchor on the word "${word.trim()}" this week` }));
    setStage("reveal");
    // start spawning stars
    spawnYourWord();
    spawnSeedStars();
  };

  const spawnYourWord = () => {
    const id = starIdRef.current++;
    const newStar = {
      id,
      text: word.trim(),
      x: 50,
      y: 50,
      delay: 0,
      you: true,
    };
    setStars((s) => [...s, newStar]);
  };

  const spawnSeedStars = () => {
    // spawn a stream of seed words over time
    let i = 0;
    const spawn = () => {
      if (i++ > 80) return;
      const id = starIdRef.current++;
      const w = SEED_WORDS[Math.floor(Math.random() * SEED_WORDS.length)];
      const newStar = {
        id,
        text: w,
        x: 4 + Math.random() * 88,
        y: 4 + Math.random() * 88,
        delay: 0,
        you: false,
      };
      setStars((s) => [...s.filter(st => Date.now() - st.born < 14000 || st.you), { ...newStar, born: Date.now() }]);
      setTimeout(spawn, 220 + Math.random() * 380);
    };
    setTimeout(spawn, 400);
  };

  // Orb scale
  const orbScale = breathPhase === "inhale" ? 2.2 : 1;
  const orbMs = breathPhase === "inhale" ? 4000 : 6000;

  if (stage === "intro") {
    return (
      <div className="phase">
        <Eyebrow>Guided Reset</Eyebrow>
        <h2 className="display">Bring it all together.</h2>
        <p className="lede">
          You've recognised your signals, practised breathing, sorted some of your load, found a boundary, and named your next step.
        </p>
        <p className="lede">
          Now we're going to bring it together in a guided reset. Sit comfortably. Place both feet on the floor. Let your shoulders drop.
        </p>

        <window.Sketchnote
          src="assets/sketchnotes/anchor-word.jpeg"
          alt="The Anchor Word — a purposeful tool for wellbeing. Sketchnote summarising how it works: chosen during the Guided Reset, sits as the north star on the Personal Wellbeing Plan, and reappears on the Close page as your anchor for the week. Functions: intention-setting, implementation cue, continuity device, personalisation."
          caption="The Anchor Word — how it works"
          defaultOpen={true}
        />

        <div className="pullquote">
          That word will become your anchor for the week.
        </div>

        <div className="actions">
          <PrimaryButton onClick={startBreathing}>Begin the reset</PrimaryButton>
        </div>
      </div>
    );
  }

  if (stage === "reveal") {
    return (
      <div className="phase" style={{ padding: 0 }}>
        <div className="dark-canvas" ref={containerRef}>
          <Eyebrow style={{ color: "rgba(247,243,236,0.5)" }}>
            <span style={{ color: "rgba(247,243,236,0.5)" }}>Anchor word</span>
          </Eyebrow>
          <div style={{ marginBottom: 20 }}></div>
          <div className="anchor-final">"{word}"</div>
          <p className="caption" style={{ color: "rgba(247,243,236,0.55)", textAlign: "center", maxWidth: 320, margin: "0 auto" }}>
            Carry this word into the week. When pressure rises, return to it.
          </p>

          <div className="anchor-board">
            <div className="anchor-board-label">Others are anchoring on…</div>
            <div className="constellation">
              {stars.map((s) => (
                <span
                  key={s.id}
                  className={`star-word ${s.you ? "you" : ""}`}
                  style={{ left: s.x + "%", top: s.y + "%", animationDelay: s.delay + "ms" }}
                >
                  {s.text}
                </span>
              ))}
            </div>
          </div>

          <div className="anchor-howto">
            <div className="anchor-howto-label">How to use your word this week</div>
            <ul className="anchor-howto-list">
              <li><strong>Write it where you'll see it.</strong> Top of your planner, on a sticky note at your desk, or as your phone lock-screen.</li>
              <li><strong>Say it before the hard moments.</strong> Before opening that email. Before walking into class. Before the parent meeting.</li>
              <li><strong>Return to it when you wobble.</strong> When you feel tension rising, take one breath and silently say your word.</li>
              <li><strong>Let it shape one small choice a day.</strong> If your word is <em>rest</em>, choose rest once. If it's <em>boundaries</em>, hold one this week.</li>
            </ul>
            <p className="anchor-howto-foot">
              You are not the only one carrying this.
            </p>
          </div>

          <div style={{ marginTop: "auto", paddingTop: 40, width: "100%", maxWidth: 360 }}>
            <button
              className="btn btn-primary btn-block"
              style={{ background: "#F7F3EC", color: "#14110F" }}
              onClick={() => go("plan")}
            >
              Continue to my plan
            </button>
          </div>
        </div>
      </div>
    );
  }

  // breathing or prompt stage — share dark canvas
  return (
    <div className="phase" style={{ padding: 0 }}>
      <div className="dark-canvas">
        <Eyebrow>
          <span style={{ color: "rgba(247,243,236,0.5)" }}>Guided Reset</span>
        </Eyebrow>

        <div className="orb-stage">
          <div className="orb-frame">
            <div className="orb-ring"></div>
            <div className="orb" style={{
              transform: `scale(${orbScale})`,
              transition: `transform ${orbMs}ms cubic-bezier(.4,0,.2,1)`,
            }}></div>
          </div>
          <div className="breath-label">{breathLabel}</div>
        </div>

        {stage === "breathing" && (
          <div style={{ width: "100%", maxWidth: 320, marginTop: 24 }}>
            <p style={{ color: "rgba(247,243,236,0.7)", fontFamily: "var(--serif)", fontSize: 17, textAlign: "center", lineHeight: 1.5 }}>
              Ask yourself: <em>what am I carrying that feels heavy? What part of this is mine right now? What part is not?</em>
            </p>
            <p style={{ color: "rgba(247,243,236,0.55)", fontFamily: "var(--serif)", fontSize: 14, textAlign: "center", lineHeight: 1.5, marginTop: 18, fontStyle: "italic" }}>
              When you're ready, you'll choose <strong style={{ color: "rgba(247,243,236,0.85)", fontStyle: "normal" }}>one word</strong> to anchor you for the week — something like <em>calm, clarity, boundaries, rest, courage.</em>
            </p>
            <button
              className="btn btn-ghost btn-block"
              style={{ color: "rgba(247,243,236,0.85)", marginTop: 18, border: "1px solid rgba(247,243,236,0.25)" }}
              onClick={moveToPrompt}
            >
              I'm ready — choose my word →
            </button>
          </div>
        )}

        {stage === "prompt" && (
          <div style={{ width: "100%", maxWidth: 320, marginTop: 20 }}>
            <p style={{ color: "rgba(247,243,236,0.6)", fontSize: 13, textAlign: "center", marginBottom: 12, letterSpacing: "0.04em" }}>
              Calm. Clarity. Strength. Courage. Boundaries. Patience. Recovery.
            </p>
            <input
              className="anchor-input"
              placeholder="your word"
              value={word}
              onChange={(e) => setWord(e.target.value)}
              autoFocus
              maxLength={20}
              onKeyDown={(e) => e.key === "Enter" && submitWord()}
            />
            <button
              className="btn btn-primary btn-block"
              style={{ background: "#F7F3EC", color: "#14110F", marginTop: 28 }}
              onClick={submitWord}
              disabled={!word.trim()}
            >
              Hold this word
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

window.GuidedPhase = GuidedPhase;
