const FilterRail = ({ filters, setFilters, counts }) => {
  const Section = ({ title, jp, children, extra }) => (
    <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--border-1)" }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginBottom: 8 }}>
        <span style={{ fontSize: 11, fontWeight: 600, color: "var(--fg-1)", textTransform: "uppercase", letterSpacing: "0.05em" }}>{title}</span>
        <span className="jp-sub" style={{ fontSize: 10 }}>{jp}</span>
      </div>
      {extra}
      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>{children}</div>
    </div>
  );

  const channelOpts = [
    { key: "pokemon_center", zh: "寶可夢中心", jp: "ポケモンセンター", color: "#EF4444" },
    { key: "yodobashi",      zh: "Yodobashi",  jp: "ヨドバシ",        color: "#F59E0B" },
    { key: "bic_camera",     zh: "BIC Camera", jp: "ビックカメラ",    color: "#F59E0B" },
    { key: "aeon",           zh: "AEON",       jp: "イオン",          color: "#10B981" },
    { key: "yamada",         zh: "Yamada",     jp: "ヤマダ電機",      color: "#3B82F6" },
    { key: "toys_r_us",      zh: "Toys\"R\"Us", jp: "トイザらス",     color: "#EC4899" },
    { key: "amazon",         zh: "Amazon",     jp: "アマゾン",        color: "#6B7280" },
    { key: "other",          zh: "其他",       jp: "その他",          color: "#6B7280" },
  ];

  const typeOpts = [
    { key: "lottery",  zh: "抽選",     jp: "lottery",  color: "#3B82F6" },
    { key: "preorder", zh: "予約",     jp: "preorder", color: "#10B981" },
    { key: "walk_in",  zh: "店頭販售", jp: "walk-in",  color: "#F59E0B" },
  ];

  const toggle = (group, key) => {
    setFilters(f => {
      const has = f[group].includes(key);
      // Don't let user re-check a zero-count option
      if (!has && counts?.[group]?.[key] === 0) return f;
      return { ...f, [group]: has ? f[group].filter(k => k !== key) : [...f[group], key] };
    });
  };

  const ColorDot = ({ c, dim }) => (
    <span style={{ width: 8, height: 8, borderRadius: 999, background: c, marginRight: 2, opacity: dim ? 0.35 : 1 }} />
  );

  // A single filter row. Disables visually when count === 0.
  const FilterRow = ({ opt, group, checked, count }) => {
    const disabled = count === 0;
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 6, opacity: disabled ? 0.5 : 1 }}>
        <ColorDot c={opt.color} dim={disabled} />
        <label style={{
          flex: 1, display: "flex", alignItems: "center", gap: 8,
          padding: "6px 8px", margin: "0 -8px", borderRadius: 6,
          cursor: disabled ? "not-allowed" : "pointer",
          transition: "background 120ms", userSelect: "none",
        }}
        onMouseEnter={e => { if (!disabled) e.currentTarget.style.background = "var(--ink-50)"; }}
        onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
          <input type="checkbox"
            checked={checked && !disabled}
            disabled={disabled}
            onChange={() => !disabled && toggle(group, opt.key)}
            style={{ accentColor: "var(--red-500)", width: 14, height: 14, margin: 0, cursor: disabled ? "not-allowed" : "pointer" }} />
          <span style={{ fontSize: 13, color: disabled ? "var(--fg-3)" : "var(--fg-1)", fontWeight: 500 }}>{opt.zh}</span>
          <span className="jp-sub" style={{ fontSize: 11 }}>{opt.jp}</span>
          <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--fg-3)", fontVariantNumeric: "tabular-nums" }}>
            {disabled ? "(暫無資料)" : count ?? ""}
          </span>
        </label>
      </div>
    );
  };

  // Channel legend block — moved OFF the map, into filter rail above the toggles.
  const ChannelLegend = () => (
    <div style={{
      background: "var(--ink-25)", border: "1px solid var(--border-1)",
      borderRadius: 6, padding: "8px 10px", marginBottom: 10,
      display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px 10px",
    }}>
      <div style={{ gridColumn: "1 / -1", fontSize: 10, fontWeight: 600, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 2 }}>
        Pin 顏色對照 · Pin legend
      </div>
      {[
        ["#EF4444","Pokémon"],["#F59E0B","Yodo / BIC"],
        ["#10B981","AEON"],["#3B82F6","Yamada"],
        ["#EC4899","Toys\"R\"Us"],["#6B7280","其他"]
      ].map(([c,l]) => (
        <div key={l} style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 10.5, color: "var(--fg-2)" }}>
          <span style={{ width: 7, height: 7, borderRadius: 999, background: c, flexShrink: 0 }}/>
          <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l}</span>
        </div>
      ))}
    </div>
  );

  return (
    <aside style={{
      width: 260, flexShrink: 0, background: "#fff",
      borderRight: "1px solid var(--border-1)",
      display: "flex", flexDirection: "column", overflow: "auto",
    }}>
      <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--border-1)" }}>
        <div style={{ position: "relative" }}>
          <div style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)" }}>
            <Icon name="search" size={14} color="var(--fg-3)" />
          </div>
          <input placeholder="搜尋商品或店家…"
            value={filters.q}
            onChange={e => setFilters(f => ({ ...f, q: e.target.value }))}
            style={{
              width: "100%", height: 32, padding: "0 10px 0 32px", boxSizing: "border-box",
              border: "1px solid var(--border-2)", borderRadius: 6,
              font: "var(--ts-body)", outline: "none", background: "var(--ink-25)",
            }} />
        </div>
      </div>

      <Section title="通路類別" jp="Channel" extra={<ChannelLegend/>}>
        {channelOpts.map(o => (
          <FilterRow key={o.key} opt={o} group="channels"
            checked={filters.channels.includes(o.key)}
            count={counts?.channels[o.key]} />
        ))}
      </Section>

      <Section title="販售類型" jp="Sale type">
        {typeOpts.map(o => (
          <FilterRow key={o.key} opt={o} group="types"
            checked={filters.types.includes(o.key)}
            count={counts?.types[o.key]} />
        ))}
      </Section>

      <Section title="購買條件" jp="Requirements">
        <Checkbox label="排除需日本帳號" jp="exclude JP account"
          checked={filters.noJpAccount} onChange={() => setFilters(f => ({ ...f, noJpAccount: !f.noJpAccount }))} />
        <Checkbox label="排除需現場取貨" jp="exclude in-store pickup"
          checked={filters.noInStore} onChange={() => setFilters(f => ({ ...f, noInStore: !f.noInStore }))} />
        <Checkbox label="只看進行中" jp="active only"
          checked={filters.activeOnly} onChange={() => setFilters(f => ({ ...f, activeOnly: !f.activeOnly }))} />
      </Section>

      <Section title="地區" jp="Region">
        <Checkbox label="全部地區" jp="all regions" checked={filters.regions.length === 0}
          onChange={() => setFilters(f => ({ ...f, regions: [] }))} />
        <Checkbox label="東京 23 區" jp="Tokyo 23ku" checked={filters.regions.includes("tokyo")}
          onChange={() => toggle("regions", "tokyo")} />
        <Checkbox label="神奈川" jp="Kanagawa" checked={filters.regions.includes("kanagawa")}
          onChange={() => toggle("regions", "kanagawa")} />
        <Checkbox label="千葉" jp="Chiba" checked={filters.regions.includes("chiba")}
          onChange={() => toggle("regions", "chiba")} />
      </Section>

      <div style={{ marginTop: "auto", padding: 14, borderTop: "1px solid var(--border-1)" }}>
        <div style={{ fontSize: 11, color: "var(--fg-3)", marginBottom: 6 }}>資料來源 · Source</div>
        <div style={{ fontSize: 12, color: "var(--fg-2)" }}>gamepedia.jp</div>
        <div style={{ font: "var(--ts-mono)", fontSize: 10.5, color: "var(--fg-3)", marginTop: 2 }}>178 rec · 2026-04-22</div>
      </div>
    </aside>
  );
};

window.FilterRail = FilterRail;
