import { fetchSessionUser, postUserAffiliateRequest } from "../auth/session.js";
import { showToast } from "../components/toast.js";
import { escapeHtml } from "../utils/escape-html.js";
import { t } from "../config/site.js";

const ICON_SPONSOR = `<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>`;
const ICON_CALENDAR = `<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>`;
const ICON_MESSAGE = `<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>`;

async function loadSponsors() {
  try {
    const r = await fetch(`data/sponsors.json?v=${Date.now()}`, { cache: "no-store" });
    if (!r.ok) return [];
    const j = await r.json();
    return Array.isArray(j) ? j : [];
  } catch {
    return [];
  }
}

function affiliateErrorHint(err, status) {
  if (err === "auth" || status === 401) return t("affiliateToastAuth");
  if (err === "sponsor") return t("affiliateToastSponsor");
  if (err === "message") return t("affiliateToastMessage");
  if (err === "message_long") return t("affiliateToastMessageLong");
  if (err === "investment_date") return t("affiliateToastInvestmentDate");
  if (err === "db") return t("affiliateToastDb");
  if (err === "schema") return t("affiliateToastSchema");
  if (err === "save") return t("affiliateToastSave");
  if (err === "method") return t("affiliateToastMethod");
  if (status === 404) return t("affiliateToast404");
  if (status === 0) return t("affiliateToastNetwork");
  if (err) return `${t("affiliateToastErrPrefix")} (${err}).`;
  if (status >= 500) return t("affiliateToastServer");
  return t("affiliateToastFail");
}

export async function renderAffiliatePage(outlet) {
  const [user, sponsors] = await Promise.all([fetchSessionUser(), loadSponsors()]);
  if (!user) {
    outlet.innerHTML = `
      <section class="relative w-full min-w-0 space-y-8 px-1 pb-4">
        <header class="relative overflow-hidden rounded-3xl border border-white/[0.08] bg-[#1e2739] p-8 shadow-panel ring-1 ring-white/[0.04] sm:p-10">
          <div class="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_80%_60%_at_100%_0%,rgba(22,119,255,0.09),transparent)]"></div>
          <div class="relative space-y-3">
            <span class="inline-flex items-center gap-2 rounded-full border border-accent/25 bg-accent/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-accent-bright">${t("affiliateEyebrow")}</span>
            <h1 class="text-3xl font-bold tracking-tight text-white sm:text-4xl">${t("affiliateTitle")}</h1>
            <p class="max-w-2xl text-sm leading-relaxed text-slate-400 sm:text-base">${t("affiliateGuestHint")}</p>
            <button id="affiliate-open-login" type="button" class="k-btn k-btn--primary btn-site-primary mt-2 rounded-xl px-5 py-2.5 text-sm font-semibold">${t("headerLogin")}</button>
          </div>
        </header>
      </section>
    `;
    outlet.querySelector("#affiliate-open-login")?.addEventListener("click", () => globalThis.__siteOpenLogin?.());
    return;
  }

  const options = sponsors
    .map((s) => {
      const id = String(s.id ?? "").trim();
      if (!id) return "";
      return `<option value="${escapeHtml(id)}">${escapeHtml(String(s.title || id))}</option>`;
    })
    .filter(Boolean)
    .join("");

  outlet.innerHTML = `
    <section class="relative w-full min-w-0 space-y-8 px-1 pb-4">
      <header class="relative overflow-hidden rounded-3xl border border-white/[0.08] bg-[#1e2739] p-8 shadow-panel ring-1 ring-white/[0.04] sm:p-10">
        <div class="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_80%_60%_at_100%_0%,rgba(22,119,255,0.09),transparent)]"></div>
        <div class="relative space-y-3">
          <span class="inline-flex items-center gap-2 rounded-full border border-accent/25 bg-accent/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-accent-bright">${t("affiliateEyebrow")}</span>
          <h1 class="text-3xl font-bold tracking-tight text-white sm:text-4xl">${t("affiliateTitle")}</h1>
        </div>
      </header>
      <form id="affiliate-form" class="space-y-4 rounded-3xl border border-white/[0.08] bg-[#1e2739] p-6 shadow-panel ring-1 ring-white/[0.05] sm:p-7">
        <div>
          <label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-slate-500">${t("affiliateLabelSponsor")}</label>
          <div class="relative">
            <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_SPONSOR}</span>
            <select id="affiliate-sponsor" class="input-site text-sm" required>
              <option value="">${t("affiliateSponsorPlaceholder")}</option>
              ${options}
            </select>
          </div>
        </div>
        <div>
          <label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-slate-500">${t("affiliateLabelDate")}</label>
          <div class="relative">
            <span class="pointer-events-none absolute left-3 top-1/2 z-[1] -translate-y-1/2 text-slate-500">${ICON_CALENDAR}</span>
            <input id="affiliate-investment-date" type="date" class="input-site text-sm" />
          </div>
          <p class="mt-1 text-xs text-slate-500">${t("affiliateDateHint")}</p>
        </div>
        <div>
          <label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-slate-500">${t("affiliateLabelMessage")}</label>
          <div class="relative">
            <span class="pointer-events-none absolute left-3 top-3 z-[1] text-slate-500">${ICON_MESSAGE}</span>
            <textarea id="affiliate-message" class="input-site min-h-[140px] text-sm" maxlength="2000" placeholder="${escapeHtml(t("affiliateMessagePlaceholder"))}" required></textarea>
          </div>
          <p class="mt-1 text-xs text-slate-500">${t("affiliateMessageRules")}</p>
        </div>
        <div class="flex flex-wrap items-center justify-between gap-3">
          <p class="text-xs text-slate-500">${t("affiliateSender")} <span class="font-semibold text-slate-300">${escapeHtml(user.username)}</span></p>
          <button id="affiliate-submit" type="submit" class="k-btn k-btn--primary btn-site-primary rounded-xl px-5 py-2.5 text-sm font-semibold">${t("affiliateSubmit")}</button>
        </div>
      </form>
    </section>
  `;

  const form = outlet.querySelector("#affiliate-form");
  const sponsorSelect = outlet.querySelector("#affiliate-sponsor");
  const investmentDate = outlet.querySelector("#affiliate-investment-date");
  const msg = outlet.querySelector("#affiliate-message");
  const submitBtn = outlet.querySelector("#affiliate-submit");

  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    const sponsorId = String(sponsorSelect.value || "").trim();
    const sponsorTitle = sponsorId ? String(sponsorSelect.options[sponsorSelect.selectedIndex]?.text || "").trim() : "";
    const message = String(msg.value || "").trim();
    const inv = investmentDate && investmentDate.value ? String(investmentDate.value).trim() : "";

    if (!sponsorId) {
      showToast(t("affiliateToastSelectSponsor"), "error");
      return;
    }
    if (message.length < 8) {
      showToast(t("affiliateToastMessageShort"), "error");
      return;
    }

    submitBtn.disabled = true;
    const { ok, data, status } = await postUserAffiliateRequest({
      sponsorId,
      sponsorTitle,
      investmentDate: inv,
      message,
    });
    submitBtn.disabled = false;
    if (!ok) {
      const err = typeof data?.error === "string" ? data.error : "";
      showToast(affiliateErrorHint(err, status), "error");
      return;
    }
    form.reset();
    showToast(t("affiliateToastSuccess"), "success");
  });
}
