/* Home.jsx — Hero, mission, featured camps, gallery teaser, newsletter */

function HomePage({ setRoute }) {
  const goTo = (id) => (e) => {
    e.preventDefault();
    setRoute(id);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <div>
      <Hero setRoute={setRoute} />
      <Marquee items={[
        "Summer 2026 Pre-Registration Open",
        "6 Camp Sites Across Philly",
        "Ages 6–18",
        "Free + Subsidized",
        "Dance · Theatre · Voice"
      ]} />
      <MissionBlock />
      <FeaturedCamps setRoute={setRoute} />
      <ProgramsTeaser setRoute={setRoute} />
      <GalleryTeaser setRoute={setRoute} />
      <GetInvolvedRow setRoute={setRoute} />
      <NewsletterStrip />
    </div>
  );
}

function Hero({ setRoute }) {
  return (
    <section style={{ position: "relative", overflow: "hidden", paddingBottom: 80 }}>
      <div className="container" style={{ paddingTop: 64 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.15fr 0.85fr", gap: 56, alignItems: "center" }} className="hero-grid">
          <div>
            <div style={{ display: "flex", gap: 10, marginBottom: 22, flexWrap: "wrap" }}>
              <span className="chip" style={{ background: "var(--c-accent)" }}>Summer 2026</span>
              <span className="chip">Pre-Registration Open</span>
            </div>
            <h1
              className="display"
              style={{
                fontSize: "clamp(48px, 8.4vw, 132px)",
                margin: "0 0 24px",
              }}
            >
              Where<br />
              <span style={{ color: "var(--c-primary)" }}>Philly kids</span><br />
              find their<br />
              <span style={{ fontStyle: "italic", fontWeight: 700 }}>spotlight.</span>
            </h1>
            <p
              style={{
                fontSize: 19,
                lineHeight: 1.5,
                maxWidth: 520,
                color: "var(--c-ink-soft)",
                marginBottom: 32,
              }}
            >
              Performing arts summer camps, after-school programs, and showcases
              — across six neighborhoods, for ages 6 to 18.
            </p>
            <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
              <a href="#camps" onClick={(e) => { e.preventDefault(); setRoute("camps"); window.scrollTo(0,0); }} className="btn">
                Register for Summer Camp →
              </a>
              <a href="#programs" onClick={(e) => { e.preventDefault(); setRoute("programs"); window.scrollTo(0,0); }} className="btn secondary">
                Find a program near me
              </a>
            </div>

            <div style={{ display: "flex", gap: 36, marginTop: 56, flexWrap: "wrap" }}>
              <Stat n="6" label="Camp sites" />
              <Stat n="10+" label="Year-round programs" />
              <Stat n="600+" label="Young artists / yr" />
            </div>
          </div>

          <div style={{ position: "relative" }}>
            <a
              href="#gallery"
              onClick={(e) => { e.preventDefault(); setRoute("gallery"); window.scrollTo({ top: 0, behavior: "smooth" }); }}
              aria-label="View Spring Arts Showcase gallery"
              style={{
                display: "block",
                aspectRatio: "4/5", borderRadius: 22, overflow: "hidden",
                border: "2px solid var(--c-ink)", boxShadow: "var(--shadow-lift)",
                cursor: "pointer",
              }}
            >
              <img
                src="/img/DSC01907.jpg"
                alt="Three young performers in red dresses on stage at the PPR Spring Arts Showcase — click to view gallery"
                style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
              />
            </a>
            <div
              style={{
                position: "absolute",
                top: -18,
                right: -10,
                transform: "rotate(8deg)",
              }}
            >
              <div className="sticker" style={{ background: "var(--c-primary)", color: "var(--c-paper)" }}>
                FEATURING
              </div>
            </div>
            <a
              href="#gallery"
              onClick={(e) => { e.preventDefault(); setRoute("gallery"); window.scrollTo({ top: 0, behavior: "smooth" }); }}
              className="card"
              style={{
                position: "absolute",
                bottom: -28,
                left: -28,
                width: 220,
                background: "var(--c-accent)",
                transform: "rotate(-4deg)",
                color: "inherit",
                textDecoration: "none",
                cursor: "pointer",
                display: "block",
              }}
            >
              <div className="display" style={{ fontSize: 24, lineHeight: 1.05 }}>
                Spring Arts<br />Showcase
              </div>
              <div style={{ fontFamily: "var(--f-mono)", fontSize: 12, marginTop: 8 }}>
                04 · 28 · 2026 · Venice Island
              </div>
            </a>
          </div>
        </div>
      </div>

      {/* decorative shapes */}
      <div
        style={{
          position: "absolute",
          left: "-6%",
          top: "30%",
          width: 220,
          height: 220,
          borderRadius: "50%",
          background: "var(--c-tertiary)",
          opacity: 0.18,
          zIndex: -1,
        }}
      />

      <style>{`
        @media (max-width: 900px) {
          .hero-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
        }
      `}</style>
    </section>
  );
}

function Stat({ n, label }) {
  return (
    <div>
      <div className="display" style={{ fontSize: 48, lineHeight: 1, color: "var(--c-primary)" }}>{n}</div>
      <div style={{
        fontFamily: "var(--f-mono)",
        fontSize: 11,
        letterSpacing: "0.12em",
        textTransform: "uppercase",
        color: "var(--c-ink-soft)",
        marginTop: 6,
      }}>{label}</div>
    </div>
  );
}

function MissionBlock() {
  return (
    <section className="section" style={{ background: "var(--c-paper)", borderTop: "2px solid var(--c-ink)", borderBottom: "2px solid var(--c-ink)" }}>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "0.4fr 1fr", gap: 56 }} className="mission-grid">
          <div>
            <div className="eyebrow">Our mission</div>
            <div className="display" style={{ fontSize: 56, marginTop: 12, lineHeight: 0.95 }}>
              The arts,<br />for every<br />Philadelphian.
            </div>
          </div>
          <div>
            <p style={{ fontSize: 22, lineHeight: 1.45, color: "var(--c-ink)" }}>
              Our mission is to cultivate vibrant, inclusive performing arts experiences
              that <span style={{ background: "var(--c-accent)", padding: "0 6px" }}>reflect and celebrate the diverse voices</span> of
              Philadelphia&apos;s communities. Through accessible programming, creative
              collaboration, and high-quality artistic opportunities, we empower
              individuals of all ages to explore their creativity, build confidence,
              and connect with one another.
            </p>
            <p style={{ fontSize: 17, lineHeight: 1.6, color: "var(--c-ink-soft)", marginTop: 18 }}>
              By supporting local artists, nurturing emerging talent, and activating
              neighborhood spaces, we strengthen the social fabric of our city and
              ensure the arts remain a vital, equitable resource for all Philadelphians.
            </p>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          .mission-grid { grid-template-columns: 1fr !important; gap: 24px !important; }
        }
      `}</style>
    </section>
  );
}

function FeaturedCamps({ setRoute }) {
  return (
    <section className="section">
      <div className="container">
        <SectionHeader
          eyebrow="Summer 2026 — Pre-Registration"
          title="Six camps. One unforgettable summer."
          right={
            <a href="#camps" onClick={(e) => { e.preventDefault(); setRoute("camps"); window.scrollTo(0,0); }} className="btn ghost small">
              View all sites →
            </a>
          }
        />

        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(3, 1fr)",
            gap: 20,
          }}
          className="camps-grid"
        >
          {["athletic", "hawthorne", "holmesburg"]
            .map(id => window.CAMP_SITES.find(c => c.id === id))
            .filter(Boolean)
            .map((camp, i) => (
              <CampPreviewCard key={camp.id} camp={camp} setRoute={setRoute} index={i} />
            ))}
        </div>

        <style>{`
          @media (max-width: 980px) { .camps-grid { grid-template-columns: 1fr 1fr !important; } }
          @media (max-width: 640px) { .camps-grid { grid-template-columns: 1fr !important; } }
        `}</style>
      </div>
    </section>
  );
}

// Per-facility hero shots for the home-page camp cards. Keyed by camp.id so
// rearranging the featured list automatically picks the right photo. Falls
// back to a generic showcase shot if a facility photo isn't on disk yet.
const FACILITY_PHOTOS = {
  athletic:    "https://i0.wp.com/billypenn.com/wp-content/uploads/2017/09/athleticreccenter-creditdanyahenninger-02crop.jpg?fit=780%2C439&ssl=1",
  hawthorne:   "https://upload.wikimedia.org/wikipedia/commons/5/53/Hawthorne_Cultural_Center_1200_Carpenter_St_Philadelphia_PA_%28DSC_3177%29.jpg",
  holmesburg:  "/img/cr-161-1-resized-20260507-145553.jpg"
};
const FALLBACK_CAMP_IMAGES = [
  "/img/DSC01207.jpg",
  "/img/DSC01528.jpg",
  "/img/DSC01873.jpg"
];

function CampPreviewCard({ camp, setRoute, index }) {
  const photo = FACILITY_PHOTOS[camp.id] || FALLBACK_CAMP_IMAGES[(index || 0) % FALLBACK_CAMP_IMAGES.length];
  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ aspectRatio: "5/4", overflow: "hidden", borderBottom: "2px solid var(--c-ink)" }}>
        <img
          src={photo}
          alt={`${camp.name} — performing arts camp at Philadelphia Parks & Recreation`}
          loading="lazy"
          style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
        />
      </div>
      <div style={{ padding: 22 }}>
        <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
          <span className={`chip ${camp.type === "Intro" ? "intro" : "yptc"}`}>{camp.type}</span>
          <span className="chip">{camp.ageRange}</span>
        </div>
        <div className="display" style={{ fontSize: 24, marginBottom: 6 }}>{camp.name}</div>
        <div style={{ fontSize: 14, color: "var(--c-ink-soft)", marginBottom: 16 }}>
          {camp.region} · {camp.address.split(",")[0]}
        </div>
        <a
          href="#camps"
          onClick={(e) => { e.preventDefault(); setRoute("camps"); window.scrollTo(0,0); }}
          className="btn small"
          style={{ width: "100%", justifyContent: "center" }}
        >
          Pre-register →
        </a>
      </div>
    </div>
  );
}

function ProgramsTeaser({ setRoute }) {
  const programs = [
    { type: "Dance",   count: 4, color: "#F5C6B0", icon: "💃" },
    { type: "Theater", count: 3, color: "#F2D88F", icon: "🎭" },
    { type: "Music",   count: 3, color: "#C9D9B0", icon: "🎤" },
  ];

  return (
    <section className="section" style={{ background: "var(--c-cream-deep)", borderTop: "2px solid var(--c-ink)", borderBottom: "2px solid var(--c-ink)" }}>
      <div className="container">
        <SectionHeader
          eyebrow="Year-round programs"
          title="Find your art form."
          subtitle="Performing arts rec center programs across the city. Filter by program type and find one walking distance from home."
        />

        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }} className="prog-grid">
          {programs.map((p) => (
            <a
              key={p.type}
              href="#programs"
              onClick={(e) => { e.preventDefault(); setRoute("programs"); window.scrollTo(0,0); }}
              style={{ textDecoration: "none", color: "inherit" }}
            >
              <div className="card" style={{ background: p.color, transition: "transform 200ms" }}
                onMouseEnter={(e) => e.currentTarget.style.transform = "translate(-4px, -4px)"}
                onMouseLeave={(e) => e.currentTarget.style.transform = "translate(0, 0)"}
              >
                <div style={{ fontSize: 56, marginBottom: 16 }}>{p.icon}</div>
                <div className="display" style={{ fontSize: 32, marginBottom: 4 }}>{p.type}</div>
                <div style={{ fontFamily: "var(--f-mono)", fontSize: 12, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--c-ink-soft)" }}>
                  {p.count} active locations · find on map →
                </div>
              </div>
            </a>
          ))}
        </div>

        <style>{`
          @media (max-width: 880px) { .prog-grid { grid-template-columns: 1fr !important; } }
        `}</style>
      </div>
    </section>
  );
}

// Spring Showcase teaser photos (5). Curated from the /img manifest so the
// home page shows a representative spread of the night.
const TEASER_PHOTOS = [
  { src: "/img/DSC00829.jpg", alt: "Young dancers in blue costumes mid-performance" },
  { src: "/img/DSC01140.jpg", alt: "Solo dancer mid-performance" },
  { src: "/img/DSC01300.jpg", alt: "Packed audience in the Venice Island house" },
  { src: "/img/DSC02436.jpg", alt: "Closing curtain call" },
  { src: "/img/DSC00779.jpg", alt: "Backstage warm-up before the show" },
];

function GalleryTile({ src, alt, gridRow }) {
  return (
    <div style={{
      borderRadius: 14, overflow: "hidden", border: "2px solid var(--c-ink)",
      gridRow: gridRow || undefined,
    }}>
      <img src={src} alt={alt} loading="lazy"
        style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
    </div>
  );
}

function GalleryTeaser({ setRoute }) {
  return (
    <section className="section">
      <div className="container">
        <SectionHeader
          eyebrow="04 · 28 · 2026 · Spring Arts Showcase"
          title="From the stage."
          right={
            <a href="#gallery" onClick={(e) => { e.preventDefault(); setRoute("gallery"); window.scrollTo(0,0); }} className="btn ghost small" style={{ color: "var(--c-ink)" }}>
              View full gallery →
            </a>
          }
        />
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gridTemplateRows: "1fr 1fr", gap: 16, height: 540 }} className="gal-grid">
          <GalleryTile src={TEASER_PHOTOS[0].src} alt={TEASER_PHOTOS[0].alt} gridRow="1 / span 2" />
          <GalleryTile src={TEASER_PHOTOS[1].src} alt={TEASER_PHOTOS[1].alt} />
          <GalleryTile src={TEASER_PHOTOS[2].src} alt={TEASER_PHOTOS[2].alt} />
          <GalleryTile src={TEASER_PHOTOS[3].src} alt={TEASER_PHOTOS[3].alt} />
          <GalleryTile src={TEASER_PHOTOS[4].src} alt={TEASER_PHOTOS[4].alt} />
        </div>
        <style>{`
          @media (max-width: 700px) {
            .gal-grid { grid-template-columns: 1fr 1fr !important; height: 380px !important; }
            .gal-grid > :first-child { grid-row: span 2 !important; }
          }
        `}</style>
      </div>
    </section>
  );
}

function GetInvolvedRow({ setRoute }) {
  return (
    <section className="section-tight" style={{ background: "var(--c-ink)", color: "var(--c-cream)" }}>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }} className="involved-grid">
          <CTACard
            color="var(--c-primary)"
            label="For rec center leaders"
            title="Promote a program at your center."
            body="Submit your program details — name, location, contact — and our team will review and add it to the citywide map."
            cta="Promote a program →"
            onClick={() => { setRoute("promote"); window.scrollTo(0,0); }}
          />
          <CTACard
            color="var(--c-accent)"
            label="For working artists & teachers"
            title="Lead a workshop with us."
            body="Got a skill you'd love to share — improv, sound design, lighting, hip-hop choreo? Tell us about it."
            cta="Workshop development →"
            onClick={() => { setRoute("workshop"); window.scrollTo(0,0); }}
          />
        </div>
        <style>{`
          @media (max-width: 800px) {
            .involved-grid { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </div>
    </section>
  );
}

function CTACard({ color, label, title, body, cta, onClick }) {
  return (
    <div
      className="card"
      style={{
        background: color,
        color: "var(--c-ink)",
        padding: 32,
      }}
    >
      <div className="eyebrow" style={{ marginBottom: 14 }}>{label}</div>
      <div className="display" style={{ fontSize: 36, marginBottom: 12, lineHeight: 1 }}>{title}</div>
      <p style={{ fontSize: 15, lineHeight: 1.55, marginBottom: 20, color: "var(--c-ink)" }}>{body}</p>
      <button onClick={onClick} className="btn secondary small">{cta}</button>
    </div>
  );
}

function NewsletterStrip() {
  const [email, setEmail] = React.useState("");
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");

  const onSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch("/api/loop", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, source: "home_newsletter" })
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.ok) throw new Error(json.error || `error_${res.status}`);
      setSubmitted(true);
    } catch (err) {
      setError("Couldn't subscribe right now. Try again in a moment.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section className="section" style={{ background: "var(--c-cream)" }}>
      <div className="container">
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "1fr 1fr",
            gap: 40,
            alignItems: "center",
          }}
          className="news-grid"
        >
          <div>
            <div className="eyebrow">Stay in the loop</div>
            <div className="display" style={{ fontSize: 56, marginTop: 12, lineHeight: 0.95 }}>
              Showtime<br />updates,<br />once a month.
            </div>
          </div>
          <div>
            {!submitted ? (
              <form onSubmit={onSubmit} style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                <input
                  type="email"
                  required
                  placeholder="you@email.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  disabled={submitting}
                  style={{
                    flex: 1,
                    minWidth: 220,
                    padding: "16px 18px",
                    border: "2px solid var(--c-ink)",
                    borderRadius: 999,
                    fontSize: 16,
                    background: "var(--c-paper)",
                    fontFamily: "var(--f-body)",
                  }}
                />
                <button type="submit" className="btn" disabled={submitting}>
                  {submitting ? "Subscribing…" : "Subscribe →"}
                </button>
              </form>
            ) : (
              <div className="card" style={{ background: "var(--c-tertiary)", color: "var(--c-paper)" }}>
                <div className="display" style={{ fontSize: 26, color: "var(--c-paper)" }}>You&apos;re on the list ✦</div>
                <div style={{ fontSize: 14, marginTop: 8, opacity: 0.85 }}>
                  Watch your inbox for showcases, audition calls, and camp news.
                </div>
              </div>
            )}
            {error && (
              <div style={{ marginTop: 12, fontSize: 13, color: "var(--c-primary-deep)" }}>{error}</div>
            )}
            <div style={{
              fontFamily: "var(--f-mono)",
              fontSize: 11,
              letterSpacing: "0.1em",
              textTransform: "uppercase",
              color: "var(--c-ink-soft)",
              marginTop: 16,
            }}>
              Showcases · audition calls · new programs · no spam.
            </div>
          </div>
        </div>
        <style>{`
          @media (max-width: 800px) {
            .news-grid { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </div>
    </section>
  );
}

function SectionHeader({ eyebrow, title, subtitle, right }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 40, gap: 24, flexWrap: "wrap" }}>
      <div style={{ maxWidth: 720 }}>
        <div className="eyebrow">{eyebrow}</div>
        <div className="display" style={{ fontSize: "clamp(36px, 5.5vw, 64px)", marginTop: 12, lineHeight: 0.98 }}>{title}</div>
        {subtitle && (
          <p style={{ fontSize: 17, color: "var(--c-ink-soft)", marginTop: 14, maxWidth: 600 }}>{subtitle}</p>
        )}
      </div>
      {right}
    </div>
  );
}

Object.assign(window, { HomePage, SectionHeader });
