import { existsSync, readFileSync } from "fs";
import path from "path";
import {
  TANK_TRACK_APP_HOME_DEEPLINK,
  TANK_TRACK_APP_HOME_URL,
} from "../config/environment";

export type StripeConnectLandingKind = "return" | "refresh";

export type StripeConnectLandingOpts = {
  title: string;
  subtitle: string;
  statusText?: string;
  ok: boolean;
  kind?: StripeConnectLandingKind;
};

const templateCache = new Map<StripeConnectLandingKind, string>();

function escapeHtml(value: string): string {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

/** Safe value for href / navigation (http(s) or custom scheme). */
function safeNavUrl(raw: string): string {
  const trimmed = raw.trim();
  if (!trimmed) return "";
  if (/^https?:\/\//i.test(trimmed)) return trimmed;
  if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed)) return trimmed;
  return "";
}

function loadTemplate(kind: StripeConnectLandingKind): string {
  const cached = templateCache.get(kind);
  if (cached) return cached;
  const fileName =
    kind === "return"
      ? "stripe-connect-return.html"
      : "stripe-connect-refresh.html";
  const candidates = [
    path.join(__dirname, "..", "assets", fileName),
    path.join(process.cwd(), "src", "assets", fileName),
  ];
  const filePath = candidates.find((p) => existsSync(p));
  if (!filePath) {
    throw new Error(`Stripe Connect HTML template not found: ${fileName}`);
  }
  const html = readFileSync(filePath, "utf8");
  templateCache.set(kind, html);
  return html;
}

function stripeConnectHomeUrl(): string {
  return TANK_TRACK_APP_HOME_URL.length > 0
    ? TANK_TRACK_APP_HOME_URL
    : "https://tanktrack.thesuitchstaging2.com";
}

function defaultHint(kind: StripeConnectLandingKind, ok: boolean): string {
  if (kind === "refresh") {
    return ok
      ? "Return to Tank Track and continue Stripe onboarding if prompted."
      : "Open Tank Track and try connecting your payout account again.";
  }
  return ok
    ? "You can close this tab and continue in the Tank Track app."
    : "Open Tank Track and try connecting your payout account again.";
}

function fillTemplate(
  kind: StripeConnectLandingKind,
  vars: Record<string, string>,
): string {
  let html = loadTemplate(kind);
  for (const [key, value] of Object.entries(vars)) {
    html = html.split(`{{${key}}}`).join(value);
  }
  return html;
}

/** HTML landing for Stripe Connect return_url / refresh_url (gas station + app user wallet). */
export function renderStripeConnectLandingPage(
  opts: StripeConnectLandingOpts,
): string {
  const kind = opts.kind ?? "return";
  const accent = opts.ok ? "#16a34a" : "#ef4444";
  const accentSoft = opts.ok
    ? "rgba(22,163,74,.18)"
    : "rgba(239,68,68,.18)";
  const icon = opts.ok ? "&#10003;" : "&#9888;";
  const statusBlock = opts.statusText
    ? `<div class="status-pill">${escapeHtml(opts.statusText)}</div>`
    : "";

  const webHome = safeNavUrl(stripeConnectHomeUrl());
  const deeplinkHome = safeNavUrl(TANK_TRACK_APP_HOME_DEEPLINK);
  const primaryHref = deeplinkHome || webHome || "#";

  return fillTemplate(kind, {
    PAGE_TITLE: escapeHtml(opts.title),
    ACCENT: accent,
    ACCENT_SOFT: accentSoft,
    ICON: icon,
    HEADING: escapeHtml(opts.title),
    SUBTITLE: escapeHtml(opts.subtitle),
    STATUS_BLOCK: statusBlock,
    HOME_URL: escapeHtml(primaryHref),
    HOME_WEB_URL: escapeHtml(webHome),
    HOME_DEEPLINK: escapeHtml(deeplinkHome),
    HINT: escapeHtml(defaultHint(kind, opts.ok)),
  });
}
