/* Keywords — единый Поиск EN+RU (YOUN-11) */
/* Единая таблица: Overall · Competition · Avg Views · Search Index · Verdict */
/* RU дополнительно: Частотность · KSI */

const API_URL_KW = "https://younalyse-api-646149995822.europe-west1.run.app";

const getProductMode = () =>
  window.PRODUCT_MODE || localStorage.getItem("youna_product_mode") || "ru";
const setProductMode = (mode) => {
  localStorage.setItem("youna_product_mode", mode);
  window.PRODUCT_MODE = mode;
  window.PRODUCT_NAME = mode === "ru" ? "Youna" : "Younalyse";
  window.PRODUCT_CURRENCY = mode === "ru" ? "rub" : "eur";
};

// ── Badges ─────────────────────────────────────────────────────────────────

const OverallScoreBadge = ({ score, signal }) => {
  if (score === undefined || score === null || score === 0)
    return <span style={{ color: "var(--fg-faint)", fontSize: 12 }}>—</span>;
  const color =
    signal === "high"
      ? "var(--good)"
      : signal === "medium"
        ? "var(--warn)"
        : "var(--bad)";
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        fontSize: 12,
        fontWeight: 600,
        color,
      }}
    >
      <span
        style={{
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          width: 32,
          height: 18,
          borderRadius: 4,
          background: color,
          color: "#fff",
          fontSize: 11,
          fontWeight: 700,
        }}
      >
        {score.toFixed(0)}
      </span>
    </span>
  );
};

const CompetitionBadge = ({ score }) => {
  if (score === undefined || score === null)
    return <span style={{ color: "var(--fg-faint)" }}>—</span>;
  const color =
    score >= 70 ? "var(--bad)" : score >= 40 ? "var(--warn)" : "var(--good)";
  const label = score >= 70 ? "High" : score >= 40 ? "Med" : "Low";
  return (
    <span style={{ fontSize: 11, fontWeight: 600, color }}>
      {label} {score.toFixed(0)}
    </span>
  );
};

const VerdictBadge = ({ verdict }) => {
  if (!verdict || verdict === "Недостаточно данных")
    return (
      <span
        style={{ fontSize: 11, color: "var(--fg-faint)", fontStyle: "italic" }}
      >
        —
      </span>
    );
  const color =
    verdict === "Отличная возможность"
      ? "var(--good)"
      : verdict === "Хорошая возможность для малого канала"
        ? "var(--good)"
        : verdict === "Высокий спрос, высокая конкуренция"
          ? "var(--warn)"
          : verdict === "Очень высокая конкуренция"
            ? "var(--bad)"
            : "var(--fg-muted)";
  return (
    <span style={{ fontSize: 11, fontWeight: 500, color }}>{verdict}</span>
  );
};

const KsiBadge = ({ signal, ksi }) => {
  if (ksi === undefined || ksi === null)
    return <span style={{ color: "var(--fg-faint)" }}>—</span>;
  const cfg = {
    high: { emoji: "🟢", color: "var(--good)" },
    medium: { emoji: "🟡", color: "var(--warn)" },
    low: { emoji: "🔴", color: "var(--bad)" },
  }[signal] || { emoji: "⚪", color: "var(--fg-faint)" };
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 4,
        fontSize: 12,
        fontWeight: 500,
        color: cfg.color,
      }}
    >
      {cfg.emoji} {ksi.toFixed(0)}
    </span>
  );
};

const FreqBar = ({ value, max }) => {
  const pct = max > 0 ? Math.min(100, (value / max) * 100) : 0;
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        fontFamily: "var(--mono)",
        fontSize: 12,
      }}
    >
      <span
        style={{
          width: 48,
          height: 4,
          borderRadius: 2,
          background: "var(--bg-sunk)",
          display: "inline-block",
          overflow: "hidden",
        }}
      >
        <span
          style={{
            display: "block",
            height: "100%",
            borderRadius: 2,
            width: pct + "%",
            background: "var(--accent)",
          }}
        />
      </span>
      {window.fmtNum(value)}
    </span>
  );
};

const LoadingDots = () => (
  <span
    style={{
      color: "var(--fg-faint)",
      fontSize: 12,
      fontFamily: "var(--mono)",
    }}
  >
    ···
  </span>
);

// ── Единая строка таблицы ──────────────────────────────────────────────────

const KeywordRow = ({
  r,
  isRU,
  maxFreq,
  isFav,
  onFavorite,
  onSearch,
  enriched,
  loading,
}) => {
  const metrics = enriched || r;
  const isLoading = loading && !enriched;
  const isMain = r.is_main;

  return (
    <tr style={isMain ? { background: "var(--bg-elev)" } : {}}>
      {/* Keyword */}
      <td>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {isMain && (
            <span
              style={{
                fontSize: 10,
                color: "var(--accent)",
                fontWeight: 600,
                background: "var(--accent-soft)",
                padding: "1px 6px",
                borderRadius: 3,
              }}
            >
              →
            </span>
          )}
          <span
            style={{
              fontWeight: isMain ? 600 : 500,
              cursor: "pointer",
              color: "var(--accent)",
            }}
            onClick={() => onSearch && onSearch(r.keyword)}
            title="Искать этот запрос"
          >
            {r.keyword}
          </span>
          {metrics.yt_cached && !isMain && (
            <span
              style={{
                fontSize: 9,
                color: "var(--fg-faint)",
                background: "var(--bg-sunk)",
                padding: "1px 4px",
                borderRadius: 2,
              }}
            >
              кэш
            </span>
          )}
        </div>
        {metrics.verdict && !metrics.error && (
          <VerdictBadge verdict={metrics.verdict} />
        )}
        {metrics.error === "limit_exceeded" && (
          <div style={{ fontSize: 11, color: "var(--bad)" }}>
            лимит исчерпан
          </div>
        )}
      </td>

      {/* Overall */}
      <td>
        {isLoading ? (
          <LoadingDots />
        ) : (
          <OverallScoreBadge
            score={metrics.overall_score}
            signal={metrics.signal}
          />
        )}
      </td>

      {/* Competition */}
      <td>
        {isLoading ? (
          <LoadingDots />
        ) : (
          <CompetitionBadge score={metrics.competition_score} />
        )}
      </td>

      {/* Avg Views */}
      <td
        style={{
          fontFamily: "var(--mono)",
          fontSize: 12,
          color: "var(--fg-muted)",
        }}
      >
        {isLoading ? (
          <LoadingDots />
        ) : (
          metrics.avg_views_formatted ||
          (metrics.avg_views ? window.fmtNum(metrics.avg_views) : "—")
        )}
      </td>

      {/* Search Index (YouTube) */}
      <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
        {isLoading ? (
          <LoadingDots />
        ) : (
          metrics.search_index_formatted ||
          (metrics.search_index ? window.fmtNum(metrics.search_index) : "—")
        )}
      </td>

      {/* RU-only: Частотность */}
      {isRU && (
        <td className="num">
          {r.frequency !== undefined && r.frequency !== null ? (
            <FreqBar value={r.frequency} max={maxFreq} />
          ) : (
            <span style={{ color: "var(--fg-faint)" }}>—</span>
          )}
        </td>
      )}

      {/* RU-only: KSI */}
      {isRU && (
        <td>
          {r.ksi !== undefined && r.ksi !== null ? (
            <KsiBadge signal={r.signal} ksi={r.ksi} />
          ) : (
            <span style={{ color: "var(--fg-faint)" }}>—</span>
          )}
        </td>
      )}

      {/* Favorite */}
      <td>
        <button
          className="btn ghost sm"
          onClick={() => onFavorite(r.keyword)}
          style={{ color: isFav ? "var(--accent)" : "var(--fg-faint)" }}
        >
          {isFav ? "★" : "☆"}
        </button>
      </td>
    </tr>
  );
};

// ── Keywords screen ────────────────────────────────────────────────────────
const KeywordsScreen = ({ userId, userProfile, activeChannel }) => {
  const [productMode, setProductModeState] = React.useState(getProductMode());
  const [searchPhrase, setSearchPhrase] = React.useState("");
  const [topicAnchor, setTopicAnchor] = React.useState("");

  const [mainRow, setMainRow] = React.useState(null);
  const [suggestions, setSuggestions] = React.useState([]);
  const [enrichedMap, setEnrichedMap] = React.useState({}); // keyword → metrics
  const [loadingEnrich, setLoadingEnrich] = React.useState(new Set());
  const [currentPhrase, setCurrentPhrase] = React.useState("");

  const [favorites, setFavorites] = React.useState([]);
  const [selectedTags, setSelectedTags] = React.useState([]);
  const [copiedTags, setCopiedTags] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [usage, setUsage] = React.useState(null);
  const [mainTab, setMainTab] = React.useState("search");
  const [error, setError] = React.useState("");

  const [usageData, setUsageData] = React.useState(null);
  React.useEffect(() => {
    if (!userId) return;
    fetch(`${API_URL_KW}/api/profile/usage?user_id=${userId}`)
      .then((r) => r.json())
      .then((data) => {
        setUsageData(data);
        // Публикуем квоту для топбара
        window._kwUsage = data;
      })
      .catch(() => {});
  }, [userId]);

  const tier = userProfile?.subscription_tier || "free";
  // Keywords доступен: start, pro, producer, studio, trial, superadmin
  // Недоступен: free, expired
  const isAvailable = !["free", "expired"].includes(tier);
  const isRU = window.PRODUCT_MODE === "ru";

  const switchProductMode = (m) => {
    setProductModeState(m);
    setProductMode(m);
    setMainRow(null);
    setSuggestions([]);
    setEnrichedMap({});
    setSearchPhrase("");
    setError("");
    loadUsage(m);
  };

  React.useEffect(() => {
    if (!userId) return;
    loadUsage();
    loadFavorites();
  }, [userId]);

  const loadUsage = (pm = productMode) => {
    if (!userId) return;
    fetch(
      `${API_URL_KW}/api/keywords/usage?user_id=${userId}&product_mode=${pm}`,
    )
      .then((r) => r.json())
      .then(setUsage)
      .catch(() => {});
  };

  const loadFavorites = () => {
    if (!userId) return;
    fetch(`${API_URL_KW}/api/keywords/favorites?user_id=${userId}`)
      .then((r) => r.json())
      .then((json) => setFavorites(json.favorites || []))
      .catch(() => {});
  };

  // ── Основной поиск ────────────────────────────────────────────────────
  const handleSearch = async (phrase) => {
    const p = (phrase || searchPhrase).trim();
    if (!p) return;
    setSearchPhrase(p);
    setCurrentPhrase(p);
    setLoading(true);
    setError("");
    setMainRow(null);
    setSuggestions([]);
    setEnrichedMap({});

    try {
      const params = new URLSearchParams({
        phrase: p,
        user_id: userId || "",
        product_mode: productMode,
      });
      if (isRU) {
        params.set("region_id", "213");
        if (topicAnchor.trim()) params.set("topic_anchor", topicAnchor.trim());
      } else {
        params.set("region_code", "US");
        params.set("lang", "en");
      }

      const resp = await fetch(`${API_URL_KW}/api/keywords/search?${params}`);
      const json = await resp.json();

      if (json.error) {
        setError(json.error);
      } else {
        setMainRow(json.main_row || null);
        setSuggestions(json.suggestions || []);
        loadUsage();

        // Автоматически загружаем метрики для первых 10 подсказок
        if (json.suggestions && json.suggestions.length > 0) {
          enrichBatch(json.suggestions.slice(0, 10).map((s) => s.keyword));
        }
      }
    } catch (e) {
      setError(isRU ? "Не удалось получить данные." : "Failed to fetch data.");
    } finally {
      setLoading(false);
    }
  };

  // ── Батч загрузка метрик (lazy) ───────────────────────────────────────
  const enrichBatch = async (keywords) => {
    const toFetch = keywords.filter(
      (kw) => !enrichedMap[kw] && !loadingEnrich.has(kw),
    );
    if (toFetch.length === 0) return;

    setLoadingEnrich((prev) => new Set([...prev, ...toFetch]));

    try {
      const resp = await fetch(`${API_URL_KW}/api/keywords/search/enrich`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          keywords: toFetch,
          user_id: userId || "",
          product_mode: productMode,
          region_code: "US",
          lang: "en",
        }),
      });
      const json = await resp.json();
      if (json.results) {
        setEnrichedMap((prev) => {
          const updated = { ...prev };
          json.results.forEach((r) => {
            updated[r.keyword] = r;
          });
          return updated;
        });
        loadUsage();
      }
    } catch (e) {
      console.error("Enrich error:", e);
    } finally {
      setLoadingEnrich((prev) => {
        const next = new Set(prev);
        toFetch.forEach((kw) => next.delete(kw));
        return next;
      });
    }
  };

  // Загружаем следующую порцию когда пользователь скроллит
  const handleLoadMore = () => {
    const alreadyLoaded = Object.keys(enrichedMap).length + 10;
    const nextBatch = suggestions
      .slice(alreadyLoaded, alreadyLoaded + 10)
      .map((s) => s.keyword);
    if (nextBatch.length > 0) enrichBatch(nextBatch);
  };

  const handleFavorite = async (keyword) => {
    const alreadyFav = favorites.some((f) => f.keyword === keyword);
    if (alreadyFav) {
      await fetch(
        `${API_URL_KW}/api/keywords/favorites/${encodeURIComponent(keyword)}?user_id=${userId}`,
        { method: "DELETE" },
      );
    } else {
      await fetch(`${API_URL_KW}/api/keywords/favorites`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          user_id: userId,
          keyword,
          product_mode: productMode,
        }),
      });
    }
    loadFavorites();
  };

  const isFav = (kw) => favorites.some((f) => f.keyword === kw);

  // Объединяем main_row + suggestions для таблицы
  const allRows = React.useMemo(() => {
    if (!mainRow) return [];
    return [mainRow, ...suggestions];
  }, [mainRow, suggestions]);

  const maxFreq = React.useMemo(() => {
    if (!isRU) return 0;
    const freqs = allRows.map((r) => r.frequency || 0).filter(Boolean);
    return freqs.length > 0 ? Math.max(...freqs) : 0;
  }, [allRows, isRU]);

  const loadedCount = Object.keys(enrichedMap).length;
  const hasMore = loadedCount < suggestions.length;

  // ── Upsell ────────────────────────────────────────────────────────────
  if (!isAvailable) {
    return (
      <div className="page" style={{ maxWidth: 720 }}>
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
            padding: "80px 32px",
            textAlign: "center",
            border: "1px dashed var(--border-strong)",
            borderRadius: "var(--radius-lg)",
            background: "var(--bg-elev)",
          }}
        >
          <div style={{ fontSize: 48, marginBottom: 16 }}>🔑</div>
          <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 8 }}>
            {window.T?.keywordsUpsell ||
              "Keyword Research недоступен на вашем тире"}
          </div>
          <button
            className="btn primary lg"
            onClick={() =>
              window.dispatchEvent(
                new CustomEvent("navigate", { detail: "plans" }),
              )
            }
          >
            {window.T?.keywordsGoToPlans || "Перейти на Plans"}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="page" style={{ maxWidth: 1200 }}>
      {/* Главные табы */}
      <div className="segmented" style={{ marginBottom: 20 }}>
        {[
          { id: "search", label: isRU ? "Поиск" : "Search" },
          {
            id: "favorites",
            label: `${isRU ? "Избранное" : "Favorites"}${favorites.length > 0 ? ` (${favorites.length})` : ""}`,
          },
        ].map((t) => (
          <button
            key={t.id}
            className={mainTab === t.id ? "active" : ""}
            onClick={() => setMainTab(t.id)}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* ── Поиск ──────────────────────────────────────────────────────── */}
      {mainTab === "search" && (
        <>
          {/* Форма */}
          <div className="form-card" style={{ marginBottom: 20 }}>
            <div
              style={{
                display: "grid",
                gridTemplateColumns: isRU ? "1fr 1fr" : "1fr",
                gap: 16,
              }}
            >
              <div>
                <h3>
                  {isRU ? "Ключевое слово или фраза" : "Keyword or phrase"}
                </h3>
                <p className="hint">
                  {isRU
                    ? "Введите одну фразу — получите список похожих запросов с метриками"
                    : "Enter one phrase — get related keywords with YouTube metrics"}
                </p>
                <div style={{ display: "flex", gap: 10 }}>
                  <input
                    className="input"
                    style={{ flex: 1 }}
                    value={searchPhrase}
                    onChange={(e) => setSearchPhrase(e.target.value)}
                    placeholder={
                      isRU ? "youtube продвижение" : "youtube growth"
                    }
                    onKeyDown={(e) => {
                      if (e.key === "Enter") handleSearch();
                    }}
                  />
                  <button
                    className="btn primary"
                    onClick={() => handleSearch()}
                    disabled={loading || !searchPhrase.trim()}
                  >
                    {loading ? (
                      <>
                        <Icon name="spinner" size={13} />{" "}
                        {isRU ? "Ищем…" : "Searching…"}
                      </>
                    ) : isRU ? (
                      "Найти"
                    ) : (
                      "Search"
                    )}
                  </button>
                  {allRows.length > 0 && (
                    <button
                      className="btn ghost sm"
                      onClick={() => {
                        setMainRow(null);
                        setSuggestions([]);
                        setSearchPhrase("");
                        setEnrichedMap({});
                        setError("");
                      }}
                    >
                      {isRU ? "Очистить" : "Clear"}
                    </button>
                  )}
                </div>
              </div>
              {isRU && (
                <div>
                  <h3>{window.T?.kwTopicTitle || "Тема канала"}</h3>
                  <p className="hint">
                    {window.T?.kwTopicHint ||
                      "Опорный запрос для расчёта силы ключей относительно ниши."}
                  </p>
                  <input
                    className="input"
                    value={topicAnchor}
                    onChange={(e) => setTopicAnchor(e.target.value)}
                    placeholder={
                      window.T?.kwTopicPlaceholder ||
                      "например: youtube продвижение"
                    }
                  />
                </div>
              )}
            </div>
          </div>

          {error && (
            <div
              style={{
                padding: "12px 16px",
                borderRadius: "var(--radius)",
                background: "rgba(220,38,38,0.08)",
                color: "var(--bad)",
                fontSize: 13,
                marginBottom: 16,
              }}
            >
              {error === "unavailable_for_tier"
                ? isRU
                  ? "Недоступно на вашем тире"
                  : "Not available on your plan"
                : error === "limit_exceeded"
                  ? isRU
                    ? "Лимит запросов исчерпан"
                    : "Monthly limit reached"
                  : error}
            </div>
          )}

          {/* Таблица результатов */}
          {allRows.length > 0 && (
            <>
              <div className="table-wrap">
                <div className="table-toolbar">
                  <span style={{ fontSize: 13, color: "var(--fg-muted)" }}>
                    {isRU ? `По запросу: ` : `Results for: `}
                    <strong>{currentPhrase}</strong>
                    {` · ${allRows.length} ${isRU ? "ключей" : "keywords"}`}
                  </span>
                  <div style={{ flex: 1 }} />
                  <span className="help">
                    {isRU
                      ? "Метрики: Wordstat + YouTube"
                      : "Source: YouTube SERP + Autocomplete"}
                  </span>
                </div>
                <div className="table-scroll">
                  <table className="data">
                    <thead>
                      <tr>
                        <th style={{ minWidth: 280 }}>
                          {isRU ? "Ключевое слово" : "Keyword"}
                        </th>
                        <th>Overall</th>
                        <th>Competition</th>
                        <th className="num">Avg Views</th>
                        <th className="num">Search Index</th>
                        {isRU && <th className="num">Частотность</th>}
                        {isRU && <th>KSI</th>}
                        <th style={{ width: 40 }}></th>
                      </tr>
                    </thead>
                    <tbody>
                      {allRows.map((r, i) => {
                        const isMainRow = r.is_main;
                        const enriched = isMainRow
                          ? null
                          : enrichedMap[r.keyword];
                        const isEnrichLoading =
                          !isMainRow &&
                          !enriched &&
                          loadingEnrich.has(r.keyword);
                        const isPending =
                          !isMainRow && !enriched && !isEnrichLoading;
                        return (
                          <KeywordRow
                            key={i}
                            r={r}
                            isRU={isRU}
                            maxFreq={maxFreq}
                            isFav={isFav(r.keyword)}
                            onFavorite={handleFavorite}
                            onSearch={handleSearch}
                            enriched={isMainRow ? r : enriched}
                            loading={isEnrichLoading}
                          />
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Load more */}
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  marginTop: 12,
                }}
              >
                {hasMore && (
                  <button className="btn sm" onClick={handleLoadMore}>
                    {isRU
                      ? `Загрузить метрики (ещё ${suggestions.length - loadedCount})`
                      : `Load metrics (${suggestions.length - loadedCount} more)`}
                  </button>
                )}
                <span style={{ fontSize: 12, color: "var(--fg-faint)" }}>
                  {isRU
                    ? `Overall = 0.5 × Avg Views + 0.5 × (1 − Competition). Нажмите на ключ чтобы искать его.`
                    : `Overall = 0.5 × demand + 0.5 × (1 − competition). Click any keyword to search it.`}
                </span>
              </div>
            </>
          )}
        </>
      )}

      {/* ── Избранное ──────────────────────────────────────────────────── */}
      {mainTab === "favorites" && (
        <div style={{ display: "flex", gap: 16, alignItems: "flex-start" }}>
          <div style={{ flex: "0 0 58%" }}>
            <div className="table-wrap">
              {favorites.length === 0 ? (
                <div
                  style={{
                    padding: "60px 32px",
                    textAlign: "center",
                    color: "var(--fg-muted)",
                  }}
                >
                  <div style={{ fontSize: 32, marginBottom: 12 }}>☆</div>
                  <div
                    style={{ fontSize: 15, fontWeight: 500, marginBottom: 6 }}
                  >
                    {isRU ? "Нет избранных ключей" : "No favorite keywords"}
                  </div>
                  <div style={{ fontSize: 13, color: "var(--fg-faint)" }}>
                    {isRU
                      ? "Добавляйте ключи через ★ в результатах поиска."
                      : "Add keywords via ★ in search results."}
                  </div>
                </div>
              ) : (
                <>
                  <div className="table-toolbar">
                    <span style={{ fontSize: 13, color: "var(--fg-muted)" }}>
                      {favorites.length} {isRU ? "ключевых слов" : "keywords"}
                    </span>
                    <div style={{ flex: 1 }} />
                    <button
                      className="btn sm"
                      onClick={() => {
                        setMainTab("search");
                        handleSearch(favorites[0]?.keyword);
                      }}
                    >
                      {isRU ? "Искать первый" : "Search first"}
                    </button>
                  </div>
                  <div className="table-scroll">
                    <table className="data">
                      <thead>
                        <tr>
                          <th style={{ minWidth: 260 }}>
                            {isRU ? "Ключевое слово" : "Keyword"}
                          </th>
                          <th>{isRU ? "Добавлено" : "Added"}</th>
                          <th style={{ width: 80, textAlign: "center" }}>
                            {isRU ? "В теги" : "To tags"}
                          </th>
                          <th style={{ width: 40 }}></th>
                        </tr>
                      </thead>
                      <tbody>
                        {favorites.map((f, i) => {
                          const isSelected = selectedTags.includes(f.keyword);
                          return (
                            <tr
                              key={i}
                              style={
                                isSelected
                                  ? { background: "var(--accent-soft)" }
                                  : {}
                              }
                            >
                              <td>
                                <span
                                  style={{
                                    fontWeight: 500,
                                    cursor: "pointer",
                                    color: "var(--accent)",
                                  }}
                                  onClick={() => {
                                    setMainTab("search");
                                    handleSearch(f.keyword);
                                  }}
                                >
                                  {f.keyword}
                                </span>
                              </td>
                              <td
                                style={{
                                  color: "var(--fg-faint)",
                                  fontSize: 12,
                                }}
                              >
                                {f.created_at
                                  ? window.fmtDate(f.created_at)
                                  : "—"}
                              </td>
                              <td style={{ textAlign: "center" }}>
                                <button
                                  className="btn ghost sm"
                                  style={{
                                    color: isSelected
                                      ? "var(--accent)"
                                      : "var(--fg-faint)",
                                    fontSize: 16,
                                  }}
                                  onClick={() => {
                                    if (isSelected)
                                      setSelectedTags((prev) =>
                                        prev.filter((t) => t !== f.keyword),
                                      );
                                    else
                                      setSelectedTags((prev) => [
                                        ...prev,
                                        f.keyword,
                                      ]);
                                  }}
                                >
                                  {isSelected ? "◉" : "○"}
                                </button>
                              </td>
                              <td>
                                <button
                                  className="btn ghost sm"
                                  onClick={() => handleFavorite(f.keyword)}
                                  style={{ color: "var(--bad)" }}
                                >
                                  ✕
                                </button>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                </>
              )}
            </div>
          </div>

          {/* Конструктор тегов */}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                border: "1px solid var(--border-strong)",
                borderRadius: "var(--radius)",
                background: "var(--bg)",
                padding: "12px 14px",
                minHeight: 160,
                display: "flex",
                flexDirection: "column",
                gap: 8,
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                }}
              >
                <span
                  style={{
                    fontSize: 12,
                    fontWeight: 500,
                    color: "var(--fg-muted)",
                  }}
                >
                  {isRU ? "Теги для видео" : "Video tags"}
                </span>
                <button
                  className="btn ghost sm"
                  disabled={selectedTags.length === 0}
                  style={{
                    color: copiedTags ? "var(--good)" : "var(--fg-faint)",
                    padding: "0 6px",
                  }}
                  onClick={() => {
                    navigator.clipboard.writeText(selectedTags.join(", "));
                    setCopiedTags(true);
                    setTimeout(() => setCopiedTags(false), 2000);
                    selectedTags.forEach((tag) => {
                      fetch(`${API_URL_KW}/api/keywords/event`, {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({
                          user_id: userId,
                          keyword: tag,
                          event_type: "copy",
                          product_mode: productMode,
                        }),
                      }).catch(() => {});
                    });
                  }}
                >
                  {copiedTags ? (
                    <>
                      <Icon name="check" size={13} />{" "}
                      {isRU ? "Скопировано" : "Copied!"}
                    </>
                  ) : (
                    <Icon name="download" size={13} />
                  )}
                </button>
              </div>
              <div
                style={{
                  flex: 1,
                  display: "flex",
                  flexWrap: "wrap",
                  gap: 6,
                  alignContent: "flex-start",
                }}
              >
                {selectedTags.length === 0 ? (
                  <span
                    style={{
                      fontSize: 13,
                      color: "var(--fg-faint)",
                      fontStyle: "italic",
                      padding: "4px 0",
                    }}
                  >
                    {isRU
                      ? "Выберите теги из избранного слева"
                      : "Select keywords from favorites on the left"}
                  </span>
                ) : (
                  selectedTags.map((tag, i) => (
                    <span
                      key={i}
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 5,
                        padding: "3px 8px",
                        borderRadius: 4,
                        background: "var(--accent-soft)",
                        border: "1px solid var(--accent)",
                        fontSize: 12,
                        color: "var(--accent)",
                      }}
                    >
                      {tag}
                      <button
                        onClick={() =>
                          setSelectedTags((prev) =>
                            prev.filter((t) => t !== tag),
                          )
                        }
                        style={{
                          background: "none",
                          border: "none",
                          cursor: "pointer",
                          color: "var(--accent)",
                          padding: 0,
                          fontSize: 13,
                          lineHeight: 1,
                        }}
                      >
                        ✕
                      </button>
                    </span>
                  ))
                )}
              </div>
              <div
                style={{
                  fontSize: 11,
                  color:
                    selectedTags.join(", ").length > 450
                      ? "var(--bad)"
                      : "var(--fg-faint)",
                  textAlign: "right",
                }}
              >
                {selectedTags.join(", ").length} / 500
              </div>
            </div>
            {selectedTags.length > 0 && (
              <div
                style={{
                  marginTop: 8,
                  padding: "8px 10px",
                  background: "var(--bg-sunk)",
                  borderRadius: "var(--radius-sm)",
                  fontSize: 11,
                  color: "var(--fg-faint)",
                  lineHeight: 1.5,
                  wordBreak: "break-word",
                }}
              >
                {selectedTags.join(", ")}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { KeywordsScreen });
