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

window.SearchRow = function SearchRow({ row, onChange, onRemove, canRemove, competitors }) {
  const filters = row.filters || {};
  const togglePlatform = (p) => {
    const next = { ...row.platforms, [p]: !row.platforms[p] };
    onChange({ ...row, platforms: next });
  };
  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${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>
          );
        })}
      </div>
      {adspyEnabled && (
        <div className="sr-adspy-filters">
          <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>
        </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>
      )}
      <button className="icon-btn sr-rm" onClick={onRemove} disabled={!canRemove} title="Remove row">
        <Icon name="trash" size={14} />
      </button>
      {(foreplayEnabled || 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"
            />
          )}
          {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>
  );
};
