import { fetchSessionUser, postUserComplaint } 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_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 [];
  }
}

export async function renderComplaintsPage(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("complaintsEyebrow")}</span>
            <h1 class="text-3xl font-bold tracking-tight text-white sm:text-4xl">${t("complaintsTitle")}</h1>
            <p class="max-w-2xl text-sm leading-relaxed text-slate-400 sm:text-base">${t("complaintsGuestHint")}</p>
            <button id="complaint-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("#complaint-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("complaintsEyebrow")}</span>
          <h1 class="text-3xl font-bold tracking-tight text-white sm:text-4xl">${t("complaintsTitle")}</h1>
        </div>
      </header>
      <form id="complaint-form" class="rounded-3xl border border-white/[0.08] bg-[#1e2739] p-6 shadow-panel ring-1 ring-white/[0.05] sm:p-7 space-y-4">
        <div>
          <label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-slate-500">${t("complaintsLabelCategory")}</label>
          <div class="grid grid-cols-2 gap-2">
            <label class="profile-choice flex cursor-pointer items-center gap-2 px-3 py-2 text-sm">
              <input type="radio" name="category" value="sponsor" class="accent-[#1677ff]" checked />
              ${t("complaintsCatSponsor")}
            </label>
            <label class="profile-choice flex cursor-pointer items-center gap-2 px-3 py-2 text-sm">
              <input type="radio" name="category" value="other" class="accent-[#1677ff]" />
              ${t("complaintsCatOther")}
            </label>
          </div>
        </div>
        <div id="complaint-sponsor-wrap">
          <label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-slate-500">${t("complaintsLabelWhichSponsor")}</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="complaint-sponsor" class="input-site text-sm">
              <option value="">${t("complaintsSponsorPlaceholder")}</option>
              ${options}
            </select>
          </div>
        </div>
        <div>
          <label class="mb-1.5 block text-[11px] font-semibold uppercase tracking-wide text-slate-500">${t("complaintsLabelMessage")}</label>
          <div class="relative">
            <span class="pointer-events-none absolute left-3 top-3 z-[1] text-slate-500">${ICON_MESSAGE}</span>
            <textarea id="complaint-message" class="input-site min-h-[140px] text-sm" maxlength="2000" placeholder="${escapeHtml(t("complaintsMessagePlaceholder"))}"></textarea>
          </div>
          <p class="mt-1 text-xs text-slate-500">${t("complaintsMessageRules")}</p>
        </div>
        <div class="flex flex-wrap items-center justify-between gap-3">
          <p class="text-xs text-slate-500">${t("complaintsSender")} <span class="font-semibold text-slate-300">${escapeHtml(user.username)}</span></p>
          <button id="complaint-submit" type="submit" class="k-btn k-btn--primary btn-site-primary rounded-xl px-5 py-2.5 text-sm font-semibold">${t("complaintsSubmit")}</button>
        </div>
      </form>
    </section>
  `;

  const form = outlet.querySelector("#complaint-form");
  const sponsorWrap = outlet.querySelector("#complaint-sponsor-wrap");
  const sponsorSelect = outlet.querySelector("#complaint-sponsor");
  const msg = outlet.querySelector("#complaint-message");
  const submitBtn = outlet.querySelector("#complaint-submit");

  const syncCategory = () => {
    const cat = form.querySelector('input[name="category"]:checked')?.value || "sponsor";
    sponsorWrap.classList.toggle("hidden", cat !== "sponsor");
  };
  form.querySelectorAll('input[name="category"]').forEach((r) => r.addEventListener("change", syncCategory));
  syncCategory();

  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    const category = form.querySelector('input[name="category"]:checked')?.value || "sponsor";
    const sponsorId = String(sponsorSelect.value || "").trim();
    const sponsorTitle = sponsorId ? String(sponsorSelect.options[sponsorSelect.selectedIndex]?.text || "").trim() : "";
    const message = String(msg.value || "").trim();

    if (category === "sponsor" && !sponsorId) {
      showToast(t("complaintsToastSelectSponsor"), "error");
      return;
    }
    if (message.length < 8) {
      showToast(t("complaintsToastMessageShort"), "error");
      return;
    }

    submitBtn.disabled = true;
    const { ok, data, status } = await postUserComplaint({ category, sponsorId, sponsorTitle, message });
    submitBtn.disabled = false;
    if (!ok) {
      if (status === 401 || data?.error === "auth") {
        showToast(t("complaintsToastAuth"), "error");
      } else if (data?.error === "db") {
        showToast(t("complaintsToastDb"), "error");
      } else {
        showToast(t("complaintsToastFail"), "error");
      }
      return;
    }
    form.reset();
    syncCategory();
    showToast(t("complaintsToastSuccess"), "success");
  });
}
