/* Venice.jsx — Venice Island Performing Arts Center page */

function VenicePage() {
  return (
    <div>
      <section style={{ position: "relative", overflow: "hidden", paddingBottom: 80 }}>
        <div className="container" style={{ paddingTop: 64 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.1fr 0.9fr", gap: 48, alignItems: "center" }} className="venice-hero">
            <div>
              <div className="eyebrow">Venice Island Performing Arts Center</div>
              <h1 className="display" style={{ fontSize: "clamp(44px, 8vw, 120px)", margin: "12px 0 22px", lineHeight: 0.95 }}>
                Our home<br />on the<br /><span style={{ fontStyle: "italic", color: "var(--c-primary)" }}>Schuylkill.</span>
              </h1>
              <p style={{ fontSize: 18, lineHeight: 1.55, color: "var(--c-ink-soft)", maxWidth: 540, marginBottom: 28 }}>
                Venice Island PAC in Manayunk is the production home for YPTC and the
                annual Spring Arts Showcase. A 250-seat proscenium theatre with full
                lighting, sound, and rehearsal spaces — bookable for community events.
              </p>
              <VeniceLinks />
            </div>

            <div style={{ position: "relative" }}>
              <div style={{
                aspectRatio: "4/5", borderRadius: 22, overflow: "hidden",
                border: "2px solid var(--c-ink)", boxShadow: "var(--shadow-lift)"
              }}>
                <img
                  src="https://www.bkparchitects.com/wp-content/uploads/2019/12/01-BKP_Venice-Island_night_1_F_original_thumb_web.jpg"
                  alt="Venice Island Performing Arts Center stage with PPR performers"
                  style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
                />
              </div>
              <div className="card" style={{
                position: "absolute", bottom: -24, left: -24,
                background: "var(--c-tertiary)", color: "var(--c-paper)",
                transform: "rotate(-3deg)", maxWidth: 220,
              }}>
                <div className="eyebrow" style={{ color: "var(--c-cream)", opacity: 0.85 }}>Address</div>
                <div className="display" style={{ fontSize: 20, color: "var(--c-paper)", marginTop: 4, lineHeight: 1.1 }}>
                  7 Lock Street<br />Philadelphia, PA 19127
                </div>
              </div>
            </div>
          </div>
        </div>
        <style>{`
          @media (max-width: 900px) { .venice-hero { grid-template-columns: 1fr !important; gap: 32px !important; } }
        `}</style>
      </section>

      <section style={{ background: "var(--c-paper)", borderTop: "2px solid var(--c-ink)", borderBottom: "2px solid var(--c-ink)" }} className="section">
        <div className="container">
          <SectionHeader eyebrow="The space" title="What you'll find inside." />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }} className="venice-grid">
            <FeatureCard
              tint="#F5C6B0"
              title="Proscenium theatre"
              spec="250 seats · audience raked"
              body="Traditional proscenium configuration with a full theatrical lighting rig and a Yamaha digital sound desk."
              photo="/img/DSC01166.jpg"
            />
            <FeatureCard
              tint="#F2D88F"
              title="Rehearsal studios"
              spec="2 rooms"
              body="Two rehearsal spaces with mirrors, marley dance floors, and upright pianos. Bookable by the hour for ensembles and instructors."
              photo="/img/venice-rehearsal.jpg"
            />
            <FeatureCard
              tint="#C9D9B0"
              title="Riverside grounds"
              spec="Outdoor stage · summer only"
              body="An outdoor amphitheater on the Schuylkill banks for free summer performances and community gatherings."
              photo="/img/venice-grounds.jpg"
            />
          </div>
        </div>
        <style>{`
          @media (max-width: 900px) { .venice-grid { grid-template-columns: 1fr !important; } }
        `}</style>
      </section>

      <section id="venice-calendar" className="section">
        <div className="container">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }} className="cal-grid">
            <div className="card" style={{ background: "var(--c-cream-deep)", padding: 32 }}>
              <div className="eyebrow">Calendar</div>
              <div className="display" style={{ fontSize: 36, marginTop: 8, lineHeight: 1 }}>
                Upcoming<br />at Venice Island.
              </div>
              <p style={{ fontSize: 15, color: "var(--c-ink-soft)", marginTop: 12, lineHeight: 1.55 }}>
                Showcases, community events, and PPR productions. The full calendar
                is hosted on the Venice Island PAC site.
              </p>
              <CalendarEntries />

            </div>

            <div className="card" style={{ background: "var(--c-ink)", color: "var(--c-cream)", padding: 32 }}>
              <div className="eyebrow" style={{ color: "var(--c-accent)" }}>Booking</div>
              <div className="display" style={{ fontSize: 36, marginTop: 8, lineHeight: 1, color: "var(--c-cream)" }}>
                Book the<br />space.
              </div>
              <p style={{ fontSize: 15, color: "rgba(251,243,226,0.75)", marginTop: 12, lineHeight: 1.55 }}>
                Venice Island PAC is available for community productions, recitals,
                and rehearsals. Rates are subsidized for nonprofits and Philadelphia
                public schools.
              </p>
              <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 12 }}>
                <RateLine venue="Proscenium theatre" rate="$1,000 / 4 hours · $150/hour after" />
                <RateLine venue="Rehearsal studio" rate="$10 / hour" />
                <RateLine venue="Outdoor amphitheater" rate="By inquiry" />
              </div>
              <BookingCTA />
            </div>
          </div>
        </div>
        <style>{`
          @media (max-width: 900px) { .cal-grid { grid-template-columns: 1fr !important; } }
        `}</style>
      </section>
    </div>
  );
}

function FeatureCard({ tint, title, spec, body, photo }) {
  return (
    <div className="card" style={{ background: tint, padding: 0, overflow: "hidden" }}>
      <div style={{ aspectRatio: "5/3", borderBottom: "2px solid var(--c-ink)", overflow: "hidden" }}>
        {photo ? (
          <img src={photo} alt={title} loading="lazy"
            style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
        ) : (
          <div className="placeholder" data-label={title.toLowerCase()}
            style={{ width: "100%", height: "100%", border: "none", borderRadius: 0 }} />
        )}
      </div>
      <div style={{ padding: 22 }}>
        <div className="display" style={{ fontSize: 22 }}>{title}</div>
        <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--c-ink-soft)", margin: "6px 0 12px" }}>
          {spec}
        </div>
        <p style={{ fontSize: 14, color: "var(--c-ink)", lineHeight: 1.55 }}>{body}</p>
      </div>
    </div>
  );
}

function CalEntry({ date, title, tag, url }) {
  return (
    <div style={{ display: "flex", gap: 14, alignItems: "center", padding: "10px 0", borderTop: "1px dashed var(--c-line)" }}>
      <div style={{ fontFamily: "var(--f-display)", fontSize: 14, fontWeight: 800, letterSpacing: "0.05em", width: 64, color: "var(--c-primary)", flexShrink: 0 }}>
        {date}
      </div>
      <div style={{ flex: 1, fontSize: 14, fontWeight: 600, minWidth: 0 }}>
        {title}
        {url && (
          <a
            href={url}
            target="_blank"
            rel="noopener noreferrer"
            style={{ marginLeft: 10, fontSize: 11, fontWeight: 600, fontFamily: "var(--f-mono)", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--c-primary-deep)", textDecoration: "underline", whiteSpace: "nowrap" }}
          >
            tickets &uarr;
          </a>
        )}
      </div>
      {tag && <span className="chip" style={{ background: "var(--c-paper)", fontSize: 10 }}>{tag}</span>}
    </div>
  );
}

function RateLine({ venue, rate }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "10px 0", borderTop: "1px dashed rgba(251,243,226,0.2)" }}>
      <div style={{ fontSize: 15 }}>{venue}</div>
      <div style={{ fontFamily: "var(--f-display)", fontWeight: 700, color: "var(--c-accent)", fontSize: 15 }}>{rate}</div>
    </div>
  );
}

// Default "see full calendar" target is the public HTML view of Venice
// Island's Google Calendar -- the same source /api/venice-events reads
// from. CMS override (venice.calendar_url) still wins if set.
const VENICE_PUBLIC_CALENDAR_URL = "https://calendar.google.com/calendar/embed?src=3078930815727a6ace4980f9c684d08408e909ba1e37afa16ff3f344393f6c3a%40group.calendar.google.com";

function VeniceLinks() {
  const book = window.useCMS ? window.useCMS("venice.booking_url", "https://www.veniceisland.org/rental") : "https://www.veniceisland.org/rental";
  const scrollToCalendar = (e) => {
    e.preventDefault();
    const el = document.getElementById("venice-calendar");
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  return (
    <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
      <a href="#venice-calendar" onClick={scrollToCalendar} className="btn">Calendar ↓</a>
      {book ? (
        <a href={book} target="_blank" rel="noopener" className="btn secondary">Book the space ↗</a>
      ) : null}
    </div>
  );
}

const CAL_PREVIEW_COUNT = 6;

function CalendarEntries() {
  // Source of truth is /api/venice-events, which reads the public Google
  // Calendar feed that veniceisland.org's events page also reads. CMS-
  // driven venice.events_json stays as a fallback so an admin can still
  // override the list manually if the feed is down or the next event
  // needs a custom blurb.
  const [feed, setFeed] = React.useState({ status: "loading", events: [] });
  const [expanded, setExpanded] = React.useState(false);

  React.useEffect(() => {
    let cancelled = false;
    fetch("/api/venice-events", { headers: { accept: "application/json" } })
      .then(r => r.ok ? r.json() : { ok: false })
      .then(j => {
        if (cancelled) return;
        if (j.ok && Array.isArray(j.events)) {
          setFeed({ status: "ok", events: j.events });
        } else {
          setFeed({ status: "error", events: [] });
        }
      })
      .catch(() => { if (!cancelled) setFeed({ status: "error", events: [] }); });
    return () => { cancelled = true; };
  }, []);

  // Manual CMS fallback. Format expected: [{ date, title, tag, url }].
  const cmsRaw = window.useCMS ? window.useCMS("venice.events_json", []) : [];
  let cmsEvents = [];
  if (Array.isArray(cmsRaw)) cmsEvents = cmsRaw;
  else if (typeof cmsRaw === "string" && cmsRaw.trim()) {
    try { cmsEvents = JSON.parse(cmsRaw); } catch { cmsEvents = []; }
  }

  const useFallback = feed.status === "error" || feed.events.length === 0;
  const entries = useFallback
    ? cmsEvents.map(e => ({ key: `cms-${e.date}-${e.title}`, date: e.date || "", title: e.title || "", tag: e.tag || "", url: e.url || null }))
    : feed.events.map(e => ({ key: e.uid || e.start, date: formatEventDate(e.start, e.all_day), title: e.title || "(untitled)", tag: "", url: e.url || null }));

  if (feed.status === "loading") {
    return (
      <p style={{ marginTop: 24, fontSize: 14, color: "var(--c-ink-soft)", fontFamily: "var(--f-mono)", letterSpacing: "0.06em" }}>
        Loading upcoming events&hellip;
      </p>
    );
  }

  if (entries.length === 0) {
    return (
      <p style={{ marginTop: 24, fontSize: 14, color: "var(--c-ink-soft)", fontStyle: "italic" }}>
        No upcoming events posted yet &mdash; check back soon.
      </p>
    );
  }

  const hasMore = entries.length > CAL_PREVIEW_COUNT;
  const visible = (hasMore && !expanded) ? entries.slice(0, CAL_PREVIEW_COUNT) : entries;
  const hiddenCount = entries.length - CAL_PREVIEW_COUNT;

  return (
    <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 10 }}>
      {visible.map(e => (
        <CalEntry key={e.key} date={e.date} title={e.title} tag={e.tag} url={e.url} />
      ))}
      {hasMore && (
        <button
          type="button"
          onClick={() => setExpanded(v => !v)}
          aria-expanded={expanded}
          style={{
            marginTop: 8,
            alignSelf: "flex-start",
            background: "var(--c-paper)",
            border: "2px solid var(--c-ink)",
            borderRadius: 999,
            padding: "10px 18px",
            minHeight: 44,
            fontFamily: "var(--f-mono)",
            fontSize: 11,
            letterSpacing: "0.12em",
            textTransform: "uppercase",
            fontWeight: 700,
            color: "var(--c-ink)",
            cursor: "pointer",
            boxShadow: "3px 3px 0 var(--c-ink)",
            transition: "transform 120ms ease, box-shadow 120ms ease",
          }}
          onMouseEnter={e => { e.currentTarget.style.transform = "translate(-2px, -2px)"; e.currentTarget.style.boxShadow = "5px 5px 0 var(--c-ink)"; }}
          onMouseLeave={e => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = "3px 3px 0 var(--c-ink)"; }}
        >
          {expanded
            ? <>Show fewer <span aria-hidden="true">&uarr;</span></>
            : <>View {hiddenCount} more {hiddenCount === 1 ? "event" : "events"} <span aria-hidden="true">&darr;</span></>}
        </button>
      )}
    </div>
  );
}

// "MAY 17" / "MAY 17 - 18" / "JUN 3" formatting, in the venue's local time.
// Venice Island operates in America/New_York; the feed is in UTC so we
// display in ET to match what users would expect from the public calendar.
function formatEventDate(iso, allDay) {
  if (!iso) return "";
  try {
    const d = new Date(iso);
    const opts = { month: "short", day: "numeric", timeZone: "America/New_York" };
    return d.toLocaleDateString("en-US", opts).toUpperCase().replace(",", "");
  } catch {
    return "";
  }
}

function BookingCTA() {
  const book = window.useCMS ? window.useCMS("venice.booking_url", "https://www.veniceisland.org/rental") : "https://www.veniceisland.org/rental";
  if (!book) return null;
  return (
    <a href={book} target="_blank" rel="noopener" className="btn ochre small" style={{ marginTop: 24 }}>
      Booking inquiry ↗
    </a>
  );
}

Object.assign(window, { VenicePage, VeniceLinks, BookingCTA, CalendarEntries });
