// Shared European tour dates and ticket routing for the post, homepage, and EPK.
function useEuropeSaleTime() {
  const [now, setNow] = React.useState(Date.now);

  React.useEffect(() => {
    const refresh = () => setNow(Date.now());
    const nextSale = [window.EUROPE_TOUR.announcementAt, window.EUROPE_TOUR.generalSaleAt]
      .map(Date.parse)
      .find((time) => time > now);
    const timer = nextSale ? setTimeout(refresh, Math.min(nextSale - now + 50, 2147483647)) : null;
    window.addEventListener("focus", refresh);
    return () => {
      clearTimeout(timer);
      window.removeEventListener("focus", refresh);
    };
  }, [now]);

  return now;
}

function EuropeSaleNote({ now }) {
  const generalSale = now >= Date.parse(window.EUROPE_TOUR.generalSaleAt)
    && window.EUROPE_TOUR.shows.every((show) => show.generalSale);
  return (
    <p className="tour-sale-note">
      {generalSale ? (
        "Tickets on general sale now."
      ) : (
        <React.Fragment>
          Tickets go on sale September 18, 2026.
          <br />11 a.m. CEST / 10 a.m. BST / 5 a.m. EDT.
        </React.Fragment>
      )}
    </p>
  );
}

function EuropeTourDates() {
  const now = useEuropeSaleTime();
  return (
    <section className="europe-tour-dates" aria-label="Giles Corey European tour dates">
      <h2 className="tour-dates-heading">Europe, UK &amp; Ireland · 2027</h2>
      <EuropeSaleNote now={now} />
      <ol className="tour-dates-list">
        {window.EUROPE_TOUR.shows.map((show) => {
          const offer = window.getEuropeTicketOffer(show, now);
          return (
            <li className="tour-date" key={show.date}>
              <time dateTime={show.date}>{window.formatEuropeDate(show.date)}</time>
              <div className="tour-date__place">
                <strong>{window.formatEuropeCity(show)}</strong>
                <span>{show.venue}</span>
              </div>
              {offer.url ? (
                <a className="tour-date__ticket" href={offer.url} target="_blank" rel="noreferrer"
                   aria-label={`${offer.label} for Giles Corey in ${show.city} at ${show.venue}`}>
                  {offer.label} ↗
                </a>
              ) : (
                <span className="tour-date__status">{offer.label}</span>
              )}
            </li>
          );
        })}
      </ol>
    </section>
  );
}

Object.assign(window, { useEuropeSaleTime, EuropeSaleNote, EuropeTourDates });
