/* =============================================================
   日本タイル型グリッド地図
   - 都道府県を地理的配置の四角タイルで表示
   - 回答施設がある県をティールで塗り、回答施設数バッジを添える
   - クリックで右（スマホは下）パネルに回答施設一覧（施設名順）
   - ランキング表示はしない（色の濃淡で件数を表さない）
   ============================================================= */

/* 11列 × 12行のグリッド。"" は空セル。 */
const JP_GRID = [
  ["", "", "", "", "", "", "", "", "", "", "hokkaido"],
  ["", "", "", "", "", "", "", "", "", "aomori", ""],
  ["", "", "", "", "", "", "", "", "akita", "iwate", ""],
  ["", "", "", "", "", "", "", "", "yamagata", "miyagi", ""],
  ["", "", "", "", "", "", "", "niigata", "fukushima", "", ""],
  ["", "", "", "", "", "ishikawa", "toyama", "nagano", "gunma", "tochigi", "ibaraki"],
  ["", "", "", "shimane", "tottori", "fukui", "gifu", "yamanashi", "saitama", "tokyo", "chiba"],
  ["", "", "yamaguchi", "hiroshima", "okayama", "hyogo", "kyoto", "shiga", "aichi", "shizuoka", "kanagawa"],
  ["", "fukuoka", "oita", "ehime", "kagawa", "osaka", "nara", "mie", "", "", ""],
  ["", "saga", "kumamoto", "miyazaki", "kochi", "tokushima", "wakayama", "", "", "", ""],
  ["nagasaki", "", "kagoshima", "", "", "", "", "", "", "", ""],
  ["okinawa", "", "", "", "", "", "", "", "", "", ""]
];

function abbrevPref(name) {
  // 末尾の 都/府/県 を外す（北海道はそのまま）
  return name.replace(/[都府県]$/, "");
}

function MapPanel({ slug, prefName, rows, onPick }) {
  if (!slug) {
    return (
      <div className="map-panel map-panel-empty">
        <Icon name="pin" size={30} />
        <p className="mp-empty-title">都道府県を選んでください</p>
        <p className="mp-empty-sub">地図でティール色の県をクリックすると、その県の回答施設（施設名順）が表示されます。</p>
      </div>
    );
  }
  if (rows.length === 0) {
    return (
      <div className="map-panel map-panel-empty">
        <Icon name="info" size={30} />
        <p className="mp-empty-title">{prefName}</p>
        <p className="mp-empty-sub">現時点で掲載できる回答施設がありません。</p>
      </div>
    );
  }
  const nH = rows.filter(r => r.type === "病院").length;
  const nC = rows.filter(r => r.type === "クリニック").length;
  const href = `都道府県別ページ.html?pref=${slug}`;
  return (
    <div className="map-panel">
      <div className="mp-head">
        <div>
          <span className="mp-eyebrow"><Icon name="pin" size={13} />{prefName}</span>
          <h3 className="mp-title">回答施設一覧</h3>
        </div>
        <span className="mp-count">{rows.length}<small>施設</small></span>
      </div>
      <p className="mp-summary">病院 {nH} ・ クリニック {nC}（施設名順で表示）</p>
      <ul className="mp-list">
        {rows.map((r, i) => (
          <li key={i} className="mp-item">
            <div className="mp-item-top">
              <span className="mp-name">{r.facility}</span>
              <HasTag value={r.has_surgery} />
            </div>
            {r.address && <p className="mp-addr">{r.address}</p>}
            <div className="mp-item-tags">
              <TypeBadge value={r.type} />
              <span className="mp-years">
                <span className="mp-y"><i>23</i><RangeBadge value={r.y2023_range} /></span>
                <span className="mp-y"><i>24</i><RangeBadge value={r.y2024_range} /></span>
                <span className="mp-y"><i>25</i><RangeBadge value={r.y2025_range} /></span>
              </span>
            </div>
            {r.note && <p className="mp-note">{r.note}</p>}
          </li>
        ))}
      </ul>
      <div className="mp-actions">
        <a className="btn btn-primary btn-sm" href={href}><Icon name="chev" size={15} />{prefName}のページへ</a>
        {onPick && <button type="button" className="btn btn-ghost btn-sm" onClick={() => onPick(slug)}><Icon name="search" size={14} />一覧でこの県だけ表示</button>}
      </div>
    </div>
  );
}

function JapanMap({ onPick }) {
  const data = window.SURVEY_DATA;
  const countBySlug = React.useMemo(() => {
    const m = {};
    data.forEach(d => { m[d.pref_slug] = (m[d.pref_slug] || 0) + 1; });
    return m;
  }, []);
  const nameBySlug = React.useMemo(() => {
    const m = {};
    window.PREF_LIST.forEach(p => { m[p.slug] = p.pref; });
    return m;
  }, []);

  const withData = window.PREF_LIST.filter(p => countBySlug[p.slug]).length;
  const [sel, setSel] = React.useState(null);

  const selRows = React.useMemo(
    () => sel ? data.filter(d => d.pref_slug === sel).sort((a, b) => a.facility.localeCompare(b.facility, "ja")) : [],
    [sel]
  );

  return (
    <section className="section map-section" id="map" aria-labelledby="map-h">
      <div className="wrap">
        <div className="section-head">
          <h2 id="map-h">地図から探す</h2>
          <span className="sub">回答施設のある <b>{withData}</b> 都道府県（数字は回答施設数）</span>
        </div>

        <div className="map-layout">
          {/* 地図 */}
          <div className="map-board-wrap">
            <div className="map-board" role="group" aria-label="都道府県タイル地図">
              {JP_GRID.flat().map((slug, idx) => {
                if (!slug) return <span key={idx} className="tile tile-empty" aria-hidden="true"></span>;
                const n = countBySlug[slug] || 0;
                const has = n > 0;
                const name = nameBySlug[slug] || slug;
                const active = sel === slug;
                if (!has) {
                  return (
                    <span key={idx} className="tile tile-nodata" title={`${name}（回答なし）`}>
                      {abbrevPref(name)}
                    </span>
                  );
                }
                return (
                  <button key={idx} type="button"
                    className={"tile tile-data" + (active ? " is-active" : "")}
                    aria-pressed={active}
                    aria-label={`${name}：回答施設 ${n} 件`}
                    onClick={() => setSel(active ? null : slug)}>
                    <span className="tile-name">{abbrevPref(name)}</span>
                    <span className="tile-n">{n}</span>
                  </button>
                );
              })}
            </div>
            <div className="map-legend">
              <span className="lg-item"><span className="lg-sw lg-data"></span>回答施設あり</span>
              <span className="lg-item"><span className="lg-sw lg-nodata"></span>回答なし</span>
              <span className="lg-note">※ 色は件数の多寡やランキングを表すものではありません。</span>
            </div>
          </div>

          {/* パネル */}
          <MapPanel slug={sel} prefName={sel ? nameBySlug[sel] : ""} rows={selRows} onPick={onPick} />
        </div>
      </div>
    </section>
  );
}
