// mb-filters.jsx — Filters sheet content (segment, category, radius, region, mode)

function RadiusSlider({ value, onChange, min = 1, max = 15 }) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 12 }}>
        <span style={{ font: "600 14px var(--ui)", color: "var(--text)" }}>Raio de busca</span>
        <span style={{ font: "800 22px var(--ui)", color: "var(--accent)" }}>{value}<span style={{ font: "600 13px var(--ui)", color: "var(--muted)", marginLeft: 2 }}>km</span></span>
      </div>
      <input type="range" min={min} max={max} value={value} step={1}
        onChange={e => onChange(Number(e.target.value))}
        className="mb-range"
        style={{ "--pct": pct + "%" }} />
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, font: "600 11px var(--ui)", color: "var(--muted)" }}>
        <span>{min} km</span><span>a partir da sua posição</span><span>{max} km</span>
      </div>
    </div>
  );
}

// Mapeia cidade do endereço para região conhecida
function cityToRegion(city) {
  if (!city) return null;
  const c = city.toLowerCase();
  if (c.includes("barra") || c.includes("coqueiro")) return "Barra dos Coqueiros";
  if (c.includes("expans")) return "Zona de Expansão";
  if (c.includes("aracaju")) return "Aracaju";
  return null;
}

function FiltersSheet({ filt, setFilt, addresses = [], segments }) {
  const segs = segments || SEGMENTS;
  const seg = segs.find(s => s.id === filt.seg);
  const set = (patch) => setFilt(f => ({ ...f, ...patch }));

  // GPS real
  const [gpsPos, setGpsPos] = React.useState(null);
  React.useEffect(() => {
    if (!navigator.geolocation) return;
    navigator.geolocation.getCurrentPosition(
      p => setGpsPos({ lat: p.coords.latitude, lng: p.coords.longitude }),
      () => setGpsPos(null), { timeout: 4000 }
    );
  }, []);

  const useGPS = () => set({ region: "Todas" });
  const useAddress = (addr) => {
    const region = cityToRegion(addr.city);
    if (region) set({ region });
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      {/* posição de busca */}
      <div>
        <div style={{ font: "600 14px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Centro da busca</div>
        {/* GPS */}
        <button onClick={useGPS} style={{
          width: "100%", display: "flex", alignItems: "center", gap: 11,
          background: filt.region === "Todas" ? "var(--accent-50)" : "var(--bg)",
          border: filt.region === "Todas" ? "1.5px solid var(--accent)" : "1.5px solid var(--line)",
          borderRadius: 14, padding: "12px 14px", cursor: "pointer", marginBottom: 8,
        }}>
          <div style={{ width: 34, height: 34, borderRadius: 999, background: filt.region === "Todas" ? "var(--accent)" : "var(--line)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name="target" size={19} color={filt.region === "Todas" ? "var(--accent-ink)" : "var(--muted)"} sw={2} />
          </div>
          <div style={{ flex: 1, textAlign: "left" }}>
            <div style={{ font: "700 13.5px var(--ui)", color: "var(--text)" }}>Minha posição (GPS)</div>
            <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)" }}>
              {gpsPos ? `${gpsPos.lat.toFixed(4)}, ${gpsPos.lng.toFixed(4)} · GPS ativo` : "Aguardando GPS…"}
            </div>
          </div>
          {filt.region === "Todas" && <Icon name="check" size={16} color="var(--accent)" sw={2.5} />}
        </button>
        {/* Endereços cadastrados */}
        {addresses.length > 0 && addresses.map(addr => {
          const region = cityToRegion(addr.city);
          const active = filt.region === region;
          return (
            <button key={addr.id} onClick={() => useAddress(addr)} style={{
              width: "100%", display: "flex", alignItems: "center", gap: 11,
              background: active ? "var(--accent-50)" : "var(--bg)",
              border: active ? "1.5px solid var(--accent)" : "1.5px solid var(--line)",
              borderRadius: 14, padding: "12px 14px", cursor: "pointer", marginBottom: 8,
            }}>
              <div style={{ width: 34, height: 34, borderRadius: 999, background: active ? "var(--accent)" : "var(--line)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <Icon name="pin" size={17} color={active ? "var(--accent-ink)" : "var(--muted)"} sw={2} />
              </div>
              <div style={{ flex: 1, textAlign: "left" }}>
                <div style={{ font: "700 13.5px var(--ui)", color: "var(--text)" }}>{addr.label || "Endereço"}</div>
                <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)" }}>
                  {[addr.street, addr.neighborhood, addr.city].filter(Boolean).join(", ")}
                  {region && <span style={{ color: "var(--accent)", marginLeft: 4 }}>· {region}</span>}
                </div>
              </div>
              {active && <Icon name="check" size={16} color="var(--accent)" sw={2.5} />}
            </button>
          );
        })}
      </div>

      <RadiusSlider value={filt.radius} onChange={v => set({ radius: v })} />

      {/* region */}
      <div>
        <div style={{ font: "600 14px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Região</div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {["Todas", ...REGIONS].map(r => (
            <Chip key={r} active={filt.region === r} onClick={() => set({ region: r })}>{r}</Chip>
          ))}
        </div>
      </div>

      {/* segment */}
      <div>
        <div style={{ font: "600 14px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Segmento</div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {segs.map(s => (
            <Chip key={s.id} icon={s.icon || segIcon(s.id)} active={filt.seg === s.id}
              onClick={() => set({ seg: filt.seg === s.id ? null : s.id, cat: null })}>{s.question || s.q}</Chip>
          ))}
        </div>
      </div>

      {/* category (depends on segment — usa IDs reais da API) */}
      {seg && (() => {
        // API segments: categories = [{id, name}]; hardcoded: cats = ["nome"]
        const cats = seg.categories && seg.categories.length > 0
          ? seg.categories.map(c => ({ id: c.id, name: c.name }))
          : (seg.cats || []).map(name => ({ id: name, name }));
        if (cats.length === 0) return null;
        return (
          <div>
            <div style={{ font: "600 14px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Categoria</div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {cats.map(c => (
                <Chip key={c.id} active={filt.cat === c.id}
                  onClick={() => set({ cat: filt.cat === c.id ? null : c.id })}>{c.name}</Chip>
              ))}
            </div>
          </div>
        );
      })()}

      {/* mode */}
      <div>
        <div style={{ font: "600 14px var(--ui)", color: "var(--text)", marginBottom: 10 }}>Forma de receber</div>
        <div style={{ display: "flex", gap: 8 }}>
          {[["todos", "Tudo", null], ["delivery", "Entrega", "bike"], ["pickup", "Retirada", "store"]].map(([id, lbl, ic]) => (
            <Chip key={id} icon={ic} active={filt.mode === id} onClick={() => set({ mode: id })}>{lbl}</Chip>
          ))}
        </div>
      </div>

      <button onClick={() => setFilt({ region: "Todas", seg: null, cat: null, radius: 8, mode: "todos" })}
        style={{ alignSelf: "center", background: "none", border: "none", cursor: "pointer", font: "700 13.5px var(--ui)", color: "var(--muted)", textDecoration: "underline", padding: 6 }}>
        Limpar filtros
      </button>
    </div>
  );
}

Object.assign(window, { RadiusSlider, FiltersSheet });
