/* Comments screen — YOUN-70 */

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

const decodeHtml = (html) => {
  if (!html) return "";
  return html
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/<br\s*\/?>/gi, "\n")
    .replace(/<[^>]+>/g, "");
};

const CommentsScreen = ({
  userId,
  activeChannel,
  onOpenVideo,
  allResults,
  onToast,
}) => {
  const [comments, setComments] = 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 [sortCol, setSortCol] = React.useState("likes");
  const [sortDir, setSortDir] = React.useState("desc");
  const [pageSize, setPageSize] = React.useState(50);
  const [page, setPage] = React.useState(0);
  const [selectedChannel, setSelectedChannel] = React.useState("");
  const [availableChannels, setAvailableChannels] = React.useState([]);

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

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

  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");
    if (currentTab === "hidden") params.set("show_hidden", "true");
    fetch(`${API_URL_COMMENTS}/api/comments?${params}`)
      .then((r) => r.json())
      .then((d) => {
        setComments(d.comments || []);
        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 setPreference = async (commentId, update) => {
    // Оптимистичное обновление
    setComments((prev) =>
      prev.map((c) => (c.id === commentId ? { ...c, ...update } : c)),
    );
    if (update.is_hidden && tab !== "hidden") {
      setComments((prev) => prev.filter((c) => c.id !== commentId));
      setTotal((prev) => prev - 1);
    }
    if (update.is_hidden === false && tab === "hidden") {
      setComments((prev) => prev.filter((c) => c.id !== commentId));
      setTotal((prev) => prev - 1);
    }
    fetch(`${API_URL_COMMENTS}/api/comments/preferences`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        user_id: userId,
        comment_id: commentId,
        ...update,
      }),
    }).catch(() => load());
  };

  const handleFavorite = (c) =>
    setPreference(c.id, { is_favorite: !c.is_favorite });
  const handleHide = (c) => setPreference(c.id, { is_hidden: true });
  const handleRestore = (c) => setPreference(c.id, { is_hidden: false });

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

  const filtered = React.useMemo(() => {
    let list = comments.filter((c) => {
      if (!search) return true;
      const q = search.toLowerCase();
      return (
        decodeHtml(c.text)?.toLowerCase().includes(q) ||
        c.author?.toLowerCase().includes(q) ||
        c.video_title?.toLowerCase().includes(q)
      );
    });
    return [...list].sort((a, b) => {
      const av = sortCol === "likes" ? a.likes || 0 : a.published_at || "";
      const bv = sortCol === "likes" ? b.likes || 0 : b.published_at || "";
      const cmp =
        typeof av === "number" ? av - bv : String(av).localeCompare(String(bv));
      return sortDir === "asc" ? cmp : -cmp;
    });
  }, [comments, search, sortCol, sortDir]);

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

  return (
    <div className="page" style={{ maxWidth: 1400 }}>
      <div className="table-wrap">
        <div className="table-toolbar">
          <Search
            value={search}
            onChange={setSearch}
            placeholder={
              window.T?.commentsSearchPlaceholder ||
              "Поиск по тексту, автору, видео…"
            }
          />
          {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?.commentsAll || "Все" },
              {
                id: "favorites",
                label: window.T?.commentsFavorites || "★ Избранное",
              },
              { id: "hidden", label: window.T?.commentsHidden || "Скрытые" },
            ].map((t) => (
              <button
                key={t.id}
                className={tab === t.id ? "active" : ""}
                onClick={() => setTab(t.id)}
              >
                {t.label}
              </button>
            ))}
          </div>
          <div style={{ flex: 1 }} />
          <CommentsExportMenu userId={userId} onToast={onToast} />
          {/* Размер страницы */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              fontSize: 12,
              color: "var(--fg-muted)",
            }}
          >
            <span>{window.T?.commentsPerPage || "Per page:"}</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" ? "★" : tab === "hidden" ? "🫥" : "💬"}
              </div>
              <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 6 }}>
                {tab === "favorites"
                  ? window.T?.commentsNoFavorites ||
                    "Нет избранных комментариев"
                  : tab === "hidden"
                    ? window.T?.commentsNoHidden || "Нет скрытых комментариев"
                    : window.T?.commentsEmpty || "Комментариев пока нет"}
              </div>
              {tab === "all" && (
                <div style={{ fontSize: 13, color: "var(--fg-faint)" }}>
                  {window.T?.commentsEmptyHint ||
                    "Запустите анализ канала чтобы собрать комментарии."}
                </div>
              )}
            </div>
          ) : (
            <table className="data">
              <thead>
                <tr>
                  <th style={{ minWidth: 400 }}>
                    {window.T?.commentsColComment || "Comment"}
                  </th>
                  <th
                    className="num"
                    onClick={() => toggleSort("likes")}
                    style={{ cursor: "pointer", userSelect: "none" }}
                  >
                    {window.T?.commentsColLikes || "Likes"}{" "}
                    <SortIco col="likes" />
                  </th>
                  <th
                    onClick={() => toggleSort("published_at")}
                    style={{ cursor: "pointer", userSelect: "none" }}
                  >
                    {window.T?.commentsColDate || "Date"}{" "}
                    <SortIco col="published_at" />
                  </th>
                  <th style={{ width: 120 }}></th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((c) => (
                  <tr key={c.id} style={{ verticalAlign: "top" }}>
                    <td style={{ paddingTop: 10, paddingBottom: 10 }}>
                      <div
                        style={{
                          fontSize: 13,
                          lineHeight: 1.6,
                          color: "var(--fg)",
                          whiteSpace: "pre-wrap",
                        }}
                      >
                        {decodeHtml(c.text)}
                      </div>
                    </td>
                    <td
                      className="num"
                      style={{ fontFamily: "var(--mono)", fontSize: 12 }}
                    >
                      {c.likes > 0 ? c.likes : "—"}
                    </td>
                    <td
                      style={{
                        fontSize: 12,
                        color: "var(--fg-faint)",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {c.published_at ? window.fmtDate(c.published_at) : "—"}
                    </td>
                    <td>
                      <div
                        style={{
                          display: "flex",
                          gap: 4,
                          justifyContent: "flex-end",
                          alignItems: "center",
                        }}
                      >
                        <button
                          className="btn ghost sm"
                          title={
                            c.is_favorite
                              ? window.T?.commentRemoveFav ||
                                "Remove from favorites"
                              : window.T?.commentAddFav || "Add to favorites"
                          }
                          style={{
                            color: c.is_favorite
                              ? "var(--warn)"
                              : "var(--fg-faint)",
                            fontSize: 15,
                          }}
                          onClick={() => handleFavorite(c)}
                        >
                          {c.is_favorite ? "★" : "☆"}
                        </button>
                        <button
                          className="btn sm"
                          title={
                            c.video_title ||
                            window.T?.commentOpenVideo ||
                            "Open video"
                          }
                          style={{ fontSize: 11, padding: "0 8px" }}
                          onClick={() => handleOpenVideo(c)}
                        >
                          {window.T?.commentVideoBtn || "Video"}
                        </button>
                        <button
                          className="btn ghost sm"
                          title={
                            tab === "hidden"
                              ? window.T?.commentRestore || "Restore"
                              : window.T?.commentHide || "Hide"
                          }
                          style={{
                            color:
                              tab === "hidden"
                                ? "var(--good)"
                                : "var(--fg-faint)",
                          }}
                          onClick={() =>
                            tab === "hidden" ? handleRestore(c) : handleHide(c)
                          }
                        >
                          <Icon name="eye" size={13} />
                        </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?.commentsOf || "of"} {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, { CommentsScreen });
