/* boatmap.jsx — クルー・シートマップ：艇を真上から見たSVGに実名簿（ROSTERS）が座る。
   整調(S)は金リング、コックス(C)は紺、バウ側に赤いバウボール。シートをタップすると氏名・カナ。
   リガー（オールの出る向き）はエントリーデータから分からないため「標準リグの図解」と明記する。 */
function BoatMap({ ev, roster }) {
  const [sel, setSel] = React.useState(null);
  if (!roster || !roster.length) return null;
  const isScull = ev.code.indexOf("×") >= 0;
  const hasCox = ev.code.indexOf("+") >= 0;
  const bySeat = {};
  roster.forEach((m) => { bySeat[m[0]] = m; });

  // 艇種ごとの想定シート（整調S=左/船尾側 → バウB=右/船首側）
  const rowers = ev.code.indexOf("8") >= 0 ? ["S", "7", "6", "5", "4", "3", "2", "B"]
    : ev.code.indexOf("4") >= 0 ? ["S", "3", "2", "B"]
    : ev.code.indexOf("2") >= 0 ? ["S", "B"]
    : ["S"];
  let seats = (hasCox ? ["C"] : []).concat(rowers);
  // 名簿が想定外のシートだけの場合（1名のみ登録の艇等）はデータ側を優先
  if (!seats.some((s) => bySeat[s])) seats = roster.map((m) => m[0]);

  const W = 460, CY = 56;
  const x0 = hasCox ? 52 : 64;
  const x1 = 412;
  const step = seats.length > 1 ? (x1 - x0) / (seats.length - 1) : 0;
  const seatName = (s) => s === "C" ? "コックス" : s === "S" ? "整調（ストローク）" : s === "B" ? "バウ" : s + "番";
  const selM = sel ? bySeat[sel] : null;

  return (
    <div className="boatmap">
      <svg viewBox={"0 0 " + W + " 112"} width="100%" aria-label="クルー配置図">
        {/* ハル（船体）：左=船尾、右=船首 */}
        <path d={"M14 " + CY + " C 70 " + (CY - 17) + ", 390 " + (CY - 17) + ", 446 " + CY +
                 " C 390 " + (CY + 17) + ", 70 " + (CY + 17) + ", 14 " + CY + " Z"}
              fill="var(--surface-2)" stroke="var(--line)" strokeWidth="1.5" />
        {/* バウボール（船首・右端） */}
        <circle cx="450" cy={CY} r="4.2" fill="var(--red)" />
        {/* シート・リガー・オール */}
        {seats.map((s, i) => {
          const x = x0 + i * step;
          const m = bySeat[s];
          const on = sel === s;
          const rowerIdx = rowers.indexOf(s);
          const side = rowerIdx >= 0 ? (rowerIdx % 2 === 0 ? -1 : 1) : 0;   // 標準リグ：交互
          return (
            <g key={s} onClick={() => m && setSel(on ? null : s)} style={{ cursor: m ? "pointer" : "default" }}>
              {s !== "C" && (isScull ? (
                <g stroke={m ? "var(--ph)" : "var(--mut)"} strokeWidth="2" opacity=".55" strokeLinecap="round">
                  <line x1={x} y1={CY - 16} x2={x - 7} y2={CY - 31} />
                  <line x1={x} y1={CY + 16} x2={x + 7} y2={CY + 31} />
                </g>
              ) : (
                <line x1={x} y1={CY + side * 16} x2={x - 8} y2={CY + side * 33}
                      stroke={m ? "var(--ph)" : "var(--mut)"} strokeWidth="2.4" opacity=".55" strokeLinecap="round" />
              ))}
              {m ? (
                <circle cx={x} cy={CY} r="14"
                        fill={s === "C" ? "var(--navy)" : on ? "var(--ph)" : "var(--surface)"}
                        stroke={s === "S" ? "var(--gold)" : on ? "var(--ph)" : "var(--line)"}
                        strokeWidth={s === "S" ? 2.6 : 1.5}
                        className={on ? "bm-on" : ""} />
              ) : (
                <circle cx={x} cy={CY} r="13" fill="none" stroke="var(--mut)" strokeWidth="1.3" strokeDasharray="3 4" opacity=".55" />
              )}
              <text x={x} y={CY + 4.5} textAnchor="middle"
                    fontFamily="var(--cond)" fontWeight="800" fontSize="12.5"
                    fill={s === "C" || on ? "#fff" : m ? "var(--ink)" : "var(--mut)"}>{s}</text>
              {s === "S" && m && <text x={x} y={CY - 22} textAnchor="middle" fontSize="9" fontWeight="700" fill="var(--gold)">整調</text>}
            </g>
          );
        })}
        {/* 進行方向 */}
        <g fontFamily="var(--cond)" fontSize="9" fontWeight="700" fill="var(--mut)">
          <text x="446" y="22" textAnchor="end">進行方向 →</text>
        </g>
      </svg>
      <div className="bm-card" aria-live="polite">
        {selM ? (
          <React.Fragment>
            <span className="bm-seat">{seatName(sel)}</span>
            <b className="bm-name"><RowerName name={selM[1]} kana={selM[2]} hideKana /></b>
            {selM[2] && <span className="bm-kana">{selM[2]}</span>}
          </React.Fragment>
        ) : (
          <span className="bm-hint">シートをタップすると選手名が出ます</span>
        )}
      </div>
      <div className="bm-note">※標準リグの図解です（実艇のリグ構成・舵手位置とは異なる場合があります）</div>
    </div>
  );
}
Object.assign(window, { BoatMap });
