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

  function SitesDetail({ sites }) {
    const [expandedIdx, setExpandedIdx] = useState(null);
    if (sites.length === 0)
      return <div style={{ color: T.inkMuted, fontSize: 13, textAlign: 'center', padding: 24 }}>Сайты пока не обработаны</div>;
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {sites.map((site, i) => (
          <div key={i} style={{ border: `1px solid ${T.borderSoft}`, borderRadius: 8, overflow: 'hidden' }}>
            <div
              onClick={() => setExpandedIdx(expandedIdx === i ? null : i)}
              style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', cursor: 'pointer', background: expandedIdx === i ? T.accentSoft : T.surface }}
            >
              <span style={{ width: 6, height: 6, borderRadius: 999, background: T.accent, flexShrink: 0 }} />
              <a href={site.url} target="_blank" rel="noopener noreferrer" onClick={(e) => e.stopPropagation()}
                style={{ flex: 1, fontSize: 12.5, color: T.accent, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textDecoration: 'none' }}>
                {site.url}
              </a>
              <span style={{ fontSize: 11, color: T.inkMuted, flexShrink: 0 }}>{site.phrases.length} фраз</span>
              <span style={{ color: T.inkSubtle, display: 'flex', transform: expandedIdx === i ? 'rotate(90deg)' : 'none', transition: 'transform .15s' }}>
                {window.SC_Icon.chevron(11)}
              </span>
            </div>
            {expandedIdx === i && site.phrases.length > 0 && (
              <div style={{ padding: '8px 12px 10px 30px', borderTop: `1px solid ${T.borderSoft}`, maxHeight: 200, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 3 }}>
                {site.phrases.map((p, j) => <div key={j} style={{ fontSize: 12.5, color: T.ink, padding: '2px 0' }}>{p}</div>)}
              </div>
            )}
          </div>
        ))}
      </div>
    );
  }

  function PhrasesDetail({ phrases, emptyText }) {
    if (phrases.length === 0)
      return <div style={{ color: T.inkMuted, fontSize: 13, textAlign: 'center', padding: 24 }}>{emptyText || 'Фразы ещё не собраны'}</div>;
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
        {phrases.map((p, i) => (
          <div key={i} style={{ padding: '6px 10px', borderRadius: 6, fontSize: 13, color: T.ink, background: i % 2 === 0 ? 'transparent' : T.bg2 }}>
            {p}
          </div>
        ))}
      </div>
    );
  }

  function RunningScreen({ activeStep, currentAction, stats, liveItems, wordstatCount, sitesList, suggestPhrases, wordstatPhrases }) {
    const [activeTab, setActiveTab] = useState('phrases');
    return (
      <div style={{ flex: 1, padding: '32px 36px', overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 24 }}>
        <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 14, padding: '24px 28px 22px', boxShadow: '0 1px 2px rgba(17,24,39,0.04)' }}>
          <Stepper active={activeStep} steps={['Поиск страниц', 'Suggest', 'Wordstat', 'Кластеризация']} />
        </div>

        <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 12, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 12 }}>
          <Spinner size={18} />
          <div style={{ flex: 1, fontSize: 14, color: T.ink, fontWeight: 500 }}>{currentAction || 'Подготовка...'}</div>
          {stats.wordstatTotal > 0 && (
            <div style={{ fontSize: 12, color: T.inkMuted, fontVariantNumeric: 'tabular-nums', fontWeight: 500 }}>
              {stats.phrases} / {stats.wordstatTotal}
            </div>
          )}
        </div>

        <div style={{ display: 'flex', gap: 14 }}>
          <StatCard label="Фраз найдено" value={stats.phrases} active={activeTab === 'phrases'} onClick={() => setActiveTab('phrases')} />
          <StatCard label="Сайты" value={stats.sites} active={activeTab === 'sites'} onClick={stats.sites > 0 ? () => setActiveTab('sites') : undefined} />
          <StatCard label="Suggest" value={stats.suggest} active={activeTab === 'suggest'} onClick={stats.suggest > 0 ? () => setActiveTab('suggest') : undefined} />
          <StatCard label="Wordstat" value={wordstatCount} active={activeTab === 'wordstat'} onClick={wordstatCount > 0 ? () => setActiveTab('wordstat') : undefined} />
        </div>

        <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 12, padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 280, overflow: 'hidden' }}>
          {activeTab === 'phrases' && (
            <>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <SectionLabel>Поток фраз</SectionLabel>
                <span style={{ fontSize: 11, color: T.inkSubtle, fontWeight: 500 }}>в реальном времени</span>
              </div>
              {liveItems.length > 0 ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 2, overflow: 'hidden' }}>
                  {liveItems.slice(-7).map((item, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 8px', borderRadius: 6, fontSize: 13, color: T.ink, animation: 'sc-slide-in 0.4s ease both' }}>
                      <span style={{ width: 5, height: 5, borderRadius: 999, background: T.accent, flexShrink: 0 }} />
                      <span style={{ flex: 1, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.phrase}</span>
                      <SourceBadge src={item.src} />
                    </div>
                  ))}
                </div>
              ) : (
                <div style={{ color: T.inkMuted, fontSize: 13, textAlign: 'center', padding: 16 }}>Ожидаем первые фразы...</div>
              )}
            </>
          )}
          {activeTab === 'sites'    && <div style={{ overflow: 'auto', flex: 1 }}><SitesDetail sites={sitesList} /></div>}
          {activeTab === 'suggest'  && <div style={{ overflow: 'auto', flex: 1 }}><PhrasesDetail phrases={suggestPhrases} /></div>}
          {activeTab === 'wordstat' && <div style={{ overflow: 'auto', flex: 1 }}><PhrasesDetail phrases={wordstatPhrases} emptyText="Фразы из Wordstat пока не получены" /></div>}
        </div>
      </div>
    );
  }

  window.RunningScreen = RunningScreen;
})();
