/* ============================================================
   FOODMAP — scrollytelling engine + essay sections
   ============================================================ */

function Scrolly({ steps, graphic, layout }) {
  const [active, setActive] = useState(0);
  const stepsRef = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      const cont = stepsRef.current;
      if (!cont) return;
      const mid = window.innerHeight * 0.5;
      const els = cont.querySelectorAll("[data-step]");
      let best = 0;
      els.forEach((el, i) => { if (el.getBoundingClientRect().top <= mid) best = i; });
      setActive(best);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); };
  }, []);

  if (layout === "overlay") {
    return (
      <div className="scrolly overlay">
        <div className="graphic"><div className="graphic-inner">{graphic(active)}</div></div>
        <div className="steps" ref={stepsRef}>
          {steps.map((s, i) => (
            <div key={i} data-step={i} className={"step" + (active === i ? " active" : "")}>
              <div className="step-card"><span className="step-n">{String(i + 1).padStart(2, "0")} / {String(steps.length).padStart(2, "0")}</span>{s}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return (
    <div className="scrolly split">
      <div className="graphic"><div className="graphic-inner">{graphic(active)}</div></div>
      <div className="steps" ref={stepsRef}>
        {steps.map((s, i) => (
          <div key={i} data-step={i} className={"step" + (active === i ? " active" : "")}>
            <span className="step-n">Step {String(i + 1).padStart(2, "0")}</span>{s}
          </div>
        ))}
      </div>
    </div>
  );
}

function Reveal({ children, style, delay }) {
  const [ref, seen] = useInView();
  return <div ref={ref} className={"reveal" + (seen ? " in" : "")} style={{ transitionDelay: (delay || 0) + "ms", ...(style || {}) }}>{children}</div>;
}

function Kicker({ children, n }) {
  return (
    <div className="kicker">
      <span className="label">{n}</span>
      <span className="line"></span>
      <span className="label">Foodmap</span>
    </div>
  );
}

/* ---------------- HERO ---------------- */
function Hero() {
  return (
    <header className="hero wide">
      <h1 className="display" style={{ margin: "0" }}>
        How the world<br /><span style={{ color: "var(--accent)" }}>feeds itself</span>
      </h1>
      <p className="lede" style={{ maxWidth: 620, marginTop: 28 }}>
        Almost nothing on your plate was grown where you're standing. Coffee, soy, wheat, chocolate: the
        modern meal is stitched together from a handful of fields, then shipped across oceans to land in
        front of you. Here's the map of who grows it, who eats it, and how fragile the thread between them
        really is.
      </p>
      <div className="hero-meta">
        <span className="label">By Zea Balgos &amp; Thomas Passmore</span>
        <span className="label sep" aria-hidden="true">·</span>
        <span className="label">6 June 2026</span>
        <span className="label sep" aria-hidden="true">·</span>
        <span className="label">UN Comtrade · 2024</span>
        <span className="label sep" aria-hidden="true">·</span>
        <span className="label">8 min read</span>
      </div>
      <div style={{ marginTop: 64 }}>
        <span className="scroll-cue"><span className="arr">↓</span> Scroll to follow the food</span>
      </div>
    </header>
  );
}

/* ---------------- 1 · INTRO PROSE ---------------- */
function Intro() {
  return (
    <section className="pad">
      <div className="prose">
        <Kicker n="01 · The premise" />
        <h2 style={{ marginBottom: 22 }}>You eat from a map you've never seen.</h2>
        <p className="drop">
          Walk through any supermarket and you are walking through a world atlas in disguise. The bananas
          are a postcard from Ecuador. The coffee is a highland in Brazil or Vietnam. The chocolate is a
          thin ribbon of West African coast. The cooking oil is very likely a single Indonesian island.
        </p>
        <p>
          We tend to think of food as <em>local</em>: a farm, a market, a kitchen. But zoom out and the
          system looks more like a global logistics network than a garden. A few places grow an outsized
          share of what everyone eats, and an enormous fleet of ships quietly redistributes it. When that
          network hums, food is cheap and invisible. When one link snaps, the price of bread changes on the
          other side of the planet.
        </p>
        <p>
          This essay follows the thread three ways: we'll <strong>trace one bean</strong> from soil to cup,
          measure <strong>how few hands</strong> control each crop, and map the <strong>mismatch</strong>
          between where food is sold and where it's devoured. Every figure below is real trade data: what
          actually crossed a border in 2024, drawn from UN Comtrade.
        </p>
      </div>
    </section>
  );
}

/* ---------------- 2 · COFFEE JOURNEY (split scrolly) ---------------- */
function CoffeeSection() {
  const steps = [
    <React.Fragment><h3>It can only grow in a stripe.</h3><p>Coffee is a tropical diva. It refuses to grow outside a band roughly 23.5° north and south of the equator, the so-called "bean belt." Most of the planet, by climate, is simply disqualified.</p></React.Fragment>,
    <React.Fragment><h3>And a few countries own that stripe.</h3><p>Inside the belt, exports stack up fast. Brazil alone ships <strong>more than a third</strong> of the world's green coffee. Add Vietnam and Colombia and three countries account for well over half of the beans that cross a border.</p></React.Fragment>,
    <React.Fragment><h3>Then it leaves home.</h3><p>Very little is drunk where it's grown. Beans are dried, bagged, and shipped north, to ports in the United States, Europe and Japan that never see a coffee plant.</p></React.Fragment>,
    <React.Fragment><h3>The biggest buyers grow none of it.</h3><p>The United States and Germany buy more coffee than anyone, together close to <strong>$14&nbsp;billion</strong> a year, and grow virtually none of it. The mismatch is the whole point: the markets most devoted to a crop tend to sit nowhere near it.</p></React.Fragment>,
  ];
  return (
    <section className="pad-sm">
      <div className="prose" style={{ marginBottom: 10 }}>
        <Kicker n="02 · One bean's journey" />
        <h2>Follow a single coffee bean.</h2>
        <p style={{ color: "var(--ink-soft)" }}>Scroll, and watch it travel from a narrow climate band to the mugs of people who couldn't grow it if they tried.</p>
      </div>
      <Scrolly steps={steps} graphic={(s) => <CoffeeJourney step={s} />} layout="split" />
    </section>
  );
}

/* ---------------- 3 · CONCENTRATION (split scrolly) ---------------- */
function ConcentrationSection() {
  const C = F.CONCENTRATION;
  const steps = C.map((r) => (
    <React.Fragment><h3>{r.crop}</h3><p>{r.note}</p></React.Fragment>
  ));
  return (
    <section className="pad-sm" style={{ background: "var(--bg-warm)", "--graphic-bg": "var(--bg-warm)", paddingTop: "9vh", paddingBottom: "9vh" }}>
      <div className="prose" style={{ marginBottom: 10 }}>
        <Kicker n="03 · Concentration & risk" />
        <h2>Most crops have very few owners.</h2>
        <p style={{ color: "var(--ink-soft)" }}>The colored part of each bar is the share controlled by the top exporters. The hatched part is everyone else combined. Notice how short the hatching gets.</p>
      </div>
      <Scrolly steps={steps} graphic={(s) => <ConcentrationBars step={s} />} layout="split" />
      <div className="prose" style={{ marginTop: 36 }}>
        <p>
          Concentration is efficient right up until it isn't. When two countries supply more than four-fifths
          of the world's traded palm oil, a drought or an export ban in one of them is no longer a local story.
          It's a global price shock. The thinner the hatching, the more the whole planet is betting on a
          few harvests going well.
        </p>
      </div>
    </section>
  );
}

/* ---------------- 4 · MISMATCH (prose + reveal chart) ---------------- */
function MismatchSection() {
  return (
    <section className="pad">
      <div className="prose">
        <Kicker n="04 · Sells it vs. buys it" />
        <h2>The sellers and the buyers are different countries.</h2>
        <p>
          A short list of giant farms feeds a long list of hungry markets. Brazil, Argentina and Thailand
          pour food out; China, Japan and the Gulf pull it in. The United States is the curveball: it's the
          world's biggest food exporter by sheer value, yet it imports even more than it ships, so on a net
          basis it lands firmly among the buyers. Population and production drifted apart decades ago, and
          trade is the rubber band stretched between them.
        </p>
      </div>
      <div className="wide" style={{ marginTop: 34 }}>
        <MismatchChart />
      </div>
      <div className="prose" style={{ marginTop: 34 }}>
        <p>
          The countries on the far left aren't failing. Many are dense, wealthy, or desert. They've simply
          decided it's cheaper to <em>buy</em> calories than to grow them. That's a perfectly rational bet,
          and it's also why a war or a closed strait can rattle dinner tables thousands of miles inland.
        </p>
      </div>
    </section>
  );
}

/* ---------------- 5 · FLOW MAP (overlay scrolly) ---------------- */
function FlowSection() {
  const steps = [
    <React.Fragment><h3>Every arrow is a shipment.</h3><p>Zoom all the way out and the food system looks like flight paths. Exporters glow; importers receive. Let's switch the cargo and watch the map redraw itself.</p></React.Fragment>,
    <React.Fragment><h3>Wheat keeps cities fed.</h3><p>The Black Sea breadbasket feeds North Africa and the Middle East. A single contested sea-lane here moves the price of bread across two continents.</p></React.Fragment>,
    <React.Fragment><h3>Soy feeds the animals.</h3><p>Most soy is never eaten by people. It's fed to pigs, chickens and salmon. The thickest arrow on Earth runs from Brazil to China, the spine of the global meat supply.</p></React.Fragment>,
    <React.Fragment><h3>Palm oil is everywhere.</h3><p>Two equatorial countries supply the oil hiding in snacks, soap and fuel worldwide. Few flows are so concentrated at the source and so dispersed at the destination.</p></React.Fragment>,
    <React.Fragment><h3>And the coffee comes home.</h3><p>Back to where we started: the tropical belt exporting wakefulness to the temperate north. Same pattern, different cargo, grown in a few places and craved everywhere.</p></React.Fragment>,
  ];
  const order = ["coffee", "wheat", "soy", "palm", "coffee"];
  return (
    <section style={{ background: "var(--ink)", color: "var(--bg)" }}>
      <div className="prose pad-sm" style={{ color: "var(--bg)" }}>
        <div className="kicker"><span className="label" style={{ color: "#b8b2a4" }}>05 · The whole network</span><span className="line" style={{ background: "#3a362c" }}></span><span className="label" style={{ color: "#b8b2a4" }}>Foodmap</span></div>
        <h2 style={{ color: "var(--bg)" }}>One planet, four cargoes, the same shape.</h2>
        <p style={{ color: "#cfc8b8" }}>Each commodity draws a different map, but every one of them starts in a few fields and fans out to the world.</p>
      </div>
      <div style={{ "--line": "#39342a", "--line-strong": "#4a4435" }}>
        <Scrolly steps={steps} graphic={(s) => <FlowMap commodity={order[s]} />} layout="overlay" />
      </div>
    </section>
  );
}

/* ---------------- 6 · EXPLORER ---------------- */
function ExplorerSection() {
  return (
    <section className="pad">
      <div className="prose">
        <Kicker n="06 · Make it personal" />
        <h2>So what does your country actually do?</h2>
        <p style={{ color: "var(--ink-soft)" }}>Every nation sits somewhere on the spectrum from farm to customer. Pick one and see what it ships out, what it can't live without buying, and whether it ends the year selling more food than it buys.</p>
      </div>
      <div className="wide" style={{ marginTop: 30 }}>
        <Explorer />
      </div>
    </section>
  );
}

/* ---------------- FOOTER ---------------- */
function Foot() {
  return (
    <footer>
      <div className="prose" style={{ color: "var(--bg)" }}>
        <span className="sticker s-coffee"><span className="dot" style={{ background: "var(--c-yellow)" }}></span>The takeaway</span>
        <h2 style={{ color: "var(--bg)", margin: "20px 0 18px" }}>Food is global. We just don't see the map.</h2>
        <p style={{ color: "#cfc8b8" }}>
          The next time something is cheap and abundant, picture the thread holding it up: a few fields, a
          long ocean, and a network that mostly works. The interesting question isn't whether it'll break.
          It's how many strands we want to rely on.
        </p>
        <div style={{ borderTop: "2px solid #39342a", marginTop: 30, paddingTop: 18 }}>
          <div className="label">Method &amp; data</div>
          <p style={{ color: "#a8a294", fontSize: "0.95rem", marginTop: 8 }}>
            Figures are <strong style={{ color: "var(--c-yellow)" }}>real 2024 trade values</strong> from
            UN&nbsp;Comtrade, covering food &amp; agriculture (Harmonized System chapters 01 to 24). One caveat
            worth keeping in mind: this is <em>trade</em> data, meaning what crosses borders, not production or
            what people actually eat. So a re-export hub like the Netherlands looks like a giant "producer," and
            roasted-coffee shares flatter countries that buy beans and re-sell them; where it mattered we counted
            only the raw beans (green coffee, cocoa beans) to keep the focus on the countries that actually grow them.
          </p>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Scrolly, Reveal, Hero, Intro, CoffeeSection, ConcentrationSection, MismatchSection, FlowSection, ExplorerSection, Foot });
