const { useState: useStateSR } = React;
const ALL_COMPETITORS_ID = '__all_competitors__';

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 onCompetitor = (e) => {
    const competitorId = e.target.value || null;
    onChange({ ...row, competitorId });
  };
  const allCompetitorsSet = row.competitorId === ALL_COMPETITORS_ID;
  const competitorSet = !!row.competitorId;
  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' : ''}`}>
      <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>
        {(competitors || []).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}
        onChange={(e) => onChange({ ...row, count: +e.target.value })}
      />
      <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>
      {foreplayEnabled && (
        <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>
          <label className="sr-mini wide" title="Foreplay publisher platforms, comma-separated">
            <span>Pub</span>
            <input
              value={filters.fpPublisherPlatforms || ''}
              onChange={(e) => setFilter('fpPublisherPlatforms', e.target.value)}
              placeholder="facebook, instagram"
            />
          </label>
          <label className="sr-mini" title="Foreplay languages, comma-separated">
            <span>Lang</span>
            <input
              value={filters.fpLanguages || ''}
              onChange={(e) => setFilter('fpLanguages', e.target.value)}
              placeholder="en"
            />
          </label>
        </div>
      )}
      {adspyEnabled && (
        <div className="sr-adspy-filters">
          <select
            className="sr-input sr-mini-select"
            value={filters.adspySiteType || ''}
            onChange={(e) => setFilter('adspySiteType', e.target.value)}
            title="AdSpy social platform"
          >
            <option value="">FB+IG</option>
            <option value="facebook">Facebook</option>
            <option value="instagram">Instagram</option>
          </select>
          <select
            className="sr-input sr-mini-select"
            value={filters.adspyMediaType || ''}
            onChange={(e) => setFilter('adspyMediaType', e.target.value)}
            title="AdSpy media type"
          >
            <option value="">Any format</option>
            <option value="video">Video</option>
            <option value="photo">Photo</option>
          </select>
          <select
            className="sr-input sr-mini-select"
            value={filters.adspyGender || ''}
            onChange={(e) => setFilter('adspyGender', e.target.value)}
            title="AdSpy gender filter"
          >
            <option value="">Any gender</option>
            <option value="female">Female</option>
            <option value="male">Male</option>
          </select>
          <label className="sr-mini" title="Minimum age for AdSpy results">
            <span>Age</span>
            <input
              type="number"
              min="18"
              max="64"
              value={filters.adspyAgeMin || ''}
              onChange={(e) => setFilter('adspyAgeMin', e.target.value)}
              placeholder="18"
            />
          </label>
          <label className="sr-mini" title="Maximum age for AdSpy results">
            <span>To</span>
            <input
              type="number"
              min="18"
              max="64"
              value={filters.adspyAgeMax || ''}
              onChange={(e) => setFilter('adspyAgeMax', e.target.value)}
              placeholder="64"
            />
          </label>
          <label className="sr-mini" title="Minimum total likes for AdSpy results">
            <span>Likes</span>
            <input
              type="number"
              min="0"
              value={filters.minLikes || ''}
              onChange={(e) => setFilter('minLikes', e.target.value)}
              placeholder="0"
            />
          </label>
          <label className="sr-mini" title="Minimum daily likes for AdSpy results">
            <span>Daily</span>
            <input
              type="number"
              min="0"
              value={filters.minDailyLikes || ''}
              onChange={(e) => setFilter('minDailyLikes', e.target.value)}
              placeholder="0"
            />
          </label>
          <select
            className="sr-input sr-mini-select"
            value={filters.orderBy || ''}
            onChange={(e) => setFilter('orderBy', e.target.value)}
            title="AdSpy sort order"
          >
            <option value="">Sort</option>
            <option value="total_likes">Likes</option>
            <option value="total_shares">Shares</option>
            <option value="created_on_asc">Oldest</option>
          </select>
          <label className="sr-mini wide" title="Country codes for AdSpy, comma-separated">
            <span>Geo</span>
            <input
              value={filters.adspyCountries || ''}
              onChange={(e) => setFilter('adspyCountries', e.target.value)}
              placeholder="US,GB"
            />
          </label>
          <label className="sr-mini" title="Ad language, e.g. eng">
            <span>Lang</span>
            <input
              value={filters.adspyLang || ''}
              onChange={(e) => setFilter('adspyLang', e.target.value)}
              placeholder="eng"
            />
          </label>
          <label className="sr-mini wide" title="Advertiser username exact match">
            <span>User</span>
            <input
              value={filters.adspyUsername || ''}
              onChange={(e) => setFilter('adspyUsername', e.target.value)}
              placeholder="username"
            />
          </label>
          <label className="sr-mini wide" title="Advertiser user ID / page ID exact match">
            <span>ID</span>
            <input
              type="number"
              min="1"
              value={filters.adspyUserId || ''}
              onChange={(e) => setFilter('adspyUserId', e.target.value)}
              placeholder="page id"
            />
          </label>
          <label className="sr-mini wide" title="Affiliate network ID">
            <span>Net</span>
            <input
              type="number"
              min="1"
              value={filters.adspyAffNetwork || ''}
              onChange={(e) => setFilter('adspyAffNetwork', e.target.value)}
              placeholder="id"
            />
          </label>
          <label className="sr-mini wide" title="Affiliate ID exact match">
            <span>Aff</span>
            <input
              value={filters.adspyAffId || ''}
              onChange={(e) => setFilter('adspyAffId', e.target.value)}
              placeholder="aff id"
            />
          </label>
          <label className="sr-mini wide" title="Offer ID exact match">
            <span>Offer</span>
            <input
              value={filters.adspyOfferId || ''}
              onChange={(e) => setFilter('adspyOfferId', e.target.value)}
              placeholder="offer id"
            />
          </label>
          <label className="sr-mini wide" title="CTA buttons, comma-separated">
            <span>CTA</span>
            <input
              value={filters.adspyButtons || ''}
              onChange={(e) => setFilter('adspyButtons', e.target.value)}
              placeholder="Shop Now"
            />
          </label>
          <label className="sr-mini date" title="Created from date, YYYY-MM-DD">
            <span>Created</span>
            <input
              value={filters.adspyCreatedFrom || ''}
              onChange={(e) => setFilter('adspyCreatedFrom', e.target.value)}
              placeholder="2026-05-01"
            />
          </label>
          <label className="sr-mini date" title="Created to date, YYYY-MM-DD">
            <span>To</span>
            <input
              value={filters.adspyCreatedTo || ''}
              onChange={(e) => setFilter('adspyCreatedTo', e.target.value)}
              placeholder="2026-05-03"
            />
          </label>
          <label className="sr-mini date" title="Seen from date, YYYY-MM-DD">
            <span>Seen</span>
            <input
              value={filters.adspySeenFrom || ''}
              onChange={(e) => setFilter('adspySeenFrom', e.target.value)}
              placeholder="2026-05-01"
            />
          </label>
          <label className="sr-mini date" title="Seen to date, YYYY-MM-DD">
            <span>To</span>
            <input
              value={filters.adspySeenTo || ''}
              onChange={(e) => setFilter('adspySeenTo', e.target.value)}
              placeholder="2026-05-03"
            />
          </label>
        </div>
      )}
      {brandsearchEnabled && (
        <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>
          <label className="sr-mini" title="Minimum views or plays for BrandSearch social ads">
            <span>Views</span>
            <input
              type="number"
              min="0"
              value={filters.bsMinViews || ''}
              onChange={(e) => setFilter('bsMinViews', e.target.value)}
              placeholder="0"
            />
          </label>
          <label className="sr-mini" title="Minimum likes for BrandSearch social ads">
            <span>Likes</span>
            <input
              type="number"
              min="0"
              value={filters.bsMinLikes || ''}
              onChange={(e) => setFilter('bsMinLikes', e.target.value)}
              placeholder="0"
            />
          </label>
          <label className="sr-mini" title="Minimum BrandSearch engagement rate">
            <span>ER%</span>
            <input
              type="number"
              min="0"
              step="0.1"
              value={filters.bsMinEngagement || ''}
              onChange={(e) => setFilter('bsMinEngagement', e.target.value)}
              placeholder="0"
            />
          </label>
          <select
            className="sr-input sr-mini-select"
            value={filters.bsSort || ''}
            onChange={(e) => setFilter('bsSort', e.target.value)}
            title="BrandSearch sort order"
          >
            <option value="">Sort</option>
            <option value="play_count">Views</option>
            <option value="like_count">Likes</option>
            <option value="engagement_rate">ER%</option>
            <option value="eu_total_reach">Reach</option>
            <option value="eu_total_spend">Spend</option>
          </select>
        </div>
      )}
      {(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>
  );
};
