/* Transcripts screen — YOUN-71 */

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

const TranscriptsScreen = ({
  userId,
  activeChannel,
  onOpenVideo,
  allResults,
  onToast,
}) => {
  const [transcripts, setTranscripts] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [loading, setLoading] = React.useState(true);
  const [tab, setTab] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const [expanded, setExpanded] = React.useState({});
  const [pageSize, setPageSize] = React.useState(50);
  const [page, setPage] = React.useState(0);
  const [sortDir, setSortDir] = React.useState("desc");
  const [selectedChannel, setSelectedChannel] = React.useState("");
  const [availableChannels, setAvailableChannels] = React.useState([]);

  React.useEffect(() => {
    if (!userId) return;
    fetch(`${API_URL_TR}/api/compare/channels-list?user_id=${userId}`)
      .then((r) => r.json())
      .then((d) => setAvailableChannels(d.channels || []))
      .catch(() => {});
  }, [userId]);

  const toggleSort = () => setSortDir((d) => (d === "asc" ? "desc" : "asc"));
  const SortIco = () => (
    <Icon
      name={sortDir === "asc" ? "chevron-up" : "chevron-down"}
      size={11}
      className="sort"
    />
  );

  // Outlier score из allResults
  const [channelAvg, setChannelAvg] = React.useState({});
  React.useEffect(() => {
    fetch(`${API_URL_TR}/api/channels/avg-views`)
      .then((r) => r.json())
      .then((d) => setChannelAvg(d.channel_avg_views || {}))
      .catch(() => {});
  }, []);

  const getOutlierScore = (channelName, views) => {
    const avg = channelAvg[channelName];
    if (!avg || avg === 0 || !views) return null;
    return views / avg;
  };

  const OutlierChip = ({ score }) => {
    if (score === null || score === undefined)
      return <span style={{ color: "var(--fg-faint)" }}>—</span>;
    let icon, bg;
    if (score >= 2) {
      icon = "🔥";
      bg = "var(--good)";
    } else if (score >= 1.2) {
      icon = "↑";
      bg = "var(--accent)";
    } else if (score >= 0.8) {
      icon = "→";
      bg = "var(--fg-faint)";
    } else {
      icon = "↓";
      bg = "var(--bad)";
    }
    return (
      <span
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 4,
          padding: "2px 7px",
          borderRadius: 4,
          background: bg,
          color: "#fff",
          fontSize: 11,
          fontFamily: "var(--mono)",
          fontWeight: 600,
          whiteSpace: "nowrap",
        }}
      >
        {icon} {score.toFixed(1)}x
      </span>
    );
  };

  const load = (
    currentTab = tab,
    currentPage = page,
    currentPageSize = pageSize,
  ) => {
    if (!userId) return;
    setLoading(true);
    const params = new URLSearchParams({
      user_id: userId,
      limit: currentPageSize,
      offset: currentPage * currentPageSize,
    });
    if (selectedChannel) params.set("channel_name", selectedChannel);
    if (currentTab === "favorites") params.set("favorites_only", "true");
    fetch(`${API_URL_TR}/api/transcripts?${params}`)
      .then((r) => r.json())
      .then((d) => {
        setTranscripts(d.transcripts || []);
        setTotal(d.total || 0);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  };

  React.useEffect(() => {
    setPage(0);
    load(tab, 0, pageSize);
  }, [userId, selectedChannel, tab]);
  React.useEffect(() => {
    load(tab, page, pageSize);
  }, [page, pageSize]);

  const toggleFavorite = async (t) => {
    // Оптимистичное обновление
    setTranscripts((prev) =>
      prev.map((tr) =>
        tr.video_id === t.video_id
          ? { ...tr, is_favorite: !tr.is_favorite }
          : tr,
      ),
    );
    const method = t.is_favorite ? "DELETE" : "POST";
    fetch(
      `${API_URL_TR}/api/transcripts/favorites/${t.video_id}?user_id=${userId}`,
      { method },
    ).catch(() => load());
  };

  const handleOpenVideo = (t) => {
    if (!onOpenVideo || !allResults) return;
    const video = allResults.find((r) => r.url === t.url);
    if (video) onOpenVideo(video);
  };

  const toggleExpand = (videoId) =>
    setExpanded((prev) => ({ ...prev, [videoId]: !prev[videoId] }));

  // Метрики из allResults по url
  const getVideoMetrics = (url) => {
    if (!allResults) return {};
    return allResults.find((r) => r.url === url) || {};
  };

  const filtered = React.useMemo(() => {
    let list = transcripts.filter((t) => {
      if (!search) return true;
      const q = search.toLowerCase();
      return (
        t.title?.toLowerCase().includes(q) ||
        t.channel_name?.toLowerCase().includes(q) ||
        t.transcript_preview?.toLowerCase().includes(q)
      );
    });
    return [...list].sort((a, b) => {
      const av = a.published_at || "";
      const bv = b.published_at || "";
      const cmp = String(av).localeCompare(String(bv));
      return sortDir === "asc" ? cmp : -cmp;
    });
  }, [transcripts, search, sortDir]);

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className="page" style={{ maxWidth: 1600 }}>
      <div className="table-wrap">
        <div className="table-toolbar">
          <Search
            value={search}
            onChange={setSearch}
            placeholder={
              window.T?.transcriptsSearchPlaceholder ||
              "Поиск по названию, каналу, тексту…"
            }
          />
          {availableChannels.length > 0 && (
            <select
              className="select"
              value={selectedChannel}
              onChange={(e) => {
                setSelectedChannel(e.target.value);
                setPage(0);
              }}
              style={{ height: 30, fontSize: 12, width: 180 }}
            >
              <option value="">
                {window.T?.resultsAllChannels || "Все каналы"}
              </option>
              {availableChannels.map((ch) => (
                <option key={ch.channel_name} value={ch.channel_name}>
                  {ch.channel_name}
                </option>
              ))}
            </select>
          )}
          <div className="segmented">
            {[
              { id: "all", label: window.T?.transcriptsAll || "Все" },
              {
                id: "favorites",
                label: window.T?.transcriptsFavorites || "★ Избранное",
              },
            ].map((t) => (
              <button
                key={t.id}
                className={tab === t.id ? "active" : ""}
                onClick={() => setTab(t.id)}
              >
                {t.label}
              </button>
            ))}
          </div>
          <div style={{ flex: 1 }} />
          <TranscriptsExportMenu userId={userId} onToast={onToast} />
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              fontSize: 12,
              color: "var(--fg-muted)",
            }}
          >
            <span>{window.T?.transcriptsPerPage || "На странице:"}</span>
            <div className="segmented">
              {[25, 50, 100].map((n) => (
                <button
                  key={n}
                  className={pageSize === n ? "active" : ""}
                  onClick={() => {
                    setPageSize(n);
                    setPage(0);
                  }}
                >
                  {n}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="table-scroll">
          {loading ? (
            <div
              style={{
                padding: "60px 32px",
                textAlign: "center",
                color: "var(--fg-faint)",
                fontSize: 13,
              }}
            >
              {window.T?.loading || "Загружаем…"}
            </div>
          ) : filtered.length === 0 ? (
            <div
              style={{
                padding: "60px 32px",
                textAlign: "center",
                color: "var(--fg-muted)",
              }}
            >
              <div style={{ fontSize: 32, marginBottom: 12 }}>
                {tab === "favorites" ? "★" : "📝"}
              </div>
              <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 6 }}>
                {tab === "favorites"
                  ? window.T?.transcriptsNoFavorites ||
                    "Нет избранных транскриптов"
                  : window.T?.transcriptsEmpty || "Транскриптов пока нет"}
              </div>
              {tab === "all" && (
                <div style={{ fontSize: 13, color: "var(--fg-faint)" }}>
                  {window.T?.transcriptsEmptyHint ||
                    "Транскрипты появятся после анализа видео."}
                </div>
              )}
            </div>
          ) : (
            <table className="data">
              <thead>
                <tr>
                  <th style={{ minWidth: 400 }}>
                    {window.T?.transcriptsColPreview || "Транскрипт (~30 сек)"}
                  </th>
                  <th className="num">Views</th>
                  <th>Engagement</th>
                  <th>Outlier</th>
                  <th
                    onClick={toggleSort}
                    style={{ cursor: "pointer", userSelect: "none" }}
                  >
                    {window.T?.transcriptsColDate || "Дата"} <SortIco />
                  </th>
                  <th style={{ width: 100 }}></th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((t) => {
                  const isExpanded = !!expanded[t.video_id];
                  const hasMore =
                    t.transcript_full &&
                    t.transcript_full.split(" ").length > 65;
                  const metrics = getVideoMetrics(t.url);
                  const outlier = getOutlierScore(
                    t.channel_name,
                    metrics.views,
                  );

                  return (
                    <tr key={t.video_id} style={{ verticalAlign: "top" }}>
                      {/* Транскрипт */}
                      <td style={{ paddingTop: 10, paddingBottom: 10 }}>
                        {/* Название видео над транскриптом */}
                        <div
                          style={{
                            fontSize: 11,
                            color: "var(--fg-faint)",
                            marginBottom: 4,
                            maxWidth: 380,
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                            whiteSpace: "nowrap",
                          }}
                        >
                          {t.channel_name} · {t.title}
                        </div>
                        <div
                          style={{
                            fontSize: 13,
                            lineHeight: 1.6,
                            color: "var(--fg)",
                          }}
                        >
                          {isExpanded
                            ? t.transcript_full
                            : t.transcript_preview}
                        </div>
                        {hasMore && (
                          <button
                            className="btn ghost sm"
                            style={{
                              fontSize: 11,
                              color: "var(--accent)",
                              marginTop: 4,
                              padding: 0,
                            }}
                            onClick={() => toggleExpand(t.video_id)}
                          >
                            {isExpanded
                              ? window.T?.transcriptsCollapse || "↑ Свернуть"
                              : window.T?.transcriptsExpand ||
                                "↓ Показать полностью"}
                          </button>
                        )}
                      </td>

                      {/* Views */}
                      <td
                        className="num"
                        style={{ fontFamily: "var(--mono)", fontSize: 12 }}
                      >
                        {metrics.views ? window.fmtNum(metrics.views) : "—"}
                      </td>

                      {/* Engagement */}
                      <td>
                        {metrics.engagementPct != null ? (
                          <span className="engagement-bar">
                            <span className="bar">
                              <span
                                className="fill"
                                style={{
                                  width:
                                    Math.min(100, metrics.engagementPct * 12) +
                                    "%",
                                }}
                              />
                            </span>
                            {metrics.engagementPct.toFixed(2)}%
                          </span>
                        ) : (
                          <span style={{ color: "var(--fg-faint)" }}>—</span>
                        )}
                      </td>

                      {/* Outlier */}
                      <td>
                        <OutlierChip score={outlier} />
                      </td>

                      {/* Дата */}
                      <td
                        style={{
                          fontSize: 12,
                          color: "var(--fg-faint)",
                          whiteSpace: "nowrap",
                        }}
                      >
                        {t.published_at ? window.fmtDate(t.published_at) : "—"}
                      </td>

                      {/* Действия: ★ · Видео */}
                      <td>
                        <div
                          style={{
                            display: "flex",
                            gap: 4,
                            justifyContent: "flex-end",
                            alignItems: "center",
                          }}
                        >
                          <button
                            className="btn ghost sm"
                            title={
                              t.is_favorite
                                ? window.T?.transcriptsRemoveFav ||
                                  "Убрать из избранного"
                                : window.T?.transcriptsAddFav || "В избранное"
                            }
                            style={{
                              color: t.is_favorite
                                ? "var(--warn)"
                                : "var(--fg-faint)",
                              fontSize: 15,
                            }}
                            onClick={() => toggleFavorite(t)}
                          >
                            {t.is_favorite ? "★" : "☆"}
                          </button>
                          <button
                            className="btn sm"
                            style={{ fontSize: 11, padding: "0 8px" }}
                            onClick={() => handleOpenVideo(t)}
                            title={t.title}
                          >
                            {window.T?.commentVideoBtn || "Видео"}
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>

        {/* Пагинация */}
        {totalPages > 1 && (
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              padding: "12px 16px",
              borderTop: "1px solid var(--border)",
              fontSize: 13,
            }}
          >
            <span style={{ color: "var(--fg-muted)" }}>
              {page * pageSize + 1}–{Math.min((page + 1) * pageSize, total)}{" "}
              {window.T?.paginationOf || "из"} {total}
            </span>
            <div style={{ display: "flex", gap: 6 }}>
              <button
                className="btn sm"
                disabled={page === 0}
                onClick={() => setPage((p) => p - 1)}
              >
                <Icon name="chevron-left" size={13} />
              </button>
              {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
                const p =
                  totalPages <= 7
                    ? i
                    : page < 4
                      ? i
                      : page > totalPages - 4
                        ? totalPages - 7 + i
                        : page - 3 + i;
                return (
                  <button
                    key={p}
                    className={"btn sm" + (p === page ? " primary" : "")}
                    onClick={() => setPage(p)}
                  >
                    {p + 1}
                  </button>
                );
              })}
              <button
                className="btn sm"
                disabled={page >= totalPages - 1}
                onClick={() => setPage((p) => p + 1)}
              >
                <Icon name="chevron-right" size={13} />
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { TranscriptsScreen });
