;(() => {
// PRODUTOS PAGE — catalog with filters
const { Link, navigate, WhatsIcon, WHATSAPP_URL, formatSpec } = window.FaukoChrome;

// Parse URL query from clean URLs like /produtos?cat=Bombas&seg=Combustíveis
function parseQuery() {
  const qs = window.location.search.replace(/^\?/, '');
  if (!qs) return {};
  const out = {};
  for (const part of qs.split('&')) {
    if (!part) continue;
    const [k, v] = part.split('=');
    out[decodeURIComponent(k)] = decodeURIComponent(v || '');
  }
  return out;
}

function setQuery(params) {
  const base = window.location.pathname || '/produtos';
  const qs = Object.entries(params).filter(([, v]) => v != null && v !== '').map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
  window.history.replaceState(null, '', base + (qs ? '?' + qs : ''));
}

const ALL_CATEGORIES = ['Bombas', 'Medidores de Vazão', 'Bicos de Abastecimento', 'Mangueiras e Carretéis', 'Filtros', 'Tanques'];

// ---------- Smart search helpers ----------
// Normalize: lowercase + strip accents
function searchNorm(s) {
  return String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
}

// Build a searchable haystack from ALL product fields + a set of normalized numeric tokens
// ("220.0" → "220") so numeric queries match regardless of stored format.
function buildSearchIndex(p) {
  const parts = [];
  for (const [k, v] of Object.entries(p)) {
    if (k === 'images' || k === 'id') continue;
    if (v == null) continue;
    if (Array.isArray(v)) parts.push(v.join(' '));
    else if (typeof v === 'string' || typeof v === 'number') parts.push(String(v));
  }
  if (p.inmetro) parts.push('inmetro certificado');
  const norm = searchNorm(parts.join(' '));
  const nums = new Set();
  for (const m of norm.matchAll(/\d+(?:[.,]\d+)?/g)) {
    const n = parseFloat(m[0].replace(',', '.'));
    if (!Number.isNaN(n)) nums.add(String(n));
  }
  return { norm, nums };
}

// Single term against one product index. Strips common unit suffixes (v, hp, lpm, w, kg)
// so "220v" matches voltagem stored as "220.0".
function termMatches(term, index) {
  const t = searchNorm(term);
  if (!t) return true;
  if (index.norm.includes(t)) return true;
  const stripped = t.replace(/(l\/min|lpm|hp|kg|v|w)$/, '');
  if (/^\d+(?:[.,]\d+)?$/.test(stripped)) {
    const num = String(parseFloat(stripped.replace(',', '.')));
    if (index.nums.has(num)) return true;
  }
  return false;
}
// ---------- end search helpers ----------
const SUBCATS = {
  'Bombas': ['Elétricas', 'Bateria', 'Manuais', 'Lubrificantes', 'Magnéticas'],
  'Medidores de Vazão': ['Mecânicos', 'Digital', 'Turbina Digital', 'Engrenagem Oval'],
  'Bicos de Abastecimento': ['Automático', 'Manual'],
  'Mangueiras e Carretéis': ['Mangueira', 'Carretel'],
  'Filtros': ['Filtro'],
  'Tanques': ['Tanque', 'Tanque e Bacia'],
};
const ALL_SEGMENTS = ['Combustíveis', 'ARLA', 'Lubrificantes'];
const ALL_VOLT = ['12V', '24V', '110V', '220V', '380V', 'Manual', 'Bateria'];
const ALL_BRANDS = ['FILL-RITE', 'Adam Pumps', 'GPI', 'Gespasa', 'Maide Machine', 'Hi-Tech', 'DYE'];

function ProdutosPage({ products }) {
  // Read initial filters from URL once (deep links from Home), then keep state local.
  const initial = React.useMemo(() => {
    const q = parseQuery();
    return {
      cat: q.cat || '',
      sub: q.sub || '',
      seg: q.seg || '',
      volt: q.volt || '',
      brand: q.brand || '',
      inmetro: q.inmetro === '1',
      search: q.search || '',
    };
  }, []);
  const [filters, setFilters] = React.useState(initial);
  const [drawerOpen, setDrawerOpen] = React.useState(false);

  // NOTE: filters are local-only. We deliberately do NOT sync them to the URL hash —
  // doing so causes ScrollToTop (listening to route) to fire on every filter change.

  const update = (key, val) => setFilters(f => ({ ...f, [key]: val, ...(key === 'cat' ? { sub: '' } : {}) }));
  const reset = () => setFilters({ cat: '', sub: '', seg: '', volt: '', brand: '', inmetro: false, search: '' });

  const searchIndexes = React.useMemo(() => {
    const m = new Map();
    for (const p of products) m.set(p.id, buildSearchIndex(p));
    return m;
  }, [products]);

  const filtered = React.useMemo(() => {
    const terms = filters.search.trim().split(/\s+/).filter(Boolean);
    return products.filter(p => {
      if (filters.cat && p.categoria !== filters.cat) return false;
      if (filters.sub && !(p.subcategorias || [p.subcategoria]).includes(filters.sub)) return false;
      if (filters.seg && !(p.segments || []).includes(filters.seg)) return false;
      if (filters.volt && !(p.voltagemTags || []).includes(filters.volt)) return false;
      if (filters.brand && p.brand !== filters.brand) return false;
      if (filters.inmetro && !p.inmetro) return false;
      if (terms.length > 0) {
        const index = searchIndexes.get(p.id);
        // AND logic: every typed term must match some field
        if (!terms.every(t => termMatches(t, index))) return false;
      }
      return true;
    });
  }, [products, filters, searchIndexes]);

  // Counters per cat
  const counts = React.useMemo(() => {
    const c = { all: products.length };
    for (const p of products) c[p.categoria] = (c[p.categoria] || 0) + 1;
    return c;
  }, [products]);

  const activeChips = [];
  if (filters.cat) activeChips.push({ key: 'cat', label: filters.cat });
  if (filters.sub) activeChips.push({ key: 'sub', label: filters.sub });
  if (filters.seg) activeChips.push({ key: 'seg', label: filters.seg });
  if (filters.volt) activeChips.push({ key: 'volt', label: filters.volt });
  if (filters.brand) activeChips.push({ key: 'brand', label: filters.brand });
  if (filters.inmetro) activeChips.push({ key: 'inmetro', label: 'INMETRO' });

  return (
    <main>
      <section className="page-hero page-hero--produtos">
        <div className="page-hero__bg" />
        <div className="container page-hero__inner">
          <span className="eyebrow eyebrow--light">Catálogo</span>
          <h1>Catálogo completo de equipamentos para abastecimento</h1>
          <p>
            86 equipamentos das principais marcas mundiais — bombas, medidores,
            bicos, mangueiras, filtros e tanques para combustíveis, ARLA 32 e lubrificantes.
          </p>
          <div className="page-hero__search">
            <SearchIcon />
            <input
              type="search"
              placeholder="Busque por modelo, código ou aplicação (FR 701, ARLA, 12V…)"
              value={filters.search}
              onChange={e => update('search', e.target.value)}
            />
          </div>
        </div>
      </section>

      <section className="produtos-layout">
        <div className="container produtos-layout__inner">
          <aside className={'filters ' + (drawerOpen ? 'filters--open' : '')}>
            <div className="filters__head">
              <h3>Filtros</h3>
              <button className="filters__reset" onClick={reset}>Limpar</button>
              <button className="filters__close" onClick={() => setDrawerOpen(false)} aria-label="Fechar">
                <CloseIcon />
              </button>
            </div>
            <FilterGroup label="Categoria">
              <FilterOption label="Todas" count={counts.all} active={!filters.cat} onClick={() => update('cat', '')} />
              {ALL_CATEGORIES.map(c => (
                <FilterOption key={c} label={c} count={counts[c] || 0} active={filters.cat === c} onClick={() => update('cat', c)} />
              ))}
            </FilterGroup>

            {filters.cat && SUBCATS[filters.cat] && (
              <FilterGroup label="Subcategoria">
                <FilterOption label="Todas" active={!filters.sub} onClick={() => update('sub', '')} />
                {SUBCATS[filters.cat].map(s => (
                  <FilterOption key={s} label={s} active={filters.sub === s} onClick={() => update('sub', s)} />
                ))}
              </FilterGroup>
            )}

            <FilterGroup label="Segmento">
              <div className="filter-pills">
                {ALL_SEGMENTS.map(s => (
                  <button key={s} className={'pill ' + (filters.seg === s ? 'pill--active' : '')}
                    onClick={() => update('seg', filters.seg === s ? '' : s)}>{s}</button>
                ))}
              </div>
            </FilterGroup>

            <FilterGroup label="Voltagem / tipo">
              <div className="filter-pills">
                {ALL_VOLT.map(v => (
                  <button key={v} className={'pill ' + (filters.volt === v ? 'pill--active' : '')}
                    onClick={() => update('volt', filters.volt === v ? '' : v)}>{v}</button>
                ))}
              </div>
            </FilterGroup>

            <FilterGroup label="Marca">
              <div className="filter-pills">
                {ALL_BRANDS.map(b => (
                  <button key={b} className={'pill ' + (filters.brand === b ? 'pill--active' : '')}
                    onClick={() => update('brand', filters.brand === b ? '' : b)}>{b}</button>
                ))}
              </div>
            </FilterGroup>

            <FilterGroup label="Certificação">
              <label className="check">
                <input type="checkbox" checked={filters.inmetro} onChange={e => update('inmetro', e.target.checked)} />
                <span>Apenas com certificação INMETRO</span>
              </label>
            </FilterGroup>
          </aside>

          <div className="produtos-results">
            <div className="produtos-results__head">
              <button className="filters__open-btn" onClick={() => setDrawerOpen(true)}>
                <FilterIcon /> Filtros
              </button>
              <div className="produtos-results__count">
                <strong>{filtered.length}</strong> de {products.length} equipamentos
              </div>
            </div>

            {activeChips.length > 0 && (
              <div className="active-chips">
                {activeChips.map(c => (
                  <button key={c.key} className="chip" onClick={() => update(c.key, c.key === 'inmetro' ? false : '')}>
                    {c.label} <CloseIcon size={12} />
                  </button>
                ))}
                <button className="chip chip--reset" onClick={reset}>Limpar tudo</button>
              </div>
            )}

            <div className="product-grid">
              {filtered.map(p => <ProductCard key={p.id} product={p} />)}
              {filtered.length === 0 && (
                <div className="empty">
                  <h3>Nenhum equipamento encontrado</h3>
                  <p>Tente outros filtros ou fale com a equipe — temos itens fora do catálogo padrão.</p>
                  <a className="btn btn--whats" href={WHATSAPP_URL} target="_blank" rel="noopener">
                    <WhatsIcon /> Fale com a Fauko
                  </a>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function FilterGroup({ label, children }) {
  return (
    <div className="filter-group">
      <h4>{label}</h4>
      {children}
    </div>
  );
}

function FilterOption({ label, count, active, onClick }) {
  return (
    <button className={'filter-opt ' + (active ? 'active' : '')} onClick={onClick}>
      <span>{label}</span>
      {count != null && <span className="filter-opt__count">{count}</span>}
    </button>
  );
}

function ProductCard({ product: p }) {
  const subTitle = [p.codigo && `Cód. ${p.codigo}`, p.brand].filter(Boolean).join(' · ');
  const specs = [];
  if (p.vazao) specs.push({ k: 'Vazão', v: formatSpec(p.vazao) });
  if (p.voltagem) {
    const volt = String(formatSpec(p.voltagem));
    specs.push({ k: 'Voltagem', v: volt + (/v$/i.test(volt) ? '' : 'V') });
  }
  if (p.motor) specs.push({ k: 'Motor', v: formatSpec(p.motor) });
  if (p.capacidade) specs.push({ k: 'Capacidade', v: formatSpec(p.capacidade) });
  if (p.entrada) specs.push({ k: 'Entrada', v: formatSpec(p.entrada) });

  return (
    <div className="card product-card" onClick={() => navigate(window.FaukoSEO.productPath(p))} role="link" tabIndex={0}
         aria-label={p.nome}
         onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); navigate(window.FaukoSEO.productPath(p)); } }}>
      <div className="product-card__media">
        {p.images && p.images.length > 0 ? (
          <img src={p.images[0]} alt={p.nome} loading="lazy" />
        ) : (
          <div className="fk-ph" style={{ position: 'absolute', inset: 0 }}>
            <span className="fk-ph__label">[FOTO] {p.nome}</span>
          </div>
        )}
        {p.inmetro && <span className="product-card__inmetro badge badge--inmetro">INMETRO</span>}
      </div>
      <div className="product-card__body">
        <div className="product-card__tags">
          <span className="badge badge--navy">{p.categoria}</span>
          {(p.subcategorias || [p.subcategoria]).filter(Boolean).map(s => (
            <span key={s} className="badge badge--gray">{s}</span>
          ))}
        </div>
        <h3>{p.nome}</h3>
        <div className="product-card__sub">{subTitle}</div>
        <ul className="product-card__specs">
          {specs.slice(0, 3).map(s => (
            <li key={s.k}><strong>{s.k}:</strong> {s.v}</li>
          ))}
        </ul>
        <div className="product-card__foot">
          <span className="product-card__cta">Ver detalhes <ArrowIconSm /></span>
          <a className="product-card__whats" href={WHATSAPP_URL} target="_blank" rel="noopener"
             onClick={e => e.stopPropagation()}>
            <WhatsIcon /> Orçar
          </a>
        </div>
      </div>
    </div>
  );
}

function ArrowIconSm() {
  return (<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6" /></svg>);
}
function CloseIcon({ size = 14 }) {
  return (<svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6l-12 12" /></svg>);
}
function SearchIcon() {
  return (<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7" /><path d="M21 21l-4-4" /></svg>);
}
function FilterIcon() {
  return (<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 6h16M7 12h10M10 18h4" /></svg>);
}

window.ProdutosPage = ProdutosPage;
window.ProductCard = ProductCard;

})();
