"use client";

import { Suspense, useEffect, useMemo } from "react";
import { useSearchParams } from "next/navigation";

/**
 * /go — payment redirect bounce page for D-Money web checkout.
 *
 * The redirect is done CLIENT-SIDE on purpose: the navigation must originate
 * from the loaded https://edrpassenger.triaplc.com/go document so the browser
 * sends `Referer: https://edrpassenger.triaplc.com` to D-Money. D-Money only
 * whitelists that origin, so a server-side 307 (whose referrer on the redirect
 * hop is browser-dependent and can be stripped) must NOT be used here.
 *
 * It fires immediately (no delay) and paints a bare white full-screen cover
 * above the sidebar/tab bar (z-40) — no portal chrome, no text on the happy
 * path. A short message shows only when the link is missing/untrusted.
 *
 * `?url=` MUST be percent-encoded by the caller (Uri.encodeComponent() in the
 * Flutter app / encodeURIComponent() on web); otherwise the query parser
 * truncates the D-Money URL at its first `&` and merch_code/sign are lost.
 * See scripts/test-go-redirect.mjs.
 */

const ALLOWED_HOSTS = (
  // Default allows both D-Money environments:
  //   test/sandbox → pgtest.d-money.dj        (base domain d-money.dj)
  //   production   → pg.d-moneyservice.dj      (base domain d-moneyservice.dj)
  process.env.NEXT_PUBLIC_DMONEY_ALLOWED_HOSTS ?? "d-money.dj,d-moneyservice.dj"
)
  .split(",")
  .map((h) => h.trim().toLowerCase())
  .filter(Boolean);

/** True only for https URLs whose host is (or is a subdomain of) an allowlisted host. */
function isTrustedDMoneyUrl(raw: string | null): raw is string {
  if (!raw) return false;
  let parsed: URL;
  try {
    parsed = new URL(raw);
  } catch {
    return false;
  }
  if (parsed.protocol !== "https:") return false;
  const host = parsed.hostname.toLowerCase();
  return ALLOWED_HOSTS.some(
    (allowed) => host === allowed || host.endsWith(`.${allowed}`),
  );
}

function RedirectView() {
  const searchParams = useSearchParams();
  const raw = searchParams.get("url");
  const target = useMemo(() => (isTrustedDMoneyUrl(raw) ? raw : null), [raw]);

  useEffect(() => {
    if (!target) return;
    // Navigate from this document so the D-Money request carries
    // Referer: https://edrpassenger.triaplc.com (the origin D-Money whitelists).
    window.location.replace(target);
  }, [target]);

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-white px-6 text-center">
      {!target && (
        <p className="text-sm text-gray-500">
          This payment link is invalid or has expired. Please start the payment
          again from the app.
        </p>
      )}
    </div>
  );
}

export default function GoPage() {
  return (
    <Suspense fallback={<div className="fixed inset-0 z-[100] bg-white" />}>
      <RedirectView />
    </Suspense>
  );
}
