// Forage & Forests — Intro / frontispiece screen.

/* eslint-disable no-undef */

function FoodForestDiagram() {
  // Prefer the painted field-guide plate at web/assets/food-forest-plate.webp.
  // If that asset isn't present, the <img> onError flips this to the stylized
  // SVG diagram below, so the page never shows a broken image.
  const [imgOk, setImgOk] = React.useState(true);

  // Fallback diagram: plant illustrations are HTML <img> tags positioned over an
  // SVG background, so the screenshot tool and any browser handle them identically.
  const layers = window.HH.LAYERS.filter((l) => l.key !== "Mycorrhizal");

  // Each plant: src, % positions and sizes inside the 720x440 frame.
  const plants = [
    { src: "/assets/plants/generated/acorns.png",            x: 11, y: 5,  w: 22, opacity: 1 },
    { src: "/assets/plants/generated/acorns.png",            x: 60, y: 8,  w: 21, opacity: 1 },
    { src: "/assets/plants/generated/elderberry.png",        x: 37, y: 24, w: 18, opacity: 1 },
    { src: "/assets/plants/generated/elderberry.png",        x: 77, y: 27, w: 17, opacity: 1 },
    { src: "/assets/plants/generated/blackberry.png",        x: 26, y: 45, w: 15, opacity: 1 },
    { src: "/assets/plants/generated/blackberry.png",        x: 62, y: 47, w: 14, opacity: 1 },
    { src: "/assets/plants/generated/chicory.png",           x: 5,  y: 55, w: 13, opacity: 1 },
    { src: "/assets/plants/generated/chicory.png",           x: 48, y: 57, w: 12, opacity: 1 },
    { src: "/assets/plants/generated/chicory.png",           x: 87, y: 57, w: 10, opacity: 1 },
    { src: "/assets/plants/generated/alpine-strawberry.png", x: 15, y: 66, w: 10, opacity: 1 },
    { src: "/assets/plants/generated/alpine-strawberry.png", x: 39, y: 67, w: 9,  opacity: 1 },
    { src: "/assets/plants/generated/alpine-strawberry.png", x: 71, y: 67, w: 9,  opacity: 1 },
    { src: "/assets/plants/generated/burdock.png",           x: 8,  y: 72, w: 17, opacity: 0.85 },
    { src: "/assets/plants/generated/burdock.png",           x: 52, y: 72, w: 16, opacity: 0.85 },
  ];

  return (
    <div style={{
      border: "1px solid var(--rule)",
      background: "var(--paper-warm)",
      padding: 18,
      position: "relative",
    }}>
      {imgOk && (
        <img
          src="/assets/food-forest-plate.webp"
          alt="A field-guide plate of one Forest food forest in cross-section, labelled canopy to fungi: White Oak with acorns, a Serviceberry in bloom, a Wild Grape vine climbing the trunk, Highbush Blueberry, Ramps, Wild Ginger groundcover, Indian Cucumber-Root among the roots, and a cluster of Golden Chanterelles."
          onError={() => setImgOk(false)}
          style={{ display: "block", width: "100%" }}
        />
      )}

      {!imgOk && (
      <>
      {/* Diagram frame */}
      <div style={{
        position: "relative",
        aspectRatio: "720 / 440",
        background: "linear-gradient(to bottom, #f4ecd1 0%, #f6efd9 55%, #e6d3a3 78%, #c8a474 78%, #8a6234 100%)",
        border: "1px solid var(--rule-soft)",
        overflow: "hidden",
      }}>
        {/* Horizon line + soil hatch */}
        <svg viewBox="0 0 720 440" preserveAspectRatio="none"
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
          <defs>
            <pattern id="hh-ground-hatch" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(45)">
              <line x1="0" y1="0" x2="0" y2="6" stroke="#5d3a1a" strokeWidth="0.5" opacity="0.5" />
            </pattern>
          </defs>
          {/* Background hills */}
          <path d="M0 320 C150 286 280 304 460 296 C580 290 660 308 720 304 L720 344 L0 344 Z"
            fill="#c5b486" opacity="0.45" />
          {/* Soil zone */}
          <rect x="0" y="344" width="720" height="96" fill="url(#hh-ground-hatch)" />
          {/* Horizon ink line */}
          <line x1="0" y1="344" x2="720" y2="344" stroke="#5d3a1a" strokeWidth="1.5" />
          {/* Vine winding up a tree trunk */}
          <g opacity="0.65">
            <path d="M150 320 C 162 240 138 180 156 80" stroke="#5d7b3e" strokeWidth="2.2" fill="none" />
            {[0, 1, 2, 3, 4].map((i) => {
              const y = 300 - i * 56;
              const x = 148 + (i % 2) * 8;
              return <ellipse key={i} cx={x} cy={y} rx="6" ry="3" fill="#5d7b3e" opacity="0.7" transform={`rotate(${30 - i * 8} ${x} ${y})`} />;
            })}
          </g>
          {/* Mycorrhizal threads — fine arcs in the soil */}
          <g opacity="0.55">
            {Array.from({ length: 28 }).map((_, i) => {
              const x = 12 + i * 26;
              const cy = 380 + (i % 3) * 16;
              return (
                <path key={i}
                  d={`M${x} ${cy} q ${8 + (i % 3) * 4} ${(i % 2) ? -6 : 6} ${20 + (i % 4) * 2} ${(i % 2) ? -2 : 2}`}
                  stroke="#3d2010" strokeWidth="0.7" fill="none" />
              );
            })}
          </g>
          {/* Layer band labels */}
          <g>
            {[
              { label: "Canopy",    y: 70  },
              { label: "Sub-canopy",y: 138 },
              { label: "Shrub",     y: 218 },
              { label: "Herb",      y: 268 },
              { label: "Ground",    y: 320 },
              { label: "Root",      y: 380 },
              { label: "Mycorrhizal", y: 420 },
            ].map((l) => (
              <g key={l.label}>
                <line x1="20" y1={l.y} x2="34" y2={l.y} stroke="#2c2417" strokeWidth="0.6" />
                <text x="36" y={l.y + 3.5} style={{ font: "600 9px 'JetBrains Mono', monospace", letterSpacing: "0.16em", fill: "#2c2417" }}>
                  {l.label.toUpperCase()}
                </text>
              </g>
            ))}
          </g>
        </svg>

        {/* HTML-positioned plant illustrations on top */}
        {plants.map((p, i) => (
          <img key={i} src={p.src} alt=""
            style={{
              position: "absolute",
              left: `${p.x}%`,
              top: `${p.y}%`,
              width: `${p.w}%`,
              mixBlendMode: "multiply",
              opacity: p.opacity,
              pointerEvents: "none",
            }}
          />
        ))}
      </div>

      <div style={{ marginTop: 12, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
        {layers.slice(0, 7).map((l) => (
          <div key={l.key} style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ width: 28, height: 28, border: "1px solid var(--rule-soft)", display: "inline-flex", alignItems: "center", justifyContent: "center", background: "var(--paper)" }}>
              <img src={l.icon} alt="" style={{ width: 22, height: 22, objectFit: "contain", mixBlendMode: "multiply" }} />
            </span>
            <div>
              <SmallCaps>{l.key}</SmallCaps>
              <div style={{ font: "italic 400 11px 'EB Garamond', serif", color: "var(--ink-soft)", lineHeight: 1.3 }}>{l.desc}</div>
            </div>
          </div>
        ))}
      </div>
      </>
      )}
    </div>
  );
}

function IntroScreen({ onPlayCards, onOpenRulebook }) {
  const openRulebook = () => {
    if (window.HHApi) window.HHApi.track("rulebook_open", { from: "intro" });
    onOpenRulebook();
  };
  const scrollToTable = () => {
    const el = document.getElementById("bring-to-table");
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <div style={{
      flex: 1,
      display: "flex",
      flexDirection: "column",
      maxWidth: 1240,
      margin: "0 auto",
      padding: "36px 28px 40px",
      width: "100%",
    }}>
      {/* Masthead */}
      <div style={{ textAlign: "center", marginBottom: 24 }}>
        <h1 style={{ margin: "0 0 6px", font: "500 64px/1 'EB Garamond', serif", color: "var(--ink)", letterSpacing: "0.01em" }}>
          Forage <span style={{ color: "var(--sepia)", fontStyle: "italic" }}>&amp;</span> Forests
        </h1>
        <div style={{ marginTop: 8 }}>
          <SmallCaps className="muted">The card game</SmallCaps>
        </div>
        <div style={{ font: "italic 400 19px 'EB Garamond', serif", color: "var(--ink-soft)", marginTop: 6 }}>
          Recognize the bounty, harvest the wild, grow a forest.
        </div>
        <p style={{ font: "400 17px/1.6 'EB Garamond', serif", color: "var(--ink)", maxWidth: 640, margin: "14px auto 0" }}>
          Every card is a real wild plant. Draw, harvest, and time your plays to
          the turning seasons, then build food forests and sets that lock in
          points — before a weevil thins your hand. Solo vs. bots or pass-and-play
          up to 6. <strong>Free online playtesting for a limited time.</strong>
        </p>
        <div style={{ marginTop: 14, display: "flex", justifyContent: "center", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
          <SmallCaps className="muted">86 cards</SmallCaps>
          <span style={{ color: "var(--rule)" }}>·</span>
          <SmallCaps className="muted">solo or up to 6</SmallCaps>
          <span style={{ color: "var(--rule)" }}>·</span>
          <SmallCaps className="muted">real plants</SmallCaps>
          <span style={{ color: "var(--rule)" }}>·</span>
          <SmallCaps className="muted">~20 minutes</SmallCaps>
        </div>
      </div>

      <div className="hh-rule-double" style={{ marginBottom: 28 }} />

      {/* Full-width food-forest plate */}
      <FoodForestDiagram />

      <p style={{ font: "italic 400 17px/1.6 'EB Garamond', serif", color: "var(--ink-soft)", textAlign: "center", maxWidth: 720, margin: "16px auto 0" }}>
        A food forest is a community of plants suited to their environment and to
        each other — each one giving something back, so the whole system thrives
        while providing food, materials, and medicine to people.
      </p>

      {/* Game pitch — what it is + how the year flows */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 20, alignItems: "start", marginTop: 28 }}>
        <div className="hh-plate">
          <div style={{ marginBottom: 6 }}>
            <SmallCaps>How it plays</SmallCaps>
          </div>
          <p style={{ font: "400 16px/1.55 'EB Garamond', serif", color: "var(--ink)", margin: 0 }}>
            Each turn you take one free card — a blind draw or a pick from the
            market — and can harvest in-season cards to buy more. Then you build:
            play a set of plants and it scores at once, locked safe in your pile.
            Builds come in three shapes — a food forest (different layers from one
            biome), a same-layer set, or a haul of mushrooms.
          </p>
          <p style={{ font: "italic 400 15px/1.5 'EB Garamond', serif", color: "var(--ink-soft)", marginTop: 10, marginBottom: 0 }}>
            Every card is a real plant, with its real season, range, and uses —
            and its value rises and falls as the seasons turn, so when you play a
            card matters as much as what it is.
          </p>
        </div>

        <div className="hh-plate">
          <SmallCaps>The four seasons</SmallCaps>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginTop: 8 }}>
            {window.HH.SEASONS.map((s) => (
              <div key={s} style={{
                textAlign: "center",
                border: "1px solid var(--rule-soft)",
                padding: "14px 6px",
                background: "var(--paper-warm)",
              }}>
                <div style={{ font: "500 15px 'EB Garamond', serif", color: "var(--ink)" }}>{s}</div>
              </div>
            ))}
          </div>
          <p style={{ font: "italic 400 13px/1.5 'EB Garamond', serif", color: "var(--ink-soft)", margin: "10px 0 0" }}>
            A card's value rises and falls with the seasons, so timing is everything — and every season change flips an event, sometimes a weevil that culls every forager's hand. Build first to lock your cards away safe.
          </p>
        </div>
      </div>

      {/* Primary calls to action */}
      <div style={{ display: "flex", flexDirection: "column", gap: 10, maxWidth: 540, width: "100%", margin: "26px auto 0" }}>
        <button className="hh-btn primary xl" onClick={onPlayCards}>
          Start the free playtest
        </button>
        <div style={{ textAlign: "center" }}>
          <SmallCaps className="muted">solo vs. bots or pass-and-play up to 6 · ~20 minutes</SmallCaps>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <button className="hh-btn lg ghost" onClick={openRulebook}>
            Read the rulebook
          </button>
          <button className="hh-btn lg ghost" onClick={scrollToTable}>
            Print &amp; playtest
          </button>
        </div>
      </div>

      {/* Field notes — why a food forest at all */}
      <div style={{ marginTop: 44 }}>
        <div className="hh-rule-double" style={{ marginBottom: 22 }} />
        <div style={{ textAlign: "center", marginBottom: 20 }}>
          <SmallCaps>Why food forests</SmallCaps>
          <h2 style={{ margin: "8px 0 4px", font: "500 34px/1.1 'EB Garamond', serif", color: "var(--ink)" }}>
            An older way to eat
          </h2>
          <p style={{ font: "italic 400 16px/1.5 'EB Garamond', serif", color: "var(--ink-soft)", maxWidth: 640, margin: "0 auto" }}>
            The game points at something real — an old, low-effort way of growing
            food that we're starting to rediscover.
          </p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 20 }}>
          {[
            {
              h: "The oldest garden",
              b: "Food forests are one of the oldest ways people grew food. Long before tidy rows there were layered groves — nuts and fruit up top, berries and herbs below. Indigenous peoples shaped whole “wild” forests into larders over centuries. The seven-layer model just gave the old idea a diagram.",
            },
            {
              h: "Keeping the wild",
              b: "Every wild plant is a backup the modern food system doesn't have — the bitter, the medicinal, the tough ones that shrug off a bad year. As farming narrows to a handful of crops, the wild edges still hold the rest. Learning a plant by name is a small way of keeping it around.",
            },
            {
              h: "Fed by the forest",
              b: "Time outside lowers stress and clears your head — the Japanese even have a word for it, shinrin-yoku. And wild food is potent: a handful of nettle or chanterelle carries nutrients the grocery store bred out long ago. Foraging feeds you twice.",
            },
          ].map((c) => (
            <div key={c.h} className="hh-plate">
              <SmallCaps>{c.h}</SmallCaps>
              <p style={{ font: "400 15px/1.6 'EB Garamond', serif", color: "var(--ink)", margin: "8px 0 0" }}>{c.b}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Bring it to the table — Kickstarter notify + playtest signup */}
      <div id="bring-to-table" style={{ marginTop: 48, scrollMarginTop: 20 }}>
        <div style={{ textAlign: "center", marginBottom: 18 }}>
          <SmallCaps>What's next</SmallCaps>
          <h2 style={{ margin: "8px 0 4px", font: "500 34px/1.1 'EB Garamond', serif", color: "var(--ink)" }}>
            From screen to tabletop
          </h2>
          <p style={{ font: "italic 400 16px/1.5 'EB Garamond', serif", color: "var(--ink-soft)", maxWidth: 620, margin: "0 auto" }}>
            The online game is the proving ground. Next, a printed edition — and
            we want it tested by real foragers at real tables first.
          </p>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 20, alignItems: "start" }}>
          <PlaytestSignup />
          <KickstarterNotify />
        </div>
      </div>

      {/* Footer */}
      <footer className="hh-footer">
        <SmallCaps className="muted">Forage &amp; Forests · a foraging &amp; food-forest card game</SmallCaps>
        <div style={{ display: "flex", gap: 16, alignItems: "center" }}>
          <a href="/print-and-play" target="_blank" rel="noopener"
            onClick={() => window.HHApi && window.HHApi.track("pnp_download", { from: "footer" })}>Print &amp; play</a>
          <a href="/privacy" target="_blank" rel="noopener">Privacy</a>
        </div>
      </footer>
    </div>
  );
}

Object.assign(window, { IntroScreen, FoodForestDiagram });
