/* ART ADDA — Editions (list) + Edition detail (per-day) */
function Editions({ go, eventId, setEventId, openArtist }) {
  useReveal();
  const D = window.ARTADDA;
  if (eventId) {
    const ev = D.events.find((e) => e.id === eventId);
    if (ev) return <EventDetail ev={ev} back={() => setEventId(null)} go={go} openArtist={openArtist} />;
  }

  const upcoming = D.events.filter((e) => e.status === "upcoming");
  const past = D.events.filter((e) => e.status === "past");

  return (
    <div className="rise-in">
      <section className="wrap page-intro">
        <p className="eyebrow reveal" style={{ marginBottom: 22 }}>The Editions</p>
        <h1 className="serif reveal">Every<br />Second Sunday</h1>
        <p className="lede reveal" style={{ maxWidth: "54ch", marginTop: 26 }}>
          Each edition is its own small show — a set of artists, a wall of work, an afternoon of conversation. Open any date to see who showed and what they brought.
        </p>
      </section>

      <section className="wrap section" style={{ paddingTop: "clamp(30px,4vw,50px)" }}>
        {upcoming.map((ev) => (
          <EditionRow key={ev.id} ev={ev} onOpen={() => setEventId(ev.id)} D={D} />
        ))}
        {past.map((ev) => (
          <EditionRow key={ev.id} ev={ev} onOpen={() => setEventId(ev.id)} D={D} />
        ))}
        <div style={{ borderTop: "1px solid var(--line-strong)" }} />
      </section>
    </div>
  );
}

function EditionRow({ ev, onOpen, D }) {
  return (
    <button className="tl-row reveal" onClick={onOpen} style={{ width: "100%", textAlign: "left", background: "none", border: 0, borderTop: "1px solid var(--line-strong)", cursor: "pointer", color: "inherit" }}>
      <div className="tl-row__date">
        <div className="tl-row__day serif">{ev.day}</div>
        <div className="tl-row__mo">{ev.month}</div>
        <div className="tl-row__yr">{ev.year}</div>
      </div>
      <div className="tl-row__body">
        <div style={{ display: "flex", justifyContent: "space-between", gap: 16, flexWrap: "wrap", alignItems: "baseline" }}>
          <div className="tl-row__title serif">{ev.title}</div>
          <span className={"tl-status " + (ev.status === "upcoming" ? "tl-status--up" : "tl-status--past")}>
            {ev.status === "upcoming" ? "Upcoming" : "View edition"}
          </span>
        </div>
        <p className="muted" style={{ maxWidth: "60ch", margin: "4px 0 0" }}>{ev.blurb}</p>
        <div className="tl-row__artists">
          {ev.artistIds.map((aid) => {
            const a = D.artistById(aid);
            return a ? <span key={aid} className="tag">{a.name}</span> : null;
          })}
          {ev.special && <span className="tag">Children's Day</span>}
          {ev.firstShow && <span className="tag">First show</span>}
        </div>
      </div>
    </button>
  );
}

function EventDetail({ ev, back, go, openArtist }) {
  useReveal();
  const D = window.ARTADDA;
  const artists = (ev.artistIds || []).map((id) => D.artistById(id)).filter(Boolean);

  // Build works for this edition's artists.
  const works = React.useMemo(() => {
    const ratios = ["4/5", "1/1", "3/4", "4/3", "5/7"];
    const out = [];
    let i = 0;
    artists.forEach((a) => {
      const n = Math.min(a.works || 3, 4);
      for (let k = 0; k < n; k++) {
        out.push({
          id: `${a.id}-${k}`,
          title: `${a.discipline.split(" ")[0]} study ${k + 1}`,
          meta: `${a.name} · ${(a.mediums && a.mediums[0]) || "Work"}`,
          label: `${a.name} — work ${k + 1}`,
          ratio: ratios[i % ratios.length],
          src: D.img.work(a.id, k + 1),
        });
        i++;
      }
    });
    return out;
  }, [ev.id]);

  const [lbIndex, setLbIndex] = useState(null);
  const navLb = (dir) => setLbIndex((p) => (p + dir + works.length) % works.length);

  return (
    <div className="rise-in">
      <section className="wrap" style={{ paddingTop: "clamp(28px,4vw,56px)" }}>
        <button className="back-link" onClick={back}>
          <span style={{ transform: "rotate(180deg)", display: "inline-flex" }}><Arrow /></span> All editions
        </button>

        {/* header */}
        <div className="event-head">
          <div className="event-head__date">
            <div className="event-head__day serif">{ev.day}</div>
            <div>
              <div className="event-head__mo mono">{ev.month} {ev.year}</div>
              <span className={"tl-status " + (ev.status === "upcoming" ? "tl-status--up" : "tl-status--past")} style={{ marginTop: 8, display: "inline-block" }}>
                {ev.status === "upcoming" ? "Upcoming" : "Past edition"}
              </span>
            </div>
          </div>
          <h1 className="h-xl serif" style={{ margin: "18px 0 0" }}>{ev.title}</h1>
          <p className="lede" style={{ maxWidth: "56ch", marginTop: 18 }}>{ev.blurb}</p>
        </div>
      </section>

      {/* hero image band */}
      <section className="wrap" style={{ marginTop: "clamp(28px,4vw,48px)" }}>
        <div className="event-hero reveal">
          <Ph label={`${ev.title} · ${ev.date} — wide shot`} src={D.img.event(ev.id, 1)} />
          <Ph label="Detail · setup" src={D.img.event(ev.id, 2)} />
          <Ph label="Detail · the crowd" src={D.img.event(ev.id, 3)} />
        </div>
      </section>

      {/* upcoming = CTA, else artists + works */}
      {ev.status === "upcoming" ? (
        <section className="wrap section">
          <div className="reveal center" style={{ maxWidth: "44ch", margin: "0 auto" }}>
            <p className="eyebrow" style={{ marginBottom: 18 }}>Submissions open</p>
            <h2 className="h-lg serif" style={{ marginBottom: 24 }}>Could your work be on this wall?</h2>
            <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
              <button className="btn" onClick={() => go("submit")}>Submit your work <Arrow /></button>
              <button className="btn btn--ghost" onClick={() => go("guidelines")}>Read guidelines</button>
            </div>
          </div>
        </section>
      ) : (
        <React.Fragment>
          {ev.special && (
            <section className="wrap section" style={{ paddingBottom: 0 }}>
              <div className="reveal" style={{ background: "var(--paper-2)", padding: "clamp(24px,3vw,40px)", maxWidth: 760 }}>
                <p className="muted" style={{ margin: 0 }}>A Children's Day special — the young artists chose, titled and put up their own work. Bold, colourful, playful and unexpected, with the community invited to be curious and ask questions.</p>
              </div>
            </section>
          )}

          {artists.length > 0 && (
            <section className="wrap section">
              <SectionHead index={String(artists.length).padStart(2, "0")} kicker="On show" title={artists.length > 1 ? "Participating artists" : "The artist"} />
              <div className="artist-grid" style={{ marginTop: 40 }}>
                {artists.map((a, i) => (
                  <button key={a.id} className="artist-card hover-rise reveal" onClick={() => openArtist(a.id)}>
                    <Ph label={`${a.name} · portrait`} src={D.img.artist(a.id)} />
                    <div className="artist-card__top">
                      <div className="artist-card__name serif">{a.name}</div>
                      <span className="num">{String(i + 1).padStart(2, "0")}</span>
                    </div>
                    <div className="artist-card__disc">{a.discipline}</div>
                  </button>
                ))}
              </div>
            </section>
          )}

          {works.length > 0 && (
            <section className="wrap section" style={{ paddingTop: 0 }}>
              <SectionHead kicker="The wall" title="Sample works">
                A selection of pieces shown this edition. Tap to view larger.
              </SectionHead>
              <div className="gal reveal" style={{ marginTop: 40 }}>
                {works.map((it, idx) => (
                  <figure className="gal__item" key={it.id} onClick={() => setLbIndex(idx)}>
                    <Ph label={it.label} ratio={it.ratio} src={it.src} />
                    <figcaption className="gal__cap">
                      <span className="t serif">{it.title}</span>
                      <span className="m">{it.meta.split(" · ")[1]}</span>
                    </figcaption>
                  </figure>
                ))}
              </div>
            </section>
          )}
        </React.Fragment>
      )}

      {/* prev / next edition */}
      <section className="wrap section" style={{ paddingTop: 0 }}>
        <EditionNav ev={ev} go={go} />
      </section>

      <Lightbox items={works} index={lbIndex} onClose={() => setLbIndex(null)} onNav={navLb} />
    </div>
  );
}

function EditionNav({ ev, go }) {
  const D = window.ARTADDA;
  const list = D.events;
  const idx = list.findIndex((e) => e.id === ev.id);
  const older = list[idx + 1];
  const newer = list[idx - 1];
  return (
    <div className="edition-nav" style={{ borderTop: "1px solid var(--line-strong)", display: "flex", justifyContent: "space-between", gap: 20, paddingTop: 28, flexWrap: "wrap" }}>
      <button className="btn btn--ghost" onClick={() => go("editions")}>All editions</button>
      <div style={{ display: "flex", gap: 12 }}>
        {newer && <span className="tag" style={{ cursor: "pointer" }} onClick={() => { window.location.hash = "editions"; window.__openEdition && window.__openEdition(newer.id); }}>Newer: {newer.title}</span>}
        {older && <span className="tag" style={{ cursor: "pointer" }} onClick={() => { window.location.hash = "editions"; window.__openEdition && window.__openEdition(older.id); }}>Older: {older.title}</span>}
      </div>
    </div>
  );
}

window.Editions = Editions;
