// chapters.jsx — guided lesson chapters: story + Octo dialog + checkpoints

const CHAPTERS = [
  {
    id: "intro",
    title: "Welcome to the Playground",
    badge: null,
    steps: [
      {
        octo: "wave",
        say: "Hi! I'm Octo. Today you and your friend Maya are building a website for the school robotics club. We'll learn Git together!",
        action: null,
      },
      {
        octo: "happy",
        say: "Look at the screen. LEFT = your laptop. RIGHT = GitHub (the cloud). The terminal at the bottom is where you'll type commands.",
        action: null,
      },
      {
        octo: "thinking",
        say: "Try this command to see what's in your folder right now. Type it in the terminal:",
        suggest: "ls",
        check: (state, lastCmd) => lastCmd === "ls",
      },
      {
        octo: "celebrate",
        say: "Empty! That's about to change. Onward!",
      },
    ],
  },
  {
    id: "init",
    title: "Chapter 1 — Make a Repository",
    badge: "init",
    steps: [
      {
        octo: "happy",
        say: "A repository (or 'repo') is just a folder Git is watching. Make one with: git init",
        suggest: "git init",
        check: (state) => state.initialized,
      },
      {
        octo: "celebrate",
        say: "BOOM! 🎉 You just created a hidden .git folder. From now on, Git tracks every change in this folder.",
      },
      {
        octo: "thinking",
        say: "Let's add a file. Type:",
        suggest: 'echo "# Robotics Club" > README.md',
        check: (state) => "README.md" in state.workingDir,
      },
      {
        octo: "happy",
        say: "Now check what Git thinks. Run:",
        suggest: "git status",
        check: (s, c) => c === "git status",
      },
      {
        octo: "thinking",
        say: "See 'Untracked files'? Red means Git sees it but isn't saving it yet. We need TWO MORE STEPS to commit it.",
      },
    ],
  },
  {
    id: "three-areas",
    title: "Chapter 2 — The Three Areas",
    badge: "first-commit",
    steps: [
      {
        octo: "happy",
        say: "Git has THREE areas: Working Directory (your edits) → Staging Area (snapshot you're preparing) → Commits (saved history). Watch the panels on the LEFT.",
      },
      {
        octo: "thinking",
        say: "Move README.md to staging:",
        suggest: "git add README.md",
        check: (s, c) => "README.md" in s.staging,
      },
      {
        octo: "celebrate",
        say: "Yellow chip! It's staged. Now SAVE it as a commit:",
        suggest: 'git commit -m "first commit"',
        check: (s) => Object.keys(s.commits).length >= 1,
      },
      {
        octo: "wave",
        say: "Beautiful! 🟢 The green dot in the commit graph is your first commit. That's a permanent snapshot.",
      },
      {
        octo: "thinking",
        say: "Make a few more files and commits. Try editing README.md and committing again:",
        suggest: 'echo "We build robots." >> README.md',
        check: (s) => s.workingDir["README.md"]?.content?.includes("robots"),
      },
      {
        octo: "happy",
        say: "Now stage and commit it (you know how!):",
        check: (s) => Object.keys(s.commits).length >= 2,
      },
    ],
  },
  {
    id: "remote",
    title: "Chapter 3 — Push to GitHub",
    badge: "first-push",
    steps: [
      {
        octo: "happy",
        say: "Your work is only on your laptop. If your laptop dies, it's gone! Let's connect to GitHub.",
      },
      {
        octo: "thinking",
        say: "Add a remote (in real life, you'd create a repo on github.com first):",
        suggest: "git remote add origin https://github.com/you/robotics.git",
        check: (s) => s.remote.exists,
      },
      {
        octo: "celebrate",
        say: "The right side woke up! Now PUSH your commits to GitHub:",
        suggest: "git push origin main",
        check: (s) => s.remote.branches.main !== undefined,
      },
      {
        octo: "wave",
        say: "Watch the right side fill up. Your commits are now safe in the cloud. ☁️",
      },
    ],
  },
  {
    id: "branches",
    title: "Chapter 4 — Branches",
    badge: "first-branch",
    steps: [
      {
        octo: "happy",
        say: "A branch is a parallel timeline. You can experiment without messing up 'main'. Make a new branch:",
        suggest: "git checkout -b add-team-page",
        check: (s) => s.HEAD === "add-team-page",
      },
      {
        octo: "thinking",
        say: "You're now on a new branch. Add a file:",
        suggest: 'echo "Team: Maya, You" > team.md',
        check: (s) => "team.md" in s.workingDir,
      },
      {
        octo: "happy",
        say: "Stage and commit (do both):",
        check: (s) => {
          const head = s.branches[s.HEAD];
          return head && s.commits[head]?.tree?.["team.md"];
        },
      },
      {
        octo: "celebrate",
        say: "See the orange dot branching off? Now hop back to main:",
        suggest: "git checkout main",
        check: (s) => s.HEAD === "main",
      },
      {
        octo: "thinking",
        say: "Notice — team.md disappeared! That's because it doesn't exist on main. Branches are real, separate worlds. Now MERGE the branch:",
        suggest: "git merge add-team-page",
        check: (s) => "team.md" in s.workingDir && s.HEAD === "main",
      },
      {
        octo: "wave",
        say: "Merged! team.md is back on main. 🎉",
      },
    ],
  },
  {
    id: "pr",
    title: "Chapter 5 — Pull Requests",
    badge: "first-pr",
    steps: [
      {
        octo: "happy",
        say: "On real teams, you don't merge straight to main. You open a Pull Request so others can review your code first.",
      },
      {
        octo: "thinking",
        say: "Make a new branch, add something, commit, and push it:",
        suggest: "git checkout -b add-logo",
        check: (s) => s.HEAD === "add-logo",
      },
      {
        octo: "happy",
        say: "Add a file, stage, commit:",
        suggest: 'echo "🤖 LOGO" > logo.txt',
        check: (s) => {
          const head = s.branches[s.HEAD];
          return head && s.commits[head]?.tree?.["logo.txt"];
        },
      },
      {
        octo: "thinking",
        say: "Push your branch:",
        suggest: "git push origin add-logo",
        check: (s) => s.remote.branches["add-logo"] !== undefined,
      },
      {
        octo: "happy",
        say: "Now open a PR. On real GitHub this is a button — from the terminal you'd use the GitHub CLI:",
        suggest: "gh pr create add-logo main",
        check: (s) => s.remote.pullRequests.length >= 1,
      },
      {
        octo: "celebrate",
        say: "PR #1 is open on the right! Teammates would review here. Once approved, merge it:",
        suggest: "gh pr merge 1",
        check: (s) => s.remote.pullRequests[0]?.status === "merged",
      },
      {
        octo: "wave",
        say: "Merged on the remote. In real life, you'd then 'git pull' to get the merged main onto your laptop.",
      },
    ],
  },
  {
    id: "conflict",
    title: "Chapter 6 — Merge Conflicts",
    badge: "first-merge",
    steps: [
      {
        octo: "thinking",
        say: "Now the scary one — conflicts. They happen when two people edit the same line. Your friend Maya is going to help.",
      },
      {
        octo: "happy",
        say: "First, make sure you're on main:",
        suggest: "git checkout main",
        check: (s) => s.HEAD === "main",
      },
      {
        octo: "thinking",
        say: "Meanwhile, on GitHub, Maya is editing the same README… watch the right side. 👀",
        auto: [
          "collab on",
          'collab edit README.md "# Robotics Club\nMaya was here!"',
          "collab push",
        ],
        check: (s) =>
          s.collaborator.active &&
          s.collaborator.pendingCommits.length === 0 &&
          Object.values(s.remote.commits).some((c) => c.author === "Riley"),
      },
      {
        octo: "happy",
        say: "Maya pushed her change. Now YOU edit the same file differently on your laptop:",
        suggest: 'echo "# Robotics Club\nYour edit here" > README.md',
        check: (s) => s.workingDir["README.md"]?.content?.includes("Your edit"),
      },
      {
        octo: "thinking",
        say: "Stage and commit YOUR version (you know how!):",
        check: (s) => {
          const head = s.branches.main;
          return head && s.commits[head]?.tree?.["README.md"]?.includes("Your edit");
        },
      },
      {
        octo: "happy",
        say: "Now pull Maya's changes. Two versions of one file = conflict time.",
        suggest: "git pull",
        check: (s, c) => c === "git pull" || c === "git fetch",
      },
      {
        octo: "wave",
        say: "Conflicts are normal! In real Git, you'd edit the file to resolve the <<<<< markers, then commit. You did it!",
      },
    ],
  },
  {
    id: "sandbox",
    title: "Free Sandbox",
    badge: null,
    steps: [
      {
        octo: "celebrate",
        say: "You finished the lesson! 🏆 Now play. Try anything. Break things. Type 'help' to see all commands.",
      },
      {
        octo: "wave",
        say: "Pro tip: feature-branch, push, then 'gh pr create' to open a PR. Type 'help' for the full command list.",
      },
    ],
  },
];

// Storyboard & dialog component
function StoryPanel({ chapterIdx, stepIdx, onNext, onPrev, onJump, lastCommand, state, hintsOn }) {
  const chapter = CHAPTERS[chapterIdx];
  const step = chapter.steps[stepIdx];

  // auto-advance when check passes
  useETerm(() => {
    if (!step) return;
    if (step.check && step.check(state, lastCommand)) {
      const t = setTimeout(() => onNext(), 700);
      return () => clearTimeout(t);
    }
  }, [state, lastCommand, chapterIdx, stepIdx]);

  if (!step) return null;
  const stepDone = step.check ? step.check(state, lastCommand) : false;

  return (
    <div className="panel panel-lg" style={{
      background: "linear-gradient(135deg, #FFEAF2 0%, #FFF1E0 100%)",
      padding: 14,
      display: "flex",
      gap: 14,
      alignItems: "flex-start",
      minHeight: 0,
      maxHeight: 130,
      overflow: "hidden",
    }}>
      <Octo mood={step.octo} size={84} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 10, marginBottom: 8,
          flexWrap: "wrap",
        }}>
          <div className="chip" style={{ background: "var(--octo)", color: "white", borderColor: "var(--ink)" }}>
            {chapter.title}
          </div>
          <div className="chip" style={{ background: "white" }}>
            step {stepIdx + 1} / {chapter.steps.length}
          </div>
          <div style={{ flex: 1 }} />
          <button className="btn" onClick={onPrev} style={{ fontSize: 11, padding: "4px 10px" }}>← back</button>
          <button className="btn btn-primary" onClick={onNext} style={{ fontSize: 11, padding: "4px 10px" }}>
            next →
          </button>
        </div>
        <div className="hand" style={{
          fontSize: 22,
          lineHeight: 1.25,
          color: "var(--ink)",
          marginBottom: step.suggest && hintsOn ? 8 : 0,
        }}>
          {step.say}
        </div>
        {step.suggest && hintsOn && (
          <div className="mono" style={{
            display: "inline-block",
            background: "#1A1410",
            color: "#FFD93D",
            padding: "5px 12px",
            borderRadius: 6,
            border: "2px solid var(--ink)",
            fontSize: 13,
            marginTop: 4,
            boxShadow: "var(--shadow-sm)",
          }}>
            $ {step.suggest}
          </div>
        )}
      </div>
    </div>
  );
}

// Chapter navigator (top bar)
function ChapterNav({ chapterIdx, stepIdx, onJump, badges }) {
  return (
    <div style={{ display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }}>
      {CHAPTERS.map((c, i) => {
        const active = i === chapterIdx;
        const done = i < chapterIdx;
        const earned = c.badge && badges.includes(c.badge);
        return (
          <button
            key={c.id}
            onClick={() => onJump(i, 0)}
            className="btn"
            style={{
              fontSize: 11,
              padding: "4px 10px",
              background: active ? "var(--joy)" : done ? "#C7F0BD" : "white",
              opacity: 1,
            }}
          >
            {done ? "✓ " : ""}{i + 1}. {c.title.replace(/^Chapter \d+ — /, "").replace(/^Welcome to the Playground$/, "Intro").replace("Free Sandbox", "Sandbox")}
            {earned && <span style={{ marginLeft: 4 }}>🏆</span>}
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, { CHAPTERS, StoryPanel, ChapterNav });
