const { SectionHeading, Card, Stat, Button, Badge, Icon } = window.AntelopeDashDesignSystem_4664c0;

const RACES = [
  {
    name: "4-Mile Dash", band: "4-Mile Dash", bandColor: "teal", featured: false,
    blurb: "A perfect introduction to trail running. Rolling hills, beautiful scenery, and a generous cutoff time to enjoy the park.",
    stats: [["Start Time", "9:15 AM"], ["Elevation Gain", "~490 ft"], ["Price", "$45"]],
    map: "course-4mile.png", gpx: "course-4mile.gpx", cta: "Sign Up", ctaVariant: "dark",
  },
  {
    name: "8-Mile Grind", band: "8-Mile Grind", bandColor: "copper", featured: true, ribbon: "Most Popular",
    blurb: "Experience the best of the park. Technical sections, steep climbs, and fast descents through the granite formations.",
    stats: [["Start Time", "9:00 AM"], ["Elevation Gain", "~1,000 ft"], ["Price", "$60"]],
    map: "course-8mile.png", gpx: "course-8mile.gpx", cta: "Sign Up", ctaVariant: "primary",
  },
  {
    name: "12-Mile Trudge", band: "12-Mile Trudge", bandColor: "slate", featured: false, ribbon: "Coming 2027", dim: true,
    blurb: "For the bold. A grueling, beautiful loop connecting the most challenging trails in Curt Gowdy — from Aspen Grove out past the reservoir. Launching next year!",
    stats: [["Start Time", "TBD", true], ["Elevation Gain", "~1,250 ft"], ["Status", "In Development"]],
    map: "course-12mile.png", gpx: "course-12mile.gpx",
  },
];

function RacesSection({ onOpenMap }) {
  async function downloadGpx(e, file, label) {
    e.preventDefault();
    try {
      const res = await fetch(`./assets/${file}`);
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `AntelopeDash-${label.replace(/[^0-9A-Za-z]+/g, "")}.gpx`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
    } catch (err) {
      window.open(`./assets/${file}`, "_blank");
    }
  }
  return (
    <section id="races" style={{ padding: "80px 24px", background: "var(--slate-100)" }}>
      <div style={{ maxWidth: "80rem", margin: "0 auto" }}>
        <div style={{ marginBottom: 56 }}>
          <SectionHeading title="Choose Your Distance" subtitle="From beginners to seasoned trail veterans, we have a course designed to test your limits." />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 32, alignItems: "start" }}>
          {RACES.map((r) => (
            <Card key={r.name} band={r.band} bandColor={r.bandColor} featured={r.featured}
              style={{ opacity: r.dim ? 0.92 : 1, transform: r.featured ? "translateY(-12px)" : "none" }}>
              {r.ribbon && (
                <Badge variant={r.featured ? "copper" : "slate"} shape="corner" style={{ position: "absolute", top: 0, right: 0, zIndex: 10 }}>{r.ribbon}</Badge>
              )}
              <p style={{ color: "var(--text-body)", margin: "0 0 24px", flex: "1 1 auto", lineHeight: 1.6 }}>{r.blurb}</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 12, marginBottom: 24 }}>
                {r.stats.map(([l, v, m]) => <Stat key={l} label={l} value={v} muted={!!m} />)}
              </div>
              {r.map ? (
                <>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16 }}>
                    <Button variant="outline" size="sm" onClick={() => onOpenMap(r.name + " Route Map", r.map)}><Icon name="map" size={16} /> Map</Button>
                    {r.gpx ? (
                      <Button variant="outline" size="sm" as="a" href={`./assets/${r.gpx}`} onClick={(e) => downloadGpx(e, r.gpx, r.name)}><Icon name="download" size={16} /> GPX</Button>
                    ) : (
                      <Button variant="outline" size="sm" as="a" href="#"><Icon name="download" size={16} /> GPX</Button>
                    )}
                  </div>
                  {r.cta && (
                    <Button variant={r.ctaVariant} fullWidth as="a" href="https://ultrasignup.com/register.aspx?did=135646" target="_blank">{r.cta}</Button>
                  )}
                </>
              ) : (
                <Button variant="outline" fullWidth><Icon name="map" size={18} /> View Proposed Route</Button>
              )}
            </Card>
          ))}
        </div>
      </div>
    </section>
  );
}
window.RacesSection = RacesSection;
