const { useState: useStatePP, useMemo: useMemoPP } = React;

window.PlatformPanel = function PlatformPanel({
  platform, ads, selected, onToggleAd, onExpandAd, minimal, density, showWinnersBadge,
  onDislikeAd,
  showPassVerdict = true,
}) {
  const p = PLATFORMS[platform] || PLATFORMS.foreplay;
  const [sortKey, setSortKey] = useStatePP('score');
  const SORTS = platform === 'adspy'
    ? ['score', 'createdAt', 'daysRunning', 'likes', 'views']
    : platform === 'brandsearch'
      ? ['score', 'createdAt', 'daysRunning', 'views', 'likes', 'engagementRate', 'reach', 'spend']
      : ['score', 'createdAt', 'daysRunning'];
  const activeSortKey = SORTS.includes(sortKey) ? sortKey : 'score';

  const sortedAds = useMemoPP(() => {
    const copy = [...ads];
    if (activeSortKey === 'score') {
      copy.sort((a, b) => (b.score ?? -1) - (a.score ?? -1));
    } else if (activeSortKey === 'createdAt') {
      copy.sort((a, b) => (b.createdAtMs || 0) - (a.createdAtMs || 0));
    } else if (activeSortKey === 'daysRunning') {
      copy.sort((a, b) => (b.daysRunning || 0) - (a.daysRunning || 0));
    } else if (activeSortKey === 'likes') {
      copy.sort((a, b) => (b.likesCount || 0) - (a.likesCount || 0));
    } else if (activeSortKey === 'views') {
      copy.sort((a, b) => (b.viewsCount || 0) - (a.viewsCount || 0));
    } else if (activeSortKey === 'engagementRate') {
      copy.sort((a, b) => (b.engagementRateCount || 0) - (a.engagementRateCount || 0));
    } else if (activeSortKey === 'reach') {
      copy.sort((a, b) => (b.reachCount || 0) - (a.reachCount || 0));
    } else if (activeSortKey === 'spend') {
      copy.sort((a, b) => (b.spendCount || 0) - (a.spendCount || 0));
    }
    return copy;
  }, [ads, activeSortKey]);

  const sel = ads.filter(a => selected.has(a.id)).length;
  const nextSort = () => setSortKey(SORTS[(SORTS.indexOf(activeSortKey) + 1) % SORTS.length]);
  const sortLabel = activeSortKey === 'score'
    ? 'Score ↓'
    : activeSortKey === 'createdAt'
      ? 'Created at ↓'
      : activeSortKey === 'daysRunning'
        ? 'Days running ↓'
        : activeSortKey === 'likes'
          ? 'Likes ↓'
          : activeSortKey === 'views'
            ? 'Views ↓'
            : activeSortKey === 'engagementRate'
              ? 'ER ↓'
              : activeSortKey === 'reach'
                ? 'Reach ↓'
                : 'Spend ↓';

  // Transcript-progress indicator: AdSpy / BrandSearch transcripts come from
  // server-side Whisper / ElevenLabs and arrive incrementally. Show how many
  // ads in this panel are still being transcribed so users see overall
  // progress instead of inferring it from per-card pills.
  const transcriptStats = useMemoPP(() => {
    if (platform !== 'adspy' && platform !== 'brandsearch') return null;
    let pending = 0;
    let done = 0;
    let total = 0;
    for (const a of ads) {
      if (!a.creativeUrl) continue;
      total += 1;
      const status = a.transcriptStatus || null;
      const has = a.transcript && a.transcript.length > 0;
      if (has) { done += 1; continue; }
      if (status === 'fallback' || status === 'unavailable' || status === 'empty') {
        done += 1;
        continue;
      }
      pending += 1;
    }
    return { pending, done, total };
  }, [ads, platform]);

  return (
    <section className="platform-panel">
      <header className="pp-hdr">
        <span className="pp-chip" style={{ background: p.bg, color: p.color }}>
          <span className="pp-dot" style={{ background: p.color }} />
          {p.label}
        </span>
        <span className="pp-count">{ads.length} ads</span>
        {transcriptStats && transcriptStats.pending > 0 && (
          <span
            className="pp-transcribing"
            title={`Generating transcripts for ${transcriptStats.pending} of ${transcriptStats.total} video ads (Whisper/ElevenLabs). Typically 5–20s per ad.`}
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 4,
              fontSize: 11,
              color: 'var(--fg-3)',
              padding: '2px 8px',
              borderRadius: 999,
              background: 'rgba(0,0,0,0.04)',
            }}
          >
            <Icon name="loader" size={11} />
            Transcribing {transcriptStats.done}/{transcriptStats.total}
          </span>
        )}
        {showWinnersBadge && (
          <span className="pp-dedupe" title="Filtered to winners using the configured passing score">
            <Icon name="bolt" size={12} /> Winners only
          </span>
        )}
        <div className="pp-spacer" />
        {sel > 0 && <span className="pp-selected">{sel} selected</span>}
        <button className="ghost-btn" onClick={nextSort} title="Cycle sort">
          Sort: {sortLabel}
        </button>
      </header>
      <div className={`pp-grid density-${density}`}>
        {sortedAds.map(a => (
          <AdCard
            key={a.resultUuid || a.cardKey || a.id}
            ad={a}
            selected={selected.has(a.id)}
            onToggle={() => onToggleAd(a.id)}
            onExpand={onExpandAd}
            onDislike={onDislikeAd}
            minimal={minimal}
            showPassVerdict={showPassVerdict}
          />
        ))}
      </div>
    </section>
  );
};
