/* Compare screen — YOUN-59 */

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

const CompareScreen = ({ userId, userProfile, oauthChannels = [] }) => {
  const [availableChannels, setAvailableChannels] = React.useState([]);
  const [selected, setSelected] = React.useState([]); // [channel_name, ...]
  const [oauthChannel, setOauthChannel] = React.useState(null);
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [loadingChannels, setLoadingChannels] = React.useState(true);
  const [error, setError] = React.useState("");

  // Загружаем список каналов из базы
  React.useEffect(() => {
    if (!userId) return;
    setLoadingChannels(true);
    fetch(`${API_URL_COMPARE}/api/compare/channels-list?user_id=${userId}`)
      .then((r) => r.json())
      .then((d) => {
        setAvailableChannels(d.channels || []);
        setLoadingChannels(false);
      })
      .catch(() => setLoadingChannels(false));
  }, [userId]);

  // OAuth канал из пропсов
  React.useEffect(() => {
    if (oauthChannels.length > 0)
      setOauthChannel(oauthChannels[0].channel_name);
  }, [oauthChannels]);

  const handleCompare = async () => {
    // Мой канал: из state или напрямую из oauthChannels (если один — state может не успеть)
    const myChannel =
      oauthChannel ||
      (oauthChannels.length === 1 ? oauthChannels[0].channel_name : null);
    const allChannels = [myChannel, ...selected].filter(Boolean);
    if (allChannels.length < 2) {
      setError(
        window.T?.compareErrorMin || "Выберите минимум 2 канала для сравнения",
      );
      return;
    }
    setError("");
    setLoading(true);
    setData(null);
    try {
      const params = new URLSearchParams({
        user_id: userId,
        channels: allChannels.join(","),
      });
      const resp = await fetch(`${API_URL_COMPARE}/api/compare?${params}`);
      const json = await resp.json();
      if (!resp.ok) {
        setError(json.detail || "Error");
        return;
      }
      setData(json.channels || []);
    } catch (e) {
      setError(window.T?.compareErrorNet || "Ошибка сети");
    } finally {
      setLoading(false);
    }
  };

  const addChannel = () => {
    if (selected.length < 3) setSelected([...selected, ""]);
  };

  const removeChannel = (idx) => {
    setSelected(selected.filter((_, i) => i !== idx));
  };

  const updateSelected = (idx, val) => {
    setSelected((prev) => {
      const next = [...prev];
      // Расширяем массив если нужно
      while (next.length <= idx) next.push("");
      next[idx] = val;
      return next;
    });
  };

  // Форматирование чисел
  const fmtNum = (n) => {
    if (!n && n !== 0) return "—";
    if (n >= 1000000) return (n / 1000000).toFixed(1) + "M";
    if (n >= 1000) return (n / 1000).toFixed(0) + "K";
    return String(n);
  };

  // Находим лучшее значение в строке (числовые)
  const getBest = (key, channels) => {
    let best = null,
      bestVal = -Infinity;
    for (const ch of channels) {
      const v = ch[key];
      if (typeof v === "number" && v > bestVal) {
        bestVal = v;
        best = ch.channel_name;
      }
    }
    return best;
  };

  const channelOptions = availableChannels.map((c) => c.channel_name);

  return (
    <div className="page" style={{ maxWidth: 1600 }}>
      {/* Выбор каналов — одна строка */}
      <div
        className="table-wrap"
        style={{ marginBottom: 20, padding: "24px 32px" }}
      >
        <div
          style={{
            display: "flex",
            gap: 8,
            alignItems: "center",
            flexWrap: "nowrap",
            overflowX: "auto",
          }}
        >
          {/* Канал 1 — OAuth / Мой */}
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: 3,
              minWidth: 0,
              width: 220,
              flexShrink: 0,
            }}
          >
            <div
              style={{
                fontSize: 10,
                color: "var(--fg-faint)",
                fontWeight: 600,
                textTransform: "uppercase",
                letterSpacing: "0.05em",
              }}
            >
              {window.T?.compareMyChannel || "Мой канал"}
            </div>
            {oauthChannels.length === 0 ? (
              <button
                className="btn sm"
                onClick={() =>
                  window.dispatchEvent(
                    new CustomEvent("navigate", { detail: "settings" }),
                  )
                }
              >
                {window.T?.compareConnectAccount || "Подключить аккаунт →"}
              </button>
            ) : oauthChannels.length === 1 ? (
              <div
                style={{
                  padding: "5px 10px",
                  borderRadius: "var(--radius)",
                  border: "1px solid var(--accent)",
                  background: "var(--accent-soft)",
                  fontSize: 13,
                  fontWeight: 500,
                  color: "var(--accent)",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                  width: 176,
                }}
              >
                {oauthChannels[0].channel_name}
              </div>
            ) : (
              <select
                className="select"
                value={oauthChannel || ""}
                onChange={(e) => setOauthChannel(e.target.value)}
                style={{ height: 32, fontSize: 13, width: 176, flexShrink: 0 }}
              >
                {oauthChannels.map((ch) => (
                  <option key={ch.channel_id} value={ch.channel_name}>
                    {ch.channel_name}
                  </option>
                ))}
              </select>
            )}
          </div>

          {/* Каналы 2–4 — всегда 3 слота */}
          {[0, 1, 2].map((idx) => {
            const val = selected[idx] || "";
            return (
              <div
                key={idx}
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: 3,
                  minWidth: 0,
                  width: 220,
                  flexShrink: 0,
                }}
              >
                <div
                  style={{
                    fontSize: 10,
                    color: "var(--fg-faint)",
                    fontWeight: 600,
                    textTransform: "uppercase",
                    letterSpacing: "0.05em",
                  }}
                >
                  {window.T?.compareChannel || "Канал"} {idx + 2}
                </div>
                <div style={{ display: "flex", gap: 4 }}>
                  <select
                    className="select"
                    value={val}
                    onChange={(e) => {
                      if (e.target.value) {
                        updateSelected(idx, e.target.value);
                      } else {
                        // Убираем слот и все после него
                        setSelected((prev) =>
                          prev.slice(0, idx).filter(Boolean),
                        );
                      }
                    }}
                    style={{
                      height: 32,
                      fontSize: 13,
                      width: 176,
                      flexShrink: 0,
                    }}
                  >
                    <option value="">
                      {window.T?.compareSelectChannel || "Выберите канал…"}
                    </option>
                    {channelOptions
                      .filter(
                        (ch) =>
                          ch !== oauthChannel &&
                          !selected.some((s, i) => s === ch && i !== idx),
                      )
                      .map((ch) => (
                        <option key={ch} value={ch}>
                          {ch}
                        </option>
                      ))}
                  </select>
                  {val && (
                    <button
                      className="btn ghost sm"
                      onClick={() => removeChannel(idx)}
                      title={window.T?.compareRemove || "Удалить"}
                    >
                      <Icon name="x" size={13} />
                    </button>
                  )}
                </div>
              </div>
            );
          })}

          {/* Кнопка сравнить */}
          <button
            className="btn primary"
            onClick={handleCompare}
            disabled={loading || loadingChannels}
            style={{ alignSelf: "flex-end", flexShrink: 0, marginLeft: "auto" }}
          >
            {loading ? (
              <>
                <Icon name="spinner" size={13} />{" "}
                {window.T?.compareLoading || "Считаем…"}
              </>
            ) : (
              window.T?.compareBtn || "Сравнить"
            )}
          </button>
        </div>

        {error && (
          <div
            style={{
              marginTop: 12,
              fontSize: 13,
              color: "var(--bad)",
              padding: "8px 12px",
              background: "rgba(220,38,38,0.08)",
              borderRadius: 6,
            }}
          >
            {error}
          </div>
        )}
      </div>

      {/* Таблица сравнения */}
      {data && data.length >= 2 && (
        <div className="table-wrap">
          <div className="table-scroll">
            <table className="data" style={{ tableLayout: "fixed" }}>
              <thead>
                <tr>
                  <th style={{ width: 200 }}>
                    {window.T?.compareMetric || "Метрика"}
                  </th>
                  {data.map((ch) => (
                    <th key={ch.channel_name} style={{ minWidth: 180 }}>
                      <div style={{ fontWeight: 600, fontSize: 13 }}>
                        {ch.channel_name}
                      </div>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {/* Индекс силы */}
                {(() => {
                  const best = getBest("strength_index", data);
                  return (
                    <tr>
                      <td
                        style={{
                          fontWeight: 600,
                          color: "var(--fg-muted)",
                          fontSize: 12,
                        }}
                      >
                        {window.T?.compareStrengthIndex || "💪 Индекс силы"}
                      </td>
                      {data.map((ch) => (
                        <td key={ch.channel_name}>
                          <div
                            style={{
                              display: "flex",
                              alignItems: "center",
                              gap: 8,
                            }}
                          >
                            <div
                              style={{
                                flex: 1,
                                height: 6,
                                borderRadius: 3,
                                background: "var(--bg-sunk)",
                                overflow: "hidden",
                              }}
                            >
                              <div
                                style={{
                                  height: "100%",
                                  width: `${ch.strength_index}%`,
                                  background:
                                    ch.channel_name === best
                                      ? "var(--good)"
                                      : "var(--accent)",
                                  borderRadius: 3,
                                }}
                              />
                            </div>
                            <span
                              style={{
                                fontWeight: 700,
                                fontSize: 14,
                                color:
                                  ch.channel_name === best
                                    ? "var(--good)"
                                    : "var(--fg)",
                                minWidth: 36,
                              }}
                            >
                              {ch.strength_index}
                            </span>
                          </div>
                        </td>
                      ))}
                    </tr>
                  );
                })()}

                {/* Подписчики */}
                {(() => {
                  const best = getBest("subscribers", data);
                  return (
                    <tr>
                      <td
                        style={{
                          fontWeight: 500,
                          fontSize: 12,
                          color: "var(--fg-muted)",
                        }}
                      >
                        {window.T?.compareSubscribers || "👥 Подписчики"}
                      </td>
                      {data.map((ch) => (
                        <td
                          key={ch.channel_name}
                          style={{
                            fontWeight: ch.channel_name === best ? 700 : 400,
                            color:
                              ch.channel_name === best
                                ? "var(--good)"
                                : "var(--fg)",
                          }}
                        >
                          {fmtNum(ch.subscribers)}
                        </td>
                      ))}
                    </tr>
                  );
                })()}

                {/* Видео в базе */}
                <tr>
                  <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                    {window.T?.compareVideosInDB || "📹 Видео в базе"}
                  </td>
                  {data.map((ch) => (
                    <td key={ch.channel_name}>{ch.video_count}</td>
                  ))}
                </tr>

                {/* Avg просмотры */}
                {(() => {
                  const best = getBest("median_views", data);
                  return (
                    <tr>
                      <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                        {window.T?.compareAvgViews || "👁 Avg views"}
                      </td>
                      {data.map((ch) => (
                        <td
                          key={ch.channel_name}
                          style={{
                            fontWeight: ch.channel_name === best ? 700 : 400,
                            color:
                              ch.channel_name === best
                                ? "var(--good)"
                                : "var(--fg)",
                          }}
                        >
                          {fmtNum(ch.median_views)}
                        </td>
                      ))}
                    </tr>
                  );
                })()}

                {/* Avg engagement */}
                {(() => {
                  const best = getBest("median_engagement", data);
                  return (
                    <tr>
                      <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                        {window.T?.compareAvgEngagement || "❤️ Avg engagement"}
                      </td>
                      {data.map((ch) => (
                        <td
                          key={ch.channel_name}
                          style={{
                            fontWeight: ch.channel_name === best ? 700 : 400,
                            color:
                              ch.channel_name === best
                                ? "var(--good)"
                                : "var(--fg)",
                          }}
                        >
                          {ch.median_engagement}%
                        </td>
                      ))}
                    </tr>
                  );
                })()}

                {/* Outlier score */}
                {(() => {
                  const best = getBest("median_outlier", data);
                  return (
                    <tr>
                      <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                        {window.T?.compareAvgOutlier || "🔥 Avg outlier"}
                      </td>
                      {data.map((ch) => (
                        <td
                          key={ch.channel_name}
                          style={{
                            fontWeight: ch.channel_name === best ? 700 : 400,
                            color:
                              ch.channel_name === best
                                ? "var(--good)"
                                : "var(--fg)",
                          }}
                        >
                          {ch.median_outlier}x
                        </td>
                      ))}
                    </tr>
                  );
                })()}

                {/* Видео в месяц */}
                {(() => {
                  const best = getBest("videos_per_month", data);
                  return (
                    <tr>
                      <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                        {window.T?.compareVideosPerMonth || "📅 Видео в месяц"}
                      </td>
                      {data.map((ch) => (
                        <td
                          key={ch.channel_name}
                          style={{
                            fontWeight: ch.channel_name === best ? 700 : 400,
                            color:
                              ch.channel_name === best
                                ? "var(--good)"
                                : "var(--fg)",
                          }}
                        >
                          {ch.videos_per_month}
                        </td>
                      ))}
                    </tr>
                  );
                })()}

                {/* Лучший день */}
                <tr>
                  <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                    {window.T?.compareBestDay || "🕐 Лучший день"}
                  </td>
                  {data.map((ch) => (
                    <td key={ch.channel_name}>{ch.best_day || "—"}</td>
                  ))}
                </tr>

                {/* Топ формат */}
                <tr>
                  <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                    {window.T?.compareTopFormat || "📏 Топ формат"}
                  </td>
                  {data.map((ch) => (
                    <td key={ch.channel_name}>{ch.top_format}</td>
                  ))}
                </tr>

                {/* Топ теги */}
                <tr>
                  <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                    {window.T?.compareTopTags || "🏷️ Топ теги"}
                  </td>
                  {data.map((ch) => (
                    <td key={ch.channel_name}>
                      <div
                        style={{ display: "flex", gap: 4, flexWrap: "wrap" }}
                      >
                        {ch.top_tags.slice(0, 3).map((t) => (
                          <span
                            key={t}
                            className="chip"
                            style={{ fontSize: 10 }}
                          >
                            #{t}
                          </span>
                        ))}
                      </div>
                    </td>
                  ))}
                </tr>

                {/* Общие теги */}
                <tr>
                  <td style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                    {window.T?.compareCommonTags || "🔗 Общие теги"}
                  </td>
                  {data.map((ch) => (
                    <td key={ch.channel_name}>
                      {ch.common_tags.length > 0 ? (
                        <div
                          style={{ display: "flex", gap: 4, flexWrap: "wrap" }}
                        >
                          {ch.common_tags.slice(0, 3).map((t) => (
                            <span
                              key={t}
                              className="chip accent"
                              style={{ fontSize: 10 }}
                            >
                              #{t}
                            </span>
                          ))}
                        </div>
                      ) : (
                        <span style={{ color: "var(--fg-faint)" }}>—</span>
                      )}
                    </td>
                  ))}
                </tr>

                {/* Топ видео */}
                <tr style={{ verticalAlign: "top" }}>
                  <td
                    style={{
                      fontSize: 12,
                      color: "var(--fg-muted)",
                      paddingTop: 10,
                    }}
                  >
                    {window.T?.compareTopVideos || "🏆 Топ видео"}
                  </td>
                  {data.map((ch) => (
                    <td key={ch.channel_name} style={{ paddingTop: 10 }}>
                      {ch.top_videos.map((v, i) => (
                        <div key={v.id} style={{ marginBottom: 6 }}>
                          <a
                            href={v.url}
                            target="_blank"
                            style={{
                              fontSize: 11,
                              color: "var(--accent)",
                              display: "block",
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                              whiteSpace: "nowrap",
                              maxWidth: 200,
                            }}
                            title={v.title}
                          >
                            {i + 1}. {v.title}
                          </a>
                          <span
                            style={{ fontSize: 10, color: "var(--fg-faint)" }}
                          >
                            {fmtNum(v.views)}{" "}
                            {window.T?.compareViews || "просмотров"}
                          </span>
                        </div>
                      ))}
                    </td>
                  ))}
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Пустое состояние */}
      {!data && !loading && (
        <div
          style={{
            padding: "60px 32px",
            textAlign: "center",
            color: "var(--fg-muted)",
          }}
        >
          <div style={{ fontSize: 48, marginBottom: 16 }}>⚖️</div>
          <div style={{ fontSize: 16, fontWeight: 500, marginBottom: 8 }}>
            {window.T?.compareSelectTitle || "Выберите каналы для сравнения"}
          </div>
          <div style={{ fontSize: 13, color: "var(--fg-faint)" }}>
            {loadingChannels
              ? window.T?.compareLoadingChannels || "Загружаем список каналов…"
              : availableChannels.length === 0
                ? window.T?.compareRunAnalysis ||
                  "Запустите анализ каналов чтобы начать сравнение"
                : window.T?.compareSelectHint ||
                  "Выберите 2–4 канала и нажмите «Сравнить»"}
          </div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { CompareScreen });
