import { fetchTelegramInvite, postTelegramInviteLink, postTelegramLink } from "../auth/session.js";
import { showToast } from "./toast.js";
import { escapeHtml } from "../utils/escape-html.js";
import { t } from "../config/site.js";

function leaderboardHtml(rows) {
  if (!rows?.length) {
    return `<p class="text-sm profile-tg-text">${t("tgInviteLeaderboardEmpty")}</p>`;
  }
  return `<ol class="space-y-2">
    ${rows
      .map(
        (r, i) => `
      <li class="profile-tg-leaderboard__item flex items-center justify-between gap-3 px-3 py-2.5 text-sm">
        <span class="flex min-w-0 items-center gap-2">
          <span class="profile-tg-rank flex h-7 w-7 shrink-0 items-center justify-center text-xs font-bold">${i + 1}</span>
          <span class="truncate font-medium profile-tg-text-strong">${escapeHtml(r.username)}</span>
        </span>
        <span class="shrink-0 tabular-nums profile-tg-text">${r.inviteCount} · 🪙 ${r.coinsEarned}</span>
      </li>`
      )
      .join("")}
  </ol>`;
}

export function profileTelegramInviteHtml(data) {
  const campaign = data.campaign || {};
  const leaderboard = Array.isArray(data.leaderboard) ? data.leaderboard : [];
  const stats = data.stats || {};
  const tg = data.telegram || {};

  const verified = Boolean(tg.verified);
  const inviteLink = stats.inviteLink ? String(stats.inviteLink) : "";
  const campaignOff =
    !campaign.active || !campaign.botConfigured || !campaign.groupConfigured;

  return `
    <div class="space-y-6">
      <div>
        <h2 class="text-lg font-semibold text-white">${t("profileTabTelegram")}</h2>
        <p class="mt-1 text-sm profile-tg-text">${t("tgInviteSubtitle")}</p>
        ${
          campaign.active && campaign.coinsPerInvite
            ? `<p class="mt-2 text-sm font-semibold text-accent-bright">${t("tgInviteRewardPer").replace("{coins}", String(campaign.coinsPerInvite))}</p>`
            : ""
        }
      </div>
      ${
        campaignOff
          ? `<div class="profile-tg-alert px-4 py-3 text-sm">${t("tgInviteCampaignPaused")}</div>`
          : ""
      }
      <div class="grid gap-6 lg:grid-cols-2">
        <div class="profile-tg-card space-y-4 p-5">
          <h3 class="text-sm font-semibold text-white">${t("tgInviteYourLink")}</h3>
          <div class="profile-tg-panel p-4">
            <p class="profile-tg-label text-[11px] font-semibold uppercase tracking-wide">${t("tgInviteTelegramStatus")}</p>
            <p id="profile-tg-invite-status" class="mt-1 text-sm profile-tg-text-strong">
              ${
                verified
                  ? escapeHtml(
                      t("tgInviteTelegramOk").replace("{user}", tg.username ? `@${tg.username}` : "")
                    )
                  : escapeHtml(t("tgInviteTelegramRequired"))
              }
            </p>
            ${
              !verified
                ? `<button type="button" id="profile-tg-invite-verify" class="k-btn k-btn--secondary btn-site-secondary mt-3 rounded-xl px-4 py-2 text-sm font-semibold">${t("tgInviteVerifyBtn")}</button>`
                : ""
            }
          </div>
          <div id="profile-tg-invite-link-wrap" class="${verified && !campaignOff ? "" : "opacity-60 pointer-events-none"}">
            <label class="profile-tg-label mb-1.5 block text-[11px] font-semibold uppercase tracking-wide">${t("tgInviteLinkLabel")}</label>
            <div class="flex flex-col gap-2 sm:flex-row">
              <input id="profile-tg-invite-link" type="text" readonly class="input-site-field flex-1 text-sm" value="${escapeHtml(inviteLink)}" placeholder="${escapeHtml(t("tgInviteLinkPlaceholder"))}" />
              <button type="button" id="profile-tg-invite-copy" class="k-btn k-btn--secondary btn-site-secondary shrink-0 rounded-xl px-4 py-2.5 text-sm font-semibold" ${inviteLink ? "" : "disabled"}>${t("tgInviteCopy")}</button>
            </div>
            <button type="button" id="profile-tg-invite-create" class="k-btn k-btn--primary btn-site-primary mt-3 w-full rounded-xl px-4 py-2.5 text-sm font-semibold sm:w-auto">${inviteLink ? t("tgInviteRefreshLink") : t("tgInviteCreateLink")}</button>
          </div>
          <ul class="space-y-1.5 text-xs profile-tg-label">
            <li>${t("tgInviteRule1")}</li>
            <li>${t("tgInviteRule2")}</li>
            <li>${t("tgInviteRule3")}</li>
          </ul>
        </div>
        <div class="profile-tg-card space-y-4 p-5">
          <h3 class="text-sm font-semibold text-white">${t("tgInviteYourStats")}</h3>
          <dl class="grid grid-cols-2 gap-3">
            <div class="profile-tg-stat p-3">
              <dt class="profile-tg-label text-[10px] font-semibold uppercase tracking-wide">${t("tgInviteStatInvites")}</dt>
              <dd id="profile-tg-invite-stat-count" class="profile-tg-stat__value mt-1 text-2xl font-bold tabular-nums">${Number(stats.inviteCount) || 0}</dd>
            </div>
            <div class="profile-tg-stat p-3">
              <dt class="profile-tg-label text-[10px] font-semibold uppercase tracking-wide">${t("tgInviteStatCoins")}</dt>
              <dd id="profile-tg-invite-stat-coins" class="profile-tg-stat__value profile-tg-stat__value--accent mt-1 text-2xl font-bold tabular-nums">${Number(stats.coinsEarned) || 0}</dd>
            </div>
          </dl>
          ${
            stats.rank
              ? `<p class="text-xs profile-tg-label">${t("tgInviteRank").replace("{rank}", String(stats.rank))}</p>`
              : ""
          }
        </div>
      </div>
      <div class="profile-tg-card p-5">
        <h3 class="mb-3 text-sm font-semibold text-white">${t("tgInviteTop10")}</h3>
        <div id="profile-tg-invite-leaderboard">${leaderboardHtml(leaderboard)}</div>
      </div>
    </div>
  `;
}

export function bindProfileTelegramInviteHandlers(container, opts = {}) {
  const linkInput = container.querySelector("#profile-tg-invite-link");
  const copyBtn = container.querySelector("#profile-tg-invite-copy");
  const createBtn = container.querySelector("#profile-tg-invite-create");
  const verifyBtn = container.querySelector("#profile-tg-invite-verify");

  verifyBtn?.addEventListener("click", async () => {
    const res = await postTelegramLink();
    if (res.ok && res.data?.verified) {
      showToast(t("tgInviteTelegramAlready"), "info");
      await opts.onReload?.();
      return;
    }
    if (res.ok && res.data?.deepLink) {
      window.open(res.data.deepLink, "_blank", "noopener,noreferrer");
      showToast(t("tgInviteTelegramOpenBot"), "info");
      return;
    }
    showToast(t("tgInviteTelegramFail"), "error");
  });

  copyBtn?.addEventListener("click", async () => {
    const val = linkInput?.value?.trim();
    if (!val) return;
    try {
      await navigator.clipboard.writeText(val);
      showToast(t("tgInviteCopied"), "success");
    } catch {
      linkInput?.select();
      showToast(t("tgInviteCopyManual"), "info");
    }
  });

  createBtn?.addEventListener("click", async () => {
    if (!(createBtn instanceof HTMLButtonElement)) return;
    createBtn.disabled = true;
    const res = await postTelegramInviteLink();
    createBtn.disabled = false;
    if (!res.ok) {
      const err = res.data?.error || "";
      if (err === "telegram_required") showToast(t("tgInviteTelegramRequired"), "error");
      else if (err === "campaign_inactive") showToast(t("tgInviteCampaignPaused"), "info");
      else if (err === "telegram_api") showToast(res.data?.description || t("tgInviteLinkFail"), "error");
      else showToast(t("tgInviteLinkFail"), "error");
      return;
    }
    if (res.data?.inviteLink && linkInput instanceof HTMLInputElement) {
      linkInput.value = res.data.inviteLink;
      if (copyBtn instanceof HTMLButtonElement) copyBtn.disabled = false;
    }
    const s = res.data?.stats;
    if (s) {
      container.querySelector("#profile-tg-invite-stat-count")?.replaceChildren(
        document.createTextNode(String(s.inviteCount || 0))
      );
      container.querySelector("#profile-tg-invite-stat-coins")?.replaceChildren(
        document.createTextNode(String(s.coinsEarned || 0))
      );
    }
    showToast(t("tgInviteLinkReady"), "success");
    void globalThis.__siteRefreshUser?.();
  });
}

export async function mountProfileTelegramInvite(mount) {
  mount.innerHTML = `<p class="text-sm profile-tg-text">${t("profileLoadingHint")}</p>`;
  const res = await fetchTelegramInvite();
  const data = res.ok ? res.data : {};
  mount.innerHTML = profileTelegramInviteHtml(data);
  bindProfileTelegramInviteHandlers(mount, {
    onReload: async () => {
      await mountProfileTelegramInvite(mount);
    },
  });
}
