﻿import fs from 'fs';
import path from 'path';
import { db, save, uid, OUTBOX_DIR } from './store';
import { PdfDocument, User } from './types';

/** Base URL of the frontend, used to build links in outbound emails. */
export const FRONTEND_URL = (process.env.FRONTEND_URL || 'http://localhost:5179').replace(/\/$/, '');

const baseStyles = `
  body { margin:0; padding:0; background:#eef0f4; font-family:'Segoe UI', Arial, sans-serif; color:#1e1b2e; }
  .wrap { max-width:640px; margin:24px auto; background:#f7f8fb; border:1px solid #e4e6ef; border-radius:18px; overflow:hidden; }
  .head { background:#ffffff; padding:28px 32px; display:flex; align-items:center; gap:16px; border-bottom:1px solid #eceef5; }
  .logo { width:56px; height:56px; border-radius:50%; background:#5b21d6; color:#fff; display:inline-block; text-align:center; line-height:56px; font-size:26px; }
  .brand { font-size:26px; font-weight:800; margin:0; }
  .brand small { display:block; font-size:14px; font-weight:500; color:#6b7280; }
  .brand small a { color:#5b21d6; text-decoration:none; }
  .hero { text-align:center; padding:36px 32px 8px; }
  .pdficon { width:88px; height:88px; border-radius:50%; background:#ece6fb; display:inline-block; line-height:88px; font-weight:700; color:#fff; }
  .pdficon span { background:#5b21d6; border-radius:8px; padding:6px 10px; font-size:14px; }
  h1 { font-size:34px; margin:20px 0 10px; }
  h1 .accent { color:#5b21d6; }
  .sub { color:#4b5563; font-size:16px; line-height:1.6; margin:0 auto 24px; max-width:480px; }
  .sub a, .sub .link { color:#5b21d6; font-weight:600; text-decoration:none; }
  .stats { background:#fff; border:1px solid #e9eaf2; border-radius:16px; margin:0 32px 24px; padding:20px 8px; }
  .stats table { width:100%; border-collapse:collapse; }
  .stats td { text-align:center; padding:6px 10px; border-left:1px solid #eef0f6; vertical-align:top; }
  .stats td:first-child { border-left:none; }
  .stat-label { color:#4b5563; font-size:13px; margin-top:8px; }
  .stat-value { font-size:26px; font-weight:800; margin-top:4px; }
  .icon-circle { width:44px; height:44px; border-radius:50%; display:inline-block; line-height:44px; font-size:20px; }
  .notice { background:#f3effd; border:1px solid #e2d9f8; border-radius:14px; margin:0 32px 28px; padding:20px 24px; display:flex; gap:16px; text-align:left; }
  .notice b { display:block; margin-bottom:6px; font-size:16px; }
  .notice p { margin:0; color:#4b5563; font-size:14px; line-height:1.6; }
  .files { background:#fff; border:1px solid #e9eaf2; border-radius:14px; margin:0 32px 24px; overflow:hidden; }
  .files table { width:100%; border-collapse:collapse; font-size:14px; }
  .files th { background:#efe9fb; text-align:left; padding:12px 18px; font-size:12px; letter-spacing:.06em; color:#4b3a86; }
  .files td { padding:14px 18px; border-top:1px solid #f0f1f7; }
  .chip { background:#e5f7ec; color:#15803d; border:1px solid #bfe8cf; border-radius:999px; padding:4px 12px; font-size:12px; font-weight:700; white-space:nowrap; }
  .btns { text-align:center; padding:4px 32px 30px; }
  .btn { display:inline-block; border-radius:12px; padding:14px 30px; font-size:16px; font-weight:700; text-decoration:none; margin:6px 8px; }
  .btn-primary { background:#4c1fd1; color:#ffffff; }
  .btn-outline { border:2px solid #5b21d6; color:#5b21d6; background:#fff; }
  .footer { text-align:center; color:#4b5563; font-size:14px; padding:18px 32px 30px; border-top:1px solid #e9eaf2; }
  .footer a { color:#5b21d6; font-weight:700; text-decoration:none; }
`;

function shell(inner: string): string {
  return `<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<style>${baseStyles}</style></head>
<body><div class="wrap">
  <div class="head">
    <span class="logo">&#9855;</span>
    <div class="brand">All in One Accessibility<small>Powered by <a href="#">Skynet Technologies</a></small></div>
  </div>
  ${inner}
  <div class="footer">&#127911; <b>Need help?</b> <a href="#">Contact support</a><br><span style="font-size:13px;color:#6b7280">We're here to help you every step of the way.</span></div>
</div></body></html>`;
}

export function renderTrialResultEmail(
  user: User,
  doc: PdfDocument,
  remediatedNow: number,
  remaining: number
): string {
  return shell(`
  <div class="hero">
    <div class="pdficon"><span>PDF</span></div>
    <h1><span class="accent">${remediatedNow} pages</span> remediated &mdash;<br><span class="accent">${remaining} pages</span> remaining</h1>
    <p class="sub">Your free trial covered the first ${remediatedNow} pages of <span class="link">${doc.name}</span>.<br>
    Upgrade your plan to remediate the remaining ${remaining} pages.</p>
  </div>
  <div class="stats"><table><tr>
    <td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#128196;</span><div class="stat-label">File</div><div class="stat-value" style="font-size:14px">${doc.name}</div></td>
    <td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#128209;</span><div class="stat-label">Total pages</div><div class="stat-value" style="color:#5b21d6">${doc.pages}</div></td>
    <td><span class="icon-circle" style="background:#e5f7ec;color:#15803d">&#10003;</span><div class="stat-label">Remediated now</div><div class="stat-value" style="color:#15803d">${remediatedNow}</div></td>
    <td><span class="icon-circle" style="background:#fdeee2;color:#ea580c">&#8987;</span><div class="stat-label">Remaining</div><div class="stat-value" style="color:#ea580c">${remaining}</div></td>
    <td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#128081;</span><div class="stat-label">Current plan</div><div class="stat-value" style="color:#5b21d6;font-size:18px">Free Trial</div></td>
  </tr></table></div>
  <div class="notice">
    <div style="font-size:26px;color:#5b21d6">&#9888;&#65039;</div>
    <div><b>The first ${remediatedNow} pages are already remediated.</b>
    <p>The remaining ${remaining} pages require a paid plan to complete remediation and ensure full accessibility compliance.</p></div>
  </div>
  <div class="btns">
    <a class="btn btn-primary" href="${FRONTEND_URL}/onboarding/plan">&#8679; Upgrade Plan</a>
    <a class="btn btn-outline" href="${FRONTEND_URL}/onboarding/plan">View Plans &#8594;</a>
    <div style="margin-top:12px"><a class="btn" style="color:#5b21d6;padding:4px" href="${FRONTEND_URL}/dashboard">Log in to Dashboard &#8250;</a></div>
  </div>`);
}

export function renderCompletionEmail(user: User, docs: PdfDocument[]): string {
  const totalPages = docs.reduce((s, d) => s + (d.remediatedPages ?? d.pages), 0);
  const rows = docs
    .map(
      (d) => `<tr>
      <td>&#128196; ${d.remediatedName ?? d.name}</td>
      <td>${d.remediatedPages ?? d.pages}</td>
      <td><span class="chip">&#10003; Completed</span></td></tr>`
    )
    .join('');
  return shell(`
  <div class="hero">
    <div class="pdficon"><span>PDF</span></div>
    <h1>Your remediated PDFs are ready</h1>
    <p class="sub">Your recent accessibility remediation jobs are complete.<br>
    You can download the files or manage them from your dashboard.</p>
  </div>
  <div class="stats"><table><tr>
    <td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#128196;</span><div class="stat-label">Total files ready</div><div class="stat-value" style="color:#5b21d6">${docs.length}</div></td>
    <td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#128209;</span><div class="stat-label">Total pages</div><div class="stat-value" style="color:#5b21d6">${totalPages}</div></td>
    <td><span class="icon-circle" style="background:#e5f7ec;color:#15803d">&#10003;</span><div class="stat-label">Status</div><div class="stat-value" style="color:#15803d;font-size:20px">Completed</div></td>
  </tr></table></div>
  <div class="files"><table>
    <tr><th>FILE NAME</th><th>PAGES</th><th>STATUS</th></tr>
    ${rows}
  </table></div>
  <div class="notice">
    <div style="font-size:26px;color:#5b21d6">&#128229;</div>
    <div><p>You'll find your remediated PDFs attached to this email.<br>
    Or log in to your <a href="${FRONTEND_URL}/dashboard" style="color:#5b21d6;font-weight:700;text-decoration:none">dashboard</a> anytime to view and manage all your files.</p></div>
  </div>
  <div class="btns">
    <a class="btn btn-primary" href="${FRONTEND_URL}/dashboard">&#8594; Log in to Dashboard</a>
    <a class="btn btn-outline" href="${FRONTEND_URL}/dashboard/remediated">&#8681; Download Files</a>
  </div>`);
}

/** Welcome email sent right after registration (same shell as designs 14/15). */
export function renderWelcomeEmail(user: User): string {
  return shell(`
  <div class="hero">
    <div class="pdficon"><span>PDF</span></div>
    <h1>Welcome, <span class="accent">${user.firstName}</span>!</h1>
    <p class="sub">Your <span class="link">AI PDF Remediation</span> account is ready.<br>
    Your free trial lets you scan &amp; remediate up to <b>5 PDF pages</b> — no payment needed.</p>
  </div>
  <div class="stats"><table><tr>
    <td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#128228;</span><div class="stat-label">Step 1</div><div class="stat-value" style="font-size:15px">Upload or scan a PDF</div></td>
    <td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#10024;</span><div class="stat-label">Step 2</div><div class="stat-value" style="font-size:15px">Run AI Remediation</div></td>
    <td><span class="icon-circle" style="background:#e5f7ec;color:#15803d">&#11015;</span><div class="stat-label">Step 3</div><div class="stat-value" style="font-size:15px">Download PDF/UA file</div></td>
  </tr></table></div>
  <div class="notice">
    <div style="font-size:26px;color:#5b21d6">&#127873;</div>
    <div><b>Free trial included — ${user.pagesRemaining} pages</b>
    <p>Tag structure &amp; reading order, image alternate text, document title &amp; language, and table headers are fixed automatically, targeting the PDF/UA standard. Plan pages are only deducted as PDFs are remediated.</p></div>
  </div>
  <div class="btns">
    <a class="btn btn-primary" href="${FRONTEND_URL}/dashboard">&#8594; Go to Dashboard</a>
    <a class="btn btn-outline" href="${FRONTEND_URL}/onboarding/plan">View Plans</a>
  </div>`);
}

/** Invoice email for one order (same shell as designs 14/15). */
export function renderInvoiceEmail(
  user: User,
  order: { orderNo: number; type: string; name: string; domain: string; date: string; amount: number; status: string }
): string {
  const dateText = new Date(order.date).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
  return shell(`
  <div class="hero">
    <div class="pdficon"><span>PDF</span></div>
    <h1>Invoice <span class="accent">#${order.orderNo}</span></h1>
    <p class="sub">Hi ${user.firstName}, here is your invoice for <span class="link">${order.name}</span>.</p>
  </div>
  <div class="stats"><table><tr>
    <td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#128179;</span><div class="stat-label">${order.type}</div><div class="stat-value" style="font-size:15px">${order.name}</div></td>
    ${order.domain ? `<td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#127760;</span><div class="stat-label">Domain</div><div class="stat-value" style="font-size:14px">${order.domain}</div></td>` : ''}
    <td><span class="icon-circle" style="background:#ece6fb;color:#5b21d6">&#128197;</span><div class="stat-label">Order date</div><div class="stat-value" style="font-size:15px">${dateText}</div></td>
    <td><span class="icon-circle" style="background:#e5f7ec;color:#15803d">&#36;</span><div class="stat-label">Amount (USD)</div><div class="stat-value" style="color:#15803d">$${order.amount.toFixed(2)}</div></td>
  </tr></table></div>
  <div class="notice">
    <div style="font-size:26px;color:#5b21d6">&#9989;</div>
    <div><b>Status: ${order.status}</b>
    <p>This is a copy of your order record. You can download the PDF invoice anytime from the Orders section of your dashboard.</p></div>
  </div>
  <div class="btns">
    <a class="btn btn-primary" href="${FRONTEND_URL}/dashboard/orders">&#8594; View Orders</a>
  </div>`);
}

/** Password reset email (same shell as designs 14/15). Link expires in 60 minutes. */
export function renderPasswordResetEmail(user: User, resetUrl: string): string {
  return shell(`
  <div class="hero">
    <div class="pdficon"><span>PDF</span></div>
    <h1>Reset your <span class="accent">password</span></h1>
    <p class="sub">Hi ${user.firstName}, we received a request to reset the password for your
    AI PDF Remediation account (<span class="link">${user.email}</span>).</p>
  </div>
  <div class="notice">
    <div style="font-size:26px;color:#5b21d6">&#128274;</div>
    <div><b>This link expires in 60 minutes</b>
    <p>If you didn't request a password reset, you can safely ignore this email — your password will not be changed.</p></div>
  </div>
  <div class="btns">
    <a class="btn btn-primary" href="${resetUrl}">&#8594; Reset Password</a>
  </div>`);
}

export function sendEmail(
  user: User,
  template: 'trial-result' | 'remediation-complete' | 'welcome' | 'invoice' | 'password-reset',
  subject: string,
  html: string
): void {
  const id = uid();
  const file = `${new Date().toISOString().replace(/[:.]/g, '-')}-${template}-${id}.html`;
  fs.writeFileSync(path.join(OUTBOX_DIR, file), html, 'utf-8');
  db.emails.push({
    id,
    userId: user.id,
    to: user.email,
    subject,
    template,
    file,
    createdAt: new Date().toISOString(),
  });
  save();
  console.log(`[email] "${subject}" -> ${user.email} (saved to outbox/${file})`);
}

