// Forage & Forests — Rulebook overlay.
// Faithful to docs/rulebook-cards-only.md (v3) and the live engine. Rendered
// as structured JSX so we get proper type, tables, and section linking
// without a markdown parser. This is the CARD game — no board, no meeples,
// no tokens.

/* eslint-disable no-undef */

// "Anatomy of a card" diagram: a real <ForageCardFace/> sample beside a
// legend describing each region the player actually sees in play.
function AnnotatedCard() {
  const all = (window.HH && window.HH.FORAGE_CARDS) || [];
  const sample =
    all.find((c) => c.card_type !== "guidance" && c.id_feature && c.foraging_tidbits && c.art_path) ||
    all.find((c) => c.card_type !== "guidance") ||
    all[0];

  const legend = [
    { title: "Name & scientific name", body: "The plant you're learning, with its Latin binomial so two cards can never be confused." },
    { title: "Layer tag", body: "Which food-forest layer(s) this card can fill when you build — Canopy, Shrub, Herb, Root, and so on." },
    { title: "Botanical illustration", body: "The visual key. Field-guide art so the plant is recognisable at a glance, play after play." },
    { title: "Biome(s) & current yield", body: "Where the plant grows and what it's worth right now, this season. \u201cDormant\u201d means no yield until a later season." },
    { title: "Seasonal yield grid", body: "Per-season value — resource icons with counts: a flame for Calories, a tincture flower for Botanicals, a seed for Seeds. The active season is highlighted; \u201c\u2014\u201d means no yield that season. A card's value = the highlighted season's icons combined." },
    { title: "How to identify", body: "What to look for in the field — leaf shape, habit, smell. Real foraging knowledge, not just flavour." },
    { title: "Field notes", body: "Foraging factoids: edibility, lookalikes, preparation, and season tips." },
  ];

  if (!sample) return null;
  return (
    <div style={{
      border: "1px solid var(--rule)",
      background: "var(--paper-warm)",
      padding: "20px 22px 22px",
      margin: "12px 0 18px",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14, flexWrap: "wrap", gap: "2px 12px" }}>
        <SmallCaps>Plate · anatomy of a card</SmallCaps>
        <SmallCaps className="muted">{sample.name}{sample.scientific_name ? ` · ${sample.scientific_name}` : ""}</SmallCaps>
      </div>

      <div className="hh-anatomy">
        <div style={{ display: "flex", justifyContent: "center" }}>
          <ForageCardFace card={sample} season="Fall" />
        </div>
        <ol style={{ margin: 0, paddingLeft: 20, font: "400 14px/1.5 'EB Garamond', serif", color: "var(--ink-soft)" }}>
          {legend.map((row, i) => (
            <li key={i} style={{ marginBottom: 8 }}>
              <strong style={{ color: "var(--ink)" }}>{row.title}.</strong> {row.body}
            </li>
          ))}
        </ol>
      </div>
    </div>
  );
}

function RulebookTOC({ onJump }) {
  const sections = [
    ["overview", "Overview"],
    ["components", "Components"],
    ["anatomy", "Anatomy of a Card"],
    ["setup", "Setup"],
    ["turn", "How a Turn Works"],
    ["market", "The Market"],
    ["building", "Building"],
    ["mushrooms", "Mushrooms & Guidance"],
    ["seasons", "Seasons & Events"],
    ["weevils", "Weevils"],
    ["scoring", "Scoring"],
    ["endgame", "Endgame & Length"],
    ["community", "Community Forests (Advanced)"],
    ["faq", "Frequently Asked Questions"],
    ["glossary", "Glossary"],
  ];
  return (
    <nav style={{
      border: "1px solid var(--rule)",
      background: "var(--paper-warm)",
      padding: 14,
      marginBottom: 20,
    }}>
      <SmallCaps>Table of contents</SmallCaps>
      <ol style={{ margin: "8px 0 0", paddingLeft: 20, columns: 2, columnGap: 30, font: "400 14px/1.7 'EB Garamond', serif" }}>
        {sections.map(([id, label]) => (
          <li key={id} style={{ breakInside: "avoid" }}>
            <a href={`#hh-rb-${id}`}
               onClick={(e) => { e.preventDefault(); onJump(id); }}
               style={{ color: "var(--ink)", textDecoration: "underline", textDecorationColor: "var(--rule)" }}>
              {label}
            </a>
          </li>
        ))}
      </ol>
    </nav>
  );
}

function RulebookContent() {
  return (
    <article className="hh-rulebook">
      <p style={{ font: "italic 400 16px/1.55 'EB Garamond', serif", color: "var(--ink-soft)" }}>
        A cards-only foraging game for 2–6 foragers, 20–30 minutes. No board,
        no meeples, no tokens — just one plant deck, one event deck, and the
        turning seasons. Collect wild plant cards, harvest the ripe ones to
        claim more from the market, and time your plays to build food forests
        before the weevils hit.
      </p>
      <p style={{ font: "italic 400 15px/1.55 'EB Garamond', serif", color: "var(--ink-soft)" }}>
        Every card is a <strong style={{ color: "var(--ink)" }}>real plant</strong>. Learn when each one yields, where it
        grows, and which food-forest layer it fills, and you turn a fistful of
        cards into a lasting, scoring pile.
      </p>
      <blockquote>
        <strong>Quick start.</strong> First time playing? Read Setup and How a
        Turn Works, then start building. Come back to Scoring and Mushrooms as
        questions come up.
      </blockquote>

      <h2 id="hh-rb-overview">Overview</h2>
      <p>
        The seasons cycle continuously — <strong>Spring → Summer → Fall → Winter → Spring …</strong>
        — with two rounds per season. On your turn you do two things in order:
      </p>
      <ol>
        <li><strong>Market acquisition.</strong> Make <em>one</em> acquisition: <strong>draw 1</strong> blind from the deck, take the <strong>oldest market card free</strong>, or buy a <strong>bundle</strong> (the free oldest card plus newer ones) in a single transaction, paying by <strong>harvesting</strong> in-season cards. You can't take a free card and then buy more.</li>
        <li><strong>Main action.</strong> Do one of: build a biome forest, build a layer set, build a mushroom set, burn a card, or pass.</li>
      </ol>
      <p>
        You score by <strong>building</strong> — committing sets of cards into your face-down
        scoring pile, where they're safe and locked in. There are <strong>two ways to
        win</strong>: build forests in a target number of <strong>distinct biomes</strong> to win the
        race outright, or be ahead on <strong>points</strong> when someone crosses the points
        target. Whichever someone reaches first ends the game.
      </p>
      <p>
        There is <strong>no hand limit</strong>. The catch: when a weevil event hits, you lose
        half the cards you're holding. Cards already built into a forest or set
        are safe. The game rewards <strong>learning the deck</strong> — each plant's yield shifts
        with the season, so <em>when</em> you play a card matters as much as <em>what</em> it is.
      </p>

      <h2 id="hh-rb-components">Components</h2>
      <ul>
        <li><strong>Plant deck — 86 cards.</strong> 71 plant cards + 11 mushroom cards + 4 Foraging Safety &amp; Guidance cards. Each plant/mushroom shows its biome(s), layer(s), per-season yield values (Cal/Bot/Seeds), and a field-guide ID note. Mushrooms carry a mycelium glyph.</li>
        <li><strong>Event deck — 24 cards.</strong> One event is revealed at each season change, colour-coded by tone (boon / blight / calm / social): pests, frost, floods and storms, feasts, droughts, abundance, the market, knowledge, gifts and trades. A few are <em>choices</em> (burn a resource card or take a bigger loss) or <em>optional</em> boons. The card flips up face-down → reveal, then you resolve its effect.</li>
        <li><strong>The Forager's Codex.</strong> The 4 guidance cards carry real safety rules instead of yields. They can't be harvested or burned and are weevil-safe (never owed to a discard event). See <a href="#hh-rb-mushrooms" onClick={(e) => { e.preventDefault(); document.getElementById("hh-rb-mushrooms")?.scrollIntoView({ behavior: "smooth", block: "start" }); }} style={{ color: "var(--ink)" }}>Mushrooms &amp; Guidance</a>.</li>
        <li><strong>Season tracker.</strong> Spring / Summer / Fall / Winter, plus a pip for the round-within-season (1 or 2).</li>
      </ul>
      <p style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>
        That's it — no meeples, no rings, no resource tokens. In this digital
        version the deck, market, season tracker, and scoring are all kept for you.
      </p>

      <h2 id="hh-rb-anatomy">Anatomy of a Card</h2>
      <p>Every card teaches its own plant. Here is how to read one:</p>
      <AnnotatedCard />
      <p style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>
        Mushroom cards use the same layout with a mycelium glyph and act as wildcards (double-stack for the Mycorrhizal layer) — see <a href="#hh-rb-mushrooms" onClick={(e) => { e.preventDefault(); document.getElementById("hh-rb-mushrooms")?.scrollIntoView({ behavior: "smooth", block: "start" }); }} style={{ color: "var(--ink)" }}>Mushrooms &amp; Guidance</a>.
      </p>

      <h2 id="hh-rb-setup">Setup</h2>
      <ol>
        <li><strong>Choose your foragers.</strong> Play solo against bots or pass-and-play with up to 6 foragers total.</li>
        <li><strong>Choose a game length</strong> — Sprint (3 biomes / 25 points, ~10 min), Standard (4 biomes / 42 points, ~20 min), or Marathon (5 biomes / 55 points, ~60 min).</li>
        <li>Shuffle the plant deck. Each forager is dealt a <strong>3-card</strong> starting hand. Hands are private.</li>
        <li>Lay out a <strong>4-card face-up market</strong>.</li>
        <li><strong>Begin at winter's end.</strong> You've just crossed the mountain pass into new lands as winter is ending — the opening <em>Across the Pass</em> round is a <strong>calm gather round</strong> (no event, no weevils) so everyone fills a hand. <strong>Spring arrives next round</strong> and turns over the first event card; the seasons cycle normally from there.</li>
      </ol>
      <p>The standard game ends when a forager builds <strong>4 distinct biomes</strong> (an instant win) or reaches <strong>42 points</strong>, whichever comes first.</p>

      <h2 id="hh-rb-turn">How a Turn Works</h2>
      <p>
        On your turn you take the <strong>market phase</strong>, then <strong>one main action</strong>, then end
        the turn. Play passes left. After every forager has taken a turn, the
        round ends; two rounds make a season. At each season change the market
        refreshes and a new event card is revealed.
      </p>
      <p><strong>The free pick &amp; market phase</strong> (optional): take your one free card — draw 1 blind from the deck, or claim a free market card — then buy extra market cards by harvesting. See <a href="#hh-rb-market" onClick={(e) => { e.preventDefault(); document.getElementById("hh-rb-market")?.scrollIntoView({ behavior: "smooth", block: "start" }); }} style={{ color: "var(--ink)" }}>The Market</a>.</p>
      <p style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>
        You <strong>choose</strong> exactly which cards to play into any build — nothing is forced. A card that fits two biomes, or a mushroom you'd rather save for a set, can always be held back.
      </p>
      <p><strong>Your main action</strong> — pick exactly one:</p>
      <table>
        <thead><tr><th>Action</th><th>Effect</th></tr></thead>
        <tbody>
          <tr><td><strong>Build a biome forest</strong></td><td>Play a set of cards from one biome covering 3+ different layers. You choose which cards. Scores immediately into your pile.</td></tr>
          <tr><td><strong>Build a layer set</strong></td><td>Play 3+ plants that all share one layer, from any biomes. You choose which cards. Scores immediately.</td></tr>
          <tr><td><strong>Build a mushroom set</strong></td><td>Play 4+ different mushroom cards together. Big points.</td></tr>
          <tr><td><strong>Burn</strong></td><td>Discard 1 card from your hand. Defensive only — clears clutter before weevils. No reward.</td></tr>
          <tr><td><strong>Pass</strong></td><td>Take no main action.</td></tr>
        </tbody>
      </table>
      <p style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>
        Drawing is your <strong>free pick</strong>, not a main action — so you can draw your one card
        <em> and</em> still build, clear, or pass the same turn.
      </p>

      <h2 id="hh-rb-market">The Market</h2>
      <p>
        Each turn you make <strong>one</strong> market acquisition — you can't take a free card
        <em> and</em> then buy more; it's a single transaction. You either take the
        <strong> oldest card for free</strong>, <em>or</em> buy a <strong>bundle</strong> in one go: the oldest card
        plus the next-newer ones beside it. (Your one free pick can instead be a
        blind <strong>deck draw</strong> — but then you've spent your acquisition and skip the
        market this turn.)
      </p>
      <p>
        The market is priced <strong>oldest → newest</strong>; buying up to a given card also
        sweeps every cheaper card before it, and the free oldest card is always
        part of the bundle. You pay by <strong>harvesting</strong> — discarding in-season cards
        whose combined <strong>value</strong> (the current season's Cal + Bot + Seeds) meets or
        exceeds the bundle's cost. You may overpay; excess value is lost.
      </p>
      <table>
        <thead><tr><th>Cards in the bundle</th><th>Added cost</th><th>Bundle total</th></tr></thead>
        <tbody>
          <tr><td>1 (oldest — free)</td><td>0</td><td>0</td></tr>
          <tr><td>2</td><td>1</td><td>1</td></tr>
          <tr><td>3</td><td>2</td><td>3</td></tr>
          <tr><td>4</td><td>3</td><td>6</td></tr>
          <tr><td>5</td><td>5</td><td>11</td></tr>
        </tbody>
      </table>
      <p>
        Cost is paid in <strong>value points</strong>, not specific resources. A Wild Garlic
        worth Cal 1 + Bot 2 = 3 value in Spring can cover a two-card bundle
        (cost 1) with value to spare. The same card in Summer is worth 0 and
        can't pay for anything.
      </p>
      <p style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>
        Mushrooms and guidance cards have no market value and can't pay for takes —
        they're worth holding for builds.
      </p>

      <h2 id="hh-rb-building">Building</h2>
      <p>
        Building is how you score. There are three kinds of build; all of them
        score the instant you play them and move the played cards face-down into
        your <strong>scoring pile</strong>, where they're safe from weevils and locked in for
        the rest of the game. <strong>You choose exactly which cards go into each build.</strong>
      </p>

      <h3>The seven layers</h3>
      <p>A build scores by the number of <strong>different layer types</strong> it covers, drawn from the permaculture stack:</p>
      <ol>
        <li><strong>Canopy</strong> — tall trees (oak, walnut, conifers)</li>
        <li><strong>Sub-canopy</strong> — understory trees (serviceberry, sassafras)</li>
        <li><strong>Shrub</strong> — berries and woody bushes (elderberry, blackberry)</li>
        <li><strong>Herb</strong> — non-woody flowering plants (ramps, nettle)</li>
        <li><strong>Ground</strong> — low spreading plants (wild strawberry, violet)</li>
        <li><strong>Vine</strong> — climbers (wild grape, groundnut)</li>
        <li><strong>Root</strong> — taproots and tubers (burdock, Jerusalem artichoke)</li>
      </ol>
      <p>An 8th <strong>Mycorrhizal Network</strong> layer unlocks only when a mushroom is in the build.</p>

      <h3>Biome forests</h3>
      <p>
        A biome forest is a set of cards covering <strong>3+ different layers</strong> in one
        biome. <strong>Multi-biome cards</strong> (most generalists list 2–3 biomes) count toward
        whichever forest you build them into, then commit to it. <strong>One plant per
        layer</strong> — you can't double up a layer with a second plant. The one exception
        is the <strong>mushroom wildcard</strong>: a mushroom may <strong>double-stack</strong> onto a
        layer that's already filled, adding the Mycorrhizal Network as one extra layer —
        but only <strong>one double-stack (one mushroom) per biome forest</strong>. A mushroom
        does <strong>not</strong> unlock a biome's restricted layers. Each biome's
        restrictions cap how many layers you can reach in a single forest (a double-stack adds one more):
      </p>
      <table>
        <thead><tr><th>Biome</th><th>Buildable layers</th><th>Max</th><th>+ mushroom</th></tr></thead>
        <tbody>
          <tr><td>Forest</td><td>All 7</td><td>7</td><td>8</td></tr>
          <tr><td>Forest Edge</td><td>All 7</td><td>7</td><td>8</td></tr>
          <tr><td>Wetland</td><td>All except Canopy</td><td>6</td><td>7</td></tr>
          <tr><td>Disturbed</td><td>All except Canopy</td><td>6</td><td>7</td></tr>
          <tr><td>Mountain</td><td>All except Vine</td><td>6</td><td>7</td></tr>
          <tr><td>Meadow</td><td>Shrub, Herb, Ground, Root</td><td>4</td><td>5</td></tr>
        </tbody>
      </table>
      <p>
        <strong>Completion bonus.</strong> Fill <em>all</em> of a biome's buildable layers and earn
        <strong> +5</strong> on top of the layer score. You may build any number of forests in the
        same biome over the game — each is scored on its own.
      </p>

      <h3>Layer sets</h3>
      <p>
        A layer set ignores biome restrictions: play <strong>3+ plants that all share
        one layer</strong> (three Herbs, four Shrubs, and so on), drawn from any biomes.
        Mushrooms and guidance don't count. It scores on its own curve
        (3 cards → 3, 4 → 6, 5 → 10, 6 → 15, 7 → 21, 8 → 28) plus the in-season value bonus.
        A layer set does <strong>not</strong> count toward the biome trigger or set bonus —
        it's the answer to "I drew the same layer over and over."
      </p>

      <h3>Mushroom sets</h3>
      <p>
        Play <strong>4+ different mushrooms</strong> (by name) together for a huge bonus —
        20 / 30 / 45 / 60 / 75 points for 4 / 5 / 6 / 7 / 8+. With only ~11
        mushrooms in the deck, this is a serious commitment, but it dwarfs
        everything else. Mushroom sets don't count toward the biome trigger.
      </p>

      <h2 id="hh-rb-mushrooms">Mushrooms &amp; Guidance</h2>
      <h3>Mushrooms — the wildcard</h3>
      <p>Mushrooms can't pay for the market (though they're forage, so you may burn one). They have three roles:</p>
      <ul>
        <li><strong>In hand</strong> — weevil-safe. Pest events never take them automatically or count them in what you owe, though you may always discard one by choice.</li>
        <li><strong>In a biome build (wildcard)</strong> — a mushroom plays two ways. <em>As its own layer:</em> like a plant, it fills one of its listed layers that's still open (several mushrooms can join a build this way, each on a different layer). <em>As a double-stack:</em> placed on top of an already-filled layer, it adds the <strong>Mycorrhizal Network</strong> as one extra layer — so a full Forest (7 layers) plus a double-stacked mushroom reaches 8 (top tier + completion). <strong>Limit: one double-stack per biome forest.</strong> A mushroom does <strong>not</strong> lift a biome's layer restrictions.</li>
        <li><strong>In a mushroom set</strong> — 4+ different ones for mega points.</li>
      </ul>
      <p style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>
        The tension: a mushroom spent plugging a forest gap can't also go in a set, and vice versa.
      </p>
      <h3>The Forager's Codex (guidance cards)</h3>
      <p>
        Four guidance cards carry real safety rules — <strong>Positive ID</strong>, <strong>Beware
        Lookalikes</strong>, <strong>Prepare &amp; Process</strong>, <strong>Harvest Responsibly</strong>. They have no
        yield, can't be harvested or burned, and are weevil-safe (never owed to a discard event, though you may give one up by choice). They do double duty:
      </p>
      <ul>
        <li><strong>Wild (spend one).</strong> When building a biome forest, add one guidance card to fill a single missing layer. It can't exceed the biome's layer cap.</li>
        <li><strong>The Codex (hold all four).</strong> Play all 4 together for a flat <strong>+25 bonus</strong> — mastery of safe foraging.</li>
      </ul>

      <h2 id="hh-rb-seasons">Seasons &amp; Events</h2>
      <p>
        The game opens at <strong>winter's end</strong> (the calm <em>Across the Pass</em> arrival round —
        no event), then seasons cycle <strong>Spring → Summer → Fall → Winter → Spring …</strong>,
        two rounds each. The <strong>first event card is a Spring event</strong>, drawn after everyone's
        had a round to gather. At every season change, the old event is discarded, the season advances, a
        new event is revealed, and the market is refreshed. The season change is
        also when <strong>card values shift</strong> — a Spring-rich card goes worthless in Summer
        and ripens again in Fall. Timing your plays around the cycle is the central
        strategic axis.
      </p>
      <p>
        The 24-card deck is colour-coded by tone — <strong>boon</strong> (good),
        <strong> blight</strong> (bad), <strong>calm</strong>, and <strong>social</strong>. At a season
        change the card flips up face-down, you reveal it, then resolve its effect.
      </p>
      <table>
        <thead><tr><th>Event</th><th>Effect</th></tr></thead>
        <tbody>
          <tr><td><strong>Still Day</strong> ⬜</td><td>Nothing — a quiet turn.</td></tr>
          <tr><td><strong>Pest Pressure</strong> 🟥</td><td>Each forager discards 1 card of their choice.</td></tr>
          <tr><td><strong>Infestation</strong> 🟥</td><td>Each forager discards half their hand (round up).</td></tr>
          <tr><td><strong>Drying Wind</strong> 🟥</td><td>Each forager discards 1 out-of-season card.</td></tr>
          <tr><td><strong>Hard Frost</strong> 🟥</td><td>Each forager discards 1 in-season card.</td></tr>
          <tr><td><strong>Sudden Storm</strong> 🟥</td><td>Each forager discards 1 card at random.</td></tr>
          <tr><td><strong>Rot</strong> 🟥</td><td>Each forager discards their lowest-value in-season card.</td></tr>
          <tr><td><strong>Thicket</strong> 🟥</td><td>Each discards 1; the forager with the most cards discards 1 more.</td></tr>
          <tr><td><strong>Wildfire</strong> 🟥</td><td>Each forager discards 1 in-season card, then draws 1.</td></tr>
          <tr><td><strong>Accident</strong> 🟥</td><td>Discard a Botanical card this season, or discard 3 cards.</td></tr>
          <tr><td><strong>Harvest Feast</strong> 🟥</td><td>Discard a Calorie card this season, or discard 3 cards.</td></tr>
          <tr><td><strong>Drought</strong> 🟥</td><td>Discard a Seed card this season, or discard 2 cards.</td></tr>
          <tr><td><strong>Bounty</strong> 🟩</td><td>Each forager draws 2 cards.</td></tr>
          <tr><td><strong>Open Market</strong> 🟩</td><td>Refresh the market; each forager takes 1 card free.</td></tr>
          <tr><td><strong>Knowledge Keeper</strong> 🟩</td><td>Look at the top 3 of the deck and keep the best 1.</td></tr>
          <tr><td><strong>Mentor's Visit</strong> 🟩</td><td>Look at the top 2 of the deck and keep the best 1.</td></tr>
          <tr><td><strong>Forager's Cache</strong> 🟩</td><td>Take the top card of the discard pile (or draw 1 if empty).</td></tr>
          <tr><td><strong>Overgrowth</strong> 🟩</td><td>Hold 4 or fewer cards? Draw 2; otherwise draw 1.</td></tr>
          <tr><td><strong>Reseed</strong> 🟩</td><td>You may discard a Seed card this season to draw 2.</td></tr>
          <tr><td><strong>Foraged Medicine</strong> 🟩</td><td>You may discard a Botanical card this season to draw 2.</td></tr>
          <tr><td><strong>Hearty Provisions</strong> 🟩</td><td>You may discard a Calorie card this season to take a free market card.</td></tr>
          <tr><td><strong>Forager's Gift</strong> 🟦</td><td>Each forager passes 1 card to the player on their left, all at once.</td></tr>
          <tr><td><strong>Generous Neighbor</strong> 🟦</td><td>Each forager passes 1 card to the player on their right, then draws 1.</td></tr>
          <tr><td><strong>Market Fair</strong> 🟦</td><td>Each forager may swap 1 hand card with 1 market card.</td></tr>
        </tbody>
      </table>

      <h2 id="hh-rb-weevils">Weevils</h2>
      <p>
        Many events cull cards from hands when revealed at a season change. For most
        (<strong>Pest Pressure</strong>, <strong>Infestation</strong>, <strong>Drying Wind</strong>,
        <strong> Hard Frost</strong>) <strong>you choose which eligible cards to drop</strong>; Sudden
        Storm is random and Rot takes your lowest-value in-season card. Mushrooms and
        guidance in your hand are safe from <em>automatic</em> loss — they never count toward
        what an event makes you discard, and random or forced discards can't take them —
        but when the pick is yours, you may always choose one. Cards in your scoring pile
        are never touched.
      </p>
      <p style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>
        <strong>Winter kills the weevils.</strong> The two true pest events — Pest Pressure and
        Infestation — are <strong>neutralized</strong> if they turn over in Winter (too cold
        for bugs): the card still appears, but has no effect. Frost and drying wind
        still bite, even in Winter.
      </p>
      <p>
        Weevils are the reason there's no hand limit: the "right" hand size is
        whatever you can afford to lose half of. Building before a season change
        locks cards safely into your scoring pile — the surest protection.
      </p>

      <h2 id="hh-rb-scoring">Scoring</h2>
      <p>Each build scores the moment you play it. The endgame just totals the scoring pile.</p>
      <p><strong>Per biome forest (different layers in one biome):</strong></p>
      <table>
        <thead><tr><th>Different layers</th><th>Base score</th></tr></thead>
        <tbody>
          <tr><td>3 (biome forest minimum)</td><td>3</td></tr>
          <tr><td>4</td><td>5</td></tr>
          <tr><td>5 (mature)</td><td>10</td></tr>
          <tr><td>6</td><td>16</td></tr>
          <tr><td>7</td><td>25</td></tr>
          <tr><td>8 (biome + Mycorrhizal Network)</td><td>40</td></tr>
        </tbody>
      </table>
      <p><strong>Per layer set (plants sharing one layer):</strong></p>
      <table>
        <thead><tr><th>Same-layer plants</th><th>Base score</th></tr></thead>
        <tbody>
          <tr><td>3 (layer set minimum)</td><td>3</td></tr>
          <tr><td>4</td><td>6</td></tr>
          <tr><td>5</td><td>10</td></tr>
          <tr><td>6</td><td>15</td></tr>
          <tr><td>7</td><td>21</td></tr>
          <tr><td>8+</td><td>28</td></tr>
        </tbody>
      </table>
      <p><strong>Per mushroom set:</strong></p>
      <table>
        <thead><tr><th>Different mushrooms</th><th>Base score</th></tr></thead>
        <tbody>
          <tr><td>4</td><td>20</td></tr>
          <tr><td>5</td><td>30</td></tr>
          <tr><td>6</td><td>45</td></tr>
          <tr><td>7</td><td>60</td></tr>
          <tr><td>8+</td><td>75</td></tr>
        </tbody>
      </table>
      <p><strong>Bonuses:</strong></p>
      <ul>
        <li><strong>Biome completion</strong> — +5 when a biome forest fills all its buildable layers (7 in Forest/Forest Edge, 6 in Wetland/Disturbed/Mountain, 4 in Meadow). The mushroom double-stack is a bonus layer on top, not required for completion. Layer sets and mushroom sets don't earn this.</li>
        <li><strong>In-season</strong> — for each card in a build that's in-season when played, add its current-season value. Building a Fall-rich forest in Fall can far outscore the same forest in Spring.</li>
        <li><strong>Forager's Codex</strong> — +25 for playing all four guidance cards together.</li>
      </ul>
      <p><strong>Biome set bonus (end of game):</strong></p>
      <table>
        <thead><tr><th>Achievement</th><th>Bonus</th></tr></thead>
        <tbody>
          <tr><td>Biome forests in 3 different biomes</td><td>+5</td></tr>
          <tr><td>Biome forests in 5 different biomes</td><td>+15</td></tr>
          <tr><td>Biome forests in all 6 biomes</td><td>+30</td></tr>
        </tbody>
      </table>
      <p>Layer sets don't count toward the biome set bonus. Highest total wins; ties break to the most builds, then the most cards still in hand.</p>

      <h2 id="hh-rb-endgame">Endgame &amp; Length</h2>
      <p>
        There are <strong>two ways to win</strong>, and the game always offers both — whichever
        a forager reaches first decides it:
      </p>
      <ul>
        <li><strong>Biome race (instant win).</strong> The moment a forager has built forests in
        the target number of <strong>different biomes</strong>, they <strong>win outright</strong> — no final
        turns, no score comparison. (Multiple forests in one biome count it once;
        layer and mushroom sets don't count.)</li>
        <li><strong>Points win.</strong> When a forager's running score reaches the points target,
        every <strong>other</strong> forager takes one final turn (the trigger player doesn't get an
        extra one), then scores are totalled and the <strong>highest score wins</strong>. A forager
        who completes their last biome on one of those final turns still steals the
        instant win.</li>
      </ul>
      <p>
        If the deck, discard, and market are all empty, the endgame triggers the
        same way: every other player takes one final turn, then highest score wins.
      </p>
      <table>
        <thead><tr><th>Preset</th><th>Biome target (instant win)</th><th>Points target</th><th>Time</th></tr></thead>
        <tbody>
          <tr><td>Sprint</td><td>3 biomes</td><td>25</td><td>~10 min</td></tr>
          <tr><td><strong>Standard</strong></td><td>4 biomes</td><td>42</td><td>~20 min</td></tr>
          <tr><td>Marathon</td><td>5 biomes</td><td>55</td><td>~60 min</td></tr>
        </tbody>
      </table>
      <p style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>The biome and points targets are co-tuned so racing wide (biomes) and building tall (points) are about equally fast — the choice is real. This digital version plays the Standard target by default.</p>

      <h2 id="hh-rb-community">Community Forests <span style={{ font: "600 11px 'IBM Plex Mono', monospace", letterSpacing: ".08em", textTransform: "uppercase", color: "var(--accent)", border: "1px solid var(--accent)", borderRadius: 4, padding: "1px 6px", verticalAlign: "middle" }}>Advanced</span></h2>
      <p>
        <strong>Learn the base game first.</strong> Out of the box this is a game about building
        <em> your own</em> forests — that's where new foragers should start. Community Forests is an
        optional mode for groups that already know the rules and want more interaction and higher
        stakes. Turn it on at setup (it's off by default).
      </p>
      <p>
        In a community forest, no half-finished planting is truly yours to sit on — anyone can add to
        it and take credit for the growth they bring.
      </p>
      <p>
        <strong>The rule.</strong> If an <em>opponent's</em> biome forest has open layer slots (layers
        of that biome it doesn't yet fill), you may spend your <strong>main action</strong> planting
        the missing layers from your hand — one card per open layer, cards that grow in that biome.
        You score the <strong>difference</strong> between the forest's new layer tier and its old one
        (growing a 3-layer forest to 5 layers scores 10 − 3 = <strong>7</strong>), plus the
        <strong> +5 completion bonus</strong> if you fill its last layer, plus the usual in-season
        bonus on the cards you add. The owner <strong>keeps every point they scored</strong>, and the
        biome still counts only toward <em>their</em> biome race. Restricted layers stay closed unless
        the forest has a mushroom (or you add one).
      </p>
      <p>
        <strong>The reverse trap.</strong> Completing a forest earns points but <strong>never biome
        credit</strong>, so the two win conditions prey on each other. A biome-racer can leave thin
        builds as <em>bait</em>, hoping rivals burn turns topping them up instead of racing. But every
        open layer you leave is <em>income</em> for someone else — your half-built deep Forest is the
        most efficient points on the table, so expose too much and you fund the very points win you're
        trying to outrun. And points-per-card <em>rise</em> as a biome fills (the 7th card is worth far
        more than the 4th), so a banked-but-incomplete deep biome is your richest prize and your
        biggest liability at once.
      </p>
      <p style={{ fontStyle: "italic", color: "var(--ink-soft)" }}>
        Because completing forests is an extra income stream, this mode uses higher points targets to
        keep the race fair: Sprint 3 biomes / 32 points · Standard 4 / 53 · Marathon 5 / 79. In the
        digital game, look for the dashed <em>⤳ Grow…</em> actions on your turn.
      </p>

      <h2 id="hh-rb-faq">Frequently Asked Questions</h2>
      <p><strong>Can I take several market cards in one turn?</strong> Only as a single <em>bundle</em> — the free oldest card plus the next-newer ones beside it, paid in one transaction by harvesting in-season cards. You can't take the free card and then buy more separately. Then take your one main action.</p>
      <p><strong>Do I have to play every matching card when I build a biome?</strong> No. You choose exactly which cards go into the build from a composer — handy when a card could fit two biomes or you want to save a mushroom for a set.</p>
      <p><strong>Which card gets discarded when a weevil hits?</strong> You decide. Eligible cards become tappable; mushrooms and guidance are always safe.</p>
      <p><strong>Can a mushroom be in a forest and a set?</strong> No — once a card is built into a forest or set it's locked into your scoring pile. That's the core tension.</p>
      <p><strong>What if I have nothing worth building?</strong> Use your free pick to draw 1 (or grab a market card), burn dead weight before a weevil, or just pass. Seasons loop, so a worthless card now may ripen again — if it survives the weevils.</p>

      <h2 id="hh-rb-glossary">Glossary</h2>
      <ul>
        <li><strong>Biome forest</strong> — A built set from one biome with 3+ different layers. Counts toward the biome trigger and set bonus; can earn the completion bonus.</li>
        <li><strong>Build</strong> — A biome forest, layer set, or mushroom set. Scores immediately, then cards lock into your scoring pile.</li>
        <li><strong>Burn</strong> — Discard a hand card. Defensive only — softens the next weevil. No reward.</li>
        <li><strong>Codex</strong> — The 4 Foraging Safety &amp; Guidance cards. Play all four together for +25.</li>
        <li><strong>Completion bonus</strong> — +5 when a biome forest fills all its buildable layers.</li>
        <li><strong>Harvest</strong> — Discard an in-season card to pay value toward an extra market take. Harvested cards leave play; built cards score.</li>
        <li><strong>In-season</strong> — A card whose current-season yield row is non-zero. Mushrooms are in-season only in their fruiting seasons.</li>
        <li><strong>Layer</strong> — Canopy, Sub-canopy, Shrub, Herb, Ground, Vine, Root, or Mycorrhizal. Builds score by number of distinct layers.</li>
        <li><strong>Layer set</strong> — A build of 3+ plants that all share one layer, from any biomes. Scores on its own curve; doesn't count toward the biome trigger or set bonus.</li>
        <li><strong>Multi-biome card</strong> — Lists 2–3 biomes; counts toward a forest in any of them, but commits when played.</li>
        <li><strong>Mushroom set</strong> — 4+ different mushrooms played together. Big scoring tier.</li>
        <li><strong>Mycorrhizal Network</strong> — The extra layer a mushroom adds by double-stacking a filled layer (one per forest). It does not lift the biome's restrictions.</li>
        <li><strong>Scoring pile</strong> — Your face-down stack of built cards. Safe from weevils, locked for the game.</li>
        <li><strong>Value</strong> — A card's current-season Cal+Bot+Seeds total. Pays for market takes. Mushrooms and guidance have no value.</li>
        <li><strong>Weevil</strong> — A pest event that culls cards from hands at a season change.</li>
      </ul>
    </article>
  );
}

function Rulebook({ onClose }) {
  const bodyRef = React.useRef(null);
  const jumpTo = (id) => {
    const el = document.getElementById(`hh-rb-${id}`);
    if (el && bodyRef.current) {
      bodyRef.current.scrollTo({ top: el.offsetTop - 16, behavior: "smooth" });
    }
  };
  // close on Esc
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  const TOC = RulebookTOC;
  const Content = RulebookContent;
  return (
    <div className="hh-overlay" onClick={(e) => { if (e.target.classList.contains("hh-overlay")) onClose(); }}>
      <div className="panel">
        <header>
          <div>
            <SmallCaps>Card game · Rulebook</SmallCaps>
            <h2>Forage &amp; Forests</h2>
          </div>
          <button className="hh-btn icon-btn" onClick={onClose} aria-label="Close rulebook">
            <CloseIcon />
          </button>
        </header>
        <div className="body" ref={bodyRef}>
          <TOC onJump={jumpTo} />
          <Content />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Rulebook });
