/* global React */
(function () {
  const { useState } = React;
  const T = window.SC_T;
  const Icon = window.SC_Icon;

  const PAGE_SIZES = [100, 500, 1000, 0];

  function ResultRow({ row }) {
    const [hover, setHover] = useState(false);
    return (
      <div
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{
          display: 'grid', gridTemplateColumns: '1fr 160px 140px 110px',
          padding: '11px 18px', borderBottom: `1px solid ${T.borderSoft}`,
          fontSize: 13, alignItems: 'center',
          background: hover ? T.accentSoft : 'transparent', transition: 'background .12s ease',
        }}
      >
        <div style={{ color: T.ink, fontWeight: 500, paddingRight: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.phrase}</div>
        <div style={{ color: T.inkMuted, fontSize: 12.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', paddingRight: 8 }}>{row.cluster || '—'}</div>
        <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: T.ink, fontWeight: 600 }}>{(row.freq || 0).toLocaleString('ru')}</div>
        <div><SourceBadge src={row.src} /></div>
      </div>
    );
  }

  function ResultsScreen({ rows, totalCount, seedCount, aiCount, suggestCount, wordstatCount, allLoaded, onLoadAll }) {
    const [q, setQ] = useState('');
    const [srcFilter, setSrcFilter] = useState('all');
    const [sortCol, setSortCol] = useState('freq');
    const [sortAsc, setSortAsc] = useState(false);
    const [pageSize, setPageSize] = useState(500);

    const filtered = rows
      .filter((r) => (srcFilter === 'all' || r.src === srcFilter) && (!q || r.phrase.toLowerCase().includes(q.toLowerCase()) || r.cluster.toLowerCase().includes(q.toLowerCase())))
      .sort((a, b) => {
        const va = a[sortCol] ?? 0, vb = b[sortCol] ?? 0;
        const rv = typeof va === 'number' ? va - vb : String(va).localeCompare(String(vb), 'ru');
        return sortAsc ? rv : -rv;
      });

    const displayed = pageSize === 0 ? filtered : filtered.slice(0, pageSize);
    const onSort = (col) => { if (sortCol === col) setSortAsc(!sortAsc); else { setSortCol(col); setSortAsc(col !== 'freq'); } };
    const handlePageSize = async (s) => { setPageSize(s); if (!allLoaded && (s === 0 || s > rows.length)) await onLoadAll(); };

    const srcOpts = [{ v: 'all', l: 'Все' }, { v: 'seed', l: 'Seed' }, { v: 'ai', l: 'AI' }, { v: 'suggest', l: 'Suggest' }, { v: 'wordstat', l: 'Wordstat' }];

    return (
      <div style={{ flex: 1, padding: '24px 28px', overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
          <StatCard label="Всего фраз"    value={totalCount}   active />
          <StatCard label="Затравки"      value={seedCount} />
          <StatCard label="AI расширение" value={aiCount} />
          <StatCard label="Suggest"       value={suggestCount} />
          <StatCard label="Wordstat"      value={wordstatCount} />
        </div>

        <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 14, overflow: 'hidden', flex: 1, display: 'flex', flexDirection: 'column' }}>
          {/* Toolbar */}
          <div style={{ padding: '12px 16px', borderBottom: `1px solid ${T.borderSoft}`, display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0, flexWrap: 'wrap' }}>
            <div style={{ position: 'relative', flex: 1, minWidth: 200, maxWidth: 360 }}>
              <span style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)', color: T.inkMuted, display: 'flex', pointerEvents: 'none' }}>
                {Icon.search(14)}
              </span>
              <input
                value={q} onChange={(e) => setQ(e.target.value)}
                placeholder="Поиск по фразам и кластерам..."
                style={{ width: '100%', padding: '7px 12px 7px 32px', border: `1px solid ${T.border}`, borderRadius: 8, fontSize: 13, fontFamily: 'inherit', outline: 'none', background: T.surface }}
                onFocus={(e) => { e.target.style.borderColor = T.accent; e.target.style.boxShadow = `0 0 0 3px ${T.accentSoft}`; }}
                onBlur={(e)  => { e.target.style.borderColor = T.border;  e.target.style.boxShadow = 'none'; }}
              />
            </div>

            <div style={{ display: 'inline-flex', padding: 3, background: '#F3F4F6', borderRadius: 8, gap: 2 }}>
              {srcOpts.map((o) => (
                <button key={o.v} onClick={() => setSrcFilter(o.v)} style={{ padding: '5px 11px', border: 'none', borderRadius: 6, cursor: 'pointer', background: srcFilter === o.v ? T.surface : 'transparent', color: srcFilter === o.v ? T.ink : T.inkMuted, fontSize: 12, fontWeight: 600, fontFamily: 'inherit', boxShadow: srcFilter === o.v ? '0 1px 2px rgba(17,24,39,0.08)' : 'none', transition: 'all .12s ease' }}>
                  {o.l}
                </button>
              ))}
            </div>

            <div style={{ display: 'inline-flex', padding: 3, background: '#F3F4F6', borderRadius: 8, gap: 2 }}>
              {PAGE_SIZES.map((s) => (
                <button key={s} onClick={() => handlePageSize(s)} style={{ padding: '5px 10px', border: 'none', borderRadius: 6, cursor: 'pointer', background: pageSize === s ? T.surface : 'transparent', color: pageSize === s ? T.ink : T.inkMuted, fontSize: 12, fontWeight: 600, fontFamily: 'inherit', boxShadow: pageSize === s ? '0 1px 2px rgba(17,24,39,0.08)' : 'none', transition: 'all .12s ease' }}>
                  {s === 0 ? 'Все' : s.toLocaleString('ru')}
                </button>
              ))}
            </div>

            <span style={{ fontSize: 12, color: T.inkMuted, fontWeight: 500, marginLeft: 'auto', whiteSpace: 'nowrap' }}>
              {displayed.length.toLocaleString('ru')}
              {filtered.length > displayed.length && ` из ${filtered.length.toLocaleString('ru')}`}
              {` / всего ${totalCount.toLocaleString('ru')}`}
            </span>
          </div>

          {/* Table */}
          <div style={{ flex: 1, overflow: 'auto' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 160px 140px 110px', padding: '10px 18px', background: '#FAFBFC', borderBottom: `1px solid ${T.borderSoft}`, fontSize: 11, fontWeight: 600, letterSpacing: 0.8, textTransform: 'uppercase', color: T.inkMuted, position: 'sticky', top: 0, zIndex: 1 }}>
              {[['phrase', 'Фраза'], ['cluster', 'Кластер'], ['freq', 'Кол-во поисков'], ['src', 'Источник']].map(([k, l]) => (
                <div key={k} onClick={() => onSort(k)} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, userSelect: 'none', justifyContent: k === 'freq' ? 'flex-end' : 'flex-start' }}>
                  {l}{sortCol === k && <span style={{ fontSize: 9, opacity: 0.7 }}>{sortAsc ? '▲' : '▼'}</span>}
                </div>
              ))}
            </div>
            {displayed.map((r, i) => <ResultRow key={r.phrase + i} row={r} />)}
            {displayed.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: T.inkMuted, fontSize: 13 }}>Ничего не нашлось</div>}
          </div>
        </div>
      </div>
    );
  }

  window.ResultsScreen = ResultsScreen;
})();
