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

function layout(title: string, body: string): string {
  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="robots" content="noindex, nofollow">
  <title>${esc(title)}</title>
  <link rel="stylesheet" href="/styles.css">
</head>
<body>
  <header class="top">
    <div class="brand">
      <span class="mark" aria-hidden="true"></span>
      <div>
        <strong>Optimize Solutions</strong>
        <span>Payments</span>
      </div>
    </div>
  </header>
  <main>${body}</main>
</body>
</html>`;
}

export function renderHome(): string {
  return layout(
    "Optimize Solutions Payments",
    `<section class="card">
      <p class="eyebrow">Payment gateway</p>
      <h1>Optimize Solutions Payment Gateway</h1>
      <p class="lead">One iPay merchant account for every Optimize Solutions product. This hub starts the checkout, receives the bank callback, and sends the customer back to the product that asked for the payment.</p>
      <ol class="steps">
        <li>The product creates a checkout with its API key.</li>
        <li>The customer pays on iPay. Card details never touch this site.</li>
        <li>iPay notifies this hub, and the hub notifies that product.</li>
      </ol>
    </section>`
  );
}

export function renderMessage(input: { title: string; message: string; actionHref?: string; actionLabel?: string }): string {
  const action = input.actionHref
    ? `<p class="actions"><a class="button" href="${esc(input.actionHref)}">${esc(input.actionLabel || "Continue")}</a></p>`
    : "";
  return layout(
    input.title,
    `<section class="card">
      <h1>${esc(input.title)}</h1>
      <p class="lead">${esc(input.message)}</p>
      ${action}
    </section>`
  );
}

export function renderPay(input: {
  checkoutUrl: string;
  fields: Record<string, string>;
  amount: string;
  description: string;
  customerName: string;
}): string {
  const inputs = Object.entries(input.fields)
    .map(([name, value]) => `<input type="hidden" name="${esc(name)}" value="${esc(value)}">`)
    .join("");
  const description = input.description ? `<p class="muted">${esc(input.description)}</p>` : "";
  const customer = input.customerName ? `<p class="muted">Customer: ${esc(input.customerName)}</p>` : "";
  return layout(
    "Redirecting to iPay",
    `<section class="card">
      <p class="eyebrow">Secure checkout</p>
      <h1>Sending you to iPay</h1>
      <p class="amount">${esc(input.amount)}</p>
      ${description}
      ${customer}
      <p class="lead">Card, LankaQR, and iPay wallet details are entered on iPay, not on this page.</p>
      <form id="ipay-checkout" method="POST" action="${esc(input.checkoutUrl)}" accept-charset="UTF-8">
        ${inputs}
        <button class="button" type="submit">Continue to iPay</button>
      </form>
    </section>
    <script src="/pay.js"></script>`
  );
}

export type AdminRow = {
  createdAt: Date;
  productId: string;
  orderId: string;
  amount: string;
  status: string;
  ipayStatus: string | null;
  webhook: string;
};

function formatTime(value: Date): string {
  return new Intl.DateTimeFormat("en-GB", {
    timeZone: "Asia/Colombo",
    year: "numeric",
    month: "short",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  }).format(value);
}

export function renderAdminLogin(message?: string): string {
  const note = message ? `<p class="warn">${esc(message)}</p>` : "";
  return layout(
    "Payments admin",
    `<section class="card narrow">
      <p class="eyebrow">Operations</p>
      <h1>Recent payments</h1>
      <p class="lead">Enter the admin key to view the latest checkouts.</p>
      ${note}
      <form method="POST" action="/admin/payments" class="stack">
        <label for="key">Admin key</label>
        <input id="key" name="key" type="password" autocomplete="current-password" required>
        <button class="button" type="submit">View payments</button>
      </form>
    </section>`
  );
}

export function renderAdmin(rows: AdminRow[], counts: Record<string, number>): string {
  const summary = ["PENDING", "PAID", "FAILED", "CANCELLED"]
    .map((status) => `<span class="pill ${esc(status.toLowerCase())}">${esc(status)} ${counts[status] ?? 0}</span>`)
    .join("");
  const body = rows.length
    ? rows
        .map(
          (row) => `<tr>
            <td>${esc(formatTime(row.createdAt))}</td>
            <td>${esc(row.productId)}</td>
            <td><code>${esc(row.orderId)}</code></td>
            <td>${esc(row.amount)}</td>
            <td><span class="pill ${esc(row.status.toLowerCase())}">${esc(row.status)}</span></td>
            <td>${esc(row.ipayStatus || "—")}</td>
            <td>${esc(row.webhook)}</td>
          </tr>`
        )
        .join("")
    : `<tr><td colspan="7">No payments yet.</td></tr>`;
  return layout(
    "Recent payments",
    `<section class="card wide">
      <p class="eyebrow">Operations</p>
      <h1>Recent payments</h1>
      <div class="summary">${summary}</div>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Time (Colombo)</th>
              <th>Product</th>
              <th>Order</th>
              <th>Amount</th>
              <th>Status</th>
              <th>iPay</th>
              <th>Webhook</th>
            </tr>
          </thead>
          <tbody>${body}</tbody>
        </table>
      </div>
      <p class="muted">Showing the latest ${rows.length} of the stored payments. Counts above are all-time.</p>
    </section>`
  );
}
