const { useEffect: useEffectSR, useRef: useRefSR, useState: useStateSR } = React;
const ALL_COMPETITORS_ID = '__all_competitors__';
const FOREPLAY_PUBLISHER_OPTIONS = [
  ['facebook', 'Facebook'],
  ['instagram', 'Instagram'],
  ['tiktok', 'TikTok'],
  ['youtube', 'YouTube'],
];
const FOREPLAY_LANGUAGE_OPTIONS = [
  ['en', 'English'],
  ['es', 'Spanish'],
  ['fr', 'French'],
  ['de', 'German'],
  ['pt', 'Portuguese'],
  ['it', 'Italian'],
  ['nl', 'Dutch'],
  ['ar', 'Arabic'],
  ['hi', 'Hindi'],
];
const ADSPY_CTA_OPTIONS = [
  'Learn More',
  'Shop Now',
  'Sign Up',
  'Send Message',
];
const splitFilterList = (value) => String(value || '').split(',').map(s => s.trim()).filter(Boolean);
const selectedValues = (event) => Array.from(event.target.selectedOptions || []).map(o => o.value).filter(Boolean);
const joinFilterList = (values) => [...new Set((values || []).map(v => String(v || '').trim()).filter(Boolean))].join(', ');
const ADSPY_COUNTRY_OPTIONS = ['US', 'UK', 'CA', 'AU', 'DE', 'FR', 'ES', 'IT', 'NL', 'BR'];
const ADSPY_LANGUAGE_OPTIONS = [
  ['eng', 'English'],
  ['spa', 'Spanish'],
  ['fre', 'French'],
  ['ger', 'German'],
  ['por', 'Portuguese'],
  ['ita', 'Italian'],
  ['dut', 'Dutch'],
];
const ADSPY_DROPDOWN_LABELS = [
  'siteType', 'gender', 'ages', 'dailyLikes', 'totalLikes',
  'mediaType', 'createdBetween', 'seenBetween', 'networks', 'affiliate',
  'advertiser', 'technologies', 'countries', 'language', 'buttons',
];
const adspyFilterIsActive = (filters, id) => {
  if (id === 'siteType') return !!filters.adspySiteType;
  if (id === 'mediaType') return !!filters.adspyMediaType;
  if (id === 'gender') return !!filters.adspyGender;
  if (id === 'ages') return !!(filters.adspyAgeMin || filters.adspyAgeMax);
  if (id === 'dailyLikes') return !!(filters.minDailyLikes || filters.maxDailyLikes);
  if (id === 'totalLikes') return !!(filters.minLikes || filters.maxLikes);
  if (id === 'createdBetween') return !!(filters.adspyCreatedFrom || filters.adspyCreatedTo);
  if (id === 'seenBetween') return !!(filters.adspySeenFrom || filters.adspySeenTo);
  if (id === 'networks') return !!filters.adspyAffNetwork;
  if (id === 'affiliate') return !!(filters.adspyAffId || filters.adspyOfferId);
  if (id === 'advertiser') return !!(filters.adspyUsername || filters.adspyUserId);
  if (id === 'technologies') return !!filters.adspyTech;
  if (id === 'countries') return !!filters.adspyCountries;
  if (id === 'language') return !!filters.adspyLang;
  if (id === 'buttons') return filters.adspyCtaMode === 'custom' || !!filters.adspyButtons;
  return false;
};
const optionLabel = (options, value) => {
  const match = (options || []).find(option => {
    const optionValue = Array.isArray(option) ? option[0] : option;
    return String(optionValue) === String(value);
  });
  if (!match) return value ? String(value) : '';
  return Array.isArray(match) ? match[1] : match;
};
const compactListPreview = (value, options, maxItems = 2) => {
  const values = splitFilterList(value);
  if (!values.length) return '';
  const labels = values.map(item => optionLabel(options, item)).filter(Boolean);
  if (labels.length <= maxItems) return labels.join(', ');
  return `${labels.slice(0, maxItems).join(', ')} +${labels.length - maxItems}`;
};
const rangePreview = (minValue, maxValue, { defaultMin = '', defaultMax = '', suffix = '' } = {}) => {
  const minText = minValue || defaultMin;
  const maxText = maxValue || defaultMax;
  if (!minValue && !maxValue) return '';
  if (minText && maxText) return `${minText}-${maxText}${suffix}`;
  if (minText) return `Min ${minText}${suffix}`;
  return `Max ${maxText}${suffix}`;
};
const numberPreview = (value) => {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed.toLocaleString() : String(value || '');
};
const AdspyDropdown = ({ id, label, preview, active, open, onToggle, onClose, onReset, children }) => {
  const dropdownRef = useRefSR(null);

  useEffectSR(() => {
    if (!open) return undefined;
    const onMouseDown = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        onClose?.();
      }
    };
    const onKeyDown = (event) => {
      if (event.key === 'Escape') onClose?.();
    };
    document.addEventListener('mousedown', onMouseDown);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('mousedown', onMouseDown);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [open, onClose]);

  return (
    <div ref={dropdownRef} className={`adspy-dd ${open ? 'open' : ''}${active ? ' active' : ''}`}>
      <button type="button" className="adspy-dd-trigger" onClick={() => onToggle(id)}>
        <span className="adspy-dd-trigger-text">
          <span className="adspy-dd-label">{label}</span>
          {preview ? <small className="adspy-dd-preview">{preview}</small> : null}
        </span>
        <Icon name="chevronDown" size={14} />
      </button>
      {open && (
        <div className="adspy-dd-menu">
          <div className="adspy-dd-body">{children}</div>
          <button type="button" className="adspy-dd-reset" onClick={onReset}>
            <Icon name="x" size={14} /> Reset
          </button>
        </div>
      )}
    </div>
  );
};
const AdspyRadio = ({ name, value, options, onChange }) => (
  <div className="adspy-dd-options">
    {options.map(([optionValue, label]) => (
      <label key={String(optionValue || 'all')} className="adspy-dd-option">
        <input
          type="radio"
          name={name}
          checked={(value || '') === optionValue}
          onChange={() => onChange(optionValue)}
        />
        <span>{label}</span>
      </label>
    ))}
  </div>
);
const AdspyChecks = ({ values, options, onChange }) => {
  const selected = new Set(splitFilterList(values));
  const toggle = (value) => {
    const next = new Set(selected);
    next.has(value) ? next.delete(value) : next.add(value);
    onChange(joinFilterList([...next]));
  };
  return (
    <div className="adspy-dd-options adspy-dd-scroll">
      {options.map(option => {
        const value = Array.isArray(option) ? option[0] : option;
        const label = Array.isArray(option) ? option[1] : option;
        return (
          <label key={value} className="adspy-dd-option">
            <input type="checkbox" checked={selected.has(value)} onChange={() => toggle(value)} />
            <span>{label}</span>
          </label>
        );
      })}
    </div>
  );
};
const RANGE_UI_MAX = 1000;
const LARGE_RANGE_CURVE = 2.4;
const curvedRangeEnabled = (min, max) => min === 0 && max > 100;
const valueToSliderPosition = (value, max) => Math.round(
  Math.pow(Math.max(0, Math.min(max, value)) / max, 1 / LARGE_RANGE_CURVE) * RANGE_UI_MAX,
);
const sliderPositionToValue = (position, max) => Math.round(
  max * Math.pow(Math.max(0, Math.min(RANGE_UI_MAX, position)) / RANGE_UI_MAX, LARGE_RANGE_CURVE),
);
const AdspyRange = ({ label, min, max, value, onChange }) => {
  const numeric = Math.max(min, Math.min(max, parseInt(value, 10) || min));
  const useCurvedScale = curvedRangeEnabled(min, max);
  const sliderValue = useCurvedScale ? valueToSliderPosition(numeric, max) : numeric;
  const sliderMax = useCurvedScale ? RANGE_UI_MAX : max;
  const displayValue = numeric.toLocaleString();
  return (
    <label className="adspy-dd-range">
      <span>{label}: {displayValue}{numeric >= max && max === 65 ? '+' : ''}</span>
      <input
        type="range"
        min={useCurvedScale ? 0 : min}
        max={sliderMax}
        value={sliderValue}
        step={1}
        onChange={(e) => {
          const next = useCurvedScale
            ? sliderPositionToValue(Number(e.target.value), max)
            : Number(e.target.value);
          onChange(String(next));
        }}
      />
      {useCurvedScale && <small>Fine control at low values, full range up to {max.toLocaleString()}.</small>}
    </label>
  );
};
const AdspyText = ({ label, value, onChange, type = 'text' }) => (
  <label className="adspy-dd-field">
    <strong>{label}</strong>
    <input type={type} value={value || ''} onChange={(e) => onChange(e.target.value)} />
  </label>
);

window.PlatformFilterSections = function PlatformFilterSections({
  filters = {},
  platforms = {},
  onFilterChange,
  onFiltersChange,
  idPrefix = 'filters',
}) {
  const [openForeplayFilter, setOpenForeplayFilter] = useStateSR(null);
  const [openAdspyFilter, setOpenAdspyFilter] = useStateSR(null);
  const [openBrandFilter, setOpenBrandFilter] = useStateSR(null);
  const foreplayEnabled = !!platforms?.foreplay;
  const adspyEnabled = !!platforms?.adspy;
  const brandsearchEnabled = !!platforms?.brandsearch;
  const setFilter = (key, value) => onFilterChange?.(key, value);
  const setFilters = (patch) => {
    if (onFiltersChange) onFiltersChange(patch);
    else Object.entries(patch || {}).forEach(([key, value]) => setFilter(key, value));
  };
  const ctaOptionSet = new Set(ADSPY_CTA_OPTIONS);
  const adspyCtaMode = filters.adspyCtaMode || (filters.adspyButtons ? 'custom' : 'all');
  const adspyButtons = splitFilterList(filters.adspyButtons);
  const selectedAdspyButtons = adspyButtons.length
    ? adspyButtons.filter(value => ctaOptionSet.has(value))
    : ADSPY_CTA_OPTIONS;
  const customAdspyButtons = adspyButtons.filter(value => !ctaOptionSet.has(value));
  const setAdspyCtaMode = (mode) => {
    if (mode === 'custom') {
      setFilters({
        adspyCtaMode: 'custom',
        adspyButtons: filters.adspyButtons || joinFilterList(ADSPY_CTA_OPTIONS),
      });
      return;
    }
    setFilters({ adspyCtaMode: 'all', adspyButtons: '' });
  };
  const setAdspyButtons = (selected, customText) => {
    setFilters({
      adspyCtaMode: 'custom',
      adspyButtons: joinFilterList([
        ...(selected || []),
        ...splitFilterList(customText),
      ]),
    });
  };
  const resetAdspyFilter = (id) => {
    const resets = {
      siteType: { adspySiteType: '' },
      gender: { adspyGender: '' },
      ages: { adspyAgeMin: '', adspyAgeMax: '' },
      dailyLikes: { minDailyLikes: '', maxDailyLikes: '' },
      totalLikes: { minLikes: '', maxLikes: '' },
      mediaType: { adspyMediaType: '' },
      createdBetween: { adspyCreatedFrom: '', adspyCreatedTo: '' },
      seenBetween: { adspySeenFrom: '', adspySeenTo: '' },
      networks: { adspyAffNetwork: '' },
      affiliate: { adspyAffId: '', adspyOfferId: '' },
      advertiser: { adspyUsername: '', adspyUserId: '' },
      technologies: { adspyTech: '' },
      countries: { adspyCountries: '' },
      language: { adspyLang: '' },
      buttons: { adspyCtaMode: 'all', adspyButtons: '' },
    };
    setFilters(resets[id] || {});
  };
  const adspyFilterPreview = (id) => {
    if (id === 'siteType') return optionLabel([['facebook', 'Facebook'], ['instagram', 'Instagram']], filters.adspySiteType);
    if (id === 'mediaType') return optionLabel([['video', 'Video'], ['photo', 'Photo']], filters.adspyMediaType);
    if (id === 'gender') return optionLabel([['female', 'Female'], ['male', 'Male']], filters.adspyGender);
    if (id === 'ages') return rangePreview(filters.adspyAgeMin, filters.adspyAgeMax, { defaultMin: '18', defaultMax: '65' });
    if (id === 'dailyLikes') return rangePreview(filters.minDailyLikes, filters.maxDailyLikes, { suffix: '/day' });
    if (id === 'totalLikes') return rangePreview(filters.minLikes, filters.maxLikes, { suffix: ' likes' });
    if (id === 'createdBetween') return rangePreview(filters.adspyCreatedFrom, filters.adspyCreatedTo);
    if (id === 'seenBetween') return rangePreview(filters.adspySeenFrom, filters.adspySeenTo);
    if (id === 'networks') return filters.adspyAffNetwork ? `ID ${filters.adspyAffNetwork}` : '';
    if (id === 'affiliate') {
      return [filters.adspyAffId && `Aff ${filters.adspyAffId}`, filters.adspyOfferId && `Offer ${filters.adspyOfferId}`]
        .filter(Boolean)
        .join(', ');
    }
    if (id === 'advertiser') {
      return [filters.adspyUsername, filters.adspyUserId && `Page ${filters.adspyUserId}`]
        .filter(Boolean)
        .join(', ');
    }
    if (id === 'technologies') return compactListPreview(filters.adspyTech, []);
    if (id === 'countries') return compactListPreview(filters.adspyCountries, ADSPY_COUNTRY_OPTIONS);
    if (id === 'language') return optionLabel(ADSPY_LANGUAGE_OPTIONS, filters.adspyLang);
    if (id === 'buttons') {
      if (adspyCtaMode !== 'custom' && !filters.adspyButtons) return '';
      return compactListPreview(filters.adspyButtons || joinFilterList(ADSPY_CTA_OPTIONS), ADSPY_CTA_OPTIONS);
    }
    return '';
  };
  const renderAdspyFilter = (id) => {
    const labels = {
      siteType: 'Site type',
      gender: 'Gender',
      ages: 'Ages',
      dailyLikes: 'Daily likes',
      totalLikes: 'Total likes',
      mediaType: 'Media type',
      createdBetween: 'Created Between',
      seenBetween: 'Seen Between',
      networks: 'Networks',
      affiliate: 'Affiliate',
      advertiser: 'Advertiser',
      technologies: 'Technologies',
      countries: 'Countries',
      language: 'Language',
      buttons: 'Buttons',
    };
    let body = null;
    if (id === 'siteType') {
      body = (
        <AdspyRadio
          name={`${idPrefix}-adspy-site`}
          value={filters.adspySiteType || ''}
          onChange={(value) => setFilter('adspySiteType', value)}
          options={[['', 'Facebook or Instagram'], ['facebook', 'Facebook'], ['instagram', 'Instagram']]}
        />
      );
    } else if (id === 'gender') {
      body = (
        <AdspyRadio
          name={`${idPrefix}-adspy-gender`}
          value={filters.adspyGender || ''}
          onChange={(value) => setFilter('adspyGender', value)}
          options={[['', 'Any gender'], ['female', 'Female'], ['male', 'Male']]}
        />
      );
    } else if (id === 'ages') {
      const minAge = filters.adspyAgeMin || '18';
      const maxAge = filters.adspyAgeMax || '65';
      body = (
        <>
          <div className="adspy-dd-help">From {minAge} to {maxAge}{Number(maxAge) >= 65 ? ' +' : ''}</div>
          <AdspyRange label="Min age" min={18} max={65} value={minAge} onChange={(value) => setFilter('adspyAgeMin', value)} />
          <AdspyRange label="Max age" min={18} max={65} value={maxAge} onChange={(value) => setFilter('adspyAgeMax', value)} />
        </>
      );
    } else if (id === 'dailyLikes') {
      body = (
        <>
          <AdspyRange label="Min daily likes" min={0} max={1000} value={filters.minDailyLikes || '0'} onChange={(value) => setFilter('minDailyLikes', value)} />
          <AdspyRange label="Max daily likes" min={0} max={1000} value={filters.maxDailyLikes || '1000'} onChange={(value) => setFilter('maxDailyLikes', value)} />
        </>
      );
    } else if (id === 'totalLikes') {
      body = (
        <>
          <AdspyRange label="Min total likes" min={0} max={100000} value={filters.minLikes || '0'} onChange={(value) => setFilter('minLikes', value)} />
          <AdspyRange label="Max total likes" min={0} max={100000} value={filters.maxLikes || '100000'} onChange={(value) => setFilter('maxLikes', value)} />
        </>
      );
    } else if (id === 'mediaType') {
      body = (
        <AdspyRadio
          name={`${idPrefix}-adspy-media`}
          value={filters.adspyMediaType || ''}
          onChange={(value) => setFilter('adspyMediaType', value)}
          options={[['', 'Any media type'], ['video', 'Video'], ['photo', 'Photo']]}
        />
      );
    } else if (id === 'createdBetween') {
      body = (
        <>
          <AdspyText label="Created from" type="date" value={filters.adspyCreatedFrom} onChange={(value) => setFilter('adspyCreatedFrom', value)} />
          <AdspyText label="Created to" type="date" value={filters.adspyCreatedTo} onChange={(value) => setFilter('adspyCreatedTo', value)} />
        </>
      );
    } else if (id === 'seenBetween') {
      body = (
        <>
          <AdspyText label="Seen from" type="date" value={filters.adspySeenFrom} onChange={(value) => setFilter('adspySeenFrom', value)} />
          <AdspyText label="Seen to" type="date" value={filters.adspySeenTo} onChange={(value) => setFilter('adspySeenTo', value)} />
        </>
      );
    } else if (id === 'networks') {
      body = (
        <AdspyText
          label="Affiliate Network ID"
          type="number"
          value={filters.adspyAffNetwork}
          onChange={(value) => setFilter('adspyAffNetwork', value)}
        />
      );
    } else if (id === 'affiliate') {
      body = (
        <>
          <AdspyText label="Affiliate ID" value={filters.adspyAffId} onChange={(value) => setFilter('adspyAffId', value)} />
          <AdspyText label="Offer ID" value={filters.adspyOfferId} onChange={(value) => setFilter('adspyOfferId', value)} />
        </>
      );
    } else if (id === 'advertiser') {
      body = (
        <>
          <AdspyText label="Advertiser" value={filters.adspyUsername} onChange={(value) => setFilter('adspyUsername', value)} />
          <AdspyText label="Page ID" type="number" value={filters.adspyUserId} onChange={(value) => setFilter('adspyUserId', value)} />
        </>
      );
    } else if (id === 'technologies') {
      body = (
        <AdspyText
          label="Technology IDs"
          value={filters.adspyTech}
          onChange={(value) => setFilter('adspyTech', value)}
        />
      );
    } else if (id === 'countries') {
      body = <AdspyChecks values={filters.adspyCountries} options={ADSPY_COUNTRY_OPTIONS} onChange={(value) => setFilter('adspyCountries', value)} />;
    } else if (id === 'language') {
      body = <AdspyRadio name={`${idPrefix}-adspy-lang`} value={filters.adspyLang || ''} onChange={(value) => setFilter('adspyLang', value)} options={[['', 'Any language'], ...ADSPY_LANGUAGE_OPTIONS]} />;
    } else if (id === 'buttons') {
      body = (
        <>
          <AdspyRadio
            name={`${idPrefix}-adspy-cta`}
            value={adspyCtaMode}
            onChange={setAdspyCtaMode}
            options={[['all', 'All buttons'], ['custom', 'Choose buttons']]}
          />
          {adspyCtaMode === 'custom' && (
            <>
              <AdspyChecks values={joinFilterList(selectedAdspyButtons)} options={ADSPY_CTA_OPTIONS} onChange={(value) => setAdspyButtons(splitFilterList(value), customAdspyButtons.join(', '))} />
              <AdspyText label="Custom CTA" value={customAdspyButtons.join(', ')} onChange={(value) => setAdspyButtons(selectedAdspyButtons, value)} />
            </>
          )}
        </>
      );
    }
    return (
      <AdspyDropdown
        key={id}
        id={`${idPrefix}-${id}`}
        label={labels[id]}
        preview={adspyFilterPreview(id)}
        open={openAdspyFilter === id}
        active={adspyFilterIsActive(filters, id)}
        onToggle={() => setOpenAdspyFilter(openAdspyFilter === id ? null : id)}
        onClose={() => setOpenAdspyFilter(null)}
        onReset={() => resetAdspyFilter(id)}
      >
        {body}
      </AdspyDropdown>
    );
  };
  const brandSlider = ({ id, label, filterKey, max, suffix = '' }) => (
    <AdspyDropdown
      key={id}
      id={`${idPrefix}-${id}`}
      label={label}
      preview={filters[filterKey] ? `Min ${numberPreview(filters[filterKey])}` : ''}
      open={openBrandFilter === id}
      active={!!filters[filterKey]}
      onToggle={() => setOpenBrandFilter(openBrandFilter === id ? null : id)}
      onClose={() => setOpenBrandFilter(null)}
      onReset={() => setFilter(filterKey, '')}
    >
      <AdspyRange
        label={`Min ${label}`}
        min={0}
        max={max}
        value={filters[filterKey] || '0'}
        onChange={(value) => setFilter(filterKey, value)}
      />
      {suffix && <div className="adspy-dd-help">Value is sent as minimum {suffix}.</div>}
    </AdspyDropdown>
  );
  return (
    <>
      {foreplayEnabled && (
        <section className="sr-filter-section sr-filter-section-foreplay">
          <div className="sr-filter-section-head">
            <span><i aria-hidden="true" /> Foreplay filters</span>
          </div>
          <div className="sr-foreplay-filters">
            <select
              className="sr-input sr-mini-select"
              value={filters.fpLiveStatus || ''}
              onChange={(e) => setFilter('fpLiveStatus', e.target.value)}
              title="Foreplay ad status"
            >
              <option value="">Any status</option>
              <option value="live">Live ads</option>
              <option value="inactive">Inactive ads</option>
            </select>
            <label className="sr-mini" title="Minimum days running for Foreplay ads">
              <span>Days</span>
              <input
                type="number"
                min="0"
                value={filters.fpMinDays || ''}
                onChange={(e) => setFilter('fpMinDays', e.target.value)}
                placeholder="15"
              />
            </label>
            <select
              className="sr-input sr-mini-select wide"
              value={filters.fpOrder || ''}
              onChange={(e) => setFilter('fpOrder', e.target.value)}
              title="Foreplay sort order"
            >
              <option value="">Default sort</option>
              <option value="longest_running">Longest running</option>
              <option value="saved_newest">Newest saved</option>
              <option value="saved_oldest">Oldest saved</option>
            </select>
            <select
              className="sr-input sr-mini-select"
              value="video"
              onChange={() => setFilter('fpFormat', 'video')}
              title="Foreplay creative format (locked to video)"
              disabled
            >
              <option value="video">Video</option>
            </select>
            <AdspyDropdown
              id={`${idPrefix}-fp-pub`}
              label="Pub"
              preview={compactListPreview(filters.fpPublisherPlatforms, FOREPLAY_PUBLISHER_OPTIONS)}
              open={openForeplayFilter === 'fp-pub'}
              active={!!filters.fpPublisherPlatforms}
              onToggle={() => setOpenForeplayFilter(openForeplayFilter === 'fp-pub' ? null : 'fp-pub')}
              onClose={() => setOpenForeplayFilter(null)}
              onReset={() => setFilter('fpPublisherPlatforms', '')}
            >
              <AdspyChecks
                values={filters.fpPublisherPlatforms}
                options={FOREPLAY_PUBLISHER_OPTIONS}
                onChange={(value) => setFilter('fpPublisherPlatforms', value)}
              />
            </AdspyDropdown>
            <AdspyDropdown
              id={`${idPrefix}-fp-lang`}
              label="Lang"
              preview={compactListPreview(filters.fpLanguages || 'en', FOREPLAY_LANGUAGE_OPTIONS)}
              open={openForeplayFilter === 'fp-lang'}
              active={!!filters.fpLanguages}
              onToggle={() => setOpenForeplayFilter(openForeplayFilter === 'fp-lang' ? null : 'fp-lang')}
              onClose={() => setOpenForeplayFilter(null)}
              onReset={() => setFilter('fpLanguages', 'en')}
            >
              <AdspyChecks
                values={filters.fpLanguages || 'en'}
                options={FOREPLAY_LANGUAGE_OPTIONS}
                onChange={(value) => setFilter('fpLanguages', value || 'en')}
              />
            </AdspyDropdown>
          </div>
        </section>
      )}
      {adspyEnabled && (
        <section className="sr-filter-section sr-filter-section-adspy">
          <div className="sr-filter-section-head">
            <span><i aria-hidden="true" /> AdSpy filters</span>
          </div>
          <div className="sr-adspy-filters">
            {ADSPY_DROPDOWN_LABELS.map(renderAdspyFilter)}
          </div>
        </section>
      )}
      {brandsearchEnabled && (
        <section className="sr-filter-section sr-filter-section-brandsearch">
          <div className="sr-filter-section-head">
            <span><i aria-hidden="true" /> BrandSearch filters</span>
          </div>
          <div className="sr-brandsearch-filters">
            <select
              className="sr-input sr-mini-select sr-bs-platform"
              value={filters.bsPlatform || ''}
              onChange={(e) => setFilter('bsPlatform', e.target.value)}
              title="BrandSearch ad platform"
            >
              <option value="">All BS</option>
              <option value="meta">Meta</option>
              <option value="tiktok">TikTok</option>
              <option value="instagram">Instagram</option>
            </select>
            {brandSlider({ id: 'bs-views', label: 'Views', filterKey: 'bsMinViews', max: 1000000, suffix: 'views/plays' })}
            {brandSlider({ id: 'bs-likes', label: 'Likes', filterKey: 'bsMinLikes', max: 100000, suffix: 'likes' })}
            {brandSlider({ id: 'bs-er', label: 'ER%', filterKey: 'bsMinEngagement', max: 100, suffix: 'engagement rate' })}
            {brandSlider({ id: 'bs-reach', label: 'Reach', filterKey: 'bsMinReach', max: 1000000, suffix: 'reach' })}
            {brandSlider({ id: 'bs-min-spend', label: 'Min spend', filterKey: 'bsMinSpend', max: 100000, suffix: 'spend' })}
            {brandSlider({ id: 'bs-max-spend', label: 'Max spend', filterKey: 'bsMaxSpend', max: 100000, suffix: 'spend cap' })}
          </div>
        </section>
      )}
    </>
  );
};

window.SearchRow = function SearchRow({ row, onChange, onRemove, onSearch, searching, canRemove, competitors }) {
  const filters = row.filters || {};
  const togglePlatform = (p) => {
    const next = {
      foreplay: !!row.platforms?.foreplay,
      adspy: !!row.platforms?.adspy,
      brandsearch: !!row.platforms?.brandsearch,
      metaads: false,
    };
    next[p] = !next[p];
    onChange({ ...row, platforms: next });
  };
  const selectAllPlatforms = () => onChange({
    ...row,
    platforms: { foreplay: true, adspy: true, brandsearch: true, metaads: false },
  });
  const setFilter = (key, value) => {
    onChange({ ...row, filters: { ...filters, [key]: value } });
  };
  const setFilters = (patch) => {
    onChange({ ...row, filters: { ...filters, ...patch } });
  };
  const onCompetitor = (e) => {
    const competitorId = e.target.value || null;
    onChange({ ...row, competitorId });
  };
  const allCompetitorsSet = row.competitorId === ALL_COMPETITORS_ID;
  const competitorSet = !!row.competitorId;
  const sortedCompetitors = [...(competitors || [])].sort((a, b) => {
    const labelA = String(a?.name || a?.id || '').toLowerCase();
    const labelB = String(b?.name || b?.id || '').toLowerCase();
    return labelA.localeCompare(labelB) || String(a?.id || '').localeCompare(String(b?.id || ''));
  });
  const foreplayEnabled = !!row.platforms?.foreplay;
  const adspyEnabled = !!row.platforms?.adspy;
  const brandsearchEnabled = !!row.platforms?.brandsearch;
  return (
    <div className={`search-row${foreplayEnabled ? ' has-foreplay' : ''}${adspyEnabled ? ' has-adspy' : ''}${brandsearchEnabled ? ' has-brandsearch' : ''}`}>
      <div className="sr-main-controls">
      <select
        className="sr-input sr-select"
        value={row.competitorId || ''}
        onChange={onCompetitor}
        title="Choose keyword-wide search, all competitors, or one competitor"
      >
        <option value="">Keyword search</option>
        <option value={ALL_COMPETITORS_ID}>All competitors</option>
        {sortedCompetitors.map(c => (
          <option key={c.id} value={c.id}>{c.name}</option>
        ))}
      </select>
      <input
        className="sr-input"
        value={row.query}
        onChange={(e) => onChange({ ...row, query: e.target.value })}
        placeholder={allCompetitorsSet ? 'Optional keyword across competitor ads' : competitorSet ? 'Optional keyword within competitor' : 'Brand or keyword (e.g. mushroom coffee)'}
      />
      <input
        className="sr-input sr-num"
        value={row.count}
        type="number"
        min={1}
        max={100}
        title="Total winning ads across selected platforms (minimum ~20% per platform when 2+ platforms are selected)"
        onChange={(e) => onChange({ ...row, count: +e.target.value })}
      />
      </div>
      <div className="sr-actions">
      <div className="sr-toggles">
        {Object.entries(PLATFORMS).map(([key, p]) => {
          const on = row.platforms[key];
          const live = key === 'foreplay' || key === 'adspy' || key === 'brandsearch';
          return (
            <button
              key={key}
              className={`plat-toggle ${on ? 'on' : 'off'}`}
              onClick={() => live && togglePlatform(key)}
              style={on ? { background: p.bg, color: p.color, borderColor: p.bg } : {}}
              title={live ? `Toggle ${p.label}` : `${p.label} — backend not wired yet`}
              disabled={!live}
            >
              <span className="plat-dot" style={{ background: on ? p.color : '#b2b8c2' }} />
              {p.label}
            </button>
          );
        })}
        <button className="plat-toggle all" onClick={selectAllPlatforms} title="Use all live sources">
          All
        </button>
      </div>
      <button
        type="button"
        className="sr-row-search"
        onClick={onSearch}
        disabled={!!searching}
        title="Search only this row"
      >
        {searching ? <><Icon name="loader" size={14} className="icon-spin" /> Searching</> : <><Icon name="search" size={14} /> Search</>}
      </button>
      <button className="icon-btn sr-rm" onClick={onRemove} disabled={!canRemove} title="Remove row">
        <Icon name="trash" size={14} />
      </button>
      </div>
      <PlatformFilterSections
        filters={filters}
        platforms={row.platforms}
        onFilterChange={setFilter}
        onFiltersChange={setFilters}
        idPrefix={`search-row-${row.id}`}
      />
      {(foreplayEnabled || adspyEnabled || brandsearchEnabled) && (
        <div className="sr-url-fields">
          {foreplayEnabled && (
            <input
              className="sr-input sr-url-input"
              value={filters.foreplayUrl || ''}
              onChange={(e) => setFilter('foreplayUrl', e.target.value)}
              placeholder="Foreplay ad URL"
              title="Fetch only this Foreplay ad"
            />
          )}
          {adspyEnabled && (
            <>
              <input
                className="sr-input sr-url-input"
                value={filters.adspyUrl || ''}
                onChange={(e) => setFilter('adspyUrl', e.target.value)}
                placeholder="AdSpy ad URL substring"
                title="Search AdSpy ads containing this URL string"
              />
              <input
                className="sr-input sr-url-input"
                value={filters.adspyLandingUrl || ''}
                onChange={(e) => setFilter('adspyLandingUrl', e.target.value)}
                placeholder="AdSpy landing-page URL substring"
                title="Search AdSpy landing pages containing this URL string"
              />
            </>
          )}
          {brandsearchEnabled && (
            <input
              className="sr-input sr-url-input"
              value={filters.brandsearchUrl || ''}
              onChange={(e) => setFilter('brandsearchUrl', e.target.value)}
              placeholder="BrandSearch ad URL"
              title="Fetch only this BrandSearch ad"
            />
          )}
        </div>
      )}
    </div>
  );
};
