import { landingConfig } from "./config.mjs";
import { accountUrl, parseCatalogue, publicUrl } from "./catalogue.mjs";
const copy = {
  en: {
    loading: "Loading plans…",
    error:
      "Plans are temporarily unavailable. Please try again or contact info@awentir.ai.",
    empty:
      "Online subscriptions are not available right now. Contact us for access.",
    retry: "Try again",
    choose: "Choose",
    signIn: "Sign in to subscribe",
    month: "/ month",
    briefs: "Briefs per month",
    ai: "AI calls per month",
    unlimited: "Unlimited",
    kyc: "Identity verification required before payment.",
    test: "Test environment — no live payments.",
    registration: "Already have an account?",
    login: "Sign in",
    closed:
      "New account registration is currently closed. Existing users can sign in to subscribe.",
    payment:
      "Create an account or sign in, review your plan, then pay securely with Stripe. No payment is taken on this page.",
  },
  es: {
    loading: "Cargando planes…",
    error:
      "Los planes no están disponibles temporalmente. Reintentá o contactá a info@awentir.ai.",
    empty:
      "Las suscripciones en línea no están disponibles. Contactanos para solicitar acceso.",
    retry: "Reintentar",
    choose: "Elegir",
    signIn: "Ingresar para suscribirse",
    month: "/ mes",
    briefs: "Briefs por mes",
    ai: "Llamadas de IA por mes",
    unlimited: "Sin límite",
    kyc: "Requiere verificar tu identidad antes del pago.",
    test: "Entorno de prueba: sin pagos reales.",
    registration: "¿Ya tenés una cuenta?",
    login: "Iniciar sesión",
    closed:
      "El registro de cuentas está cerrado por ahora. Los usuarios existentes pueden ingresar para suscribirse.",
    payment:
      "Creá tu cuenta o ingresá, revisá el plan y pagá de forma segura con Stripe. No se realiza ningún cobro en esta página.",
  },
};
const panel = document.getElementById("pricing-content");
const retry = document.getElementById("pricing-retry");
const state = document.getElementById("pricing-status");
let catalogue = null,
  failure = false,
  pending = false;
function locale() {
  return document.documentElement.lang === "es" ? "es" : "en";
}
function node(tag, value, className) {
  const element = document.createElement(tag);
  if (value !== undefined) element.textContent = value;
  if (className) element.className = className;
  return element;
}
function render() {
  const lang = locale(),
    labels = copy[lang];
  document.querySelectorAll("[data-account-link]").forEach((link) => {
    link.href = accountUrl(
      landingConfig.appOrigin,
      lang,
      null,
      link.dataset.accountLink === "register",
    );
  });
  panel.replaceChildren();
  retry.textContent = labels.retry;
  retry.hidden = !failure;
  state.setAttribute("role", failure ? "alert" : "status");
  state.textContent = pending
    ? labels.loading
    : failure
      ? labels.error
      : !catalogue?.enabled || !catalogue.plans.length
        ? labels.empty
        : "";
  if (!catalogue || failure || pending || !catalogue.enabled) return;
  if (catalogue.mode === "test")
    panel.append(node("p", labels.test, "pricing-notice"));
  const grid = node("div", undefined, "pricing-grid");
  for (const plan of catalogue.plans) {
    const card = node("article", undefined, "pricing-card");
    const heading = node("h3", plan.name);
    heading.id = `plan-${plan.code}`;
    card.setAttribute("aria-labelledby", heading.id);
    card.append(heading);
    if (plan.description?.[lang])
      card.append(node("p", plan.description[lang], "pricing-description"));
    card.append(
      node(
        "p",
        `${new Intl.NumberFormat(lang, { style: "currency", currency: "USD" }).format(plan.amount / 100)} ${labels.month}`,
        "pricing-price",
      ),
    );
    const list = node("ul");
    for (const feature of plan.features?.[lang] || [])
      list.append(node("li", feature));
    if (plan.briefLimit !== undefined)
      list.append(
        node("li", `${labels.briefs}: ${plan.briefLimit ?? labels.unlimited}`),
      );
    if (plan.aiLimit !== undefined)
      list.append(
        node("li", `${labels.ai}: ${plan.aiLimit ?? labels.unlimited}`),
      );
    card.append(list);
    if (plan.kycRequired) card.append(node("p", labels.kyc, "pricing-note"));
    const action = node(
      "a",
      catalogue.registrationEnabled
        ? `${labels.choose} ${plan.name}`
        : labels.signIn,
      "cta",
    );
    action.href = accountUrl(
      landingConfig.appOrigin,
      lang,
      plan.code,
      catalogue.registrationEnabled,
    );
    card.append(action);
    grid.append(card);
  }
  panel.append(grid, node("p", labels.payment, "pricing-note"));
  if (!catalogue.registrationEnabled)
    panel.append(node("p", labels.closed, "pricing-note"));
  const existing = node("p", `${labels.registration} `, "pricing-note");
  const login = node("a", labels.login);
  login.href = accountUrl(landingConfig.appOrigin, lang, null, false);
  existing.append(login);
  panel.append(existing);
}
async function load() {
  if (pending) return;
  pending = true;
  failure = false;
  render();
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 12000);
  try {
    const url = publicUrl(landingConfig.catalogueUrl);
    const response = await fetch(url, {
      credentials: "omit",
      redirect: "error",
      cache: "no-store",
      signal: controller.signal,
      headers: { Accept: "application/json" },
    });
    if (
      !response.ok ||
      !response.headers.get("content-type")?.includes("application/json")
    )
      throw new Error("catalogue_unavailable");
    catalogue = parseCatalogue(
      await response.json(),
      landingConfig.expectedMode,
    );
  } catch {
    catalogue = null;
    failure = true;
  } finally {
    clearTimeout(timer);
    pending = false;
    render();
  }
}
retry.addEventListener("click", load);
new MutationObserver(render).observe(document.documentElement, {
  attributes: true,
  attributeFilter: ["lang"],
});
void load();
