const { useState: useARPState, useEffect: useARPEffect, useRef: useARPRef } = React;

function _arStatusText(stage) {
  if (!stage) return 'Starting auto-remodel...';
  switch (stage) {
    case 'queued': return 'Starting auto-remodel...';
    case 'crawling': return 'Crawling and scoring...';
    case 'picked': return 'Top picks selected...';
    case 'filtering': return 'Filtering picked ads...';
    case 'filter_done': return 'Filter audit complete...';
    case 'remodeling': return 'Generating remodeled scripts...';
    case 'done': return 'Auto-remodel complete';
    case 'cancelled': return 'Auto-remodel stopped';
    case 'failed': return 'Auto-remodel failed';
    default: return stage;
  }
}

function _arMetaText(stage, adsFound, targetAds, picked, varsDone, varsTotal, ev) {
  if (stage === 'failed' && ev?.error) return ev.error;
  const bits = [];
  if (targetAds > 0 && (stage === 'crawling' || stage === 'queued')) {
    bits.push(`${adsFound}/${targetAds} ads found`);
  }
  if (picked != null && picked >= 0 && ['picked', 'filtering', 'filter_done', 'remodeling', 'done'].includes(stage)) {
    bits.push(`${picked} pick${picked === 1 ? '' : 's'}`);
  }
  if (ev?.overrides) bits.push(`${ev.overrides} filter override${ev.overrides === 1 ? '' : 's'}`);
  if (varsTotal > 0 && (stage === 'remodeling' || stage === 'done')) {
    bits.push(`${varsDone}/${varsTotal} variants`);
  }
  return bits.join(' · ');
}

window.AutoRemodelPanel = function AutoRemodelPanel({
  open,
  onClose,
  directionOptions = [],
  running,
  stage,
  lastEvent,
  adsFound = 0,
  targetAds = 0,
  variantsDone = 0,
  variantsTotal = 0,
  sources = { foreplay: true, adspy: true, brandsearch: true },
  onToggleSource,
  onSelectAllSources,
  onRun,
  onStop,
  starting = false,
}) {
  const [count, setCount] = useARPState('5');
  const [nVariants, setNVariants] = useARPState('1');
  const [maxAdsPerDirection, setMaxAdsPerDirection] = useARPState('');
  const [maxAdsPerPlatform, setMaxAdsPerPlatform] = useARPState('');
  const [selectedDirectionIds, setSelectedDirectionIds] = useARPState(new Set());
  const [pickerOpen, setPickerOpen] = useARPState(false);
  const [estimate, setEstimate] = useARPState(null);
  const [estimating, setEstimating] = useARPState(false);
  const [estimateError, setEstimateError] = useARPState('');
  const pickerRef = useARPRef(null);
  const defaultDirectionsLoadedRef = useARPRef(false);
  const directions = Array.isArray(directionOptions) ? directionOptions : [];
  const selectedIds = [...selectedDirectionIds];
  const countMax = window.RESILIA_LIMITS?.autoRemodelCountMax || 10000;
  const adsPerDirectionMax = window.RESILIA_LIMITS?.searchAdsPerDirectionMax || 10000;
  const adsPerPlatformMax = window.RESILIA_LIMITS?.searchAdsPerPlatformMax || 100000;
  const capNum = Math.max(1, Math.min(countMax, parseInt(count, 10) || 5));
  const variants = Math.max(1, Math.min(5, parseInt(nVariants, 10) || 1));
  const directionBudget = maxAdsPerDirection === ''
    ? null
    : Math.max(1, Math.min(adsPerDirectionMax, parseInt(maxAdsPerDirection, 10) || 1));
  const platformBudget = maxAdsPerPlatform === ''
    ? null
    : Math.max(1, Math.min(adsPerPlatformMax, parseInt(maxAdsPerPlatform, 10) || 1));
  const randomPoolSize = directions.length;
  const pickerLabel = selectedIds.length
    ? `${selectedIds.length} direction${selectedIds.length === 1 ? '' : 's'} selected`
    : `Random ${Math.min(capNum, randomPoolSize)} direction${Math.min(capNum, randomPoolSize) === 1 ? '' : 's'}`;
  const labelFor = (d) => d.display_name || d.description || d.brand_name || d.name || d.id;
  const typeLabel = (d) => d.type === 'competitor' ? 'Competitor' : 'Keyword';
  const selectedDirectionPreview = selectedIds.length
    ? directions.filter(d => selectedDirectionIds.has(d.id))
    : [];
  const liveKeys = Object.keys(PLATFORMS).filter(k => k === 'foreplay' || k === 'adspy' || k === 'brandsearch');
  const selectedSources = liveKeys.filter(k => sources[k]);
  const busy = running || starting;

  useARPEffect(() => {
    if (running && targetAds > 0) setCount(String(targetAds));
  }, [running, targetAds]);

  useARPEffect(() => {
    if (!directions.length || defaultDirectionsLoadedRef.current) return;
    setSelectedDirectionIds(new Set(directions.map(d => d.id).filter(Boolean)));
    defaultDirectionsLoadedRef.current = true;
  }, [directions.map(d => d.id).join('|')]);

  useARPEffect(() => {
    if (!open) return;
    let cancelled = false;
    if (selectedSources.length === 0) {
      setEstimate(null);
      setEstimating(false);
      setEstimateError('Pick at least one source');
      return () => { cancelled = true; };
    }
    setEstimating(true);
    setEstimateError('');
    const timer = setTimeout(async () => {
      try {
        const out = await RESILIA_API.estimateAutoRemodel({
          mode: 'auto_search',
          directionId: null,
          directionIds: selectedIds,
          count: capNum,
          nVariants: variants,
          platforms: selectedSources,
        });
        if (!cancelled) setEstimate(out);
      } catch (e) {
        if (!cancelled) setEstimateError(e.message || 'Estimate unavailable');
      } finally {
        if (!cancelled) setEstimating(false);
      }
    }, 250);
    return () => { cancelled = true; clearTimeout(timer); };
  }, [open, count, nVariants, selectedIds.join('|'), selectedSources.join('|')]);

  useARPEffect(() => {
    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]);

  if (!open && !running && stage !== 'done' && stage !== 'failed' && stage !== 'cancelled') return null;

  const pickedCount = lastEvent?.picked_count
    ?? (Array.isArray(lastEvent?.picked_ad_ids) ? lastEvent.picked_ad_ids.length : null)
    ?? lastEvent?.picked;
  let pct = 0;
  if (stage === 'crawling' || stage === 'queued') pct = targetAds > 0 ? Math.min(adsFound / targetAds, 1) * 35 : 8;
  else if (stage === 'picked') pct = 40;
  else if (stage === 'filtering') pct = 55;
  else if (stage === 'filter_done') pct = 65;
  else if (stage === 'remodeling') pct = 65 + (variantsTotal > 0 ? Math.min(variantsDone / variantsTotal, 1) * 35 : 0);
  else if (stage === 'done') pct = 100;
  else if (stage === 'cancelled') pct = Math.max(8, targetAds > 0 ? Math.min(adsFound / targetAds, 1) * 35 : 8);
  else if (stage === 'failed') pct = 8;
  const meta = _arMetaText(stage, adsFound, targetAds, pickedCount, variantsDone, variantsTotal, lastEvent);

  const toggleDirection = (id) => {
    setSelectedDirectionIds(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };
  const selectAllDirections = () => setSelectedDirectionIds(new Set(directions.map(d => d.id)));
  const allDirectionsPicked = directions.length > 0 && selectedDirectionIds.size >= directions.length;

  const run = () => {
    onRun({
      mode: 'auto_search',
      directionId: null,
      directionIds: selectedIds,
      count: capNum,
      nVariants: variants,
      platforms: selectedSources,
      maxAdsPerDirection: directionBudget,
      maxAdsPerPlatform: platformBudget,
    });
  };

  return (
    <div className="search-card ar-card">
      <div className="sc-hdr">
        <span className="sc-title">Auto-Remodel</span>
        <span className="sc-sub">One-click crawl, score, filter audit, and remodel</span>
        <div className="sc-actions">
          {onClose && !running && <button className="icon-btn" onClick={onClose} title="Close"><Icon name="x" size={14} /></button>}
        </div>
      </div>

      <div className="ar-sources" style={{ paddingTop: 8, alignItems: 'stretch' }}>
        <label className="ar-target">
          <span>How many ads</span>
          <input type="number" min={1} max={countMax} value={count} onChange={(e) => setCount(e.target.value)} />
        </label>
        <label className="ar-target">
          <span>Variants per ad</span>
          <input type="number" min={1} max={5} value={nVariants} onChange={(e) => setNVariants(e.target.value)} />
        </label>
        <label className="ar-target" style={{ display: 'none' }}>
          <span>Ads per direction cap</span>
          <input
            type="number"
            min={1}
            max={adsPerDirectionMax}
            value={maxAdsPerDirection}
            placeholder="No cap"
            title={`Maximum ads to fetch per direction and source. Blank leaves direction search uncapped. Max ${adsPerDirectionMax}.`}
            onChange={(e) => setMaxAdsPerDirection(e.target.value)}
          />
        </label>
        <label className="ar-target" style={{ display: 'none' }}>
          <span>Ads per source cap</span>
          <input
            type="number"
            min={1}
            max={adsPerPlatformMax}
            value={maxAdsPerPlatform}
            placeholder="No cap"
            title={`Maximum ads to fetch per source across this run. Blank leaves the source uncapped. Max ${adsPerPlatformMax}.`}
            onChange={(e) => setMaxAdsPerPlatform(e.target.value)}
          />
        </label>
        <div className="ar-dirs ar-dirs-inline" ref={pickerRef} style={{ minWidth: 280 }}>
          <button
            type="button"
            className={`ar-dirs-trigger ${selectedIds.length > 0 ? 'active' : ''}`}
            onClick={() => setPickerOpen(o => !o)}
            aria-expanded={pickerOpen}
            aria-haspopup="listbox"
            disabled={busy}
          >
            <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">
                  {selectedIds.length === 0
                    ? 'No picks -> random directions, including competitors.'
                    : `${selectedIds.length} picked - only these will run.`}
                </span>
                <div className="ar-dirs-actions">
                  {!allDirectionsPicked && (
                    <button className="ar-dirs-clear" onClick={selectAllDirections}>
                      Select all
                    </button>
                  )}
                  {selectedIds.length > 0 && (
                    <button className="ar-dirs-clear" onClick={() => setSelectedDirectionIds(new Set())}>
                      Clear
                    </button>
                  )}
                </div>
              </div>
              <div className="ar-dirs-grid">
                {directions.map((d) => {
                  const on = selectedDirectionIds.has(d.id);
                  return (
                    <label key={d.id} className={`ar-dir-pill ${on ? 'on' : 'off'}`} title={typeLabel(d)}>
                      <input
                        type="checkbox"
                        checked={on}
                        onChange={() => toggleDirection(d.id)}
                      />
                      <span className="ar-dir-label">{labelFor(d)}</span>
                      {d.type === 'competitor' && <span style={{ fontSize: 10, opacity: 0.72 }}>competitor</span>}
                    </label>
                  );
                })}
              </div>
            </div>
          )}
          {directions.length > 0 && (
            <div className="ar-dirs-preview" title={selectedDirectionPreview.map(labelFor).join(', ')}>
              {selectedDirectionPreview.slice(0, 6).map(d => (
                <span key={d.id} className="ar-dir-preview-pill">{labelFor(d)}</span>
              ))}
              {selectedDirectionPreview.length > 6 && <span className="ar-dir-preview-more">+{selectedDirectionPreview.length - 6}</span>}
            </div>
          )}
        </div>
        <div className="ar-sources-spacer" />
        {Object.entries(PLATFORMS).map(([key, p]) => {
          const sourceOn = !!sources[key];
          const live = key === 'foreplay' || key === 'adspy' || key === 'brandsearch';
          return (
            <button
              key={key}
              className={`plat-toggle ${sourceOn ? 'on' : 'off'}`}
              onClick={() => live && onToggleSource && onToggleSource(key)}
              style={sourceOn ? { background: p.bg, color: p.color, borderColor: p.bg } : {}}
              title={live ? `Use ${p.label}` : `${p.label} — backend not wired yet`}
              disabled={busy || !live}
            >
              <span className="plat-dot" style={{ background: sourceOn ? p.color : '#b2b8c2' }} />
              {p.label}
            </button>
          );
        })}
        <button
          className="plat-toggle all"
          onClick={() => onSelectAllSources && onSelectAllSources()}
          title="Use all live sources"
          disabled={busy}
        >
          All
        </button>
        {running ? (
          <button className="btn-secondary" onClick={() => onStop && onStop()}>
            <Icon name="x" size={14} /> Stop
          </button>
        ) : (
          <button className="btn-primary" onClick={run} disabled={starting || selectedSources.length === 0}>
            <Icon name="bolt" size={14} /> {starting ? 'Starting...' : 'Run Auto-Remodel'}
          </button>
        )}
      </div>

      <div style={{ padding: '0 16px 12px', color: 'var(--fg-3)', fontSize: 12 }}>
        {estimating && 'Estimating cost...'}
        {!estimating && estimate && (
          <span>Estimated ${estimate.estimated_usd} · ~{estimate.foreplay_credits_estimate} Foreplay credits · {estimate.directions_in_scope} direction{estimate.directions_in_scope === 1 ? '' : 's'}</span>
        )}
        {!estimating && estimateError && <span>{estimateError}</span>}
      </div>

      {(running || stage === 'done' || stage === 'failed' || stage === 'cancelled') && (
        <div className="ar-progress">
          <div className="ar-progress-head">
            <span className={`ar-spinner ${running ? 'spin' : ''}`} />
            <span className="ar-progress-status">{_arStatusText(stage)}</span>
            {meta && <span className="ar-progress-meta">{meta}</span>}
          </div>
          <div className="ar-progress-bar">
            <div className="ar-progress-fill" style={{ width: `${Math.max(0, Math.min(100, pct))}%` }} />
          </div>
        </div>
      )}
    </div>
  );
};
