/* PostHomeView — 大会終了後のホーム画面（総括ビュー）
 * ビルド無し React18 + babel standalone。window.RW / window.KANSAI を同期的に読む。
 * props: { onOpenEvent(evKey), goTab(tabId) }
 * goTab に渡すタブID（親側の実IDに合わせて書き換えやすいよう定数化）
 */
const PH2_TABS = {
  entry: "entry",      // エントリー（種目別）
  schedule: "schedule", // 日程（時系列）
  taikai: "results",     // 大会（チーム別・記録詳細）
};

const PH2_DIV_LABEL = {
  intercollege: "インカレ",
  oxford: "オックスフォード盾",
  japanopen: "ジャパンオープン",
};

function PostHomeView({ onOpenEvent, goTab }) {
  const open = onOpenEvent || function () {};
  const jump = goTab || function () {};

  const data = React.useMemo(function () {
    const RW = window.RW || {};
    const KAN = window.KANSAI || {};
    const events = RW.EVENTS || [];
    const getRaces = typeof RW.realRaces === "function" ? RW.realRaces : function () { return []; };
    const isMinor = typeof RW.isMinorTeam === "function" ? RW.isMinorTeam : function () { return false; };

    let totalRaces = 0;
    const champs = [];
    const nameByEv = {}; // key/code → 種目名（新記録欄の表示用）

    events.forEach(function (ev) {
      nameByEv[ev.key] = ev.name;
      nameByEv[ev.code] = ev.name;

      const races = getRaces(ev.key) || [];
      totalRaces += races.length;

      const finalA = races.find(function (r) { return r.round === "A決勝"; });
      let winner = null;
      if (finalA && finalA.lanes) {
        winner = finalA.lanes.find(function (l) { return l.rank === 1; }) || null;
      }

      champs.push({
        evKey: ev.key,
        evName: ev.name,
        cat: ev.cat,
        div: ev.div,
        team: winner ? winner.team : null,
        person: winner && winner.name && !isMinor(winner.team) ? winner.name : null,
        time: winner ? winner.t2000 : null,
      });
    });

    const recsAll = (KAN.NEWREC && KAN.NEWREC.items) || [];   // NEWREC = {items:[...]} 形式
    const recs = recsAll
      .slice()
      .sort(function (a, b) { return (Number(b.gain) || 0) - (Number(a.gain) || 0); })
      .slice(0, 5);

    return {
      totalRaces: totalRaces,
      eventCount: events.length,
      champs: champs,
      recs: recs,
      recCount: recsAll.length,
      nameByEv: nameByEv,
    };
  }, []);

  function recEvName(ev) {
    return data.nameByEv[ev] || ev;
  }

  function fmtGain(gain) {
    const g = Number(gain);
    if (!isFinite(g) || g <= 0) return null;
    return g.toFixed(2) + "秒更新";
  }

  return (
    <div className="ph2-root">

      {/* 1) 大会総括ヘッダ */}
      <header className="ph2-hero">
        <p className="ph2-hero-eyebrow">全日程終了</p>
        <h2 className="ph2-hero-title">大会はすべて終わりました</h2>
        <div className="ph2-hero-facts">
          <div className="ph2-fact">
            <span className="ph2-fact-num">5</span>
            <span className="ph2-fact-label">日間</span>
          </div>
          <div className="ph2-fact">
            <span className="ph2-fact-num">{data.eventCount}</span>
            <span className="ph2-fact-label">種目</span>
          </div>
          <div className="ph2-fact">
            <span className="ph2-fact-num">{data.totalRaces}</span>
            <span className="ph2-fact-label">レース</span>
          </div>
        </div>
        <p className="ph2-hero-note">結果はこのページの下と、各タブからいつでも見られます。</p>
      </header>

      {/* 2) 種目別チャンピオン一覧 */}
      <section className="ph2-sec">
        <div className="ph2-sec-head">
          <h3 className="ph2-sec-title">種目別チャンピオン</h3>
          <p className="ph2-sec-sub">A決勝1位のクルー。カードを押すと種目の全結果へ。</p>
        </div>
        <div className="ph2-champ-row" role="list">
          {data.champs.map(function (c) {
            return (
              <button
                key={c.evKey}
                type="button"
                role="listitem"
                className="ph2-champ"
                data-cat={c.cat}
                onClick={function () { open(c.evKey); }}
              >
                <span className="ph2-champ-medal" aria-hidden="true">金</span>
                <span className="ph2-champ-ev">{c.evName}</span>
                <span className="ph2-champ-div">{PH2_DIV_LABEL[c.div] || ""}</span>
                {c.team ? (
                  <React.Fragment>
                    <span className="ph2-champ-main">{c.person || c.team}</span>
                    {c.person ? <span className="ph2-champ-team">{c.team}</span> : null}
                    {c.time ? <span className="ph2-champ-time">{c.time}</span> : null}
                  </React.Fragment>
                ) : (
                  <span className="ph2-champ-main ph2-champ-pending">結果集計中</span>
                )}
              </button>
            );
          })}
        </div>
      </section>

      {/* 3) 今大会の新記録ダイジェスト */}
      <section className="ph2-sec">
        <div className="ph2-sec-head">
          <h3 className="ph2-sec-title">今大会の新記録</h3>
          <p className="ph2-sec-sub">大学記録を塗り替えたレースが{data.recCount}件ありました。上位5件を紹介します。</p>
        </div>
        <ol className="ph2-rec-list">
          {data.recs.map(function (r, i) {
            const gainText = fmtGain(r.gain);
            return (
              <li key={r.ev + "-" + r.team + "-" + i} className="ph2-rec">
                <span className="ph2-rec-rank">{i + 1}</span>
                <span className="ph2-rec-body">
                  <span className="ph2-rec-line1">
                    <span className="ph2-rec-ev">{recEvName(r.ev)}</span>
                    <span className="ph2-rec-team">{r.team}</span>
                  </span>
                  <span className="ph2-rec-line2">
                    <span className="ph2-rec-time">{r.t}</span>
                    <span className="ph2-rec-old">これまでの記録 {r.old}（{r.oldY}年）</span>
                  </span>
                </span>
                {gainText ? <span className="ph2-rec-gain">{gainText}</span> : null}
              </li>
            );
          })}
        </ol>
        <button
          type="button"
          className="ph2-rec-more"
          onClick={function () { jump(PH2_TABS.taikai); }}
        >
          新記録{data.recCount}件をすべて見る（大会タブへ）
        </button>
      </section>

      {/* 4) タブ案内 */}
      <section className="ph2-sec">
        <div className="ph2-sec-head">
          <h3 className="ph2-sec-title">この結果の見方</h3>
        </div>
        <div className="ph2-guide">
          <button type="button" className="ph2-guide-row" onClick={function () { jump(PH2_TABS.entry); }}>
            <span className="ph2-guide-key">種目から見る</span>
            <span className="ph2-guide-desc">種目ごとの出場クルーと全レース結果</span>
            <span className="ph2-guide-tab">エントリー</span>
          </button>
          <button type="button" className="ph2-guide-row" onClick={function () { jump(PH2_TABS.schedule); }}>
            <span className="ph2-guide-key">時系列で見る</span>
            <span className="ph2-guide-desc">5日間のレースを日付順にたどる</span>
            <span className="ph2-guide-tab">日程</span>
          </button>
          <button type="button" className="ph2-guide-row" onClick={function () { jump(PH2_TABS.taikai); }}>
            <span className="ph2-guide-key">チーム別に見る</span>
            <span className="ph2-guide-desc">大学ごとの成績と新記録の一覧</span>
            <span className="ph2-guide-tab">大会</span>
          </button>
        </div>
      </section>

    </div>
  );
}

Object.assign(window, { PostHomeView });
