/* =============================================================
   全国ページ — フィルタ / 検索 / ソート / 3つの表示モード
   ============================================================= */
const { useState, useMemo, useEffect } = React;

const YEARS = [
  { key: "y2023_range", label: "2023" },
  { key: "y2024_range", label: "2024" },
  { key: "y2025_range", label: "2025" }
];

/* セグメント型トグル */
function Segmented({ options, value, onChange, label }) {
  return (
    <div className="seg" role="radiogroup" aria-label={label}>
      {options.map(o => (
        <button key={o.value} type="button" role="radio" aria-checked={value === o.value}
          className={"seg-btn" + (value === o.value ? " is-on" : "")}
          onClick={() => onChange(o.value)}>
          {o.icon && <Icon name={o.icon} size={15} />}{o.label}
        </button>
      ))}
    </div>
  );
}

/* レンジ絞り込みチップ */
function RangeChips({ selected, onToggle }) {
  return (
    <div className="chips" role="group" aria-label="件数レンジで絞り込み">
      {window.RANGES.map(r => {
        const on = selected.includes(r);
        return (
          <button key={r} type="button" aria-pressed={on}
            className={"chip" + (on ? " is-on" : "")}
            onClick={() => onToggle(r)}>
            {on && <Icon name="check" size={13} />}{r}
          </button>
        );
      })}
    </div>
  );
}

/* ---- 1行＝1施設（テーブル行 / カード / レンジ重視） ---- */
function YearProgression({ row }) {
  return (
    <div className="yprog">
      {YEARS.map((y, i) => (
        <React.Fragment key={y.key}>
          <div className="yprog-item">
            <span className="yprog-label">{y.label}</span>
            <RangeBadge value={row[y.key]} />
          </div>
          {i < YEARS.length - 1 && <Icon name="chev" size={14} />}
        </React.Fragment>
      ))}
    </div>
  );
}

function FacilityCard({ row, prefHref }) {
  return (
    <article className="fcard">
      <div className="fcard-top">
        <div>
          <h3 className="fcard-name">{row.facility}</h3>
          {row.address && <p className="fcard-addr"><Icon name="pin" size={12} />{row.address}</p>}
          <div className="fcard-meta">
            <a className="pref-link" href={prefHref}><Icon name="pin" size={13} />{row.pref}</a>
            <TypeBadge value={row.type} />
          </div>
        </div>
        <HasTag value={row.has_surgery} />
      </div>
      <YearProgression row={row} />
      {row.note && <p className="fcard-note">{row.note}</p>}
      <a className="fcard-link" href={prefHref}>{row.pref}のページへ <Icon name="chev" size={14} /></a>
    </article>
  );
}

/* 地図セクションの表示切替（false で非表示） */
const SHOW_MAP = false;

function App() {
  const data = window.SURVEY_DATA;
  const prefsWithData = useMemo(() => {
    const s = new Set(data.map(d => d.pref_slug));
    return window.PREF_LIST.filter(p => s.has(p.slug));
  }, []);

  const [q, setQ] = useState("");
  const [pref, setPref] = useState("all");
  const [type, setType] = useState("all");
  const [hasOnly, setHasOnly] = useState(false);      // 有のみ
  const [rangeYear, setRangeYear] = useState("y2025_range");
  const [ranges, setRanges] = useState([]);           // 空＝すべて
  const [sort, setSort] = useState("name");           // name | range
  const [view, setView] = useState("table");          // table | card | trend

  const toggleRange = (r) =>
    setRanges(s => s.includes(r) ? s.filter(x => x !== r) : [...s, r]);

  const results = useMemo(() => {
    let rows = data.filter(d => {
      if (q && !d.facility.toLowerCase().includes(q.trim().toLowerCase())) return false;
      if (pref !== "all" && d.pref_slug !== pref) return false;
      if (type !== "all" && d.type !== type) return false;
      if (hasOnly && d.has_surgery !== "有") return false;
      if (ranges.length && !ranges.includes(d[rangeYear])) return false;
      return true;
    });
    if (sort === "name") {
      rows = [...rows].sort((a, b) => a.facility.localeCompare(b.facility, "ja"));
    } else {
      rows = [...rows].sort((a, b) => {
        const diff = (window.RANGE_ORDER[b.y2025_range] ?? -2) - (window.RANGE_ORDER[a.y2025_range] ?? -2);
        return diff !== 0 ? diff : a.facility.localeCompare(b.facility, "ja");
      });
    }
    return rows;
  }, [q, pref, type, hasOnly, ranges, rangeYear, sort]);

  const prefHref = (slug) => `都道府県別ページ.html?pref=${slug}`;
  const activeFilters = (pref !== "all") + (type !== "all") + (hasOnly ? 1 : 0) + (ranges.length ? 1 : 0) + (q ? 1 : 0);

  const resetAll = () => { setQ(""); setPref("all"); setType("all"); setHasOnly(false); setRanges([]); setSort("name"); };

  const pickFromMap = (slug) => {
    setPref(slug);
    const f = document.getElementById("finder");
    if (f) f.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <React.Fragment>
      <TopNote />
      <SiteHeader current="national" />
      <Crumbs items={[{ label: "ホーム", href: "index.html" }, { label: "斜視手術件数 全国調査（2023–2025）" }]} />

      {/* HERO */}
      <header className="hero hero-banner">
        <div className="wrap">
          <h1 className="sr-only">斜視手術件数 全国調査（2023–2025）｜回答施設を都道府県から探す</h1>
          <div className="hero-figure">
            <img src={(window.__resources && window.__resources.heroImg) || "hero.png"} width="1672" height="941"
              alt="斜視手術件数 全国調査（2023–2025）。日本地図と医療機関、眼鏡をかけた子どもと家族のイラスト。回答施設内集計。" />
          </div>
          <p className="lede">締切までに回答のあった医療機関を、都道府県・種別・実施有無・件数レンジで絞り込めます。<br className="ld-br" />優劣の比較を目的とするものではありません。</p>
          <div className="hero-actions">
            {SHOW_MAP && <a className="btn btn-primary" href="#map"><Icon name="pin" size={16} />地図から探す</a>}
            <a className={"btn " + (SHOW_MAP ? "btn-ghost" : "btn-primary")} href="#finder"><Icon name="search" size={16} />条件で絞り込む</a>
          </div>
        </div>
      </header>

      {/* MAP + FINDER */}
      <main id="main">
        {SHOW_MAP && <JapanMap onPick={pickFromMap} />}

        <section className="section" id="finder">
          <div className="wrap">
            <div className="section-head">
              <h2>回答施設をさがす</h2>
              <span className="sub">該当 <b>{results.length}</b> 件 / 全 {data.length} 件（回答施設）</span>
            </div>

            <form className="panel filterbar" onSubmit={e => e.preventDefault()} aria-label="絞り込み">
              {/* 検索 */}
              <div className="fb-search">
                <Icon name="search" size={18} />
                <input type="search" value={q} onChange={e => setQ(e.target.value)}
                  placeholder="施設名でフリーワード検索" aria-label="施設名でフリーワード検索" />
                {q && <button type="button" className="fb-clear" onClick={() => setQ("")} aria-label="検索をクリア"><Icon name="x" size={15} /></button>}
              </div>

              <div className="fb-grid">
                <label className="field">
                  <span className="field-label">都道府県</span>
                  <div className="select-wrap">
                    <select value={pref} onChange={e => setPref(e.target.value)}>
                      <option value="all">すべての都道府県</option>
                      {window.PREF_LIST.map(p => {
                        const has = prefsWithData.some(x => x.slug === p.slug);
                        return <option key={p.slug} value={p.slug} disabled={!has}>{p.pref}{has ? "" : "（回答なし）"}</option>;
                      })}
                    </select>
                    <Icon name="chev" size={16} />
                  </div>
                </label>

                <label className="field">
                  <span className="field-label">種別</span>
                  <div className="select-wrap">
                    <select value={type} onChange={e => setType(e.target.value)}>
                      <option value="all">病院・クリニック</option>
                      <option value="病院">病院</option>
                      <option value="クリニック">クリニック</option>
                    </select>
                    <Icon name="chev" size={16} />
                  </div>
                </label>

                <fieldset className="field field-toggle">
                  <legend className="field-label">実施有無</legend>
                  <Segmented label="実施有無" value={hasOnly ? "only" : "both"}
                    onChange={v => setHasOnly(v === "only")}
                    options={[{ value: "both", label: "有無両方" }, { value: "only", label: "実施有のみ" }]} />
                </fieldset>
              </div>

              {/* レンジ絞り込み */}
              <div className="fb-range">
                <div className="fb-range-head">
                  <span className="field-label">件数レンジで絞り込み</span>
                  <div className="fb-range-year">
                    <span className="muted-label">対象年</span>
                    <Segmented label="対象年" value={rangeYear} onChange={setRangeYear}
                      options={YEARS.map(y => ({ value: y.key, label: y.label }))} />
                  </div>
                </div>
                <RangeChips selected={ranges} onToggle={toggleRange} />
              </div>

              {/* ツールバー：ソート・表示・リセット */}
              <div className="fb-toolbar">
                <div className="fb-tool">
                  <span className="muted-label">並び替え</span>
                  <Segmented label="並び替え" value={sort} onChange={setSort}
                    options={[{ value: "name", label: "施設名順" }, { value: "range", label: "2025レンジ順" }]} />
                </div>
                <div className="fb-tool">
                  <span className="muted-label">表示</span>
                  <Segmented label="表示モード" value={view} onChange={setView}
                    options={[
                      { value: "table", label: "テーブル", icon: "rows" },
                      { value: "card", label: "カード", icon: "grid" },
                      { value: "trend", label: "レンジ重視", icon: "trend" }
                    ]} />
                </div>
                {activeFilters > 0 &&
                  <button type="button" className="btn btn-ghost btn-sm fb-reset" onClick={resetAll}>
                    <Icon name="x" size={14} />絞り込みをリセット（{activeFilters}）
                  </button>}
              </div>
            </form>

            {sort === "range" &&
              <p className="sort-note"><Icon name="info" size={14} />「2025レンジ順」は便宜的な区分の並びです（500件以上＞300–499＞150–299＞60–149＞30–59＞10–29＞0–9＞未回答）。ランキングや優劣を示すものではありません。</p>}

            {/* 結果 */}
            {results.length === 0 ? (
              <div className="empty panel panel-pad">
                <Icon name="search" size={26} />
                <p>条件に一致する回答施設が見つかりませんでした。</p>
                <button className="btn btn-ghost btn-sm" onClick={resetAll}>絞り込みをリセット</button>
              </div>
            ) : view === "table" ? (
              <div className="table-wrap panel">
                <table className="rtable">
                  <thead>
                    <tr>
                      <th scope="col">都道府県</th><th scope="col">施設名</th><th scope="col">種別</th>
                      <th scope="col">実施有無</th><th scope="col">2023</th><th scope="col">2024</th><th scope="col">2025</th>
                      <th scope="col"><span className="sr-only">リンク</span></th>
                    </tr>
                  </thead>
                  <tbody>
                    {results.map((r, i) => (
                      <tr key={i}>
                        <td><a className="pref-link" href={prefHref(r.pref_slug)}>{r.pref}</a></td>
                        <td className="cell-name">
                          <span>{r.facility}</span>
                          {r.address && <span className="cell-addr">{r.address}</span>}
                          {r.note && <span className="cell-note">{r.note}</span>}
                        </td>
                        <td><TypeBadge value={r.type} /></td>
                        <td><HasTag value={r.has_surgery} /></td>
                        <td><RangeBadge value={r.y2023_range} /></td>
                        <td><RangeBadge value={r.y2024_range} /></td>
                        <td><RangeBadge value={r.y2025_range} /></td>
                        <td className="cell-go"><a href={prefHref(r.pref_slug)} aria-label={`${r.pref}のページへ`}><Icon name="chev" size={16} /></a></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : view === "card" ? (
              <div className="card-grid">
                {results.map((r, i) => <FacilityCard key={i} row={r} prefHref={prefHref(r.pref_slug)} />)}
              </div>
            ) : (
              <div className="trend-list panel">
                {results.map((r, i) => (
                  <div className="trend-row" key={i}>
                    <div className="trend-id">
                      <a className="trend-name" href={prefHref(r.pref_slug)}>{r.facility}</a>
                      {r.address && <p className="trend-addr"><Icon name="pin" size={12} />{r.address}</p>}
                      <div className="trend-sub">
                        <a className="pref-link" href={prefHref(r.pref_slug)}><Icon name="pin" size={12} />{r.pref}</a>
                        <TypeBadge value={r.type} /><HasTag value={r.has_surgery} />
                      </div>
                    </div>
                    <YearProgression row={r} />
                  </div>
                ))}
              </div>
            )}

            {/* 都道府県ショートカット */}
            <div className="pref-shortcuts">
              <span className="muted-label">回答のある都道府県：</span>
              <div className="pref-chip-row">
                {prefsWithData.map(p => (
                  <a key={p.slug} className="pref-chip" href={prefHref(p.slug)}>
                    {p.pref}<span className="pref-chip-n">{data.filter(d => d.pref_slug === p.slug).length}</span>
                  </a>
                ))}
              </div>
            </div>
          </div>
        </section>

        <SurveyOverview />

        <AboutSurvey />

        <ExpertComments />

        <section className="section">
          <div className="wrap">
            <div className="reference-grid">
              <DpcBox />
              <EvidenceLinks />
            </div>
          </div>
        </section>
      </main>

      <FooterNotes />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
