/* Login + Analysis screens */

const LoginScreen = ({ onLogin }) => {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");
  const [showForgot, setShowForgot] = React.useState(false);

  const [authAction, setAuthAction] = React.useState("idle"); // idle | signing-in | creating

  const submit = async (e) => {
    e.preventDefault();
    if (!email.trim() || !password.trim()) return;
    setLoading(true);
    setError("");
    setAuthAction("signing-in");

    try {
      // Сначала пробуем войти
      const { data, error } =
        await window.supabaseClient.auth.signInWithPassword({
          email,
          password,
        });

      if (!error) {
        // Успешный вход
        setLoading(false);
        setAuthAction("idle");
        onLogin(data.user);
        return;
      }

      // Если аккаунта нет — регистрируем автоматически
      const isNotFound =
        error.message?.toLowerCase().includes("invalid login") ||
        error.message?.toLowerCase().includes("invalid credentials") ||
        error.message?.toLowerCase().includes("user not found") ||
        error.status === 400;

      if (isNotFound) {
        setAuthAction("creating");
        const { data: signUpData, error: signUpError } =
          await window.supabaseClient.auth.signUp({
            email,
            password,
            options: {
              data: {
                product_mode: window.PRODUCT_MODE || "ru",
              },
            },
          });

        if (signUpError) {
          setError(signUpError.message);
          setLoading(false);
          setAuthAction("idle");
          return;
        }

        // Supabase может вернуть user без session если включено email confirmation
        if (signUpData?.user && !signUpData?.session) {
          setError("Check your email to confirm your account.");
          setLoading(false);
          setAuthAction("idle");
          return;
        }

        // Явно обновляем product_mode через API после регистрации
        try {
          await fetch(
            "https://younalyse-api-646149995822.europe-west1.run.app/api/profile/product-mode",
            {
              method: "PATCH",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                user_id: signUpData.user.id,
                product_mode: window.PRODUCT_MODE || "ru",
              }),
            },
          );
        } catch {}

        setLoading(false);
        setAuthAction("idle");
        onLogin(signUpData.user, true); // второй аргумент — isNewUser
        return;
      }

      // Другая ошибка (неверный пароль и т.д.)
      setError(error.message);
      setLoading(false);
      setAuthAction("idle");
    } catch (err) {
      setError("Connection error. Please try again.");
      setLoading(false);
      setAuthAction("idle");
    }
  };

  return (
    <>
      <div className="login-shell">
        <div className="login-art">
          <div className="login-art-bg" />
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 10,
              fontWeight: 600,
              fontSize: 14,
            }}
          >
            <span className="brand-mark">y</span>{" "}
            {window.T?.productName || "younalyse"}
          </div>
          <div>
            <h2>
              {window.T?.productTagline ||
                "YouTube channel analysis, without the spreadsheet sprawl."}
            </h2>
            <p>
              {window.T?.productDescription ||
                "Pull videos, transcripts, and audience signals into one place."}
            </p>
          </div>
          <div
            style={{
              fontSize: 11.5,
              color: "var(--fg-faint)",
              fontFamily: "var(--mono)",
            }}
          >
            v0.4.2 · internal
          </div>
        </div>
        <div className="login-form">
          <form className="login-form-inner" onSubmit={submit}>
            <div>
              <h1>{window.T?.authTitle || "Welcome"}</h1>
              <p
                style={{
                  margin: "6px 0 0",
                  color: "var(--fg-muted)",
                  fontSize: 13,
                }}
              >
                {window.T?.authSubtitle || "Sign in or create a new account."}
              </p>
            </div>
            <div className="field">
              <label>Email</label>
              <input
                className="input"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                autoFocus
              />
            </div>
            <div className="field">
              <label>Password</label>
              <input
                className="input"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>
            {error && (
              <div
                style={{
                  color: "var(--bad)",
                  fontSize: 13,
                  padding: "8px 12px",
                  background: "rgba(220,38,38,0.08)",
                  borderRadius: 6,
                }}
              >
                {error}
              </div>
            )}
            <button className="btn primary lg" type="submit" disabled={loading}>
              {loading ? (
                <>
                  <Icon name="spinner" size={14} />
                  {authAction === "creating"
                    ? ` ${window.T?.authCreating || "Creating account…"}`
                    : ` ${window.T?.authSigningIn || "Signing in…"}`}
                </>
              ) : (
                window.T?.authContinue || "Continue →"
              )}
            </button>
            <div
              style={{
                fontSize: 12,
                color: "var(--fg-faint)",
                textAlign: "center",
                lineHeight: 1.5,
              }}
            >
              {window.T?.authNewHint ||
                "New here? We'll create your account automatically."}
            </div>
            <div className="help" style={{ textAlign: "center" }}>
              {window.T?.authForgot || "Forgot password?"}{" "}
              <a
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  setShowForgot(true);
                }}
              >
                {window.T?.authReset || "Reset via email"}
              </a>
            </div>
          </form>
        </div>
      </div>
      {showForgot && (
        <ForgotPasswordModal onClose={() => setShowForgot(false)} />
      )}
    </>
  );
};

// ── AnalysisScreen ─────────────────────────────────────────────────────────

const AnalysisScreen = ({
  onRun,
  runState,
  runLog,
  runProgress,
  onStop,
  onViewResults,
  onNewAnalysis,
  userProfile,
  userId,
}) => {
  const [mode, setMode] = React.useState("channel");
  const [channels, setChannels] = React.useState("");
  const [videoUrls, setVideoUrls] = React.useState("");
  const [contentFilter, setContentFilter] = React.useState("all");
  const [maxVideos, setMaxVideos] = React.useState(20);
  const [analyzeComments, setAnalyzeComments] = React.useState(false);
  const [generateSummary, setGenerateSummary] = React.useState(false);
  const [usageData, setUsageData] = React.useState(null);

  const tier = userProfile?.subscription_tier || "trial";
  const isClaudeAvailable =
    !["free", "start", "trial", "expired"].includes(tier) ||
    userProfile?.is_superadmin;

  const CHANNELS_PER_RUN = {
    free: 0,
    trial: 3,
    expired: 0,
    start: 3,
    pro: 5,
    producer: 10,
    studio: 10,
    superadmin: 999,
  };
  const channelLimit = userProfile?.is_superadmin
    ? 999
    : CHANNELS_PER_RUN[tier] || 3;

  const channelLines = channels
    .split(/[,\n]/)
    .map((s) => s.trim())
    .filter(Boolean);
  const videoLines = videoUrls
    .split(/[\n]/)
    .map((s) => s.trim())
    .filter(Boolean);

  const videoUrlLimits = {
    trial: 3,
    start: 10,
    pro: 50,
    producer: 50,
    studio: 50,
    agency: 50,
    superadmin: 200,
  };
  const videoUrlLimit = videoUrlLimits[tier] || 0;
  const videoLimitReached =
    mode === "video" && videoLines.length > videoUrlLimit;
  const channelCount =
    mode === "channel" ? channelLines.length : videoLines.length;

  React.useEffect(() => {
    if (!userId) return;
    fetch(
      `https://younalyse-api-646149995822.europe-west1.run.app/api/profile/usage?user_id=${userId}`,
    )
      .then((r) => r.json())
      .then((d) => {
        setUsageData(d);
        window._analysisUsage = d;
      })
      .catch(() => {});
  }, [userId]);

  // Cmd+Enter запускает ран
  React.useEffect(() => {
    const handler = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter") handleRun();
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [channels, videoUrls, mode]);

  // runState: "idle" | "running" | "done" — прогресс показываем на той же странице

  const handleRun = () => {
    if (mode === "video") {
      onRun({
        mode: "video",
        video_urls: videoLines,
        analyzeComments,
        generateSummary,
      });
    } else {
      onRun({
        mode: "channel",
        channels: channelLines,
        contentFilter,
        maxVideos,
        analyzeComments,
        generateSummary,
      });
    }
  };

  const canRun =
    mode === "channel"
      ? channelLines.length > 0
      : videoLines.length > 0 && videoUrlLimit > 0;

  const T = window.T || {};

  const contentFilterOptions = [
    { id: "all", label: T.filterAll || "Все" },
    { id: "horizontal", label: T.filterHorizontal || "Горизонтальные" },
    { id: "shorts", label: T.filterShorts || "Shorts" },
  ];

  return (
    <div className="page" style={{ maxWidth: 720 }}>
      {/* ── Переключатель режима ── */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 12,
          marginBottom: 20,
        }}
      >
        <div className="segmented">
          <button
            className={mode === "channel" ? "active" : ""}
            onClick={() => setMode("channel")}
          >
            📺 {T.analysisChannel || "Канал"}
          </button>
          <button
            className={mode === "video" ? "active" : ""}
            onClick={() => setMode("video")}
          >
            🎬 {T.analysisVideoUrls || "Ссылки на видео"}
          </button>
        </div>
        <span className="help">
          {mode === "channel"
            ? T.analysisChannelHint ||
              "Анализ последних видео с одного или нескольких каналов"
            : T.analysisVideoHint ||
              "Анализ конкретных видео по ссылкам — по одной на строку"}
        </span>
      </div>

      {/* ── Ввод ── */}
      {mode === "channel" ? (
        <div className="form-card" style={{ marginBottom: 16 }}>
          <div className="tag-input-wrap">
            <textarea
              className="textarea"
              rows={4}
              value={channels}
              onChange={(e) => setChannels(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.metaKey && !e.ctrlKey) {
                  e.stopPropagation();
                }
              }}
              placeholder="https://youtube.com/@channelname"
              style={{ fontSize: 13 }}
            />
            <div className="help-row">
              <span>
                {channelLines.length} {T.analysisChannelsDetected || "каналов"}
                {channelLines.length > channelLimit && (
                  <span style={{ color: "var(--bad)", marginLeft: 6 }}>
                    — макс. {channelLimit}
                  </span>
                )}
                {channelLines.length <= channelLimit && channelLimit < 999 && (
                  <span style={{ color: "var(--fg-faint)", marginLeft: 6 }}>
                    · макс. {channelLimit}
                  </span>
                )}
              </span>
              <span>
                <span className="kbd">⌘</span> <span className="kbd">↵</span>{" "}
                {T.analysisToRun || "запустить"}
              </span>
            </div>
          </div>
        </div>
      ) : (
        <div className="form-card" style={{ marginBottom: 16 }}>
          <div className="tag-input-wrap">
            <textarea
              className="textarea"
              rows={5}
              value={videoUrls}
              onChange={(e) => setVideoUrls(e.target.value)}
              placeholder={
                "https://youtube.com/watch?v=dQw4w9WgXcQ\nhttps://youtu.be/abc123"
              }
              style={{ fontSize: 13 }}
            />
            <div className="help-row">
              <span
                style={{ color: videoLimitReached ? "var(--bad)" : undefined }}
              >
                {videoLines.length} {T.analysisVideosDetected || "видео"}
                {videoUrlLimit > 0 && ` · лимит ${videoUrlLimit} для ${tier}`}
                {videoLimitReached && ` — первые ${videoUrlLimit}`}
              </span>
              <span>
                <span className="kbd">⌘</span> <span className="kbd">↵</span>{" "}
                {T.analysisToRun || "запустить"}
              </span>
            </div>
          </div>
          {videoUrlLimit === 0 && (
            <div
              style={{
                marginTop: 12,
                padding: "10px 14px",
                borderRadius: "var(--radius)",
                background: "var(--bg-sunk)",
                border: "1px solid var(--border)",
                fontSize: 13,
                color: "var(--fg-muted)",
              }}
            >
              {T.analysisVideoUnavailable ||
                "Анализ по URL доступен начиная с плана Start."}{" "}
              <a
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  window.dispatchEvent(
                    new CustomEvent("navigate", { detail: "plans" }),
                  );
                }}
              >
                {T.viewPlans || "Смотреть планы →"}
              </a>
            </div>
          )}
        </div>
      )}

      {/* ── Настройки (только channel mode) ── */}
      {mode === "channel" && (
        <div className="form-card" style={{ marginBottom: 16 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {/* Тип контента */}
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <span
                style={{
                  fontSize: 13,
                  color: "var(--fg-muted)",
                  flex: "0 0 160px",
                }}
              >
                {T.filterLabel || "Тип контента"}
              </span>
              <div className="segmented">
                {contentFilterOptions.map((opt) => (
                  <button
                    key={opt.id}
                    className={contentFilter === opt.id ? "active" : ""}
                    onClick={() => setContentFilter(opt.id)}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Макс. видео */}
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <span
                style={{
                  fontSize: 13,
                  color: "var(--fg-muted)",
                  flex: "0 0 160px",
                }}
              >
                {T.filterMaxVideos || "Видео с канала"}
              </span>
              <input
                className="input"
                type="number"
                min={1}
                max={200}
                value={maxVideos}
                onChange={(e) => setMaxVideos(+e.target.value)}
                style={{ width: 80 }}
              />
              <span className="help">{T.filterVideos || "видео"}</span>
            </div>

            {/* Claude AI */}
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <span
                style={{
                  fontSize: 13,
                  color: "var(--fg-muted)",
                  flex: "0 0 160px",
                }}
              >
                {T.filterAI || "AI анализ"}
              </span>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <label
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 7,
                    cursor: isClaudeAvailable ? "pointer" : "not-allowed",
                  }}
                >
                  <input
                    type="checkbox"
                    checked={analyzeComments}
                    disabled={!isClaudeAvailable}
                    onChange={(e) => {
                      setAnalyzeComments(e.target.checked);
                      setGenerateSummary(e.target.checked);
                    }}
                  />
                  <span
                    style={{
                      fontSize: 13,
                      color: isClaudeAvailable
                        ? "var(--fg)"
                        : "var(--fg-faint)",
                    }}
                  >
                    {T.filterAnalyzeWithClaude ||
                      "Анализировать комментарии с Claude"}
                  </span>
                </label>
                {!isClaudeAvailable && (
                  <button
                    className="btn ghost sm"
                    onClick={() =>
                      window.dispatchEvent(
                        new CustomEvent("navigate", { detail: "plans" }),
                      )
                    }
                    style={{
                      color: "var(--accent)",
                      fontSize: 12,
                      fontWeight: 500,
                      padding: "0 6px",
                      height: 24,
                      border: "1px solid var(--accent)",
                      borderRadius: "var(--radius-sm)",
                    }}
                  >
                    {window.PRODUCT_MODE === "en"
                      ? "Available on Pro →"
                      : "Доступно на Про →"}
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Кнопка запуска ── */}
      {runState === "idle" && (
        <div style={{ paddingTop: 4 }}>
          <button
            className="btn primary lg"
            onClick={handleRun}
            disabled={!canRun}
          >
            <Icon name="play" size={13} />
            {T.runAnalysis || "Запустить анализ"}
          </button>
        </div>
      )}

      {/* ── Инлайн прогресс ── */}
      {(runState === "running" || runState === "done") && (
        <InlineProgress
          progress={runProgress}
          state={runState}
          analyzeComments={analyzeComments}
          onStop={onStop}
          onViewResults={onViewResults}
          onNewAnalysis={() => {
            onNewAnalysis();
          }}
          T={T}
        />
      )}
    </div>
  );
};

// ── InlineProgress — прогресс на той же странице ─────────────────────────

const InlineProgress = ({
  progress,
  state,
  analyzeComments,
  onStop,
  onViewResults,
  onNewAnalysis,
  T,
}) => {
  const isDone = state === "done";

  const allStages = [
    { id: "init", label: T.pipelineInit || "Запускаю" },
    { id: "collect", label: T.pipelineCollect || "Собираю видео" },
    { id: "transcript", label: T.pipelineTranscript || "Читаю транскрипты" },
    { id: "comments", label: T.pipelineComments || "Собираю комментарии" },
    { id: "analyze", label: T.pipelineAnalyze || "Анализирую" },
    { id: "done", label: T.pipelineDone || "Готово" },
  ];

  const stages = allStages.filter((s) => s.id !== "analyze" || analyzeComments);
  const currentIdx = isDone
    ? stages.length
    : Math.min(progress, stages.length - 1);

  return (
    <div style={{ paddingTop: 24 }}>
      {/* Горизонтальный пайплайн */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 0,
          marginBottom: 32,
        }}
      >
        {stages.map((s, i) => {
          const done = i < currentIdx;
          const active = i === currentIdx && !isDone;
          const isLast = i === stages.length - 1;
          return (
            <React.Fragment key={s.id}>
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  gap: 8,
                  minWidth: 80,
                }}
              >
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: "50%",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    fontSize: 13,
                    fontWeight: 700,
                    background:
                      done || isDone
                        ? "var(--accent)"
                        : active
                          ? "var(--accent-soft)"
                          : "var(--bg-sunk)",
                    border: active
                      ? "2px solid var(--accent)"
                      : "2px solid transparent",
                    color:
                      done || isDone
                        ? "white"
                        : active
                          ? "var(--accent)"
                          : "var(--fg-faint)",
                    transition: "all 0.3s",
                    boxShadow: active ? "0 0 0 4px var(--accent-soft)" : "none",
                  }}
                >
                  {done || isDone ? (
                    <Icon name="check" size={14} />
                  ) : active ? (
                    <span
                      style={{
                        width: 8,
                        height: 8,
                        borderRadius: "50%",
                        background: "var(--accent)",
                        display: "block",
                        animation: "pulse 1.2s ease-in-out infinite",
                      }}
                    />
                  ) : (
                    <span
                      style={{
                        width: 6,
                        height: 6,
                        borderRadius: "50%",
                        background: "var(--fg-faint)",
                        display: "block",
                      }}
                    />
                  )}
                </div>
                <span
                  style={{
                    fontSize: 11,
                    textAlign: "center",
                    lineHeight: 1.3,
                    color:
                      done || isDone
                        ? "var(--fg)"
                        : active
                          ? "var(--accent)"
                          : "var(--fg-faint)",
                    fontWeight: active || done || isDone ? 500 : 400,
                    maxWidth: 80,
                  }}
                >
                  {s.label}
                </span>
              </div>
              {!isLast && (
                <div
                  style={{
                    flex: 1,
                    height: 2,
                    background:
                      i < currentIdx || isDone
                        ? "var(--accent)"
                        : "var(--border)",
                    transition: "background 0.3s",
                    marginBottom: 22,
                  }}
                />
              )}
            </React.Fragment>
          );
        })}
      </div>

      {/* Кнопки */}
      <div style={{ display: "flex", gap: 10 }}>
        {!isDone && (
          <button className="btn danger" onClick={onStop}>
            <Icon name="x" size={13} /> {T.stopRun || "Остановить"}
          </button>
        )}
        {isDone && (
          <>
            <button className="btn" onClick={onNewAnalysis}>
              <Icon name="plus" size={13} /> {T.newAnalysis || "Новый анализ"}
            </button>
            <button className="btn primary" onClick={onViewResults}>
              <Icon name="arrow-right" size={13} />{" "}
              {T.viewResults || "Смотреть результаты"}
            </button>
          </>
        )}
      </div>
    </div>
  );
};

// ── RunProgress ────────────────────────────────────────────────────────────

const RunProgress = ({
  log,
  progress,
  state,
  channelCount,
  mode,
  analyzeComments,
  onStop,
  onViewResults,
  onNewAnalysis,
}) => {
  const T = window.T || {};
  const isDone = state === "done";

  const allStages = [
    { id: "init", label: T.pipelineInit || "Запускаю" },
    { id: "collect", label: T.pipelineCollect || "Собираю видео" },
    { id: "transcript", label: T.pipelineTranscript || "Читаю транскрипты" },
    { id: "comments", label: T.pipelineComments || "Собираю комментарии" },
    { id: "analyze", label: T.pipelineAnalyze || "Анализирую" },
    { id: "done", label: T.pipelineDone || "Готово" },
  ];

  // Шаг "Анализирую" только если включён Claude AI
  const stages = allStages.filter((s) => s.id !== "analyze" || analyzeComments);

  const currentIdx = isDone
    ? stages.length
    : Math.min(progress, stages.length - 1);

  return (
    <div className="page" style={{ maxWidth: 720 }}>
      {/* ── Горизонтальный пайплайн ── */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 0,
          marginBottom: 48,
          marginTop: 24,
        }}
      >
        {stages.map((s, i) => {
          const done = i < currentIdx;
          const active = i === currentIdx && !isDone;
          const isLast = i === stages.length - 1;

          return (
            <React.Fragment key={s.id}>
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  gap: 8,
                  minWidth: 80,
                }}
              >
                {/* Dot */}
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: "50%",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    fontSize: 13,
                    fontWeight: 700,
                    background:
                      done || isDone
                        ? "var(--accent)"
                        : active
                          ? "var(--accent-soft)"
                          : "var(--bg-sunk)",
                    border: active
                      ? "2px solid var(--accent)"
                      : "2px solid transparent",
                    color:
                      done || isDone
                        ? "white"
                        : active
                          ? "var(--accent)"
                          : "var(--fg-faint)",
                    transition: "all 0.3s",
                    boxShadow: active ? "0 0 0 4px var(--accent-soft)" : "none",
                  }}
                >
                  {done || isDone ? (
                    <Icon name="check" size={14} />
                  ) : active ? (
                    <span
                      style={{
                        width: 8,
                        height: 8,
                        borderRadius: "50%",
                        background: "var(--accent)",
                        animation: "pulse 1.2s ease-in-out infinite",
                      }}
                    />
                  ) : (
                    <span
                      style={{
                        width: 6,
                        height: 6,
                        borderRadius: "50%",
                        background: "var(--fg-faint)",
                      }}
                    />
                  )}
                </div>
                {/* Label */}
                <span
                  style={{
                    fontSize: 11,
                    textAlign: "center",
                    lineHeight: 1.3,
                    color:
                      done || isDone
                        ? "var(--fg)"
                        : active
                          ? "var(--accent)"
                          : "var(--fg-faint)",
                    fontWeight: active || done || isDone ? 500 : 400,
                    maxWidth: 80,
                  }}
                >
                  {s.label}
                </span>
              </div>
              {/* Connector line */}
              {!isLast && (
                <div
                  style={{
                    flex: 1,
                    height: 2,
                    background:
                      i < currentIdx || isDone
                        ? "var(--accent)"
                        : "var(--border)",
                    transition: "background 0.3s",
                    marginBottom: 22,
                  }}
                />
              )}
            </React.Fragment>
          );
        })}
      </div>

      {/* ── Кнопки ── */}
      <div style={{ display: "flex", gap: 10, justifyContent: "center" }}>
        {!isDone && (
          <button className="btn danger" onClick={onStop}>
            <Icon name="x" size={13} /> {T.stopRun || "Остановить"}
          </button>
        )}
        {isDone && (
          <>
            <button className="btn" onClick={onNewAnalysis}>
              <Icon name="plus" size={13} /> {T.newAnalysis || "Новый анализ"}
            </button>
            <button className="btn primary" onClick={onViewResults}>
              <Icon name="arrow-right" size={13} />{" "}
              {T.viewResults || "Смотреть результаты"}
            </button>
          </>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { LoginScreen, AnalysisScreen, RunProgress });
