// instructors-page.jsx — Filter sidebar, sort bar, instructor grid

const InstructorsPage = ({ initialSearch, setPage, onSelectInstructor }) => {
  const data = window.useSiteData();
  const isMobile = window.useIsMobile();
  const { instructors, categories } = data;
  const [topic, setTopic] = React.useState(initialSearch?.topic || '');
  const [location, setLocation] = React.useState(initialSearch?.location || '');
  const [catFilter, setCatFilter] = React.useState('all');
  const [priceMax, setPriceMax] = React.useState(250);
  const [minRating, setMinRating] = React.useState(0);
  const [minExp, setMinExp] = React.useState(0);
  const [availOnly, setAvailOnly] = React.useState(false);
  const [sortBy, setSortBy] = React.useState('best');
  const [viewMode, setViewMode] = React.useState('grid');
  // Sidebar default: open on desktop, closed (drawer) on mobile.
  const [sidebarOpen, setSidebarOpen] = React.useState(!isMobile);
  React.useEffect(() => { setSidebarOpen(!isMobile); }, [isMobile]);

  React.useEffect(() => {
    setTopic(initialSearch?.topic || '');
    setLocation(initialSearch?.location || '');
  }, [initialSearch]);

  const filtered = React.useMemo(() => {
    let r = [...instructors];
    if (topic) {
      const q = topic.toLowerCase();
      r = r.filter(i =>
        i.subject.toLowerCase().includes(q) ||
        i.category.toLowerCase().replace('-', ' ').includes(q) ||
        i.specialties.some(s => s.toLowerCase().includes(q)) ||
        categories.find(c => c.id === i.category)?.name.toLowerCase().includes(q)
      );
    }
    if (location) {
      const q = location.toLowerCase();
      r = r.filter(i =>
        i.city.toLowerCase().includes(q) ||
        i.state.toLowerCase().includes(q) ||
        `${i.city}, ${i.state}`.toLowerCase().includes(q)
      );
    }
    if (catFilter !== 'all') r = r.filter(i => i.category === catFilter);
    r = r.filter(i => i.rate <= priceMax);
    if (minRating > 0) r = r.filter(i => i.rating >= minRating);
    if (minExp > 0) r = r.filter(i => i.experience >= minExp);
    if (availOnly) r = r.filter(i => i.available);
    switch (sortBy) {
      case 'rating':     return r.sort((a, b) => b.rating - a.rating);
      case 'price-low':  return r.sort((a, b) => a.rate - b.rate);
      case 'price-high': return r.sort((a, b) => b.rate - a.rate);
      case 'reviews':    return r.sort((a, b) => b.reviewCount - a.reviewCount);
      case 'experience': return r.sort((a, b) => b.experience - a.experience);
      default:           return r;
    }
  }, [instructors, topic, location, catFilter, priceMax, minRating, minExp, availOnly, sortBy]);

  const clearAll = () => {
    setTopic(''); setLocation(''); setCatFilter('all'); setPriceMax(250);
    setMinRating(0); setMinExp(0); setAvailOnly(false); setSortBy('best');
  };

  const hasFilters = topic || location || catFilter !== 'all' || priceMax < 250 || minRating > 0 || minExp > 0 || availOnly;

  // ── Sidebar ────────────────────────────────────────────────────────────────
  // Desktop: a fixed-width inline panel that animates in/out.
  // Mobile:  a full-screen overlay drawer that covers everything.
  const Sidebar = () => {
    if (isMobile) {
      if (!sidebarOpen) return null;
      return (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 9000,
          background: 'rgba(10,12,24,0.4)',
          display: 'flex', justifyContent: 'flex-end',
        }} onClick={() => setSidebarOpen(false)}>
          <aside style={{
            background: '#fff', width: '88vw', maxWidth: 340,
            height: '100%', overflowY: 'auto', padding: '20px 18px',
            boxShadow: '-8px 0 30px rgba(0,0,0,0.18)',
          }} onClick={e => e.stopPropagation()}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
              <div style={{ fontWeight: 700, fontSize: 16, color: 'oklch(18% 0.03 265)' }}>Filters</div>
              <button onClick={() => setSidebarOpen(false)} style={{ background: 'oklch(96% 0.01 265)', border: 'none', borderRadius: 8, width: 32, height: 32, cursor: 'pointer', fontSize: 18, color: 'oklch(40% 0.04 265)', fontFamily: "'Plus Jakarta Sans', sans-serif" }}>×</button>
            </div>
            <SidebarBody />
          </aside>
        </div>
      );
    }
    return (
      <aside style={{
        width: sidebarOpen ? 280 : 0, flexShrink: 0, overflow: 'hidden',
        transition: 'width 0.3s ease',
      }}>
        <div style={{ width: 280, paddingRight: 24 }}>
          <SidebarBody />
        </div>
      </aside>
    );
  };

  const SidebarBody = () => (
    <>
        {/* Search inputs */}
        <div style={{ marginBottom: 28 }}>
          <label style={labelStyle}>What to learn</label>
          <div style={inputWrap}>
            <svg style={iconStyle} viewBox="0 0 20 20" fill="none">
              <circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="1.6"/>
              <path d="M14 14l3 3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
            </svg>
            <input
              style={filterInput}
              placeholder="Subject, sport, instrument…"
              value={topic}
              onChange={e => setTopic(e.target.value)}
            />
          </div>
        </div>
        <div style={{ marginBottom: 28 }}>
          <label style={labelStyle}>Location</label>
          <div style={inputWrap}>
            <svg style={iconStyle} viewBox="0 0 20 20" fill="none">
              <path d="M10 2a6 6 0 0 1 6 6c0 4-6 10-6 10S4 12 4 8a6 6 0 0 1 6-6z" stroke="currentColor" strokeWidth="1.6"/>
              <circle cx="10" cy="8" r="2" stroke="currentColor" strokeWidth="1.6"/>
            </svg>
            <input
              style={filterInput}
              placeholder="City or state"
              value={location}
              onChange={e => setLocation(e.target.value)}
            />
          </div>
        </div>

        <div style={{ borderTop: '1px solid oklch(90% 0.01 265)', paddingTop: 24, marginBottom: 24 }}>
          {/* Category */}
          <label style={labelStyle}>Category</label>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 24 }}>
            {[{ id: 'all', name: 'All Categories' }, ...categories].map(cat => (
              <button key={cat.id} onClick={() => setCatFilter(cat.id)} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                background: catFilter === cat.id ? 'oklch(22% 0.06 265)' : 'transparent',
                color: catFilter === cat.id ? '#fff' : 'oklch(42% 0.04 265)',
                border: `1px solid ${catFilter === cat.id ? 'transparent' : 'oklch(90% 0.01 265)'}`,
                borderRadius: 8, padding: '8px 12px', cursor: 'pointer',
                fontSize: 13, fontWeight: catFilter === cat.id ? 600 : 400,
                fontFamily: "'Plus Jakarta Sans', sans-serif", transition: 'all 0.15s',
                textAlign: 'left',
              }}>
                <span>{cat.name}</span>
                {cat.id !== 'all' && (
                  <span style={{ fontSize: 11, opacity: 0.7 }}>{cat.count || instructors.filter(i => i.category === cat.id).length}</span>
                )}
              </button>
            ))}
          </div>

          {/* Price */}
          <label style={labelStyle}>Max Price: <strong style={{ color: 'oklch(22% 0.06 265)' }}>${priceMax}/hr</strong></label>
          <input type="range" min={40} max={250} step={5} value={priceMax}
            onChange={e => setPriceMax(+e.target.value)}
            style={{ width: '100%', accentColor: 'oklch(22% 0.06 265)', marginBottom: 24 }} />

          {/* Rating */}
          <label style={labelStyle}>Minimum Rating</label>
          <div style={{ display: 'flex', gap: 6, marginBottom: 24, flexWrap: 'wrap' }}>
            {[[0,'Any'],[4,'4.0+'],[4.5,'4.5+'],[4.8,'4.8+']].map(([v, l]) => (
              <button key={v} onClick={() => setMinRating(v)} style={{
                padding: '6px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600,
                background: minRating === v ? 'oklch(22% 0.06 265)' : 'oklch(96% 0.01 265)',
                color: minRating === v ? '#fff' : 'oklch(42% 0.04 265)',
                border: 'none', cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif",
              }}>{l}</button>
            ))}
          </div>

          {/* Experience */}
          <label style={labelStyle}>Experience</label>
          <div style={{ display: 'flex', gap: 6, marginBottom: 24, flexWrap: 'wrap' }}>
            {[[0,'Any'],[3,'3+ yrs'],[5,'5+ yrs'],[10,'10+ yrs']]
              .map(([v, l]) => (
              <button key={v} onClick={() => setMinExp(v)} style={{
                padding: '6px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600,
                background: minExp === v ? 'oklch(22% 0.06 265)' : 'oklch(96% 0.01 265)',
                color: minExp === v ? '#fff' : 'oklch(42% 0.04 265)',
                border: 'none', cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif",
              }}>{l}</button>
            ))}
          </div>

          {/* Availability */}
          <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', marginBottom: 24 }}>
            <div
              onClick={() => setAvailOnly(v => !v)}
              style={{
                width: 40, height: 22, borderRadius: 11,
                background: availOnly ? 'oklch(22% 0.06 265)' : 'oklch(85% 0.02 265)',
                position: 'relative', cursor: 'pointer', transition: 'background 0.2s', flexShrink: 0,
              }}>
              <div style={{
                width: 18, height: 18, borderRadius: '50%', background: '#fff',
                position: 'absolute', top: 2, left: availOnly ? 20 : 2,
                transition: 'left 0.2s', boxShadow: '0 1px 4px rgba(0,0,0,0.2)',
              }} />
            </div>
            <span style={{ fontSize: 13, color: 'oklch(42% 0.04 265)', fontWeight: 500 }}>Available now only</span>
          </label>

          {hasFilters && (
            <button onClick={clearAll} style={{
              width: '100%', background: 'none',
              border: '1px solid oklch(88% 0.01 265)', borderRadius: 8,
              padding: '9px', fontSize: 13, color: 'oklch(52% 0.03 265)',
              cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif",
              fontWeight: 500,
            }}>Clear All Filters</button>
          )}
        </div>
    </>
  );

  const labelStyle = { display: 'block', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'oklch(52% 0.03 265)', marginBottom: 8 };
  const inputWrap = { display: 'flex', alignItems: 'center', background: '#fff', border: '1.5px solid oklch(88% 0.01 265)', borderRadius: 10, overflow: 'hidden' };
  const iconStyle = { width: 16, height: 16, marginLeft: 12, flexShrink: 0, color: 'oklch(62% 0.03 265)' };
  const filterInput = { border: 'none', outline: 'none', padding: '12px 12px', fontSize: 16, flex: 1, fontFamily: "'Plus Jakarta Sans', sans-serif", background: 'transparent', color: 'oklch(22% 0.06 265)', minHeight: 44 };

  return (
    <div style={{ minHeight: '100vh', background: 'oklch(97.5% 0.006 60)', paddingTop: isMobile ? 60 : 68 }}>
      {/* Top search bar — single line on desktop, stacked on mobile */}
      <div style={{ background: '#fff', borderBottom: '1px solid oklch(90% 0.01 265)', padding: isMobile ? '12px 16px' : '16px 40px' }}>
        <div style={{
          display: 'flex',
          alignItems: isMobile ? 'stretch' : 'center',
          gap: isMobile ? 10 : 12,
          maxWidth: 1280, margin: '0 auto',
          flexDirection: isMobile ? 'column' : 'row',
        }}>
          {!isMobile && (
            <>
              <button onClick={() => setPage('home')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'oklch(52% 0.03 265)', fontSize: 13, fontFamily: "'Plus Jakarta Sans', sans-serif", display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' }}>
                <svg style={{ width: 16, height: 16 }} viewBox="0 0 20 20" fill="none"><path d="M12 4L6 10l6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                Home
              </button>
              <div style={{ width: 1, height: 20, background: 'oklch(88% 0.01 265)' }} />
            </>
          )}
          <div style={{
            flex: 1, display: 'flex',
            flexDirection: isMobile ? 'column' : 'row',
            alignItems: isMobile ? 'stretch' : 'center',
            background: 'oklch(97% 0.008 60)', borderRadius: 10,
            border: '1.5px solid oklch(88% 0.01 265)', overflow: 'hidden',
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', flex: 1,
              borderBottom: isMobile ? '1px solid oklch(90% 0.01 265)' : 'none',
            }}>
              <svg style={{ width: 16, height: 16, marginLeft: 12, color: 'oklch(62% 0.03 265)', flexShrink: 0 }} viewBox="0 0 20 20" fill="none">
                <circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="1.6"/>
                <path d="M14 14l3 3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
              </svg>
              <input value={topic} onChange={e => setTopic(e.target.value)} placeholder="Subject, sport, instrument…" style={{ ...filterInput, fontSize: 16 }} />
            </div>
            {!isMobile && <div style={{ width: 1, height: 20, background: 'oklch(88% 0.01 265)' }} />}
            <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
              <svg style={{ width: 16, height: 16, marginLeft: 12, color: 'oklch(62% 0.03 265)', flexShrink: 0 }} viewBox="0 0 20 20" fill="none">
                <path d="M10 2a6 6 0 0 1 6 6c0 4-6 10-6 10S4 12 4 8a6 6 0 0 1 6-6z" stroke="currentColor" strokeWidth="1.6"/>
                <circle cx="10" cy="8" r="2" stroke="currentColor" strokeWidth="1.6"/>
              </svg>
              <input value={location} onChange={e => setLocation(e.target.value)} placeholder="City or state" style={{ ...filterInput, fontSize: 16, maxWidth: isMobile ? undefined : 200 }} />
            </div>
          </div>
        </div>
      </div>

      <div style={{
        maxWidth: 1280, margin: '0 auto',
        padding: isMobile ? '20px 16px' : '32px 40px',
        display: 'flex', gap: isMobile ? 0 : 32, alignItems: 'flex-start',
      }}>
        <Sidebar />

        {/* Main content */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {/* Sort & view bar */}
          <div style={{
            display: 'flex',
            flexDirection: isMobile ? 'column' : 'row',
            justifyContent: 'space-between',
            alignItems: isMobile ? 'stretch' : 'center',
            gap: isMobile ? 12 : 0,
            marginBottom: isMobile ? 16 : 24,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <button onClick={() => setSidebarOpen(v => !v)} style={{ background: 'none', border: '1px solid oklch(88% 0.01 265)', borderRadius: 8, padding: '7px 12px', fontSize: 12, fontWeight: 600, color: 'oklch(42% 0.04 265)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                <svg style={{ width: 14, height: 14 }} viewBox="0 0 20 20" fill="none">
                  <line x1="3" y1="5" x2="17" y2="5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
                  <line x1="3" y1="10" x2="13" y2="10" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
                  <line x1="3" y1="15" x2="10" y2="15" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
                </svg>
                {isMobile ? 'Filters' : (sidebarOpen ? 'Hide Filters' : 'Show Filters')}
              </button>
              <span style={{ fontSize: 14, color: 'oklch(52% 0.03 265)' }}>
                <strong style={{ color: 'oklch(22% 0.06 265)', fontSize: 16 }}>{filtered.length}</strong> instructors found
              </span>
              {hasFilters && (
                <button onClick={clearAll} style={{ fontSize: 12, color: 'oklch(52% 0.03 265)', background: 'none', border: 'none', cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif", textDecoration: 'underline' }}>Clear all</button>
              )}
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              {/* Sort */}
              <select value={sortBy} onChange={e => setSortBy(e.target.value)} style={{
                border: '1.5px solid oklch(88% 0.01 265)', borderRadius: 8,
                padding: '8px 14px', fontSize: 13, color: 'oklch(32% 0.04 265)',
                background: '#fff', cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif",
                fontWeight: 500, outline: 'none',
                flex: isMobile ? 1 : 'none',
              }}>
                <option value="best">Best Match</option>
                <option value="rating">Highest Rating</option>
                <option value="reviews">Most Reviews</option>
                <option value="experience">Most Experience</option>
                <option value="price-low">Price: Low to High</option>
                <option value="price-high">Price: High to Low</option>
              </select>
              {/* View toggle — hidden on mobile (always grid) */}
              {!isMobile && (
                <div style={{ display: 'flex', background: 'oklch(95% 0.01 265)', borderRadius: 8, padding: 2, gap: 2 }}>
                  {[['grid','Grid'],['list','List']].map(([v, l]) => (
                    <button key={v} onClick={() => setViewMode(v)} style={{
                      padding: '6px 14px', borderRadius: 6, fontSize: 12, fontWeight: 600,
                      background: viewMode === v ? '#fff' : 'transparent',
                      color: viewMode === v ? 'oklch(22% 0.06 265)' : 'oklch(55% 0.03 265)',
                      border: 'none', cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif",
                      boxShadow: viewMode === v ? '0 1px 4px rgba(0,0,0,0.1)' : 'none',
                      transition: 'all 0.15s',
                    }}>{l}</button>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Active filter chips */}
          {hasFilters && (
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 20 }}>
              {topic && <FilterChip label={`"${topic}"`} onRemove={() => setTopic('')} />}
              {location && <FilterChip label={location} onRemove={() => setLocation('')} />}
              {catFilter !== 'all' && <FilterChip label={categories.find(c => c.id === catFilter)?.name} onRemove={() => setCatFilter('all')} />}
              {priceMax < 250 && <FilterChip label={`Under $${priceMax}/hr`} onRemove={() => setPriceMax(250)} />}
              {minRating > 0 && <FilterChip label={`${minRating}+ stars`} onRemove={() => setMinRating(0)} />}
              {minExp > 0 && <FilterChip label={`${minExp}+ yrs exp`} onRemove={() => setMinExp(0)} />}
              {availOnly && <FilterChip label="Available now" onRemove={() => setAvailOnly(false)} />}
            </div>
          )}

          {/* Results */}
          {filtered.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '80px 40px' }}>
              <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 32, color: 'oklch(72% 0.03 265)', marginBottom: 12 }}>No instructors found</div>
              <p style={{ fontSize: 14, color: 'oklch(55% 0.03 265)', marginBottom: 20 }}>Try adjusting your filters or searching for a different subject.</p>
              <button onClick={clearAll} style={{ background: 'oklch(22% 0.06 265)', color: '#fff', border: 'none', borderRadius: 10, padding: '12px 28px', fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Clear Filters</button>
            </div>
          ) : viewMode === 'grid' ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 20 }}>
              {filtered.map(ins => (
                <window.InstructorCard key={ins.id} instructor={ins} viewMode="grid" onSelect={() => onSelectInstructor && onSelectInstructor(ins.id)} />
              ))}
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {filtered.map(ins => (
                <window.InstructorCard key={ins.id} instructor={ins} viewMode="list" onSelect={() => onSelectInstructor && onSelectInstructor(ins.id)} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const FilterChip = ({ label, onRemove }) => (
  <span style={{
    display: 'inline-flex', alignItems: 'center', gap: 6,
    background: 'oklch(22% 0.06 265)', color: '#fff',
    fontSize: 12, fontWeight: 600, padding: '5px 12px',
    borderRadius: 20,
  }}>
    {label}
    <button onClick={onRemove} style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)', cursor: 'pointer', padding: 0, fontSize: 14, lineHeight: 1, fontFamily: "'Plus Jakarta Sans', sans-serif" }}>×</button>
  </span>
);

Object.assign(window, { InstructorsPage, FilterChip });
