/* global React, ReactDOM,
   MONTHS_SUMMARY, getMonthDetail, monthShortLabel,
   DashHeader, SectionHead, MonthCard, Heatmap,
   ChannelDonut, CarClassBars, CountsPanel,
   formatYen */

const { useState, useRef, useEffect, useMemo } = React;

function App() {
  const months = MONTHS_SUMMARY.months;
  const monthKeys = months.map(m => m.month);

  // 達成率が一番低い月 (≒ 注目すべき月) を初期選択 … ではなく、最も売掛が積み上がっている7月を初期選択
  const [selectedMonth, setSelectedMonth] = useState(monthKeys[0]);

  const detailRef = useRef(null);

  const detail = useMemo(() => getMonthDetail(selectedMonth), [selectedMonth]);

  function handleSelect(m) {
    setSelectedMonth(m);
    // 詳細セクションへスクロール
    requestAnimationFrame(() => {
      if (detailRef.current) {
        const top = detailRef.current.getBoundingClientRect().top + window.scrollY - 16;
        window.scrollTo({ top, behavior: "smooth" });
      }
    });
  }

  const num = parseInt(selectedMonth.slice(5, 7), 10);
  const totalChannelAmount = detail.by_channel.reduce((a, b) => a + b.amount, 0);
  const totalCarClassAmount = detail.by_car_class.reduce((a, b) => a + b.amount, 0);

  return (
    <div className="app">
      <DashHeader generatedAt={MONTHS_SUMMARY.generated_at} />

      {/* Section A: Month cards */}
      <section className="section">
        <SectionHead
          num="A"
          title="月別 売掛サマリー"
          hint="クリックで詳細"
        />
        <div className="month-cards">
          {months.map(m => (
            <MonthCard
              key={m.month}
              data={m}
              selected={m.month === selectedMonth}
              onClick={() => handleSelect(m.month)}
            />
          ))}
        </div>
      </section>

      {/* Section B: OTA Heatmap */}
      <section className="section">
        <SectionHead
          num="B"
          title="月 × OTA ヒートマップ"
          hint="セルクリックで該当月を選択 · 濃いほど売掛が大きい"
        />
        <Heatmap
          months={monthKeys}
          selectedMonth={selectedMonth}
          onCellClick={handleSelect}
        />
      </section>

      {/* Section C: Month detail */}
      <section className="section" ref={detailRef}>
        <SectionHead
          num="C"
          title={`${num}月 内訳`}
          hint={`合計 ${formatYen(detail.summary.total_amount)} / 目標 ${formatYen(detail.summary.target_amount)}`}
        />

        <div className="detail">
          <div className="detail__panel">
            <div className="detail__panel-title">OTA 別構成</div>
            <ChannelDonut byChannel={detail.by_channel} total={totalChannelAmount} />
          </div>

          <div className="detail__panel">
            <div className="detail__panel-title">車種クラス別</div>
            <CarClassBars byCarClass={detail.by_car_class} total={totalCarClassAmount} />
          </div>

          <div className="detail__panel">
            <div className="detail__panel-title">件数 / 目標差分</div>
            <CountsPanel summary={detail.summary} />
          </div>
        </div>
      </section>

      <footer className="footer">
        <div className="footer__links">
          <a href="/api/sales/months">/api/sales/months</a>
          <a href="https://github.com/Jotamiura/miyakojima-ota">github.com/Jotamiura/miyakojima-ota</a>
        </div>
        <div className="footer__build">Phase 1 · GOGO model · build 2026.05.28</div>
      </footer>
    </div>
  );
}

// data.js (bootstrapPromise) が API からデータ取得を終えてからレンダリング
window.bootstrapPromise.then(() => {
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
});
