// listpage.jsx — 商品一覧ページ
const { useState: useStateL, useMemo: useMemoL } = React;

function ListPage({ initialFilters, onOpen, query }) {
  const [filters, setFilters] = useStateL(initialFilters || {
    variety: [], origin: [], shape: [], hardness: [], maker: [], tag: [], price: null, minRating: null,
  });
  const [sort, setSort] = useStateL("rank");
  const [view, setView] = useStateL("list");
  const [drawer, setDrawer] = useStateL(false);

  const PRICE_TEST = {
    a: (p) => p.price < 1000, b: (p) => p.price >= 1000 && p.price < 1500,
    c: (p) => p.price >= 1500 && p.price < 2000, d: (p) => p.price >= 2000,
  };

  // 絞り込み適用
  const filtered = useMemoL(() => {
    return PRODUCTS.filter((p) => {
      if (filters.variety.length && !filters.variety.includes(p.variety)) return false;
      if ((filters.origin || []).length && !filters.origin.includes(p.origin)) return false;
      if (filters.shape.length && !filters.shape.includes(p.shape)) return false;
      if (filters.hardness.length && !filters.hardness.includes(p.hardness)) return false;
      if (filters.maker.length && !filters.maker.includes(p.maker)) return false;
      if (filters.tag.length && !filters.tag.every((t) => p.tags.includes(t))) return false;
      if (filters.price && !PRICE_TEST[filters.price](p)) return false;
      if (filters.minRating && p.rating < filters.minRating) return false;
      if (query) {
        const q = query.toLowerCase();
        const hay = `${p.name}${makerName(p.maker)}${varietyName(p.variety)}${shapeName(p.shape)}${p.tags.join("")}`.toLowerCase();
        if (!hay.includes(q)) return false;
      }
      return true;
    });
  }, [filters, query]);

  // 並べ替え
  const sorted = useMemoL(() => {
    const a = [...filtered];
    if (sort === "rank") a.sort((x, y) => x.rank - y.rank);
    if (sort === "rating") a.sort((x, y) => y.rating - x.rating);
    if (sort === "priceLow") a.sort((x, y) => x.price - y.price);
    if (sort === "priceHigh") a.sort((x, y) => y.price - x.price);
    if (sort === "cost") a.sort((x, y) => x.pricePer100 - y.pricePer100);
    return a;
  }, [filtered, sort]);

  // 各ファセットの件数（現在の絞り込みを尊重しつつ概算）
  const counts = useMemoL(() => {
    const c = { variety: {}, origin: {}, shape: {}, hardness: {}, maker: {} };
    PRODUCTS.forEach((p) => {
      c.variety[p.variety] = (c.variety[p.variety] || 0) + 1;
      c.origin[p.origin] = (c.origin[p.origin] || 0) + 1;
      c.shape[p.shape] = (c.shape[p.shape] || 0) + 1;
      c.hardness[p.hardness] = (c.hardness[p.hardness] || 0) + 1;
      c.maker[p.maker] = (c.maker[p.maker] || 0) + 1;
    });
    return c;
  }, []);

  const SORTS = [
    { id: "rank", label: "人気順" },
    { id: "rating", label: "評価順" },
    { id: "priceLow", label: "価格が安い" },
    { id: "cost", label: "コスパ" },
  ];

  const activeCount = filters.variety.length + (filters.origin || []).length + filters.shape.length + filters.hardness.length + filters.maker.length +
    filters.tag.length + (filters.price ? 1 : 0) + (filters.minRating ? 1 : 0);

  return (
    <main className="wrap" style={{ paddingTop: 26, paddingBottom: 20 }}>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 13, color: "var(--ink-soft)", marginBottom: 6 }}>ホーム / 商品一覧</div>
        <h1 style={{ fontFamily: "var(--font-head)", fontSize: "clamp(26px,4vw,36px)", margin: 0 }}>
          干し芋 商品一覧
          {query && <span style={{ fontSize: 16, color: "var(--ink-soft)", fontWeight: 400 }}>　「{query}」の検索結果</span>}
        </h1>
      </div>

      {/* モバイル用 絞り込みバー */}
      <div className="mob-filter-bar">
        <button className="btn btn-ghost btn-sm" onClick={() => setDrawer(true)} style={{ flex: 1 }}>
          <Ico name="filter" size={16} /> 絞り込み {activeCount > 0 && `(${activeCount})`}
        </button>
        <div className="sortsel" style={{ flexShrink: 0 }}>
          {SORTS.slice(0, 2).map((s) => (
            <button key={s.id} className={sort === s.id ? "on" : ""} onClick={() => setSort(s.id)}>{s.label}</button>
          ))}
        </div>
      </div>

      <div className="list-layout">
        {/* サイドの絞り込み */}
        <aside className={`filters ${drawer ? "open" : ""}`}>
          <FilterPanel filters={filters} setFilters={setFilters} counts={counts}
            onClose={drawer ? () => setDrawer(false) : null} />
        </aside>
        {drawer && <div className="filters-scrim" onClick={() => setDrawer(false)} />}

        {/* 一覧本体 */}
        <div>
          <div className="list-toolbar">
            <div className="list-count"><b className="num">{sorted.length}</b> 件の商品</div>
            <div className="toolbar-right">
              <div className="sortsel">
                {SORTS.map((s) => (
                  <button key={s.id} className={sort === s.id ? "on" : ""} onClick={() => setSort(s.id)}>{s.label}</button>
                ))}
              </div>
              <div className="viewtoggle">
                <button className={view === "list" ? "on" : ""} onClick={() => setView("list")} aria-label="リスト表示"><Ico name="list" size={17} /></button>
                <button className={view === "grid" ? "on" : ""} onClick={() => setView("grid")} aria-label="グリッド表示"><Ico name="grid" size={17} /></button>
              </div>
            </div>
          </div>

          {sorted.length === 0 ? (
            <div className="card empty">
              <div className="big">🍠</div>
              <div style={{ fontWeight: 700, fontSize: 17, color: "var(--ink)" }}>条件に合う商品が見つかりませんでした</div>
              <div style={{ fontSize: 14, marginTop: 6 }}>絞り込み条件をゆるめてお試しください。</div>
            </div>
          ) : view === "list" ? (
            <div className="rows">
              {sorted.map((p) => <ProductRow key={p.id} p={p} onOpen={onOpen} />)}
            </div>
          ) : (
            <div className="grid-cards">
              {sorted.map((p) => <ProductCard key={p.id} p={p} onOpen={onOpen} />)}
            </div>
          )}
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { ListPage });
