/**
 * Transactional email via Resend.
 *
 * Three flows for launch:
 *   - sendWelcomeEmail() — on signup
 *   - sendPaymentReceipt() — on successful NexaPay webhook
 *   - sendRenewalReminder() — daily cron when subscription_end < 3 days out
 *
 * All functions return { ok: boolean, id?: string, error?: string } and
 * never throw — email is best-effort and must not break the auth or
 * payment flow if Resend is unreachable.
 */

const RESEND_API = 'https://api.resend.com/emails';
const FROM_DEFAULT = 'VYNDR <grades@vyndr.app>';

interface SendResult {
  ok: boolean;
  id?: string;
  error?: string;
}

async function send(payload: { to: string; subject: string; html: string; text: string }): Promise<SendResult> {
  const apiKey = process.env.RESEND_API_KEY;
  if (!apiKey) {
    if (process.env.NODE_ENV !== 'production') {
      console.warn('[email] RESEND_API_KEY not set, skipping send to', payload.to);
    }
    return { ok: false, error: 'RESEND_API_KEY missing' };
  }

  try {
    const res = await fetch(RESEND_API, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        from: process.env.RESEND_FROM_EMAIL || FROM_DEFAULT,
        to: [payload.to],
        subject: payload.subject,
        html: payload.html,
        text: payload.text,
      }),
    });

    if (!res.ok) {
      const body = await res.text().catch(() => '');
      return { ok: false, error: `${res.status} ${body.slice(0, 200)}` };
    }

    const data = await res.json().catch(() => ({}));
    return { ok: true, id: (data as { id?: string }).id };
  } catch (err) {
    return { ok: false, error: err instanceof Error ? err.message : 'unknown' };
  }
}

const TEMPLATE_FOOTER = `\n\n— VYNDR\nBuilt in Detroit.\n\nNot a sportsbook. Gamble responsibly. 1-800-522-4700.\n`;

const TEMPLATE_HTML_WRAP = (body: string) => `
<!doctype html>
<html><body style="margin:0;padding:32px 16px;background:#0A0A0F;color:#F0F0F5;font-family:'Instrument Sans',-apple-system,system-ui,sans-serif;line-height:1.6">
  <div style="max-width:560px;margin:0 auto;background:#12121A;border:1px solid #2A2A3A;border-radius:16px;padding:32px">
    <h1 style="font-size:22px;font-weight:800;letter-spacing:0.10em;margin:0 0 24px;color:#E8E8F0;font-family:'IBM Plex Mono','JetBrains Mono',monospace">
      VYND<span style="color:#00D4A0;text-shadow:0 0 12px rgba(0,212,160,0.6)">R</span>
    </h1>
    ${body}
    <hr style="border:none;border-top:1px solid #2A2A3A;margin:32px 0 16px" />
    <p style="font-size:11px;color:#5A5A6A;margin:0;font-family:'JetBrains Mono',monospace">
      Built in Detroit. Not a sportsbook. Gamble responsibly. 1-800-522-4700.
    </p>
  </div>
</body></html>`;

export async function sendWelcomeEmail(email: string): Promise<SendResult> {
  // Session 10 — copy updated to reflect the per-day quota (3 free
  // reads/day), Stripe founder pricing, and the live soccer engine.
  const site = process.env.NEXT_PUBLIC_SITE_URL || 'https://vyndr.app';
  const subject = 'Welcome to VYNDR — your reads are ready';
  const body = `
    <p style="font-size:16px">Welcome to VYNDR.</p>
    <p>You have <strong>3 free reads per day</strong>. Every read runs your prop through our intelligence engine — the same signals the books use to set lines.</p>
    <p><strong>Quick start:</strong></p>
    <ol style="padding-left:20px;line-height:1.7">
      <li>Go to <a href="${site}/scan" style="color:#00D4A0">vyndr.app/scan</a></li>
      <li>Pick a player, stat, and line</li>
      <li>Hit &ldquo;Read It&rdquo; — your grade appears in seconds</li>
    </ol>
    <p>When you&rsquo;re ready for unlimited reads and full reasoning breakdowns, founder pricing starts at <strong>$14.99/mo (locked for life)</strong>: <a href="${site}/pricing" style="color:#00D4A0">vyndr.app/pricing</a></p>
    <p>The <strong>World Cup 2026 intelligence engine is live</strong> — soccer props are graded with xG regression, altitude impact, referee card rates, and penalty taker signals that nobody else has.</p>
    <p style="margin-top:24px"><a href="${site}/scan"
        style="display:inline-block;padding:12px 24px;background:#00D4A0;color:#0A0A0F;text-decoration:none;border-radius:8px;font-weight:700">
      Read your first prop →
    </a></p>
    <p style="margin-top:24px;color:#8A8A9A">See what the market doesn&rsquo;t.<br>— VYNDR</p>
  `;
  const text =
`Welcome to VYNDR.

You have 3 free reads per day. Every read runs your prop through our intelligence engine — the same signals the books use to set lines.

Quick start:
  1. Go to ${site}/scan
  2. Pick a player, stat, and line
  3. Hit "Read It" — your grade appears in seconds

When you're ready for unlimited reads and full reasoning breakdowns, founder pricing starts at $14.99/mo (locked for life): ${site}/pricing

The World Cup 2026 intelligence engine is live — soccer props are graded with xG regression, altitude impact, referee card rates, and penalty taker signals that nobody else has.

See what the market doesn't.
— VYNDR
${TEMPLATE_FOOTER}`;
  return send({ to: email, subject, html: TEMPLATE_HTML_WRAP(body), text });
}

export async function sendPaymentReceipt(
  email: string,
  opts: { tier: 'analyst' | 'desk'; amount: string; renewsAt: string },
): Promise<SendResult> {
  const tierLabel = opts.tier === 'desk' ? 'Desk' : 'Analyst';
  const subject = `Receipt — VYNDR ${tierLabel} Access`;
  const body = `
    <p style="font-size:16px">Payment received. You&rsquo;re in.</p>
    <table style="width:100%;border-collapse:collapse;margin:16px 0">
      <tr><td style="padding:6px 0;color:#8A8A9A;font-size:13px">Tier</td>
          <td style="padding:6px 0;text-align:right;font-family:'JetBrains Mono',monospace">${tierLabel}</td></tr>
      <tr><td style="padding:6px 0;color:#8A8A9A;font-size:13px">Amount</td>
          <td style="padding:6px 0;text-align:right;font-family:'JetBrains Mono',monospace">${opts.amount}</td></tr>
      <tr><td style="padding:6px 0;color:#8A8A9A;font-size:13px">Renews</td>
          <td style="padding:6px 0;text-align:right;font-family:'JetBrains Mono',monospace">${opts.renewsAt}</td></tr>
    </table>
    <p>Full intelligence unlocked. Go read something.</p>
    <p><a href="${process.env.NEXT_PUBLIC_SITE_URL || 'https://vyndr.app'}/scan"
        style="display:inline-block;padding:12px 24px;background:#1A4A3A;color:#F0F0F5;text-decoration:none;border-radius:12px;font-weight:600">
      Start reading →
    </a></p>
  `;
  const text =
`Payment received. You're in.

Tier: ${tierLabel}
Amount: ${opts.amount}
Renews: ${opts.renewsAt}

Full intelligence unlocked. Go read something.
${TEMPLATE_FOOTER}`;
  return send({ to: email, subject, html: TEMPLATE_HTML_WRAP(body), text });
}

// Tiny HTML escape so any caller-supplied value can't inject markup.
const esc = (s: string | number) =>
  String(s)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');

export async function sendPasswordResetEmail(email: string, resetLink: string): Promise<SendResult> {
  const subject = 'Reset your VYNDR password';
  const safeLink = esc(resetLink);
  const body = `
    <p style="font-size:16px">Reset your password.</p>
    <p>Click the link below to set a new password. This link expires in 1 hour and can only be used once.</p>
    <p style="margin-top:24px">
      <a href="${safeLink}"
         style="display:inline-block;padding:12px 24px;background:#1A5A42;color:#E8FFF4;text-decoration:none;border-radius:12px;font-weight:600">
        Reset Password →
      </a>
    </p>
    <p style="margin-top:16px;color:#7A7A8E;font-size:13px">
      If you didn&rsquo;t request this, ignore this email. Your password won&rsquo;t change.
    </p>
  `;
  const text =
`Reset your VYNDR password.

Click here: ${resetLink}

This link expires in 1 hour and can only be used once. If you didn't request this, ignore this email.
${TEMPLATE_FOOTER}`;
  return send({ to: email, subject, html: TEMPLATE_HTML_WRAP(body), text });
}

export async function sendQuotaReminderEmail(email: string): Promise<SendResult> {
  const subject = 'You used all 5 reads this month. Good taste.';
  const checkoutUrl = `${process.env.NEXT_PUBLIC_SITE_URL || 'https://vyndr.app'}/api/checkout?tier=analyst`;
  const body = `
    <p style="font-size:16px">You used all 5 reads this month.</p>
    <p>Next month you get 5 more — or unlock unlimited right now.</p>
    <p style="margin-top:16px">
      <span style="font-family:'IBM Plex Mono','JetBrains Mono',monospace;font-size:28px;font-weight:800;color:#00D4A0;text-shadow:0 0 12px rgba(0,212,160,0.6)">$14.99</span>
      <span style="color:#7A7A8E;font-size:14px">/mo · Locked for life</span>
    </p>
    <p style="color:#FFB347;font-size:13px;font-weight:600">This rate disappears June 15.</p>
    <p style="margin-top:20px">
      <a href="${esc(checkoutUrl)}"
         style="display:inline-block;padding:12px 24px;background:#1A5A42;color:#E8FFF4;text-decoration:none;border-radius:12px;font-weight:600">
        Unlock Unlimited Reads →
      </a>
    </p>
  `;
  const text =
`You used all 5 reads this month.

Next month you get 5 more — or unlock unlimited for $14.99/mo.

This rate disappears June 15.

${checkoutUrl}
${TEMPLATE_FOOTER}`;
  return send({ to: email, subject, html: TEMPLATE_HTML_WRAP(body), text });
}

export async function sendCancellationEmail(
  email: string,
  opts: { accessUntil: string; iqScore?: number; record?: string },
): Promise<SendResult> {
  const subject = "We're sorry to see you go.";
  const pricingUrl = `${process.env.NEXT_PUBLIC_SITE_URL || 'https://vyndr.app'}/pricing`;
  const statsLine = opts.iqScore != null
    ? `<p style="color:#7A7A8E;font-size:14px">VYNDR IQ: ${esc(opts.iqScore)}. Record: ${esc(opts.record ?? 'N/A')}. You were on a good run.</p>`
    : '';
  const body = `
    <p style="font-size:16px">Your subscription has been cancelled.</p>
    <p>Your access continues until <strong>${esc(opts.accessUntil)}</strong>. Your Ledger and grade history are still here if you come back.</p>
    ${statsLine}
    <p style="margin-top:20px">
      <a href="${esc(pricingUrl)}"
         style="display:inline-block;padding:12px 24px;background:#1A5A42;color:#E8FFF4;text-decoration:none;border-radius:12px;font-weight:600">
        Come Back Anytime →
      </a>
    </p>
  `;
  const text =
`Your VYNDR subscription has been cancelled.

Access continues until ${opts.accessUntil}.

${opts.iqScore != null ? `VYNDR IQ: ${opts.iqScore}. Record: ${opts.record ?? 'N/A'}.\n` : ''}Come back anytime: ${pricingUrl}
${TEMPLATE_FOOTER}`;
  return send({ to: email, subject, html: TEMPLATE_HTML_WRAP(body), text });
}

export async function sendRenewalReminder(
  email: string,
  opts: { daysLeft: number; renewalLink: string; tier: string },
): Promise<SendResult> {
  const subject = `Your VYNDR access expires in ${opts.daysLeft} day${opts.daysLeft === 1 ? '' : 's'}`;
  const body = `
    <p style="font-size:16px">Your <strong>${opts.tier}</strong> access expires in ${opts.daysLeft} day${opts.daysLeft === 1 ? '' : 's'}.</p>
    <p>If you renew, you keep the same pricing and zero interruption to your reads. If you don&rsquo;t, you&rsquo;ll drop back to 5 reads/month with the analysis blurred.</p>
    <p style="margin-top:24px"><a href="${opts.renewalLink}"
        style="display:inline-block;padding:12px 24px;background:#1A4A3A;color:#F0F0F5;text-decoration:none;border-radius:12px;font-weight:600">
      Renew now →
    </a></p>
  `;
  const text =
`Your ${opts.tier} access expires in ${opts.daysLeft} day${opts.daysLeft === 1 ? '' : 's'}.

Renew now: ${opts.renewalLink}
${TEMPLATE_FOOTER}`;
  return send({ to: email, subject, html: TEMPLATE_HTML_WRAP(body), text });
}
