/* hero.jsx — ヒーロー（夜明けの水面＋6艇のアニメ）と LiveStrip
   大会名・会場・日程はすべて data.js の META から組み立てる。
   大会を差し替えても、このファイルを直さずに文言が追従する。 */
function Hero({ counts }) {
  const RW = window.RW;
  const M = window.KANSAI.META;
  // のべ人数＝Σ(クルー数 × その艇に乗る人数・舵手込み)。
  // 1人が2種目に出ることがあるので、実際の人数より多くなる＝「のべ」と書く。
  // この大会はクルー種目の名簿を扱わないので、艇種ごとの人数(RW.seatsOf)だけで数える。
  const heads = RW.EVENTS.reduce((n, ev) => n + ev.entries.length * RW.seatsOf(ev), 0);
  // 出場した都道府県の数（PREF＝学校名→都道府県）
  const prefCount = new Set(Object.values(window.KANSAI.PREF || {})).size;
  // 「第37回」→「37th」
  const no = String(M.edition || "").replace(/[^0-9]/g, "");
  const ordSuffix = (n) => (n % 100 >= 11 && n % 100 <= 13) ? "th" : (["th", "st", "nd", "rd"][n % 10] || "th");
  const enTitle = ((no ? no + ordSuffix(Number(no)) + " " : "") + (M.titleEn || "")).trim();
  // 会場「浜松市天竜ボート場（静岡・浜松市天竜区）」＝ venue ＋ venueSub の括弧の中身
  const venueArea = (String(M.venueSub || "").match(/[（(]([^）)]*)[）)]/) || [])[1] || "";
  const venueLine = M.venue + (venueArea ? "（" + venueArea + "）" : "");
  // 日程「3月20日(金) – 22日(日)」（月をまたぐときは終わりの日にも月を付ける）
  const mo = (d) => String(d.date).split("/")[0];
  const da = (d) => String(d.date).split("/")[1];
  const jpDay = (d, withMonth) => (withMonth ? mo(d) + "月" : "") + da(d) + "日(" + d.dow + ")";
  const d0 = M.days[0], dz = M.days[M.days.length - 1];
  const dateLine = M.days.length > 1 ? jpDay(d0, true) + " – " + jpDay(dz, mo(dz) !== mo(d0)) : jpDay(d0, true);
  // 併催大会はこの大会には無い（cohosts は空配列）。他大会に使い回したときだけ出る。
  const cohosts = M.cohosts || [];
  return (
    <header className="hero">
<div className="h-bg" aria-hidden="true" />
      <span className="h-stars" aria-hidden="true" />
      <span className="h-shore" aria-hidden="true" />
      <span className="h-grain" aria-hidden="true" />
      <image-slot id="kansai-hero" class="h-slot" fit="cover"></image-slot>
      <span className="h-scrim" aria-hidden="true" />
      <span className="h-glow" aria-hidden="true" />
      <span className="h-lanes" aria-hidden="true" />
      <p className="h-tagline" aria-hidden="true">EVERY<br />STROKE<br />COUNTS.</p>
      {/* 水面アニメ：波＋6クルーが左→右に競漕（タイトルの下の水面ゾーンに配置） */}
      <div className="h-water" aria-hidden="true">
        <svg className="hw-wave back" viewBox="0 0 800 40" preserveAspectRatio="none">
          <path d="M0 22 Q100 10 200 22 T400 22 T600 22 T800 22 V40 H0 Z" />
        </svg>
        <div className="hw-race">
          {[
            { y: 1, w: 62, o: 0.28, d: 41, delay: -19 },
            { y: 12, w: 71, o: 0.36, d: 42.5, delay: -21 },
            { y: 23, w: 80, o: 0.45, d: 40, delay: -18.5 },
            { y: 33, w: 89, o: 0.54, d: 43, delay: -20 },
            { y: 44, w: 99, o: 0.63, d: 41.5, delay: -19.5 },
            { y: 55, w: 110, o: 0.72, d: 42, delay: -20.5 },
          ].map((b, i) => (
            <div className="hw-lane" key={i} style={{ "--y": b.y + "px", "--d": b.d + "s", "--delay": b.delay + "s" }}>
              <svg className="hw-boat" viewBox="0 0 120 18" style={{ width: b.w + "px", color: "rgba(255,255,255," + b.o + ")" }}>
                <g stroke="currentColor" strokeWidth="1.1" strokeLinecap="round">
                  <line x1="38" y1="9" x2="32" y2="3" /><line x1="54" y1="9" x2="60" y2="15" />
                  <line x1="70" y1="9" x2="64" y2="3" /><line x1="86" y1="9" x2="92" y2="15" />
                </g>
                <path d="M8 9 C30 6.5 92 6.5 114 8.4 C115 8.7 115 9.3 114 9.6 C92 11.5 30 11.5 8 9 Z" fill="currentColor" />
              </svg>
            </div>
          ))}
        </div>
        <svg className="hw-wave front" viewBox="0 0 800 40" preserveAspectRatio="none">
          <path d="M0 24 Q100 12 200 24 T400 24 T600 24 T800 24 V40 H0 Z" />
        </svg>
      </div>
      <div className="inner">
        <h1>
          <span className="en">{enTitle}</span>
          {M.title} <span className="yr">{M.year}</span>
        </h1>
        <div className="h-meta">
          <span className="h-line"><IconPin size={14} />{venueLine}</span>
          <span className="h-line"><IconCal size={14} />{dateLine}</span>
          {cohosts.length > 0 && (
            <span className="h-cohost"><i>併催</i>{cohosts.join("／")}</span>
          )}
        </div>
        <div className="h-stats">
          {[[counts.events, "種目"], [counts.entries, "クルー"], [heads.toLocaleString(), "のべ人数"], [counts.teams, "校"], [RW.DAYS.length, "日間"]].map(([n, l]) => (
            <div className="h-stat" key={l}>
              <span className="tick" /><b>{n}</b><span>{l}</span>
            </div>
          ))}
        </div>
        <p className="h-statnote">各都道府県の予選を勝ち抜いた{counts.teams}校（{prefCount}都道府県）が出場</p>
      </div>
      <a className="h-credit" href="https://www.instagram.com/hiroshi.rowing/" target="_blank" rel="noopener noreferrer">created by 中野紘志</a>
    </header>
  );
}

function LiveStrip({ ord, phase, onOpen, onOpenRace, onOpenResults }) {
  const { live, next } = window.RW.liveAndNext(ord);
  const cur = live[0], up = next[0];
  if (phase === "during" && cur) {
    return (
      <div className="livestrip" onClick={onOpenRace ? () => onOpenRace(cur.id) : onOpen}>
        <span className="lanes" />
        <div className="ls-in">
          <span className="dotlive" /><span className="ls-lbl">Live</span>
          <div className="ls-text">
            {/* 部門は1つだけなので、部門名の代わりに日付を出す */}
            <div className="t1">進行中 · {cur.date}({cur.dow}) {cur.t}</div>
            <div className="t2">{cur.ev.code}　{cur.ev.name}　<span style={{ opacity: .7 }}>{cur.round}{cur.grp ? " " + cur.grp : ""}</span></div>
          </div>
          <span className="ls-go">見る ›</span>
        </div>
      </div>
    );
  }
  const firstLabel = phase === "before" ? "最初のレース" : "次のレース";
  const afterClick = onOpenResults || onOpen;
  return (
    <div className="livestrip idle" onClick={phase === "after" ? afterClick : (up && onOpenRace ? () => onOpenRace(up.id) : onOpen)}>
      <div className="ls-in">
        <span className="dotlive" />
        <span className="ls-lbl" style={{ letterSpacing: ".1em" }}>{phase === "after" ? "RESULT" : "NEXT"}</span>
        <div className="ls-text">
          <div className="t1">{phase === "after" ? "大会終了 · リザルト確定" : up ? `${firstLabel} · ${up.date}(${up.dow}) ${up.t}` : "本日は終了しました"}</div>
          <div className="t2">{phase === "after" ? "メダル・順位を見る" : up ? `${up.ev.code}　${up.ev.name}` : "—"}</div>
        </div>
        <span className="ls-go" style={{ color: "var(--ph-ink)" }}>{phase === "after" ? "結果 ›" : up ? "見る ›" : "日程 ›"}</span>
      </div>
    </div>
  );
}

Object.assign(window, { Hero, LiveStrip });
