// BrowsePage.jsx — Directory with search, filters, card grid

const BrowsePage = ({ navigate, initialParams = {} }) => {
  const [search, setSearch] = React.useState(initialParams.search || '');
  const [activeCategory, setActiveCategory] = React.useState(initialParams.category || 'all');
  const [activeActivities, setActiveActivities] = React.useState([]);
  const [sortBy, setSortBy] = React.useState('distance');
  const [showFilters, setShowFilters] = React.useState(false);

  const allListings = window.LISTINGS_DATA;

  const filtered = React.useMemo(() => {
    let result = [...allListings];

    // Category filter
    if (activeCategory !== 'all') {
      result = result.filter(l => l.category === activeCategory);
    }

    // Search filter
    if (search.trim()) {
      const q = search.toLowerCase();
      result = result.filter(l =>
        l.name.toLowerCase().includes(q) ||
        l.city.toLowerCase().includes(q) ||
        l.state.toLowerCase().includes(q) ||
        l.category.toLowerCase().includes(q) ||
        l.shortDesc.toLowerCase().includes(q) ||
        l.activities.some(a => a.toLowerCase().includes(q)) ||
        l.tags.some(t => t.toLowerCase().includes(q))
      );
    }

    // Activity filters
    if (activeActivities.length > 0) {
      result = result.filter(l =>
        activeActivities.every(act =>
          l.activities.some(a => a.toLowerCase().includes(act.toLowerCase())) ||
          l.tags.some(t => t.toLowerCase().includes(act.toLowerCase()))
        )
      );
    }

    // Sort
    if (sortBy === 'distance') result.sort((a, b) => a.distance - b.distance);
    else if (sortBy === 'rating') result.sort((a, b) => (b.rating ?? -1) - (a.rating ?? -1));
    else if (sortBy === 'reviews') result.sort((a, b) => (b.reviewCount ?? -1) - (a.reviewCount ?? -1));
    else if (sortBy === 'name') result.sort((a, b) => a.name.localeCompare(b.name));

    return result;
  }, [search, activeCategory, activeActivities, sortBy]);

  const toggleActivity = (act) => {
    setActiveActivities(prev =>
      prev.includes(act) ? prev.filter(a => a !== act) : [...prev, act]
    );
  };

  const clearFilters = () => {
    setSearch('');
    setActiveCategory('all');
    setActiveActivities([]);
    setSortBy('distance');
  };

  const hasFilters = search || activeCategory !== 'all' || activeActivities.length > 0;

  return (
    <div style={{ paddingTop: 68, minHeight: '100vh' }}>

      {/* ── PAGE HEADER ── */}
      <div style={{
        background: 'linear-gradient(160deg, var(--bark) 0%, var(--bark-mid) 100%)',
        padding: 'clamp(2rem, 4vw, 3.5rem) clamp(1.5rem, 4vw, 3rem)',
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: 'repeating-linear-gradient(0deg, transparent, transparent 3px, rgba(255,255,255,0.012) 3px, rgba(255,255,255,0.012) 4px)',
        }}/>
        <div style={{ maxWidth: 1280, margin: '0 auto', position: 'relative', zIndex: 1 }}>
          <div style={{
            fontFamily: 'DM Mono, monospace', fontSize: 11,
            letterSpacing: '0.15em', textTransform: 'uppercase',
            color: 'var(--orange)', marginBottom: 10,
          }}>
            {activeCategory === 'all' ? 'All Farms' : activeCategory + 's'}
          </div>
          <h1 style={{
            fontFamily: 'Playfair Display, serif',
            fontSize: 'clamp(28px, 5vw, 52px)', fontWeight: 700,
            color: 'var(--cream)', marginBottom: 20,
          }}>
            {activeCategory === 'all'
              ? 'Find a Farm Near You'
              : window.CATEGORIES.find(c => c.id === activeCategory)?.label || activeCategory
            }
          </h1>

          {/* Search bar */}
          <div style={{ display: 'flex', gap: 8, maxWidth: 560 }}>
            <div style={{ flex: 1, position: 'relative' }}>
              <span style={{
                position: 'absolute', left: 14, top: '50%',
                transform: 'translateY(-50%)', fontSize: 16, pointerEvents: 'none',
              }}>🔍</span>
              <input
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search by name, city, activity..."
                style={{
                  width: '100%', padding: '12px 16px 12px 42px',
                  borderRadius: 8, border: '2px solid transparent',
                  background: 'rgba(253,246,236,0.93)', fontSize: 15,
                  fontFamily: 'Source Serif 4, serif', color: 'var(--bark)',
                  outline: 'none', transition: 'border-color 0.2s',
                }}
                onFocus={e => e.target.style.borderColor = 'var(--orange)'}
                onBlur={e => e.target.style.borderColor = 'transparent'}
              />
            </div>
            <button
              onClick={() => setShowFilters(f => !f)}
              style={{
                background: showFilters ? 'var(--orange)' : 'rgba(253,246,236,0.15)',
                border: `2px solid ${showFilters ? 'var(--orange)' : 'rgba(255,255,255,0.2)'}`,
                color: showFilters ? '#fff' : 'var(--cream)',
                borderRadius: 8, padding: '12px 20px',
                fontSize: 14, fontFamily: 'Source Serif 4, serif', fontWeight: 600,
                cursor: 'pointer', transition: 'all 0.2s',
                display: 'flex', alignItems: 'center', gap: 6,
              }}
            >
              <span>⚙</span> Filters
              {(activeActivities.length > 0) && (
                <span style={{
                  background: '#fff', color: 'var(--orange)',
                  borderRadius: '50%', width: 18, height: 18,
                  fontSize: 11, display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 700,
                }}>{activeActivities.length}</span>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* ── FILTER PANEL ── */}
      {showFilters && (
        <div style={{
          background: 'var(--cream-dark)',
          borderBottom: '1px solid var(--cream-mid)',
          padding: '20px clamp(1.5rem, 4vw, 3rem)',
          animation: 'fadeIn 0.2s ease',
        }}>
          <div style={{ maxWidth: 1280, margin: '0 auto' }}>
            <div style={{ marginBottom: 16 }}>
              <div style={{
                fontFamily: 'DM Mono, monospace', fontSize: 11,
                letterSpacing: '0.1em', textTransform: 'uppercase',
                color: 'var(--bark-light)', marginBottom: 10,
              }}>Activities & Features</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {window.ACTIVITIES_LIST.map(act => (
                  <button key={act}
                    onClick={() => toggleActivity(act)}
                    style={{
                      background: activeActivities.includes(act) ? 'var(--orange)' : '#fff',
                      color: activeActivities.includes(act) ? '#fff' : 'var(--bark)',
                      border: `1px solid ${activeActivities.includes(act) ? 'var(--orange)' : 'var(--cream-mid)'}`,
                      borderRadius: 40, padding: '6px 14px',
                      fontSize: 13, fontFamily: 'Source Serif 4, serif',
                      cursor: 'pointer', transition: 'all 0.15s',
                    }}
                  >{act}</button>
                ))}
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{
                fontFamily: 'DM Mono, monospace', fontSize: 11,
                letterSpacing: '0.1em', textTransform: 'uppercase',
                color: 'var(--bark-light)',
              }}>Sort by:</div>
              {[
                { id: 'distance', label: 'Distance' },
                { id: 'rating', label: 'Top Rated' },
                { id: 'reviews', label: 'Most Reviewed' },
                { id: 'name', label: 'Name A–Z' },
              ].map(opt => (
                <button key={opt.id}
                  onClick={() => setSortBy(opt.id)}
                  style={{
                    background: sortBy === opt.id ? 'var(--bark)' : '#fff',
                    color: sortBy === opt.id ? 'var(--cream)' : 'var(--bark)',
                    border: `1px solid ${sortBy === opt.id ? 'var(--bark)' : 'var(--cream-mid)'}`,
                    borderRadius: 6, padding: '6px 14px',
                    fontSize: 13, fontFamily: 'Source Serif 4, serif',
                    cursor: 'pointer', transition: 'all 0.15s',
                  }}
                >{opt.label}</button>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* ── CATEGORY TABS ── */}
      <div style={{
        background: '#fff',
        borderBottom: '1px solid var(--cream-mid)',
        position: 'sticky', top: 68, zIndex: 50,
        overflowX: 'auto',
      }}>
        <div style={{
          maxWidth: 1280, margin: '0 auto',
          padding: '0 clamp(1.5rem, 4vw, 3rem)',
          display: 'flex', gap: 0,
        }}>
          {window.CATEGORIES.map(cat => (
            <button
              key={cat.id}
              onClick={() => setActiveCategory(cat.id)}
              style={{
                background: 'none', border: 'none', cursor: 'pointer',
                padding: '14px 18px',
                fontFamily: 'Source Serif 4, serif',
                fontSize: 14,
                fontWeight: activeCategory === cat.id ? 600 : 400,
                color: activeCategory === cat.id ? 'var(--orange)' : 'var(--bark-light)',
                borderBottom: activeCategory === cat.id ? '3px solid var(--orange)' : '3px solid transparent',
                transition: 'all 0.2s', whiteSpace: 'nowrap',
              }}
              onMouseEnter={e => { if (activeCategory !== cat.id) e.currentTarget.style.color = 'var(--bark)'; }}
              onMouseLeave={e => { if (activeCategory !== cat.id) e.currentTarget.style.color = 'var(--bark-light)'; }}
            >
              {cat.icon} {cat.label}
              <span style={{
                marginLeft: 6, fontSize: 11,
                fontFamily: 'DM Mono, monospace',
                color: activeCategory === cat.id ? 'var(--orange)' : 'var(--bark-light)',
                opacity: 0.7,
              }}>
                {cat.id === 'all'
                  ? allListings.length
                  : allListings.filter(l => l.category === cat.id).length
                }
              </span>
            </button>
          ))}
        </div>
      </div>

      {/* ── RESULTS ── */}
      <div style={{
        maxWidth: 1280, margin: '0 auto',
        padding: 'clamp(1.5rem, 3vw, 2.5rem) clamp(1.5rem, 4vw, 3rem)',
      }}>

        {/* Results bar */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          marginBottom: 24, flexWrap: 'wrap', gap: 12,
        }}>
          <div style={{
            fontFamily: 'Source Serif 4, serif', fontSize: 15,
            color: 'var(--bark-light)',
          }}>
            <span style={{ fontWeight: 600, color: 'var(--bark)' }}>{filtered.length}</span>
            {' '}farm{filtered.length !== 1 ? 's' : ''} found
            {activeCategory !== 'all' && <span style={{ color: 'var(--orange)' }}> in {activeCategory}s</span>}
          </div>
          {hasFilters && (
            <button onClick={clearFilters} style={{
              background: 'none', border: '1px solid var(--orange)',
              borderRadius: 6, padding: '6px 14px',
              fontSize: 13, fontFamily: 'Source Serif 4, serif',
              color: 'var(--orange)', cursor: 'pointer', transition: 'all 0.15s',
            }}
            onMouseEnter={e => { e.currentTarget.style.background = 'var(--orange-pale)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'none'; }}
            >✕ Clear filters</button>
          )}
        </div>

        {/* Card grid */}
        {filtered.length === 0 ? (
          <div style={{
            textAlign: 'center', padding: '80px 20px',
            color: 'var(--bark-light)',
          }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>🌾</div>
            <h3 style={{
              fontFamily: 'Playfair Display, serif', fontSize: 24,
              color: 'var(--bark)', marginBottom: 8,
            }}>No farms found</h3>
            <p style={{ fontSize: 15, marginBottom: 24 }}>Try adjusting your search or filters</p>
            <button onClick={clearFilters} style={{
              background: 'var(--orange)', color: '#fff',
              border: 'none', borderRadius: 8, padding: '12px 24px',
              fontSize: 14, fontFamily: 'Source Serif 4, serif', fontWeight: 600,
              cursor: 'pointer',
            }}>Clear all filters</button>
          </div>
        ) : (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(290px, 1fr))',
            gap: 24,
          }}>
            {filtered.map((listing, i) => (
              <div key={listing.id} style={{ animation: `fadeUp 0.4s ${Math.min(i, 8) * 0.04}s ease both`, opacity: 0 }}>
                <FarmCard
                  listing={listing}
                  featured={listing.featured}
                  onClick={() => navigate('listing', { id: listing.id })}
                />
              </div>
            ))}
          </div>
        )}

        {/* Submit listing CTA */}
        <div style={{
          marginTop: 64,
          background: 'var(--cream-dark)',
          borderRadius: 16, padding: 'clamp(2rem, 4vw, 3rem)',
          display: 'flex', alignItems: 'center', gap: 24,
          flexWrap: 'wrap',
          backgroundImage: 'var(--parchment-texture)',
          border: '1px solid var(--cream-mid)',
        }}>
          <div style={{ flex: 1, minWidth: 240 }}>
            <div style={{
              fontFamily: 'DM Mono, monospace', fontSize: 11,
              letterSpacing: '0.12em', textTransform: 'uppercase',
              color: 'var(--orange)', marginBottom: 8,
            }}>For farm owners</div>
            <h3 style={{
              fontFamily: 'Playfair Display, serif', fontSize: 24, fontWeight: 700,
              color: 'var(--bark)', marginBottom: 8,
            }}>List Your Farm</h3>
            <p style={{ fontSize: 14, color: 'var(--bark-light)', lineHeight: 1.6 }}>
              Get your farm in front of thousands of families looking for their next adventure.
            </p>
          </div>
          <button
            onClick={() => navigate('about')}
            style={{
              background: 'var(--bark)', color: 'var(--cream)',
              border: 'none', cursor: 'pointer',
              padding: '14px 28px', borderRadius: 10,
              fontSize: 15, fontFamily: 'Source Serif 4, serif', fontWeight: 600,
              transition: 'all 0.2s', whiteSpace: 'nowrap',
            }}
            onMouseEnter={e => { e.currentTarget.style.background = 'var(--bark-mid)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'var(--bark)'; e.currentTarget.style.transform = 'none'; }}
          >Submit a Listing →</button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { BrowsePage });
