// 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 — max current-run winning ads to output
  onPerDirectionTarget,  // (value) => void
  maxAdsPerDirection,    // string | number — optional crawler stop cap
  onMaxAdsPerDirection,  // (value) => void
  maxAdsPerPlatform,     // string | number — optional crawler stop cap
  onMaxAdsPerPlatform,   // (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
  onSelectAllPickedDirections, // () => void
  onRun,        // () => void
  onStop,       // () => void
  running,      // boolean
  progress,     // { crawlState, totalScored, winners, directionsSatisfied, directionsTotal, creditsRemaining } | null
}) {
  const liveKeys = Object.keys(PLATFORMS).filter(k => k === 'foreplay' || k === 'adspy' || k === 'brandsearch');
  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 directionPool = dirs;
  const allPicked = dirs.length > 0 && picked.size >= dirs.length;
  const labelFor = (d) => d.display_name || d.brand_name || d.id;
  const targetMax = window.RESILIA_LIMITS?.autoresearchPerDirectionMax || 1000;
  const adsPerDirectionMax = window.RESILIA_LIMITS?.searchAdsPerDirectionMax || 10000;
  const adsPerPlatformMax = window.RESILIA_LIMITS?.searchAdsPerPlatformMax || 100000;
  const pickerLabel = picked.size > 0
    ? `${picked.size} direction${picked.size === 1 ? '' : 's'} selected`
    : `All ${directionPool.length} direction${directionPool.length === 1 ? '' : 's'}`;
  const fetchedLabel = Object.entries(progress?.platformAdsFetched || {})
    .map(([source, count]) => `${source}: ${count}`)
    .join(' · ');

  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}>
              <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)} current-run scored · {(progress?.winners || 0)} winning ads loaded · {(progress?.directionsSatisfied || 0)}/{(progress?.directionsTotal || 0)} direction checks done
              {fetchedLabel ? ` · fetched ${fetchedLabel}` : ''}
              {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={Math.max(1, dirs.length || 30)}
            value={numDirections}
            placeholder="5"
            onChange={(e) => onNumDirections(e.target.value)}
            title="How many directions are selected for this run. Use the Directions picker to choose a subset."
          />
        </label>
        <label className="ar-target">
          <span>Total ads</span>
          <input
            type="number"
            min={1}
            max={targetMax}
            step={1}
            value={perDirectionTarget}
            placeholder="1"
            title={`Maximum winning ads to output for this Autoresearch run. Max ${targetMax}.`}
            onChange={(e) => onPerDirectionTarget(e.target.value)}
          />
        </label>
        <label className="ar-target" style={{ display: 'none' }}>
          <span>Ads per direction cap</span>
          <input
            type="number"
            min={1}
            max={adsPerDirectionMax}
            step={1}
            value={maxAdsPerDirection}
            placeholder="100"
            title={`Maximum ads to fetch per direction and source. Default 100. Max ${adsPerDirectionMax}.`}
            onChange={(e) => onMaxAdsPerDirection(e.target.value)}
          />
        </label>
        <label className="ar-target" style={{ display: 'none' }}>
          <span>Ads per source cap</span>
          <input
            type="number"
            min={1}
            max={adsPerPlatformMax}
            step={1}
            value={maxAdsPerPlatform}
            placeholder="No cap"
            title={`Maximum ads to fetch per source across this run. Blank leaves the source uncapped. Max ${adsPerPlatformMax}.`}
            onChange={(e) => onMaxAdsPerPlatform(e.target.value)}
          />
        </label>
        <div className="ar-sources-spacer" />
        {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 ? `Use ${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={onSelectAllSources} title="Use all live sources">
          All
        </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 → all ${directionPool.length} directions will run, including competitors.`
                    : `${picked.size} picked — only these will run.`}
                </span>
                <div className="ar-dirs-actions">
                  {!allPicked && (
                    <button className="ar-dirs-clear" onClick={onSelectAllPickedDirections}>
                      Select all
                    </button>
                  )}
                  {picked.size > 0 && (
                    <button className="ar-dirs-clear" onClick={onClearPickedDirections}>
                      Clear
                    </button>
                  )}
                </div>
              </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>
  );
};
