// Autoresearch sub-section of the Research tab.
// A single Run button kicks off the crawler against every direction in
// search_directions.json. Source toggles mirror the Search card.
const { useState: useARState, useEffect: useAREffect, useRef: useARRef } = React;

window.AutoresearchPanel = function AutoresearchPanel({
  sources,      // { foreplay: true, adspy: false, ... }
  onToggleSource, // (key) => void
  onSelectAllSources, // () => void — enables every *live* source in one click
  perDirectionTarget,    // string | number — how many winning ads to find per direction
  onPerDirectionTarget,  // (value) => void
  numDirections,         // string | number — how many directions to crawl (cap)
  onNumDirections,       // (value) => void
  directions,            // [{ id, display_name, brand_name, type }]
  pickedDirections,      // Set<string> — explicit direction ids (empty = auto-pick by numDirections)
  onTogglePickedDirection, // (id) => void
  onClearPickedDirections, // () => void
  onRun,        // () => void
  onStop,       // () => void
  running,      // boolean
  progress,     // { crawlState, totalScored, winners, directionsSatisfied, directionsTotal, creditsRemaining } | null
  disabled,     // boolean
}) {
  const liveKeys = Object.keys(PLATFORMS).filter(k => k === 'foreplay' || k === 'adspy' || k === 'brandsearch');
  const allOn = liveKeys.length > 0 && liveKeys.every(k => sources[k]);
  const sourceLabel = liveKeys.filter(k => sources[k]).map(k => PLATFORMS[k].label).join(' + ') || 'sources';
  const showProgress = running || (progress && progress.crawlState && progress.crawlState !== 'idle');
  const dirPct = progress && progress.directionsTotal
    ? Math.min(100, Math.round((progress.directionsSatisfied || 0) * 100 / progress.directionsTotal))
    : 0;
  const picked = pickedDirections || new Set();
  const dirs = Array.isArray(directions) ? directions : [];
  const randomDirs = sources?.brandsearch ? dirs : dirs.filter(d => d.type !== 'competitor');
  const labelFor = (d) => d.display_name || d.brand_name || d.id;
  const capNum = Math.max(1, parseInt(numDirections, 10) || 5);
  const pickerLabel = picked.size > 0
    ? `${picked.size} direction${picked.size === 1 ? '' : 's'} selected`
    : `Random ${Math.min(capNum, randomDirs.length)} of ${randomDirs.length}`;

  const [pickerOpen, setPickerOpen] = useARState(false);
  const pickerRef = useARRef(null);
  useAREffect(() => {
    if (!pickerOpen) return;
    const onClick = (e) => {
      if (pickerRef.current && !pickerRef.current.contains(e.target)) setPickerOpen(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') setPickerOpen(false); };
    document.addEventListener('mousedown', onClick);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [pickerOpen]);
  return (
    <div className="search-card ar-card">
      <div className="sc-hdr">
        <span className="sc-title">Autoresearch</span>
        <div className="sc-actions">
          {running ? (
            <button className="btn-secondary" onClick={onStop}>
              <Icon name="x" size={14} /> Stop
            </button>
          ) : (
            <button className="btn-primary" onClick={onRun} disabled={disabled}>
              <Icon name="bolt" size={14} /> Run Autoresearch
            </button>
          )}
        </div>
      </div>
      {showProgress && (
        <div className="ar-progress">
          <div className="ar-progress-head">
            <span className={`ar-spinner ${running ? 'spin' : ''}`} />
            <span className="ar-progress-status">
              {progress?.crawlState === 'starting' || !progress?.crawlState
                ? 'Starting autoresearch…'
                : progress?.crawlState === 'done'
                  ? 'Autoresearch complete'
                  : `Scanning ${sourceLabel}…`}
            </span>
            <span className="ar-progress-meta">
              {(progress?.totalScored || 0)} scored · {(progress?.winners || 0)} winners · {(progress?.directionsSatisfied || 0)}/{(progress?.directionsTotal || 0)} directions
              {typeof progress?.creditsRemaining === 'number' ? ` · ${progress.creditsRemaining} credits left` : ''}
            </span>
          </div>
          <div className="ar-progress-bar">
            <div className="ar-progress-fill" style={{ width: `${dirPct}%` }} />
          </div>
        </div>
      )}
      <div className="ar-sources">
        <label className="ar-target">
          <span>Directions to crawl</span>
          <input
            type="number"
            min={1}
            max={30}
            value={numDirections}
            placeholder="5"
            onChange={(e) => onNumDirections(e.target.value)}
            title="How many directions to search this run. Ignored when you pick specific directions below."
          />
        </label>
        <label className="ar-target">
          <span>Winners per direction</span>
          <input
            type="number"
            min={1}
            max={50}
            value={perDirectionTarget}
            placeholder="1"
            onChange={(e) => onPerDirectionTarget(e.target.value)}
          />
        </label>
        <div className="ar-sources-spacer" />
        <button
          className={`plat-toggle ${allOn ? 'on' : 'off'}`}
          onClick={onSelectAllSources}
          title="Select every live source"
        >
          <span className="plat-dot" style={{ background: allOn ? 'var(--accent-1)' : '#b2b8c2' }} />
          All
        </button>
        {Object.entries(PLATFORMS).map(([key, p]) => {
          const on = !!sources[key];
          const live = key === 'foreplay' || key === 'adspy' || key === 'brandsearch';
          return (
            <button
              key={key}
              className={`plat-toggle ${on ? 'on' : 'off'}`}
              onClick={() => live && onToggleSource(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>
      {dirs.length > 0 && (
        <div className="ar-dirs" ref={pickerRef}>
          <button
            type="button"
            className={`ar-dirs-trigger ${picked.size > 0 ? 'active' : ''}`}
            onClick={() => setPickerOpen(o => !o)}
            aria-expanded={pickerOpen}
            aria-haspopup="listbox"
          >
            <span className="ar-dirs-trigger-label">Directions</span>
            <span className="ar-dirs-trigger-value">{pickerLabel}</span>
            <span className={`ar-dirs-chevron ${pickerOpen ? 'up' : ''}`}>
              <Icon name="chevronDown" size={14} />
            </span>
          </button>
          {pickerOpen && (
            <div className="ar-dirs-popover" role="listbox">
              <div className="ar-dirs-popover-head">
                <span className="ar-dirs-popover-hint">
                  {picked.size === 0
                    ? `No picks → run will randomly sample ${Math.min(capNum, randomDirs.length)} of ${randomDirs.length}. BrandSearch includes competitor brand lookups.`
                    : `${picked.size} picked — only these will run.`}
                </span>
                {picked.size > 0 && (
                  <button className="ar-dirs-clear" onClick={onClearPickedDirections}>
                    Clear
                  </button>
                )}
              </div>
              <div className="ar-dirs-grid">
                {dirs.map((d) => {
                  const on = picked.has(d.id);
                  return (
                    <label key={d.id} className={`ar-dir-pill ${on ? 'on' : 'off'}`}>
                      <input
                        type="checkbox"
                        checked={on}
                        onChange={() => onTogglePickedDirection(d.id)}
                      />
                      <span className="ar-dir-label">{labelFor(d)}</span>
                    </label>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};
