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

  function Sidebar({ seeds, setSeeds, siteUrls, setSiteUrls, manual, setManual, state, onRun, questionLoading,
                     cookieStatus, onSaveCookies, history, onResume }) {
    const [cookieOpen, setCookieOpen] = useState(false);
    const [cookieInput, setCookieInput] = useState('');
    const [siteUrlsOpen, setSiteUrlsOpen] = useState(() => !!siteUrls?.trim());
    const [savingCookie, setSavingCookie] = useState(false);
    const running = state === 'running';
    const email = window.SC_Auth.getEmail() || '';

    const handleSave = async () => {
      if (!cookieInput.trim()) return;
      setSavingCookie(true);
      await onSaveCookies(cookieInput.trim());
      setSavingCookie(false);
      setCookieInput('');
      setCookieOpen(false);
    };

    const handleLogout = () => window.SC_Auth.logout();

    return (
      <aside style={{
        width: 300, height: '100%', background: T.surface,
        borderRight: `1px solid ${T.border}`,
        display: 'flex', flexDirection: 'column', flexShrink: 0,
      }}>
        <div style={{ padding: '20px 22px 16px' }}>
          <LogoBlock />
        </div>

        <div style={{ padding: '0 22px 18px', display: 'flex', flexDirection: 'column', gap: 16, flex: 1, overflow: 'auto' }}>
          <div>
            <SectionLabel style={{ marginBottom: 8 }}>Затравочные фразы</SectionLabel>
            <Textarea
              value={seeds} onChange={setSeeds}
              placeholder={'купить диваны\nмягкая мебель\nкресло в гостиную...'}
              rows={7}
            />
            <div style={{ fontSize: 11, color: T.inkSubtle, marginTop: 6, display: 'flex', justifyContent: 'space-between' }}>
              <span>{seeds.split('\n').filter((l) => l.trim()).length} / 10 фраз</span>
              <span>каждая с новой строки</span>
            </div>
          </div>

          {/* ── Анализ сайта ─────────────────────────────────── */}
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: siteUrlsOpen ? 8 : 0 }}>
              <SectionLabel>
                Анализ сайта
                {!siteUrlsOpen && siteUrls?.trim() && (
                  <span style={{ marginLeft: 6, background: T.accent, color: '#fff', borderRadius: 10, fontSize: 10, padding: '1px 6px', fontWeight: 600 }}>
                    {siteUrls.split('\n').filter((l) => l.trim()).length}
                  </span>
                )}
              </SectionLabel>
              <button
                onClick={() => setSiteUrlsOpen(!siteUrlsOpen)}
                style={{
                  border: 'none', background: 'transparent', cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  fontSize: 12, color: T.inkMuted, fontFamily: 'inherit', padding: 4,
                }}
              >
                {siteUrlsOpen ? 'Скрыть' : 'Добавить'}
                <span style={{ display: 'inline-flex', color: T.inkSubtle, transform: siteUrlsOpen ? 'rotate(90deg)' : 'none', transition: 'transform .15s' }}>
                  {Icon.chevron(12)}
                </span>
              </button>
            </div>
            {siteUrlsOpen && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, animation: 'sc-fade-in .18s ease' }}>
                <Textarea
                  value={siteUrls} onChange={setSiteUrls}
                  rows={3}
                  placeholder={'https://example.com\nhttps://example.com/about'}
                />
                <div style={{ fontSize: 11, color: T.inkSubtle, lineHeight: 1.5 }}>
                  ИИ проанализирует сайт и задаст точечные вопросы
                </div>
              </div>
            )}
          </div>

          <ToggleCard
            title="Ручная проверка"
            subtitle="Уточнять фразы в процессе"
            on={manual} onChange={setManual}
          />

          <PrimaryButton
            onClick={onRun}
            disabled={running || questionLoading || !seeds.trim()}
            loading={running || questionLoading}
          >
            {running ? 'Идёт сборка...' : questionLoading ? 'Генерирую вопросы...' : 'Запустить сборку'}
          </PrimaryButton>

          <Divider />

          <div>
            <SectionLabel style={{ marginBottom: 8 }}>Wordstat</SectionLabel>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 0' }}>
              <StatusPill
                ok={cookieStatus.ok}
                label={cookieStatus.ok ? `Готово: ${cookieStatus.count} cookie` : 'Куки не настроены'}
              />
              <button
                onClick={() => setCookieOpen(!cookieOpen)}
                style={{
                  border: 'none', background: 'transparent', cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  fontSize: 12, color: T.inkMuted, fontFamily: 'inherit', padding: 4,
                }}
              >
                {cookieOpen ? 'Скрыть' : 'Обновить'}
                <span style={{ display: 'inline-flex', color: T.inkSubtle, transform: cookieOpen ? 'rotate(90deg)' : 'none', transition: 'transform .15s' }}>
                  {Icon.chevron(12)}
                </span>
              </button>
            </div>
            {cookieOpen && (
              <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8, animation: 'sc-fade-in .18s ease' }}>
                <div style={{ fontSize: 11, color: T.inkSubtle, lineHeight: 1.5 }}>
                  wordstat.yandex.ru → DevTools → Application → Cookies → скопируйте строку
                </div>
                <Textarea value={cookieInput} onChange={setCookieInput} rows={3} placeholder="yandexuid=...; Session_id=..." />
                <GhostButton onClick={handleSave} disabled={savingCookie || !cookieInput.trim()} style={{ fontSize: 12, padding: '7px 14px' }}>
                  {savingCookie ? 'Сохраняем...' : 'Сохранить'}
                </GhostButton>
              </div>
            )}
          </div>

          <Divider />

          {history.length > 0 && (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                <SectionLabel>История</SectionLabel>
                <span style={{ fontSize: 11, color: T.inkSubtle, fontWeight: 500 }}>посл. 5</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 2, margin: '0 -6px' }}>
                {history.map((h) => (
                  <div key={h.id} onClick={() => onResume(h.id)} style={{ cursor: 'pointer' }}>
                    <HistoryItem {...h} />
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* User footer */}
        <div style={{ borderTop: `1px solid ${T.border}`, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ color: T.inkMuted, display: 'flex' }}>{Icon.user(14)}</span>
          <span style={{ flex: 1, fontSize: 12, color: T.inkMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {email}
          </span>
          <button
            onClick={handleLogout}
            title="Выйти"
            style={{
              border: 'none', background: 'transparent', cursor: 'pointer',
              color: T.inkSubtle, display: 'flex', padding: 4, borderRadius: 6,
              transition: 'color .15s',
            }}
            onMouseEnter={(e) => e.currentTarget.style.color = T.err}
            onMouseLeave={(e) => e.currentTarget.style.color = T.inkSubtle}
          >
            {Icon.logout(14)}
          </button>
        </div>
      </aside>
    );
  }

  window.Sidebar = Sidebar;
})();
