// views.jsx — Top-level views: Home, Station, Certificate, Before, Map, After, FAQ.
// Depends on globals exported by ui-bits.jsx and stations.jsx.

const { useState: useS, useEffect: useE, useMemo, useRef: useR } = React;

// ─── HOME ───────────────────────────────────────────────────────────────────
function Home({ stations, completed, setRoute }) {
  const doneCount = completed.size;
  return (
    <div style={{ padding: "20px 20px 80px", maxWidth: 760, margin: "0 auto" }}>
      {/* HERO */}
      <div className="paper" style={{
        position: "relative", padding: "30px 26px 28px",
        background: "linear-gradient(180deg, #fcf4dc 0%, #f1e3b8 100%)",
        overflow: "hidden",
      }}>
        <div style={{ position: "absolute", inset: 0, opacity: 0.4, pointerEvents: "none" }}>
          <div style={dot(40, 30, "var(--accent)", 0.18)} />
          <div style={dot(85, 12, "var(--secondary)", 0.14)} />
          <div style={dot(12, 84, "var(--tertiary)", 0.14)} />
          <div style={dot(92, 78, "var(--accent)", 0.12)} />
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap", color: "var(--ink)" }}>
          <img src="brand/tyendinaga-township.svg" alt="Tyendinaga Township"
               style={{ height: 36, width: "auto", display: "block" }} />
          <span className="h-eyebrow" style={{ color: "var(--accent-deep)" }}>
            Sunday May 24
          </span>
        </div>

        <h1 className="h-display" style={{
          margin: "10px 0 4px",
          fontSize: "clamp(44px, 9vw, 76px)",
          color: "var(--ink)",
        }}>
          Bike Rodeo
        </h1>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: -4 }}>
          <span className="h-hand" style={{ fontSize: 38, color: "var(--accent)" }}>parents'</span>
          <HandUnderline color="var(--accent)" width={140} height={10} />
          <span className="h-hand" style={{ fontSize: 38, color: "var(--accent)" }}>guide</span>
        </div>

        <p style={{
          marginTop: 18, fontSize: 16, lineHeight: 1.55, color: "var(--ink-soft)",
          maxWidth: 560,
        }}>
          Five quick stations, about an hour of riding. Open the station, pull a
          question card to start the conversation with your kid, then walk through
          the lesson with them. Volunteers run each station — you just guide.
        </p>

        <div style={{ display: "flex", gap: 12, marginTop: 22, flexWrap: "wrap" }}>
          <button className="btn btn-primary"
            onClick={() => setRoute(`station/${stations[0].id}`)}
            style={{ background: "var(--accent)" }}>
            {doneCount === 0 ? "Start at Station 1 →" :
             doneCount === stations.length ? "Review stations →" :
             `Continue (${doneCount}/${stations.length})`}
          </button>
          <button className="btn btn-primary" onClick={() => setRoute("register")}
            style={{ background: "var(--secondary)" }}>
            Register your kid →
          </button>
          <button className="btn btn-ghost" onClick={() => setRoute("before")}>
            Before you come
          </button>
        </div>

        {/* Event card */}
        <div style={{
          marginTop: 26, display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))",
          gap: 14, paddingTop: 22, borderTop: "1.5px dashed var(--rule)",
        }}>
          <EventStat label="When"  big="May 24"  small="Sunday, 11AM – 1PM" />
          <EventStat label="Where" big="Tyendinaga" small="Township" />
          <EventStat label="Ages"  big="5 – 12"   small="all skill levels" />
          <EventStat label="Cost"  big="Free"     small="just show up" />
        </div>
      </div>

      {/* STATION OVERVIEW */}
      <section style={{ marginTop: 32 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 10 }}>
          <h2 className="h-display" style={{ fontSize: "clamp(26px, 5vw, 32px)", margin: 0 }}>
            The five stations
          </h2>
          <button onClick={() => setRoute("map")}
            style={{ appearance: "none", border: 0, background: "transparent",
              fontFamily: "var(--f-body)", fontWeight: 600, color: "var(--accent)",
              cursor: "pointer", fontSize: 14 }}>
            see the map →
          </button>
        </div>

        <div style={{ display: "grid", gap: 12 }}>
          {stations.map((s) => (
            <button key={s.id} onClick={() => setRoute(`station/${s.id}`)}
              className="paper"
              style={{
                appearance: "none", textAlign: "left", cursor: "pointer",
                padding: "16px 18px", display: "flex", alignItems: "center", gap: 16,
                font: "inherit",
              }}>
              <div style={{
                flex: "0 0 auto", width: 48, height: 48, borderRadius: "50%",
                border: "2px solid var(--ink)", display: "grid", placeItems: "center",
                fontFamily: "var(--f-display)", fontStyle: "italic", fontWeight: 700,
                fontSize: 22, color: "var(--ink)",
                background: completed.has(s.id) ? "var(--ink)" : "transparent",
                color: completed.has(s.id) ? "var(--paper)" : "var(--ink)",
              }}>
                {completed.has(s.id) ? "✓" : String(s.number).padStart(2, "0")}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="h-display" style={{ fontSize: 22, lineHeight: 1.1 }}>
                  {s.title}
                </div>
                <div style={{ fontSize: 13, color: "var(--ink-mute)", marginTop: 2,
                              fontFamily: "var(--f-body)" }}>
                  {s.kicker}
                </div>
              </div>
              <div style={{ color: "var(--ink-mute)", fontSize: 22 }}>→</div>
            </button>
          ))}
        </div>
      </section>

      <FootNav setRoute={setRoute} current="home" />
    </div>
  );
}

function EventStat({ label, big, small }) {
  return (
    <div>
      <div className="h-eyebrow">{label}</div>
      <div className="h-display" style={{ fontSize: 22, lineHeight: 1.1, margin: "4px 0 2px" }}>
        {big}
      </div>
      <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{small}</div>
    </div>
  );
}

function dot(x, y, color, alpha) {
  return {
    position: "absolute", top: `${y}%`, left: `${x}%`,
    width: 22, height: 22, borderRadius: "50%",
    background: color, opacity: alpha,
    transform: "translate(-50%, -50%)",
  };
}

// ─── STATION ────────────────────────────────────────────────────────────────
function StationView({ stations, station, completed, toggleComplete, setRoute }) {
  const idx = stations.findIndex((s) => s.id === station.id);
  const prev = stations[idx - 1];
  const next = stations[idx + 1];
  const isHelmet = station.id === "helmet-fit";
  const isDone = completed.has(station.id);
  const accentByNumber = ["var(--accent)", "var(--secondary)", "var(--tertiary)", "var(--accent)", "var(--secondary)"];
  const accent = accentByNumber[(station.number - 1) % accentByNumber.length];

  // Scroll to top when station changes
  useE(() => { window.scrollTo({ top: 0, behavior: "instant" }); }, [station.id]);

  return (
    <div style={{ padding: "16px 20px 100px", maxWidth: 760, margin: "0 auto" }}>
      <button onClick={() => setRoute("home")}
        style={{ appearance: "none", border: 0, background: "transparent",
          fontFamily: "var(--f-body)", fontWeight: 600, color: "var(--ink-mute)",
          cursor: "pointer", fontSize: 13, padding: "4px 0", marginBottom: 8 }}>
        ← all stations
      </button>

      {/* Header */}
      <div style={{ display: "flex", alignItems: "flex-start", gap: 18, flexWrap: "wrap" }}>
        <div style={{ flex: "0 0 auto" }}>
          <StationStamp number={station.number} color={accent} size={92} />
        </div>
        <div style={{ flex: 1, minWidth: 200 }}>
          <div className="h-eyebrow" style={{ color: accent }}>{station.kicker}</div>
          <h1 className="h-display" style={{
            margin: "6px 0 4px", fontSize: "clamp(34px, 7vw, 52px)", lineHeight: 1,
          }}>
            {station.title}
          </h1>
          <HandUnderline color={accent} width={140} height={9} />
        </div>
      </div>

      {/* Blurb */}
      <p style={{
        marginTop: 22, fontSize: 17, lineHeight: 1.55, color: "var(--ink-soft)",
      }}>
        {station.blurb}
      </p>

      {/* Questions — surfaced FIRST, framed as the warmup step */}
      <div style={{ marginTop: 24 }}>
        <SectionStripe label={`Step 1 · Ask one before you ride`} color={accent} />
        <p style={{ margin: "8px 0 14px", fontSize: 14, color: "var(--ink-mute)", maxWidth: 520, lineHeight: 1.55 }}>
          Pull a card and let them think out loud. There are no wrong answers — you're
          just getting curious together. If you want a nudge on where the question is
          going, tap <em style={{ color: "var(--ink-soft)", fontStyle: "normal", fontWeight: 600 }}>For the grown-up</em>.
        </p>
        <QuestionCard questions={station.questions} accentColor={accent} />
      </div>

      {/* Helmet diagram for helmet station */}
      {isHelmet && (
        <div className="paper" style={{ padding: 18, marginTop: 28 }}>
          <div className="h-eyebrow" style={{ marginBottom: 8 }}>How a helmet should sit</div>
          <div style={{ display: "flex", justifyContent: "center" }}>
            <HelmetDiagram accent={accent} />
          </div>
        </div>
      )}

      {/* Sections */}
      <div style={{ marginTop: 28 }}>
        <SectionStripe label={`Step 2 · Walk through with your kid`} color={accent} />
        <ol style={{ listStyle: "none", padding: 0, margin: "14px 0 0",
                     display: "grid", gap: 14 }}>
          {station.sections.map((sec, i) => (
            <li key={i} className="paper" style={{ padding: "16px 18px", display: "flex", gap: 14 }}>
              <div style={{
                flex: "0 0 auto", width: 28, height: 28, borderRadius: "50%",
                background: accent, color: "var(--paper)",
                display: "grid", placeItems: "center",
                fontFamily: "var(--f-body)", fontWeight: 700, fontSize: 13,
              }}>
                {i + 1}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="h-display" style={{ fontSize: 20, lineHeight: 1.15 }}>
                  {sec.heading}
                </div>
                <p style={{ margin: "6px 0 0", fontSize: 15, lineHeight: 1.5, color: "var(--ink)" }}>
                  {sec.body}
                </p>
                {sec.meta && (
                  <p className="h-hand" style={{ margin: "8px 0 0", color: accent, fontSize: 22, lineHeight: 1 }}>
                    {sec.meta}
                  </p>
                )}
              </div>
            </li>
          ))}
        </ol>
      </div>

      {/* Watch for */}
      {station.watchFor && (
        <div style={{ marginTop: 28 }}>
          <SectionStripe label={`Step 3 · Watch for · praise the specific thing`} color={accent} />
          <div style={{ display: "grid", gap: 14, marginTop: 14 }}>
            {station.watchFor.map((w, i) => (
              <div key={i} className="paper" style={{ padding: "16px 18px",
                background: "linear-gradient(180deg, #fbf3df 0%, #f5e9c7 100%)" }}>
                <div className="h-display" style={{ fontSize: 19 }}>{w.heading}</div>
                <p style={{ margin: "6px 0 0", fontSize: 15, lineHeight: 1.5 }}>{w.body}</p>
                {w.praise && (
                  <div style={{
                    marginTop: 12, padding: "10px 12px", borderLeft: `3px solid ${accent}`,
                    background: "rgba(184,65,43,0.06)",
                  }}>
                    <div className="h-eyebrow" style={{ color: accent, fontSize: 10, marginBottom: 4 }}>say something like</div>
                    <div className="h-hand" style={{ fontSize: 22, color: "var(--ink)", lineHeight: 1.1 }}>
                      {w.praise}
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Mark complete */}
      <div style={{ marginTop: 32, display: "flex", justifyContent: "center" }}>
        <button onClick={() => toggleComplete(station.id)}
          className="btn"
          style={{
            background: isDone ? "transparent" : "var(--ink)",
            color: isDone ? "var(--ink)" : "var(--paper)",
            border: isDone ? "1.5px solid var(--ink)" : "0",
            padding: "14px 26px", fontSize: 15,
          }}>
          {isDone ? "✓ Done — tap to unmark" : "Mark this station done"}
        </button>
      </div>

      {/* Prev / Next */}
      <div style={{
        marginTop: 28, display: "flex", justifyContent: "space-between",
        alignItems: "center", gap: 12, flexWrap: "wrap",
      }}>
        {prev ? (
          <button className="btn btn-ghost" onClick={() => setRoute(`station/${prev.id}`)}>
            ← {prev.title}
          </button>
        ) : <span />}
        {next ? (
          <button className="btn btn-primary"
            onClick={() => setRoute(`station/${next.id}`)}
            style={{ background: accent }}>
            {next.title} →
          </button>
        ) : (
          <button className="btn btn-primary"
            onClick={() => setRoute("certificate")}
            style={{ background: "var(--ink)" }}>
            Finish · certificate →
          </button>
        )}
      </div>
    </div>
  );
}

function SectionStripe({ label, color }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
      <span style={{ width: 18, height: 4, background: color, borderRadius: 2 }} />
      <span className="h-eyebrow">{label}</span>
    </div>
  );
}

// ─── CERTIFICATE ────────────────────────────────────────────────────────────
function CertificateView({ stations, completed, setRoute, kidName, setKidName }) {
  const allDone = completed.size === stations.length;
  const [editing, setEditing] = useS(!kidName);

  return (
    <div style={{ padding: "20px 20px 80px", maxWidth: 760, margin: "0 auto" }}>
      <button onClick={() => setRoute("home")}
        className="no-print"
        style={{ appearance: "none", border: 0, background: "transparent",
          fontFamily: "var(--f-body)", fontWeight: 600, color: "var(--ink-mute)",
          cursor: "pointer", fontSize: 13, padding: "4px 0", marginBottom: 8 }}>
        ← back home
      </button>

      <div className="paper" style={{
        position: "relative", padding: "44px 28px 36px",
        background: "linear-gradient(180deg, #fcf4dc 0%, #f1e3b8 100%)",
        border: "2px double var(--ink)",
      }}>
        {/* Decorative corners */}
        {[0,1,2,3].map((c) => (
          <div key={c} aria-hidden="true" style={{
            position: "absolute", width: 28, height: 28,
            top: c < 2 ? 8 : "auto", bottom: c >= 2 ? 8 : "auto",
            left: c % 2 === 0 ? 8 : "auto", right: c % 2 === 1 ? 8 : "auto",
            border: "2px solid var(--accent)",
            borderRadius: 4,
            borderTopRightRadius: c === 0 ? 0 : 4,
            borderTopLeftRadius: c === 1 ? 0 : 4,
            borderBottomRightRadius: c === 2 ? 0 : 4,
            borderBottomLeftRadius: c === 3 ? 0 : 4,
          }} />
        ))}

        <div style={{ textAlign: "center" }}>
          <div className="h-eyebrow" style={{ color: "var(--accent-deep)" }}>
            Tyendinaga Township · Bike Rodeo
          </div>
          <h1 className="h-display" style={{
            fontSize: "clamp(36px, 8vw, 56px)",
            margin: "10px 0 0", color: "var(--ink)",
          }}>
            Certificate of
          </h1>
          <div className="h-hand" style={{
            fontSize: "clamp(56px, 14vw, 96px)",
            color: "var(--accent)", marginTop: -4, lineHeight: 1,
          }}>
            Completion
          </div>

          <p style={{ marginTop: 22, fontSize: 16, color: "var(--ink-soft)" }}>
            awarded to
          </p>

          {editing ? (
            <input type="text" value={kidName} onChange={(e) => setKidName(e.target.value)}
              onBlur={() => setEditing(false)}
              onKeyDown={(e) => e.key === "Enter" && setEditing(false)}
              autoFocus
              placeholder="your kid's name"
              style={{
                fontFamily: "var(--f-hand)", fontSize: "clamp(40px, 9vw, 64px)",
                color: "var(--ink)", background: "transparent",
                border: "none", borderBottom: "2px dashed var(--ink)",
                textAlign: "center", outline: "none", width: "min(90%, 480px)",
                padding: "2px 8px",
              }}
            />
          ) : (
            <button onClick={() => setEditing(true)} className="no-print"
              style={{
                appearance: "none", border: 0, background: "transparent",
                cursor: "text", fontFamily: "var(--f-hand)",
                fontSize: "clamp(40px, 9vw, 64px)", color: "var(--ink)",
                borderBottom: "2px dashed var(--ink)", lineHeight: 1.1,
                padding: "2px 8px",
              }}>
              {kidName || "tap to add name"}
            </button>
          )}

          <p style={{ marginTop: 22, fontSize: 16, color: "var(--ink-soft)", maxWidth: 520, marginInline: "auto" }}>
            for completing every station of the Tyendinaga Bike Rodeo —
            checking a bike, fitting a helmet, starts and stops, scanning for cars,
            and the rock dodge.
          </p>

          {/* Stations row */}
          <div style={{
            marginTop: 26, display: "flex", justifyContent: "center", gap: 10,
            flexWrap: "wrap",
          }}>
            {stations.map((s) => {
              const done = completed.has(s.id);
              return (
                <div key={s.id} title={s.title} style={{
                  width: 44, height: 44, borderRadius: "50%",
                  border: "2px solid var(--ink)",
                  background: done ? "var(--accent)" : "transparent",
                  color: done ? "var(--paper)" : "var(--ink)",
                  display: "grid", placeItems: "center",
                  fontFamily: "var(--f-display)", fontWeight: 700, fontStyle: "italic",
                  fontSize: 16,
                }}>
                  {done ? "✓" : s.number}
                </div>
              );
            })}
          </div>

          <div style={{
            marginTop: 28, display: "flex", justifyContent: "space-between",
            alignItems: "flex-end", padding: "0 6px",
          }}>
            <div style={{ textAlign: "left" }}>
              <div className="h-hand" style={{ fontSize: 26, color: "var(--ink)" }}>
                May 24, 2026
              </div>
              <div style={{ borderTop: "1.5px solid var(--ink)", paddingTop: 4,
                fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase",
                color: "var(--ink-mute)", fontWeight: 600 }}>
                date
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div className="h-hand" style={{ fontSize: 26, color: "var(--accent)" }}>
                Bike Rodeo
              </div>
              <div style={{ borderTop: "1.5px solid var(--ink)", paddingTop: 4,
                fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase",
                color: "var(--ink-mute)", fontWeight: 600 }}>
                signed
              </div>
            </div>
          </div>
        </div>
      </div>

      {!allDone && (
        <p className="no-print" style={{ marginTop: 16, textAlign: "center", color: "var(--ink-mute)", fontSize: 14 }}>
          {completed.size} of {stations.length} stations marked done — you can still finish the rest.
        </p>
      )}

      <div className="no-print" style={{ marginTop: 22, display: "flex", justifyContent: "center", gap: 12, flexWrap: "wrap" }}>
        <button className="btn btn-primary" style={{ background: "var(--accent)" }}
          onClick={() => window.print()}>
          Print certificate
        </button>
        <button className="btn btn-ghost" onClick={() => setRoute("after")}>
          What to do next →
        </button>
      </div>
    </div>
  );
}

// ─── BEFORE YOU COME ────────────────────────────────────────────────────────
function BeforeView({ setRoute }) {
  const items = [
    { icon: "🚲", title: "A bike", body: "The one your kid actually rides. Training wheels welcome." },
    { icon: "🪖", title: "A helmet", body: "Even if it doesn't fit right — we'll help you fit it at Station 2." },
    { icon: "👟", title: "Closed-toe shoes", body: "No flip-flops. Pedals are mean to bare toes." },
    { icon: "💧", title: "A water bottle", body: "Late May can be warm. Bring something to drink." },
    { icon: "☀️", title: "Sunscreen + a hat", body: "For the parents standing around. (You'll be standing around a lot.)" },
    { icon: "📝", title: "This guide", body: "Open it on your phone or print the certificate page when you're done." },
  ];

  return (
    <div style={{ padding: "20px 20px 80px", maxWidth: 760, margin: "0 auto" }}>
      <BackTo setRoute={setRoute} />
      <div className="h-eyebrow">Before the day</div>
      <h1 className="h-display" style={{ fontSize: "clamp(34px, 7vw, 48px)", margin: "6px 0 14px" }}>
        What to bring
      </h1>
      <HandUnderline color="var(--accent)" width={140} height={10} />

      <div style={{ display: "grid", gap: 14, marginTop: 26,
                    gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))" }}>
        {items.map((it) => (
          <div key={it.title} className="paper" style={{ padding: "16px 18px" }}>
            <div style={{ fontSize: 28, lineHeight: 1 }} aria-hidden="true">{it.icon}</div>
            <div className="h-display" style={{ fontSize: 20, marginTop: 6 }}>{it.title}</div>
            <p style={{ margin: "6px 0 0", fontSize: 14, lineHeight: 1.5, color: "var(--ink-soft)" }}>
              {it.body}
            </p>
          </div>
        ))}
      </div>

      <div className="paper" style={{ padding: "18px 20px", marginTop: 26,
        background: "linear-gradient(180deg, #fbf3df 0%, #f5e9c7 100%)" }}>
        <div className="h-eyebrow" style={{ color: "var(--accent-deep)" }}>Heads up</div>
        <p style={{ margin: "8px 0 0", fontSize: 15, lineHeight: 1.55 }}>
          This isn't drop-off. We need one adult per kid — you'll walk the bike between
          stations, hold the helmet while it gets adjusted, and ask the wait-in-line
          questions. Plan on the full two hours.
        </p>
      </div>

      <FootNav setRoute={setRoute} current="before" />
    </div>
  );
}

// ─── MAP / STATION ORDER ────────────────────────────────────────────────────
function MapView({ stations, completed, setRoute }) {
  return (
    <div style={{ padding: "20px 20px 80px", maxWidth: 760, margin: "0 auto" }}>
      <BackTo setRoute={setRoute} />
      <div className="h-eyebrow">The course</div>
      <h1 className="h-display" style={{ fontSize: "clamp(34px, 7vw, 48px)", margin: "6px 0 14px" }}>
        Station order
      </h1>
      <HandUnderline color="var(--secondary)" width={160} height={10} />

      <p style={{ marginTop: 18, color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.55 }}>
        The stations don't have to be done in order — but if you're new, this order
        works. Bike check before helmet check before riding. Easier stuff before harder.
      </p>

      <div className="paper" style={{ padding: 18, marginTop: 22 }}>
        <CourseDiagram stations={stations} completed={completed} onJump={(id) => setRoute(`station/${id}`)} />
      </div>

      <div style={{ marginTop: 22, display: "grid", gap: 10 }}>
        {stations.map((s) => (
          <div key={s.id} style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <div style={{
              width: 28, height: 28, borderRadius: "50%",
              background: completed.has(s.id) ? "var(--accent)" : "transparent",
              border: "2px solid var(--ink)",
              color: completed.has(s.id) ? "var(--paper)" : "var(--ink)",
              display: "grid", placeItems: "center",
              fontFamily: "var(--f-display)", fontStyle: "italic", fontWeight: 700, fontSize: 14,
              flex: "0 0 auto",
            }}>
              {completed.has(s.id) ? "✓" : s.number}
            </div>
            <div style={{ flex: 1 }}>
              <div className="h-display" style={{ fontSize: 18 }}>{s.title}</div>
              <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{s.kicker}</div>
            </div>
            <button className="btn btn-ghost" style={{ padding: "8px 14px", fontSize: 13 }}
                    onClick={() => setRoute(`station/${s.id}`)}>open</button>
          </div>
        ))}
      </div>

      <FootNav setRoute={setRoute} current="map" />
    </div>
  );
}

function CourseDiagram({ stations, completed, onJump }) {
  // Five stations arranged in a curving path
  const points = [
    { x: 60,  y: 70  },
    { x: 160, y: 38  },
    { x: 260, y: 70  },
    { x: 320, y: 150 },
    { x: 220, y: 200 },
  ];
  const W = 380, H = 240;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", maxWidth: 520, margin: "0 auto" }}>
      {/* Path */}
      <path d={pathThrough(points)} fill="none" stroke="var(--ink-mute)" strokeWidth="2" strokeDasharray="4 5" opacity="0.6" />
      {/* Start label */}
      <text x={points[0].x - 36} y={points[0].y + 4} fontFamily="var(--f-hand)" fontSize="22" fill="var(--accent)">start →</text>
      {/* End label */}
      <text x={points[4].x - 14} y={points[4].y + 40} fontFamily="var(--f-hand)" fontSize="22" fill="var(--accent)">finish ✓</text>
      {/* Stations */}
      {points.map((p, i) => {
        const s = stations[i];
        const done = completed.has(s.id);
        return (
          <g key={s.id} style={{ cursor: "pointer" }} onClick={() => onJump(s.id)}>
            <circle cx={p.x} cy={p.y} r={22}
                    fill={done ? "var(--accent)" : "var(--paper)"}
                    stroke="var(--ink)" strokeWidth="2" />
            <text x={p.x} y={p.y + 6} textAnchor="middle"
                  fontFamily="var(--f-display)" fontStyle="italic" fontWeight="700"
                  fontSize="18" fill={done ? "var(--paper)" : "var(--ink)"}>
              {done ? "✓" : s.number}
            </text>
            <text x={p.x} y={p.y + 42} textAnchor="middle"
                  fontFamily="var(--f-body)" fontWeight="600" fontSize="11" fill="var(--ink)">
              {s.title}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

function pathThrough(pts) {
  let d = `M ${pts[0].x} ${pts[0].y}`;
  for (let i = 1; i < pts.length; i++) {
    const prev = pts[i - 1], curr = pts[i];
    const cx = (prev.x + curr.x) / 2;
    const cy = (prev.y + curr.y) / 2;
    d += ` Q ${prev.x} ${curr.y} ${cx} ${cy}`;
    d += ` T ${curr.x} ${curr.y}`;
  }
  return d;
}

// ─── AFTER ─────────────────────────────────────────────────────────────────
function AfterView({ setRoute }) {
  return (
    <div style={{ padding: "20px 20px 80px", maxWidth: 760, margin: "0 auto" }}>
      <BackTo setRoute={setRoute} />
      <div className="h-eyebrow">After the rodeo</div>
      <h1 className="h-display" style={{ fontSize: "clamp(34px, 7vw, 48px)", margin: "6px 0 14px" }}>
        Keep it going
      </h1>
      <HandUnderline color="var(--tertiary)" width={160} height={10} />

      <p style={{ marginTop: 18, color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.55 }}>
        Two hours doesn't make a careful cyclist. What we did today only sticks if
        you reinforce it on the rides you take this summer. Here's what works.
      </p>

      <Cards items={[
        { eyebrow: "Ride with traffic", body: "On the road, ride on the right with the flow — not against it. Most car-bike crashes involve a rider on the wrong side. Motorists turning right look left, not right." },
        { eyebrow: "Stop. Look. Listen.", body: "Every driveway. Every intersection. Every time. Stop at the mouth of the driveway, look left, right, left again." },
        { eyebrow: "Scan, then signal", body: "Looking is more important than signalling. Make scanning a game on rides — call \"LOOK\" and hold up fingers like we did today." },
        { eyebrow: "Walk the tricky bits", body: "Busy intersections, narrow shoulders, sketchy crosswalks — walking the bike across is always an option. It's not chickening out. It's not getting hit." },
        { eyebrow: "Helmet, every time", body: "Even the driveway. Even a quick spin. The 95% of rides where nothing happens don't tell you anything about the 5% where something does." },
        { eyebrow: "Bike check, every spring", body: "Tire pressure, brake feel, chain oil, drop test. Five minutes. Catch the loose bolt before it finds you." },
      ]} />

      <FootNav setRoute={setRoute} current="after" />
    </div>
  );
}

function Cards({ items }) {
  return (
    <div style={{ display: "grid", gap: 12, marginTop: 22 }}>
      {items.map((it, i) => (
        <div key={i} className="paper" style={{ padding: "16px 18px" }}>
          <div className="h-eyebrow" style={{ color: "var(--accent-deep)" }}>{it.eyebrow}</div>
          <p style={{ margin: "8px 0 0", fontSize: 15, lineHeight: 1.55 }}>{it.body}</p>
        </div>
      ))}
    </div>
  );
}

// ─── FAQ ────────────────────────────────────────────────────────────────────
function FaqView({ setRoute }) {
  const [open, setOpen] = useS(0);
  const items = [
    { q: "Does my kid need to know how to ride already?",
      a: "No. Younger riders (with training wheels or balance bikes) are welcome at Stations 1 through 3. The riding stations need them able to coast and steer on their own." },
    { q: "Can I drop my kid off?",
      a: "Please don't. One adult per child — you walk the bike between stations, hold the helmet while we adjust it, ask the wait-in-line questions. We don't have enough volunteers to chaperone." },
    { q: "What if my kid's bike is too small / too big / broken?",
      a: "Bring it anyway. Station 1 (Bike Check) is where we figure that out, and we have a couple of loaner bikes for the worst cases. Station 2 handles fit." },
    { q: "What if it rains?",
      a: "We move under the pavilion and run the standing stations only — Bike Check, Helmet, Fit, plus the conversation cards. Watch the township page for cancellation." },
    { q: "Do I need to register?",
      a: "Just show up. If you want a head-count helper, let us know you're coming — but it's not required." },
    { q: "My kid is older / more skilled. Will they be bored?",
      a: "Honestly, sometimes. The Scanning and Rock Dodge stations stay interesting at any skill level. Encourage them to be helpers for younger kids — they pick up more by teaching it." },
    { q: "What if my kid has a meltdown?",
      a: "Walk them over to the warm-up pit, let them ride a loop with no instructions, come back when they're ready. We've all been there." },
    { q: "Are helmets provided?",
      a: "We don't have loaner helmets — bring yours. If the fit is off we'll help adjust it. If the helmet is broken or cracked, please replace it before riding." },
  ];

  return (
    <div style={{ padding: "20px 20px 80px", maxWidth: 760, margin: "0 auto" }}>
      <BackTo setRoute={setRoute} />
      <div className="h-eyebrow">Common questions</div>
      <h1 className="h-display" style={{ fontSize: "clamp(34px, 7vw, 48px)", margin: "6px 0 14px" }}>
        FAQ
      </h1>
      <HandUnderline color="var(--secondary)" width={80} height={10} />

      <div style={{ marginTop: 24, display: "grid", gap: 10 }}>
        {items.map((it, i) => {
          const isOpen = open === i;
          return (
            <div key={i} className="paper" style={{ overflow: "hidden" }}>
              <button onClick={() => setOpen(isOpen ? -1 : i)}
                style={{
                  appearance: "none", border: 0, background: "transparent",
                  cursor: "pointer", width: "100%", textAlign: "left",
                  padding: "16px 18px", display: "flex", alignItems: "center", gap: 12,
                  font: "inherit",
                }}>
                <div className="h-display" style={{ flex: 1, fontSize: 18, lineHeight: 1.2 }}>
                  {it.q}
                </div>
                <span style={{
                  color: "var(--accent)", fontSize: 20, lineHeight: 1,
                  transform: isOpen ? "rotate(45deg)" : "rotate(0)",
                  transition: "transform 160ms ease",
                }}>+</span>
              </button>
              {isOpen && (
                <div style={{ padding: "0 18px 16px 18px" }}>
                  <hr className="ink-rule" style={{ marginBottom: 12 }} />
                  <p style={{ margin: 0, fontSize: 15, lineHeight: 1.55, color: "var(--ink-soft)" }}>
                    {it.a}
                  </p>
                </div>
              )}
            </div>
          );
        })}
      </div>

      <FootNav setRoute={setRoute} current="faq" />
    </div>
  );
}

// ─── Common ────────────────────────────────────────────────────────────────
function BackTo({ setRoute }) {
  return (
    <button onClick={() => setRoute("home")}
      style={{ appearance: "none", border: 0, background: "transparent",
        fontFamily: "var(--f-body)", fontWeight: 600, color: "var(--ink-mute)",
        cursor: "pointer", fontSize: 13, padding: "4px 0", marginBottom: 8 }}>
      ← home
    </button>
  );
}

function FootNav({ setRoute, current }) {
  const tabs = [
    { id: "register", label: "Register" },
    { id: "before", label: "Before" },
    { id: "map",    label: "Map" },
    { id: "after",  label: "After" },
    { id: "faq",    label: "FAQ" },
  ];
  return (
    <div style={{
      marginTop: 40, paddingTop: 20,
      borderTop: "1.5px dashed var(--rule)",
      display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap",
    }}>
      {tabs.filter(t => t.id !== current).map(t => (
        <button key={t.id} onClick={() => setRoute(t.id)}
          className="btn btn-ghost"
          style={{ padding: "8px 14px", fontSize: 13 }}>
          {t.label} →
        </button>
      ))}
    </div>
  );
}

// ─── REGISTER ───────────────────────────────────────────────────────────────
const REGISTER_FORM_URL = "https://docs.google.com/forms/d/e/1FAIpQLSdApGFvlRdAp1qEQe17MJnrbAlR9id7EhvLRaQ-1Ae-RSHFLA/viewform";
const REGISTER_API = "https://hastings.bike/api";

function RegisterView({ setRoute }) {
  const [state, setState] = useS({ status: "loading", form: null, error: null });
  const [values, setValues] = useS({});
  const [submitting, setSubmitting] = useS(false);
  const [submitted, setSubmitted] = useS(false);
  const [submitError, setSubmitError] = useS(null);

  useE(() => {
    fetch(`${REGISTER_API}/google-form?url=${encodeURIComponent(REGISTER_FORM_URL)}`)
      .then(r => r.json())
      .then(form => setState({ status: "ready", form, error: null }))
      .catch(err => setState({ status: "error", form: null, error: String(err) }));
  }, []);

  function setField(id, v) { setValues(prev => ({ ...prev, [id]: v })); }

  async function onSubmit(e) {
    e.preventDefault();
    setSubmitting(true); setSubmitError(null);
    try {
      const r = await fetch(`${REGISTER_API}/google-form/submit`, {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          formId: state.form.formId,
          formUrl: REGISTER_FORM_URL,
          responses: values,
        }),
      });
      const result = await r.json();
      if (!result.success) throw new Error(result.error || "Submission failed");
      setSubmitted(true);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (err) {
      setSubmitError(String(err.message || err));
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div style={{ padding: "20px 20px 80px", maxWidth: 760, margin: "0 auto" }}>
      <BackTo setRoute={setRoute} />
      <div className="h-eyebrow">Sign your family up</div>
      <h1 className="h-display" style={{ fontSize: "clamp(34px, 7vw, 48px)", margin: "6px 0 14px" }}>
        Register
      </h1>
      <HandUnderline color="var(--secondary)" width={120} height={10} />

      {state.status === "loading" && (
        <p style={{ marginTop: 28, color: "var(--ink-mute)" }}>Loading the form…</p>
      )}

      {state.status === "error" && (
        <div className="paper" style={{ padding: 18, marginTop: 22 }}>
          <p style={{ margin: 0 }}>Couldn't load the form. <a href={REGISTER_FORM_URL} target="_blank" rel="noreferrer" style={{ color: "var(--accent)" }}>Open it on Google Forms →</a></p>
        </div>
      )}

      {state.status === "ready" && submitted && (
        <div className="paper" style={{ padding: "26px 22px", marginTop: 22,
          background: "linear-gradient(180deg, #fbf3df 0%, #f5e9c7 100%)" }}>
          <div className="h-hand" style={{ fontSize: 44, color: "var(--accent)" }}>You're in.</div>
          <p style={{ marginTop: 10, fontSize: 16, lineHeight: 1.55 }}>
            We got your registration. See you Sunday May 24 at the Tyendinaga Recreation Complex —
            11AM to 1PM. Read <a href="#/before" onClick={(e) => { e.preventDefault(); setRoute("before"); }}
            style={{ color: "var(--accent)", fontWeight: 600 }}>what to bring</a> before
            the day.
          </p>
        </div>
      )}

      {state.status === "ready" && !submitted && (
        <>
          <p style={{ marginTop: 18, color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.55 }}>
            Sunday May 24, 11AM – 1PM at 363 McFarlane Road, Shannonville. Free.
            Bring one adult per kid.
          </p>
          <form onSubmit={onSubmit} style={{ marginTop: 22, display: "grid", gap: 14 }}>
            {state.form.fields.map(f => (
              <FormField key={f.id} field={f} value={values[f.id] || ""} onChange={(v) => setField(f.id, v)} />
            ))}

            {submitError && (
              <div style={{ padding: 12, background: "rgba(184,65,43,0.1)",
                            border: "1px solid var(--accent)", borderRadius: 8,
                            color: "var(--accent-deep)", fontSize: 14 }}>
                {submitError}
              </div>
            )}

            <button type="submit" className="btn btn-primary" disabled={submitting}
              style={{ background: submitting ? "var(--ink-mute)" : "var(--secondary)",
                       marginTop: 6, opacity: submitting ? 0.7 : 1 }}>
              {submitting ? "Sending…" : "Register"}
            </button>
          </form>
        </>
      )}

      <FootNav setRoute={setRoute} current="register" />
    </div>
  );
}

function FormField({ field, value, onChange }) {
  const labelEl = (
    <label style={{ display: "block", fontFamily: "var(--f-body)",
      fontSize: 13, fontWeight: 600, color: "var(--ink-soft)",
      letterSpacing: "0.02em", marginBottom: 6 }}>
      {field.label}
      {field.required && <span style={{ color: "var(--accent)", marginLeft: 4 }}>*</span>}
    </label>
  );

  const baseInputStyle = {
    width: "100%", padding: "10px 12px",
    border: "1.5px solid var(--rule)", borderRadius: 8,
    fontFamily: "var(--f-body)", fontSize: 15,
    background: "rgba(255,255,255,0.5)", color: "var(--ink)",
    boxSizing: "border-box",
  };

  if (field.type === "text") {
    return (
      <div className="paper" style={{ padding: "14px 16px" }}>
        {labelEl}
        <input type="text" required={field.required}
          value={value} onChange={(e) => onChange(e.target.value)}
          style={baseInputStyle} />
      </div>
    );
  }

  if (field.type === "dropdown") {
    return (
      <div className="paper" style={{ padding: "14px 16px" }}>
        {labelEl}
        <select required={field.required} value={value}
          onChange={(e) => onChange(e.target.value)} style={baseInputStyle}>
          <option value="">—</option>
          {field.options.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      </div>
    );
  }

  if (field.type === "radio") {
    return (
      <div className="paper" style={{ padding: "14px 16px" }}>
        {labelEl}
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 4 }}>
          {field.options.map(o => {
            const active = value === o;
            return (
              <button type="button" key={o} onClick={() => onChange(o)}
                style={{
                  appearance: "none", cursor: "pointer",
                  padding: "8px 14px", borderRadius: 999,
                  border: `1.5px solid ${active ? "var(--secondary)" : "var(--rule)"}`,
                  background: active ? "var(--secondary)" : "transparent",
                  color: active ? "var(--paper)" : "var(--ink)",
                  fontFamily: "var(--f-body)", fontWeight: 600, fontSize: 14,
                }}>
                {o}
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  return null;
}

Object.assign(window, { Home, StationView, CertificateView, BeforeView, MapView, AfterView, FaqView, RegisterView });
