/* OnSumn — Filter Popup with Selector Chips */

/* ── Selector Chips (adapted from shadcn pattern, CSS springs) ── */
function SelectorChips({ options, selected, onToggle, colorMap, darkMode }) {
  return (
    <div style={{
      display: 'flex', flexWrap: 'wrap', gap: 8,
    }}>
      {options.map(option => {
        const isSelected = selected.includes(option);
        const chipColor = colorMap?.[option] || 'var(--international-orange)';

        return (
          <button
            key={option}
            onClick={() => onToggle(option)}
            style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              gap: 6,
              padding: '10px 18px',
              minHeight: 44,
              borderRadius: 100,
              fontSize: 12, fontWeight: 700, fontFamily: 'var(--font-body)',
              letterSpacing: '0.04em', textTransform: 'uppercase',
              cursor: 'pointer',
              border: isSelected ? `2px solid ${chipColor}` : (darkMode ? '2px solid rgba(255,255,255,0.15)' : '2px solid rgba(0,0,0,0.12)'),
              background: isSelected ? chipColor : (darkMode ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)'),
              color: isSelected ? '#fff' : (darkMode ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.6)'),
              transition: 'all 0.25s cubic-bezier(0.34, 1.56, 0.64, 1)',
              transform: isSelected ? 'scale(1.05)' : 'scale(1)',
              boxShadow: isSelected ? `0 4px 16px ${chipColor}44` : 'none',
            }}
          >
            <span>{option}</span>
            {/* Animated checkmark */}
            <span style={{
              display: 'inline-flex', alignItems: 'center',
              width: isSelected ? 16 : 0,
              opacity: isSelected ? 1 : 0,
              overflow: 'hidden',
              transition: 'width 0.25s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.2s',
            }}>
              <svg width="16" height="16" viewBox="0 0 20 20" fill="none"
                style={{
                  transform: isSelected ? 'scale(1)' : 'scale(0)',
                  transition: 'transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1)',
                }}>
                <path d="M5 10.5L9 14.5L15 7.5" stroke="#fff" strokeWidth="2.5"
                  strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </span>
          </button>
        );
      })}
    </div>
  );
}

/* ── Time-of-day chips ── */
const TIME_OPTIONS = ['Morning', 'Afternoon', 'Evening', 'Late Night'];
const TIME_COLORS = {
  'Morning': '#D57800',
  'Afternoon': '#FF4F00',
  'Evening': '#395542',
  'Late Night': '#7A99AC',
};

/* ── Filter Popup ── */
function FilterPopup({ darkMode, radius, activeFilters, onApply, onClose, visible }) {
  const [selectedCats, setSelectedCats] = React.useState(activeFilters?.categories || []);
  const [selectedCities, setSelectedCities] = React.useState(activeFilters?.cities || []);
  const [selectedTimes, setSelectedTimes] = React.useState(activeFilters?.times || []);
  const [selectedSounds, setSelectedSounds] = React.useState(activeFilters?.sounds || []);

  // Reset internal state when popup opens
  React.useEffect(() => {
    if (visible) {
      setSelectedCats(activeFilters?.categories || []);
      setSelectedCities(activeFilters?.cities || []);
      setSelectedTimes(activeFilters?.times || []);
      setSelectedSounds(activeFilters?.sounds || []);
    }
  }, [visible]);

  const toggleItem = (list, setList) => (item) => {
    setList(prev =>
      prev.includes(item) ? prev.filter(x => x !== item) : [...prev, item]
    );
  };

  const concertsSelected = selectedCats.includes('Concerts');

  const totalSelected = selectedCats.length + selectedCities.length + selectedTimes.length + selectedSounds.length;

  const handleClear = () => {
    setSelectedCats([]);
    setSelectedCities([]);
    setSelectedTimes([]);
    setSelectedSounds([]);
  };

  const handleApply = () => {
    onApply({
      categories: selectedCats,
      cities: selectedCities,
      times: selectedTimes,
      sounds: concertsSelected ? selectedSounds : [],
    });
    onClose();
  };

  const categoryColors = {
    'Concerts': '#D57800',
    'Cards': '#7A99AC',
    'Art': '#FF4F00',
    'Food': '#395542',
    'Culture': '#5A7A68',
  };

  const cityColors = {
    'Oakland': '#D57800',
    'SF': '#FF4F00',
    'San Jose': '#395542',
    'Vallejo': '#7A99AC',
    'Richmond': '#5A7A68',
    'Daly City': '#5B7A8D',
    'Berkeley': '#D57800',
  };

  return (
    <React.Fragment>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{
          position: 'fixed', inset: 0, zIndex: 9990,
          background: 'rgba(0,0,0,0.6)',
          backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
          opacity: visible ? 1 : 0,
          pointerEvents: visible ? 'auto' : 'none',
          transition: 'opacity 0.3s ease',
        }}
      />

      {/* Panel */}
      <div style={{
        position: 'fixed',
        top: '50%', left: '50%',
        transform: visible
          ? 'translate(-50%, -50%) scale(1)'
          : 'translate(-50%, -48%) scale(0.96)',
        zIndex: 9991,
        width: 'min(480px, 92vw)',
        maxHeight: '85vh',
        overflowY: 'auto',
        opacity: visible ? 1 : 0,
        pointerEvents: visible ? 'auto' : 'none',
        transition: 'opacity 0.3s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)',
        ...glassStyle(darkMode, 'panel'),
        background: darkMode
          ? 'linear-gradient(135deg, rgba(18,20,20,0.97), rgba(10,10,10,0.98))'
          : 'linear-gradient(135deg, rgba(255,255,255,0.97), rgba(245,245,245,0.98))',
        border: darkMode ? '1px solid rgba(255,255,255,0.1)' : '1px solid rgba(0,0,0,0.08)',
        borderRadius: Math.min(radius, 24),
        padding: 0,
      }}>
        {/* Header */}
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: '20px 24px 0',
        }}>
          <div>
            <h3 style={{
              fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 800,
              color: darkMode ? '#fff' : '#0A0A0A',
              letterSpacing: '-0.02em',
            }}>Find Your Vibe</h3>
            <p style={{
              fontFamily: 'var(--font-body)', fontSize: 12,
              color: darkMode ? 'rgba(255,255,255,0.35)' : 'rgba(0,0,0,0.4)',
              marginTop: 4,
            }}>
              {totalSelected > 0 ? `${totalSelected} filter${totalSelected > 1 ? 's' : ''} selected` : 'Select what you\'re into'}
            </p>
          </div>
          <button onClick={onClose} style={{
            background: 'none', border: 'none',
            color: darkMode ? 'rgba(255,255,255,0.4)' : 'rgba(0,0,0,0.3)',
            fontSize: 28, cursor: 'pointer', lineHeight: 1,
            minHeight: 44, minWidth: 44,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>×</button>
        </div>

        {/* Sections */}
        <div style={{ padding: '20px 24px 24px' }}>
          {/* Categories */}
          <div style={{ marginBottom: 24 }}>
            <label style={{
              fontFamily: 'var(--font-body)', fontSize: 10, fontWeight: 700,
              letterSpacing: '0.1em', textTransform: 'uppercase',
              color: darkMode ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.35)',
              display: 'block', marginBottom: 12,
            }}>What's Your Move</label>
            <SelectorChips
              options={['Concerts', 'Cards', 'Art', 'Food', 'Culture']}
              selected={selectedCats}
              onToggle={toggleItem(selectedCats, setSelectedCats)}
              colorMap={categoryColors}
              darkMode={darkMode}
            />
            {/* Category descriptions */}
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 20px',
              marginTop: 16, paddingLeft: 2,
            }}>
              {[
                ['Concerts', 'Live shows, DJ sets, open mics, club nights'],
                ['Cards', 'TCG tournaments, sports cards, collectibles, expos'],
                ['Art', 'Galleries, exhibits, murals, open studios'],
                ['Food', 'Pop-ups, markets, food trucks, tastings'],
                ['Culture', 'Festivals, block parties, community fairs'],
              ].map(([name, desc]) => (
                <div key={name} style={{
                  fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: '20px',
                  color: darkMode ? 'rgba(255,255,255,0.45)' : 'rgba(0,0,0,0.45)',
                }}>
                  <span style={{ fontWeight: 700, color: darkMode ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.65)' }}>{name}:</span> {desc}
                </div>
              ))}
            </div>

            {/* Sub-genre expand when Concerts is selected */}
            <div style={{
              maxHeight: concertsSelected ? 120 : 0,
              opacity: concertsSelected ? 1 : 0,
              overflow: 'hidden',
              transition: 'max-height 0.35s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.25s ease',
              marginTop: concertsSelected ? 16 : 0,
            }}>
              <label style={{
                fontFamily: 'var(--font-body)', fontSize: 10, fontWeight: 700,
                letterSpacing: '0.1em', textTransform: 'uppercase',
                color: darkMode ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.35)',
                display: 'block', marginBottom: 10,
              }}>What Sound</label>
              <SelectorChips
                options={window.TASTE_SOUNDS || ['EDM', 'R&B', 'Hip-Hop', 'Rock', 'Jazz', 'Classical', 'Latin', 'Indie']}
                selected={selectedSounds}
                onToggle={toggleItem(selectedSounds, setSelectedSounds)}
                colorMap={window.SOUND_COLORS || {}}
                darkMode={darkMode}
              />
            </div>
          </div>

          {/* Divider */}
          <div style={{
            height: 1,
            background: darkMode ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)',
            marginBottom: 24,
          }} />

          {/* Cities */}
          <div style={{ marginBottom: 24 }}>
            <label style={{
              fontFamily: 'var(--font-body)', fontSize: 10, fontWeight: 700,
              letterSpacing: '0.1em', textTransform: 'uppercase',
              color: darkMode ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.35)',
              display: 'block', marginBottom: 10,
            }}>Where You At</label>
            <SelectorChips
              options={['Oakland', 'SF', 'San Jose', 'Vallejo', 'Richmond', 'Daly City']}
              selected={selectedCities}
              onToggle={toggleItem(selectedCities, setSelectedCities)}
              colorMap={cityColors}
              darkMode={darkMode}
            />
          </div>

          {/* Divider */}
          <div style={{
            height: 1,
            background: darkMode ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)',
            marginBottom: 24,
          }} />

          {/* Time of day */}
          <div style={{ marginBottom: 28 }}>
            <label style={{
              fontFamily: 'var(--font-body)', fontSize: 10, fontWeight: 700,
              letterSpacing: '0.1em', textTransform: 'uppercase',
              color: darkMode ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.35)',
              display: 'block', marginBottom: 10,
            }}>When You Sliding</label>
            <SelectorChips
              options={TIME_OPTIONS}
              selected={selectedTimes}
              onToggle={toggleItem(selectedTimes, setSelectedTimes)}
              colorMap={TIME_COLORS}
              darkMode={darkMode}
            />
          </div>

          {/* Action buttons */}
          <div style={{ display: 'flex', gap: 10 }}>
            {totalSelected > 0 && (
              <button onClick={handleClear} style={{
                flex: 1,
                padding: '14px 20px', minHeight: 48,
                borderRadius: radius,
                background: 'transparent',
                border: darkMode ? '1px solid rgba(255,255,255,0.1)' : '1px solid rgba(0,0,0,0.08)',
                color: darkMode ? 'rgba(255,255,255,0.5)' : 'rgba(0,0,0,0.4)',
                fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700,
                letterSpacing: '0.03em', textTransform: 'uppercase',
                cursor: 'pointer',
                transition: 'all 0.2s',
              }}>Clear All</button>
            )}
            <button onClick={handleApply} style={{
              flex: 2,
              padding: '14px 20px', minHeight: 48,
              borderRadius: radius,
              background: 'var(--international-orange)',
              border: 'none',
              color: '#fff',
              fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700,
              letterSpacing: '0.03em', textTransform: 'uppercase',
              cursor: 'pointer',
              transition: 'all 0.2s',
              boxShadow: '0 4px 20px rgba(255,79,0,0.3)',
            }}
            onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 8px 28px rgba(255,79,0,0.4)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '0 4px 20px rgba(255,79,0,0.3)'; }}
            >
              {totalSelected > 0 ? `Show Events (${totalSelected})` : 'Show All Events'}
            </button>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

window.FilterPopup = FilterPopup;
window.SelectorChips = SelectorChips;
