import { t } from "../config/site.js";
import { fetchDailyBonusStatus, postDailyBonusClaim, notifyApiFailure } from "../auth/session.js";
import { showToast } from "./toast.js";
import { destroyLottieIcons, mountLottieIcons } from "../utils/lottie-icon.js";

const PROMO_LOTTIE_SRC = "assets/lottie/promo-code.json?v=3";
const WHEEL_LOTTIE_SRC = "assets/lottie/wheel.json?v=1";
const DAILY_LOTTIE_SRC = "assets/lottie/daily-bonus.json?v=2";
const PROMO_ICON_SRC = "assets/icons/promo-code.svg?v=3";
const WHEEL_ICON_SRC = "assets/icons/wheel.svg?v=1";
const DAILY_ICON_SRC = "assets/icons/daily-bonus.svg?v=2";

function lottieIconHtml(lottieSrc, fallbackSrc) {
  return `<span class="lottie-icon-host" data-lottie-src="${lottieSrc}" data-lottie-fallback="${fallbackSrc}"></span>`;
}

const ICON_PROMO = lottieIconHtml(PROMO_LOTTIE_SRC, PROMO_ICON_SRC);
const ICON_WHEEL = lottieIconHtml(WHEEL_LOTTIE_SRC, WHEEL_ICON_SRC);
const ICON_DAILY = lottieIconHtml(DAILY_LOTTIE_SRC, DAILY_ICON_SRC);

function quickCardHtml({ icon, title, subtitle, cta, ctaTag, ctaAttrs, ctaId, ctaClass = "" }) {
  const ctaInner = `<span class="home-quick-card__cta-label">${cta}</span>`;
  let ctaHtml = "";
  if (ctaTag === "a") {
    ctaHtml = `<a ${ctaAttrs} id="${ctaId}" class="home-quick-card__cta ${ctaClass}">${ctaInner}</a>`;
  } else {
    ctaHtml = `<button type="button" ${ctaAttrs} id="${ctaId}" class="home-quick-card__cta ${ctaClass}">${ctaInner}</button>`;
  }

  return `
    <article class="home-quick-card">
      <div class="home-quick-card__icon" aria-hidden="true">${icon}</div>
      <div class="home-quick-card__text">
        <p class="home-quick-card__title">${title}</p>
        <p class="home-quick-card__subtitle">${subtitle}</p>
      </div>
      ${ctaHtml}
    </article>
  `;
}

export async function refreshHomeDailyBonus() {
  const btn = document.getElementById("home-quick-daily-bonus");
  if (!btn || !(btn instanceof HTMLButtonElement)) return;

  btn.classList.remove("opacity-50", "opacity-60", "cursor-not-allowed");
  btn.disabled = false;
  delete btn.dataset.guest;
  btn.title = "";

  const res = await fetchDailyBonusStatus();
  if (!res.ok || !res.data) {
    btn.disabled = true;
    btn.classList.add("opacity-50", "cursor-not-allowed");
    return;
  }
  const d = res.data;
  if (!d.authenticated) {
    btn.dataset.guest = "1";
    btn.title = t("dailyBonusNeedLogin");
    return;
  }
  if (d.can_claim) {
    btn.title = t("sidebarDailyBonusTitle");
    return;
  }
  btn.disabled = true;
  btn.classList.add("opacity-60", "cursor-not-allowed");
  btn.title = t("dailyBonusAlready");
}

function bindWheelPrefetch(el) {
  if (!el) return;
  let done = false;
  const warm = () => {
    if (done) return;
    done = true;
    globalThis.__sitePrefetchRoute?.("/sans-carki");
  };
  el.addEventListener("pointerenter", warm, { passive: true });
  el.addEventListener("focus", warm);
  el.addEventListener("click", (e) => {
    warm();
    e.preventDefault();
    globalThis.__siteNavigateTo?.("/sans-carki");
  });
}

function esc(s) {
  return String(s)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

export function renderHomeQuickActions(mount) {
  if (!mount) return;
  destroyLottieIcons(mount);

  const ariaGroup = esc(t("homeQuickActionsAria"));

  mount.innerHTML = `
    <section class="home-quick-actions" role="region" aria-label="${ariaGroup}">
      <div class="home-quick-actions__grid">
        ${quickCardHtml({
          icon: ICON_PROMO,
          title: esc(t("homePromoLabel")),
          subtitle: esc(t("homePromoSubtitle")),
          cta: esc(t("homePromoCta")),
          ctaTag: "button",
          ctaId: "home-quick-promo",
          ctaAttrs: `aria-label="${esc(t("homePromoCta"))}"`,
        })}
        ${quickCardHtml({
          icon: ICON_WHEEL,
          title: esc(t("homeWheelLabel")),
          subtitle: esc(t("homeWheelSubtitle")),
          cta: esc(t("homeWheelCta")),
          ctaTag: "a",
          ctaId: "home-quick-wheel",
          ctaAttrs: `href="#/sans-carki" aria-label="${esc(t("homeWheelCta"))}"`,
          ctaClass: "k-link",
        })}
        ${quickCardHtml({
          icon: ICON_DAILY,
          title: esc(t("homeDailyLabel")),
          subtitle: esc(t("homeDailySubtitle")),
          cta: esc(t("homeDailyCta")),
          ctaTag: "button",
          ctaId: "home-quick-daily-bonus",
          ctaAttrs: `aria-label="${esc(t("homeDailyLabel"))}" title="${esc(t("sidebarDailyBonusTitle"))}"`,
        })}
      </div>
    </section>
  `;

  mount.querySelector("#home-quick-promo")?.addEventListener("click", () => {
    globalThis.__siteOpenPromoModal?.();
  });

  bindWheelPrefetch(mount.querySelector("#home-quick-wheel"));
  mountLottieIcons(mount);

  mount.querySelector("#home-quick-daily-bonus")?.addEventListener("click", async () => {
    const btn = document.getElementById("home-quick-daily-bonus");
    if (!btn || !(btn instanceof HTMLButtonElement)) return;
    if (btn.dataset.guest === "1") {
      showToast(t("dailyBonusNeedLogin"), "info");
      globalThis.__siteOpenLogin?.();
      return;
    }
    if (btn.disabled) return;
    btn.disabled = true;
    const res = await postDailyBonusClaim();
    if (res.ok && res.data && typeof res.data.coins === "number") {
      const added = typeof res.data.added === "number" ? res.data.added : 25;
      const msg = t("dailyBonusSuccess")
        .replace("{n}", String(added))
        .replace("{coin}", t("marketCoinWord"));
      showToast(msg, "success");
      await globalThis.__siteRefreshUser?.();
      await refreshHomeDailyBonus();
      return;
    }
    if (res.data?.error === "already_claimed") {
      showToast(t("dailyBonusAlready"), "info");
      await refreshHomeDailyBonus();
      return;
    }
    if (res.status === 401) {
      showToast(t("dailyBonusNeedLogin"), "info");
      globalThis.__siteOpenLogin?.();
    } else if (res.status === 0 || res.status >= 500) {
      notifyApiFailure();
    } else {
      showToast(t("dailyBonusError"), "error");
    }
    await refreshHomeDailyBonus();
  });

  void refreshHomeDailyBonus();
}
