// pages/collection.jsx — category / collection page with filter & sort

function CollectionPage() {
  const route = useRoute();
  const slug = route.params.slug;
  const found = HAP.findCategory(slug);
  const all = HAP.productsInCategory(slug);

  const [sort, setSort] = React.useState('featured');
  const [view, setView] = React.useState('grid');
  const [filterOpen, setFilterOpen] = React.useState(false);
  const [filters, setFilters] = React.useState({
    priceMax: 5000,
    inStock: false,
    onSale: false,
    sizes: new Set(),
    tags: new Set()
  });

  // Pull facet values from this collection
  const allSizes = React.useMemo(() => {
    const s = new Set();
    all.forEach(p => p.variants.forEach(v => s.add(v)));
    return [...s].slice(0, 12);
  }, [slug]);
  const allTags = React.useMemo(() => {
    const s = new Set();
    all.forEach(p => p.tags.forEach(t => s.add(t)));
    return [...s];
  }, [slug]);

  // Filter
  let filtered = all.filter(p => {
    if (p.price > filters.priceMax) return false;
    if (filters.inStock && p.stock <= 0) return false;
    if (filters.onSale && p.price >= p.compareAt) return false;
    if (filters.sizes.size > 0 && !p.variants.some(v => filters.sizes.has(v))) return false;
    if (filters.tags.size > 0 && !p.tags.some(t => filters.tags.has(t))) return false;
    return true;
  });

  // Sort
  filtered = [...filtered].sort((a, b) => {
    switch (sort) {
      case 'price-asc': return a.price - b.price;
      case 'price-desc': return b.price - a.price;
      case 'newest': return Number(b.isNew) - Number(a.isNew);
      case 'rating': return b.rating - a.rating;
      case 'name': return a.name.localeCompare(b.name);
      default: return 0;
    }
  });

  if (!found && slug !== 'all') {
    if (window.CommerceRedirects && CommerceRedirects.navigateIfRedirect('#/collections/' + slug)) {
      return <main className="container section"><p className="muted">Redirecting…</p></main>;
    }
    return (
      <main className="container section">
        <h1 className="serif">Collection not found</h1>
        <p>We couldn't find a collection at <code>/{slug}</code>.</p>
        <a className="btn btn--primary" href="#/collections">Browse all collections</a>
      </main>
    );
  }

  const top = found?.top;
  const sub = found?.sub;
  const sub2 = found?.sub2;
  const display = sub2 || sub || top;
  const heroName = display?.name || 'All products';
  const siblings = (sub?.children) || (top?.sub) || [];

  return (
    <main>
      {/* Hero */}
      <section style={{ background: 'var(--cream)', paddingBlock: 'clamp(40px, 6vw, 80px)' }}>
        <div className="container">
          <div className="crumb" style={{ marginBottom: 16 }}>
            <a href="#/">Home</a>
            <span className="sep">/</span>
            {top && <a href={'#/collections/' + top.slug}>{top.name}</a>}
            {sub && <><span className="sep">/</span><a href={'#/collections/' + sub.slug}>{sub.name}</a></>}
            {sub2 && <><span className="sep">/</span><span className="here">{sub2.name}</span></>}
            {!sub && !sub2 && top && <span className="here"></span>}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 32, alignItems: 'end' }} className="coll-hero">
            <div>
              <h1 className="serif" style={{ fontSize: 'var(--fs-display)', lineHeight: 1.05 }}>{heroName}</h1>
              <p style={{ color: 'var(--ink-2)', maxWidth: 540, marginTop: 12 }}>
                {collectionBlurb(display, all.length)}
              </p>
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 24, flexWrap: 'wrap' }}>
              <StatBlock n={all.length} l="products" />
              <StatBlock n={`${Math.round(all.reduce((s,p) => s + (1 - p.price/p.compareAt), 0) / Math.max(1, all.length) * 100)}%`} l="avg saving" />
              <StatBlock n={`₹${Math.min(...all.map(p => p.price)) || 0}+`} l="from" />
            </div>
          </div>
        </div>
      </section>

      {/* Sub-category chips */}
      {siblings.length > 0 && (
        <div style={{ borderBottom: '1px solid var(--line)', background: 'var(--paper)' }}>
          <div className="container" style={{ display: 'flex', gap: 8, paddingBlock: 14, overflowX: 'auto' }}>
            {top && (
              <a href={'#/collections/' + top.slug} className={'tag' + (top.slug === slug ? '' : ' tag--soft')}
                 style={{ background: top.slug === slug ? 'var(--forest)' : 'var(--cream)', color: top.slug === slug ? 'var(--paper)' : 'var(--ink)', border: 'none' }}>
                All {top.name}
              </a>
            )}
            {siblings.map(s => (
              <a key={s.slug} href={'#/collections/' + s.slug} className={'tag' + (s.slug === slug ? '' : ' tag--soft')}
                 style={{ background: s.slug === slug ? 'var(--forest)' : 'var(--cream)', color: s.slug === slug ? 'var(--paper)' : 'var(--ink)', border: 'none', whiteSpace: 'nowrap' }}>
                {s.name}
              </a>
            ))}
          </div>
        </div>
      )}

      {/* Toolbar + grid */}
      <div className="container" style={{ paddingBlock: 32 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 32 }} className="coll-grid">

          {/* Filter sidebar */}
          <aside className="coll-filter" style={{ position: 'sticky', top: 'calc(var(--header-h) + 16px)', alignSelf: 'flex-start' }}>
            <FilterPanel filters={filters} setFilters={setFilters} allSizes={allSizes} allTags={allTags} />
          </aside>

          <div>
            {/* Toolbar */}
            <div className="spread" style={{ marginBottom: 20, paddingBottom: 16, borderBottom: '1px solid var(--line)', flexWrap: 'wrap', gap: 12 }}>
              <div style={{ fontSize: '.88rem', color: 'var(--muted)' }}>
                Showing {filtered.length} of {all.length}
              </div>
              <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                <button className="btn btn--sm btn--ghost mobile-only" onClick={() => setFilterOpen(true)}>
                  <Icon name="sliders" size={14} /> Filter
                </button>
                <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: '.85rem' }}>
                  Sort
                  <select className="select" value={sort} onChange={(e) => setSort(e.target.value)} style={{ padding: '8px 12px' }}>
                    <option value="featured">Featured</option>
                    <option value="newest">Newest</option>
                    <option value="price-asc">Price · low to high</option>
                    <option value="price-desc">Price · high to low</option>
                    <option value="rating">Highest rated</option>
                    <option value="name">A → Z</option>
                  </select>
                </label>
                <div style={{ display: 'inline-flex', border: '1px solid var(--line-strong)', borderRadius: 999 }}>
                  <button className="icon-btn" onClick={() => setView('grid')}
                          style={{ width: 36, height: 36, background: view === 'grid' ? 'var(--cream)' : '' }}>
                    <Icon name="grid" size={16} />
                  </button>
                  <button className="icon-btn" onClick={() => setView('list')}
                          style={{ width: 36, height: 36, background: view === 'list' ? 'var(--cream)' : '' }}>
                    <Icon name="list" size={16} />
                  </button>
                </div>
              </div>
            </div>

            {/* Grid */}
            {filtered.length === 0 ? (
              <EmptyState icon="leaf" title="No products match your filters"
                          note="Try resetting your filters or browsing a sibling category."
                          cta={{ label: 'Reset filters', href: '#' }}
                          onCta={(e) => { e?.preventDefault?.(); setFilters({ priceMax: 5000, inStock: false, onSale: false, sizes: new Set(), tags: new Set() }); }} />
            ) : view === 'grid' ? (
              <div className="product-grid">
                {filtered.map(p => <ProductCard key={p.id} p={p} />)}
              </div>
            ) : (
              <ListView items={filtered} />
            )}
          </div>
        </div>
      </div>

      {/* Mobile filter drawer */}
      {filterOpen && (
        <div className="scrim" onClick={() => setFilterOpen(false)}>
          <div className="drawer" style={{ left: 0, right: 'auto' }} onClick={(e) => e.stopPropagation()}>
            <div className="drawer__head">
              <span className="drawer__title">Filter</span>
              <button className="icon-btn" onClick={() => setFilterOpen(false)}><Icon name="close" /></button>
            </div>
            <div className="drawer__body">
              <FilterPanel filters={filters} setFilters={setFilters} allSizes={allSizes} allTags={allTags} />
            </div>
            <div className="drawer__foot">
              <button className="btn btn--primary btn--full" onClick={() => setFilterOpen(false)}>Show {filtered.length} products</button>
            </div>
          </div>
        </div>
      )}

      <style>{`
        @media (max-width: 980px) {
          .coll-grid { grid-template-columns: 1fr !important; }
          .coll-filter { display: none !important; }
        }
        @media (max-width: 720px) {
          .coll-hero { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </main>
  );
}

function StatBlock({ n, l }) {
  return (
    <div style={{ borderLeft: '1px solid var(--line-strong)', paddingLeft: 16 }}>
      <div className="serif" style={{ fontSize: '1.4rem', lineHeight: 1 }}>{n}</div>
      <div style={{ fontSize: '.72rem', color: 'var(--muted)', marginTop: 4, letterSpacing: '.08em', textTransform: 'uppercase' }}>{l}</div>
    </div>
  );
}

function FilterPanel({ filters, setFilters, allSizes, allTags }) {
  const update = (patch) => setFilters(f => ({ ...f, ...patch }));
  const toggleSet = (key, value) => {
    setFilters(f => {
      const next = new Set(f[key]);
      next.has(value) ? next.delete(value) : next.add(value);
      return { ...f, [key]: next };
    });
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      <FilterSection title="Price">
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '.8rem', color: 'var(--muted)' }}>
          <span>₹0</span>
          <span>up to {HAP.formatPrice(filters.priceMax)}</span>
        </div>
        <input type="range" min={99} max={5000} step={50} value={filters.priceMax}
               onChange={(e) => update({ priceMax: Number(e.target.value) })}
               style={{ width: '100%', accentColor: 'var(--forest)' }} />
      </FilterSection>

      <FilterSection title="Availability">
        <Toggle label="In stock only" checked={filters.inStock} onChange={(v) => update({ inStock: v })} />
        <Toggle label="On sale" checked={filters.onSale} onChange={(v) => update({ onSale: v })} />
      </FilterSection>

      {allSizes.length > 0 && (
        <FilterSection title="Size / variant">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {allSizes.map(s => (
              <button key={s}
                onClick={() => toggleSet('sizes', s)}
                className="tag"
                style={{
                  background: filters.sizes.has(s) ? 'var(--forest)' : 'var(--cream)',
                  color: filters.sizes.has(s) ? 'var(--paper)' : 'var(--ink)',
                  border: 'none', cursor: 'pointer'
                }}>{s}</button>
            ))}
          </div>
        </FilterSection>
      )}

      {allTags.length > 0 && (
        <FilterSection title="Tags">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {allTags.map(t => (
              <Check key={t} label={t} checked={filters.tags.has(t)} onChange={() => toggleSet('tags', t)} />
            ))}
          </div>
        </FilterSection>
      )}

      <button className="btn btn--ghost btn--sm" onClick={() => setFilters({ priceMax: 5000, inStock: false, onSale: false, sizes: new Set(), tags: new Set() })}>
        Reset all
      </button>
    </div>
  );
}

function FilterSection({ title, children }) {
  return (
    <div>
      <h4 style={{ fontSize: '.72rem', letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--moss)', marginBottom: 10, fontWeight: 600 }}>{title}</h4>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{children}</div>
    </div>
  );
}

function Toggle({ label, checked, onChange }) {
  return (
    <label style={{ display: 'inline-flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: '.9rem' }}>
      <span style={{
        width: 32, height: 18, borderRadius: 999,
        background: checked ? 'var(--forest)' : 'var(--line-strong)',
        position: 'relative', transition: 'background 200ms', flexShrink: 0
      }}>
        <span style={{
          position: 'absolute', top: 2, left: checked ? 16 : 2,
          width: 14, height: 14, borderRadius: 999, background: 'var(--paper)',
          transition: 'left 200ms'
        }}></span>
      </span>
      <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} style={{ display: 'none' }} />
      <span>{label}</span>
    </label>
  );
}

function Check({ label, checked, onChange }) {
  return (
    <label className="check">
      <input type="checkbox" checked={checked} onChange={onChange} />
      <span className="check__box"><Icon name="check" size={12}/></span>
      <span style={{ fontSize: '.88rem' }}>{label}</span>
    </label>
  );
}

function ListView({ items }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {items.map(p => (
        <a key={p.id} href={'#/products/' + p.slug} style={{
          display: 'grid', gridTemplateColumns: '180px 1fr auto', gap: 24,
          background: 'var(--shell)', border: '1px solid var(--line)',
          borderRadius: 'var(--r-md)', padding: 16, alignItems: 'center'
        }}>
          <div style={{ aspectRatio: '4/5', borderRadius: 'var(--r-sm)', overflow: 'hidden', background: 'var(--cream)' }}>
            <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          </div>
          <div>
            <div className="pc__vendor">{p.vendor}</div>
            <h3 className="serif" style={{ fontSize: '1.3rem', marginBlock: 4 }}>{p.name}</h3>
            {p.latin && <div style={{ fontStyle: 'italic', color: 'var(--muted)', fontSize: '.85rem' }}>{p.latin}</div>}
            <p style={{ marginTop: 8, color: 'var(--ink-2)', fontSize: '.9rem', maxWidth: 560 }}>{p.blurb.slice(0, 180)}…</p>
          </div>
          <div style={{ textAlign: 'right' }}>
            <PriceTag p={p} />
            <button className="btn btn--primary btn--sm" style={{ marginTop: 12 }}
              onClick={(e) => { e.preventDefault(); HAPStore.addToCart(p.id, p.variants[0], 1); HAPStore.markViewed(p.id); }}>
              Quick add
            </button>
          </div>
        </a>
      ))}
    </div>
  );
}

function collectionBlurb(cat, n) {
  if (!cat) return `Browse ${n} products from across the store — pebbles, stones, planters and decor.`;
  const blurbs = {
    'pebbles': 'Every pebble we stock — coloured, white, black, natural and mixed. Cleaned, graded and ready to top your pots, paths and terrariums.',
    'coloured-pebbles': 'Glossy, colour-coated pebbles with a UV-stable finish. The quickest way to add a pop of colour to pots, terrariums and craft projects.',
    'white-pebbles': 'Naturally polished white pebbles for a clean, premium look. A favourite for pot-topping, water features and path edges.',
    'black-pebbles': 'Deep, glossy black pebbles that make foliage and white pots stand out. Modern and low-fuss.',
    'natural-pebbles': 'River-tumbled stones in earthy tones — hard-wearing and ideal for borders, beds and ground cover.',
    'mixed-pebbles': 'Balanced blends of tone and size for a natural, layered finish in pots, paths and aquascapes.',
    'polished-pebbles': 'Smooth, high-shine pebbles, tumbled to a premium finish.',
    'stones-chips': 'Marble chips, gravel, lava rock, glass gems and decorative sand — for mulch, drainage, borders and aquascaping.',
    'marble-chips': 'Angular crushed marble for borders, pot mulch and drainage. Reflects light beautifully in garden beds.',
    'gravel': 'Economical natural gravel for pathways, drainage layers and large-area ground cover.',
    'lava-rock': 'Lightweight porous volcanic rock for drainage, terrariums, aquascaping and grills.',
    'glass-pebbles': 'Glossy flat-back glass gems in jewel tones — made for vases, terrariums, fish bowls and candle trays.',
    'decorative-sand': 'Fine decorative sand for terrariums, sand art and pot top-dressing.',
    'path-stones': 'Stepping stones and walkway slabs for garden paths — weather-resistant and slip-grip.',
    'leaf-stones': 'Cast stepping stones with a natural leaf-vein texture. A favourite for lawn borders.',
    'pots-planters': 'Ceramic pots and stone-finish planters — sized for tabletops, balconies and entrances.',
    'ceramic-pots': 'Clean ceramic pots for indoor styling. Pair them with our decorative pebbles.',
    'stone-planters': 'Large stone-finish floor planters for courtyards and entrances. Frost-free and weatherproof.',
    'decor': 'Buddha statues, terrarium fillers and quiet objects to finish a garden corner.',
    'buddha': 'Hand-finished resin Buddha statues for garden corners, balconies and meditation spaces.',
    'lawn-grass': 'Healthy live grass and ground-cover, supplied fresh for instant lawns and borders.'
  };
  return blurbs[cat.slug] || `Browse ${n} hand-picked items in ${cat.name.toLowerCase()}.`;
}

window.CollectionPage = CollectionPage;
window.collectionBlurb = collectionBlurb;
