const { useMemo: useSportsMemo, useState: useSportsState } = React;

const SPORTS_DATA = window.KOMITET_SPORTS;
const SPORTS_BARS = window.WC.bars;

function sportsDate(value) {
  return new Date(value + "T12:00:00");
}

function eventStart(event) {
  return new Date(event.date + "T" + event.time + ":00+03:00");
}

function monthTitle(date) {
  return new Intl.DateTimeFormat("ru-RU", { day: "numeric", month: "long" }).format(sportsDate(date));
}

function dayTitle(date) {
  return new Intl.DateTimeFormat("ru-RU", { weekday: "long", day: "numeric", month: "long" }).format(sportsDate(date));
}

function SportsIcon({ sport }) {
  if (sport === "football") {
    return <img className="sport-icon sport-icon-football" src="assets/football-ball.jpg?v=20260721" alt="" aria-hidden="true" />;
  }
  if (sport === "hockey") {
    return <svg className="sport-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 5h3l3 10 4 1.5M12 15l-2.6 3H5M18 18a2.3 2.3 0 1 0 0-4.6A2.3 2.3 0 0 0 18 18z" /></svg>;
  }
  if (sport === "tennis") {
    return <svg className="sport-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9" /><path d="M7 5.1c3.3 2.1 3.3 11.7 0 13.8M17 5.1c-3.3 2.1-3.3 11.7 0 13.8" /></svg>;
  }
  return <span className="sport-glyph sport-glyph-f1" aria-hidden="true">F1</span>;
}

function eventPubIds(event) {
  const byRule = SPORTS_DATA.pubRules
    .filter((rule) => rule.sport === event.sport && (!rule.tournament || rule.tournament === event.tournament))
    .flatMap((rule) => rule.pubIds);
  return [...new Set([...event.pubIds, ...byRule])];
}

function pubName(id) {
  const bar = SPORTS_BARS.find((item) => item.id === id);
  if (!bar) return "";
  if (id === "brussels_msk") return "Брюссель МСК";
  if (id === "brussels_spb") return "Брюссель СПБ";
  return bar.name;
}

function pubLabel(pubIds) {
  if (pubIds.length === SPORTS_BARS.length) return "Все пабы";
  return pubIds.map(pubName).filter(Boolean).join(" · ");
}

function EventRow({ event, sport, onOpenBars }) {
  const pubIds = eventPubIds(event);
  return (
    <article className="sport-event">
      <SportsIcon sport={event.sport} />
      <div className="sport-event-main">
        <div className="sport-event-label" style={{ color: sport.color }}>{sport.label} <span>· {event.tournament}</span></div>
        <div className="sport-event-time">{event.time}</div>
        <div className="sport-event-title">{event.title}</div>
        <div className="sport-event-pubs">{pubLabel(pubIds)}</div>
      </div>
      <button className="event-pubs" onClick={() => onOpenBars(pubIds)}>Пабы</button>
    </article>
  );
}

function DaySchedule({ date, events, sports, onOpenBars, label }) {
  return (
    <section className="day-schedule" aria-label={label}>
      <div className="day-heading">
        <span>{label}</span>
        <strong>{date ? dayTitle(date) : ""}</strong>
      </div>
      {events.length > 0 ? (
        <div className="sport-events">
          {events.map((event) => <EventRow key={event.id} event={event} sport={sports[event.sport]} onOpenBars={onOpenBars} />)}
        </div>
      ) : (
        <div className="schedule-empty">Трансляций пока нет</div>
      )}
    </section>
  );
}

function SportLanding() {
  const [selectedSport, setSelectedSport] = useSportsState("all");
  const [showBars, setShowBars] = useSportsState(false);
  const [selectedBarIds, setSelectedBarIds] = useSportsState(null);

  function openBars(pubIds) {
    setSelectedBarIds(pubIds || null);
    setShowBars(true);
  }

  const now = new Date();
  const nextDate = SPORTS_DATA.events
    .filter((event) => eventStart(event) >= now)
    .sort((a, b) => a.date.localeCompare(b.date) || a.time.localeCompare(b.time, "ru"))[0]?.date;
  const activeEvents = SPORTS_DATA.events
    .filter((event) => event.date === nextDate && eventStart(event) >= now)
    .sort((a, b) => a.time.localeCompare(b.time, "ru"));
  const monthEvents = SPORTS_DATA.events
    .filter((event) => eventStart(event) >= now)
    .filter((event) => selectedSport === "all" || event.sport === selectedSport)
    .sort((a, b) => a.date.localeCompare(b.date) || a.time.localeCompare(b.time, "ru"));
  const sports = Object.fromEntries(SPORTS_DATA.sports.map((sport) => [sport.id, sport]));

  return (
    <main className="sports-page">
      <header className="sports-topbar">
        <a className="sports-back" href="https://komitet.group" aria-label="Вернуться на сайт Комитет">
          <Icon name="back" size={20} stroke={2.1} />
        </a>
        <a className="sports-wordmark" href="https://komitet.group">КОМИТЕТ</a>
        <button className="sports-pubs-top" onClick={() => openBars()}>Пабы</button>
      </header>

      <section className="sports-intro">
        <h1>Спорт в пабах</h1>
        <p>Избранные трансляции на больших экранах</p>
      </section>

      <DaySchedule
        date={nextDate}
        events={activeEvents}
        sports={sports}
        onOpenBars={openBars}
        label="Ближайшие трансляции"
      />

      <section className="month-schedule">
        <div className="month-heading">
          <span>Расписание месяца</span>
          <h2>Все трансляции</h2>
        </div>
        <div className="sport-tabs" role="tablist" aria-label="Виды спорта">
          <button className={selectedSport === "all" ? "is-active" : ""} onClick={() => setSelectedSport("all")}>Все</button>
          {SPORTS_DATA.sports.map((sport) => (
            <button key={sport.id} className={selectedSport === sport.id ? "is-active" : ""} onClick={() => setSelectedSport(sport.id)}>{sport.label}</button>
          ))}
        </div>
        <div className="month-events">
          {monthEvents.length ? monthEvents.map((event) => (
            <div className="month-event" key={event.id}>
              <div className="month-event-date">{monthTitle(event.date)}</div>
              <div className="month-event-copy">
                <span style={{ color: sports[event.sport].color }}>{event.tournament}</span>
                <strong>{event.title}</strong>
              </div>
              <button onClick={() => openBars(eventPubIds(event))} aria-label={'Пабы: ' + event.title}><Icon name="pin" size={17} stroke={2} /></button>
            </div>
          )) : <div className="month-empty">В этом разделе трансляции появятся после подтверждения.</div>}
        </div>
      </section>

      <section className="sports-pubs-cta">
        <div>
          <span>Где смотреть</span>
          <strong>Санкт-Петербург и Москва</strong>
        </div>
        <button onClick={() => openBars()}>Пабы и бронирование <Icon name="arrow" size={18} stroke={2} /></button>
      </section>

      <footer className="sports-footer">Расписание обновляется после подтверждения трансляций. Время московское.</footer>
      {showBars && <BarsModal pubIds={selectedBarIds} onClose={() => setShowBars(false)} />}
    </main>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<SportLanding />);
