/**
 * Default email template catalog (Task #204).
 * Each template defines a subject + body fragment. The body is wrapped in
 * a shared branded layout at render time. Templates use {{var}} interpolation
 * via simple regex (no logic). Admin overrides in `email_templates` are
 * layered on top of these defaults.
 */

export interface TemplateDefault {
  key: string;
  subject: string;
  /** Body HTML (wrapped in branded layout). May reference {{vars}}. */
  body: string;
  /** When true, header uses restaurant brand; otherwise platform brand. */
  audience: 'customer' | 'restaurant' | 'platform';
  /** Suggested vars for the admin editor preview. */
  sampleVars?: Record<string, string>;
}

const baseBlock = (title: string, intro: string, body = '', cta = '') => `
<h1 style="margin:0 0 12px 0;font-size:22px;font-weight:700;color:#111827;letter-spacing:-0.3px;">${title}</h1>
<p style="margin:0 0 16px 0;font-size:15px;line-height:1.6;color:#374151;">${intro}</p>
${body}
${cta}
`;

export const DEFAULT_TEMPLATES: TemplateDefault[] = [
  {
    key: 'signup_otp',
    audience: 'platform',
    subject: 'Your {{appName}} verification code',
    body: baseBlock(
      'Verify your email',
      `Hi {{name}}, use the code below to finish creating your {{appName}} account. This code expires in 10 minutes.`,
      `<div style="margin:18px 0;padding:18px;background:#f9fafb;border:1px solid #e5e7eb;border-radius:12px;text-align:center;">
        <div style="font-size:32px;font-weight:700;letter-spacing:8px;color:#111827;font-family:'SF Mono',Menlo,Consolas,monospace;">{{code}}</div>
      </div>
      <p style="margin:0;font-size:13px;color:#6b7280;">If you did not request this, you can safely ignore this email.</p>`,
    ),
    sampleVars: { name: 'Alex', code: '482913', appName: 'RestroAgent' },
  },
  {
    key: 'password_reset',
    audience: 'platform',
    subject: 'Reset your {{appName}} password',
    body: baseBlock(
      'Reset your password',
      `Hi {{name}}, click the button below to set a new password for your {{appName}} account. This link expires in 1 hour.`,
      `<div style="margin:18px 0;text-align:center;"><a href="{{resetLink}}" style="display:inline-block;padding:12px 24px;background:#111827;color:#fff;text-decoration:none;border-radius:10px;font-weight:600;font-size:14px;">Reset password</a></div>
       <p style="margin:0;font-size:13px;color:#6b7280;word-break:break-all;">Or open this URL: {{resetLink}}</p>`,
    ),
    sampleVars: { name: 'Alex', resetLink: 'https://example.com/reset?token=abc', appName: 'RestroAgent' },
  },
  {
    key: 'welcome',
    audience: 'platform',
    subject: 'Welcome to {{appName}}, {{name}}!',
    body: baseBlock(
      `Welcome to {{appName}}!`,
      `Hi {{name}}, your account is ready. You can sign in any time and start configuring your AI agents, menu, and bookings.`,
      `<div style="margin:18px 0;text-align:center;"><a href="{{appUrl}}" style="display:inline-block;padding:12px 24px;background:#111827;color:#fff;text-decoration:none;border-radius:10px;font-weight:600;font-size:14px;">Go to dashboard</a></div>`,
    ),
  },
  {
    key: 'order_new_customer',
    audience: 'customer',
    subject: 'Order confirmed at {{restaurantName}} — {{orderRef}}',
    body: baseBlock(
      `Thanks for your order!`,
      `Hi {{customerName}}, we've received your order at {{restaurantName}}.`,
      `<div style="margin:14px 0;padding:14px;background:#f9fafb;border-radius:10px;">
        <div style="font-size:13px;color:#6b7280;">Order reference</div>
        <div style="font-size:18px;font-weight:700;color:#111827;">{{orderRef}}</div>
      </div>
      {{itemsHtml}}
      <table cellpadding="0" cellspacing="0" style="width:100%;margin-top:14px;font-size:14px;border-top:1px solid #e5e7eb;">
        {{subtotalRowHtml}}
        {{couponRowHtml}}
        {{loyaltyRowHtml}}
        {{giftCardRowHtml}}
        {{taxRowHtml}}
        <tr><td style="padding:10px 0 4px 0;border-top:1px solid #e5e7eb;color:#111827;font-weight:700;">Total</td><td style="padding:10px 0 4px 0;border-top:1px solid #e5e7eb;color:#111827;font-weight:700;text-align:right;">{{total}}</td></tr>
      </table>
      {{couponHtml}}
      {{giftCardHtml}}
      <p style="margin:14px 0 0 0;font-size:13px;color:#6b7280;">Delivery type: {{deliveryType}}</p>`,
    ),
  },
  {
    key: 'order_new_restaurant',
    audience: 'restaurant',
    subject: '{{count}} new order(s) at {{restaurantName}}',
    body: baseBlock(
      `New orders received`,
      `You have {{count}} new order(s) waiting in the kitchen queue.`,
      `{{ordersHtml}}<div style="margin-top:14px;text-align:center;"><a href="{{appUrl}}/order-management" style="display:inline-block;padding:10px 20px;background:#111827;color:#fff;text-decoration:none;border-radius:8px;font-weight:600;font-size:13px;">View orders</a></div>`,
    ),
  },
  {
    key: 'booking_confirmation_customer',
    audience: 'customer',
    subject: 'Booking confirmed at {{restaurantName}} — {{bookingRef}}',
    body: baseBlock(
      `Your table is booked!`,
      `Hi {{guestName}}, your reservation at {{restaurantName}} is confirmed.`,
      `<table cellpadding="0" cellspacing="0" style="width:100%;margin:14px 0;font-size:14px;">
        <tr><td style="padding:8px 0;color:#6b7280;">Reference</td><td style="padding:8px 0;color:#111827;font-weight:600;">{{bookingRef}}</td></tr>
        <tr><td style="padding:8px 0;color:#6b7280;">Date</td><td style="padding:8px 0;color:#111827;font-weight:600;">{{date}}</td></tr>
        <tr><td style="padding:8px 0;color:#6b7280;">Time</td><td style="padding:8px 0;color:#111827;font-weight:600;">{{time}}</td></tr>
        <tr><td style="padding:8px 0;color:#6b7280;">Guests</td><td style="padding:8px 0;color:#111827;font-weight:600;">{{partySize}}</td></tr>
      </table>
      <p style="margin:0;font-size:13px;color:#6b7280;">If you need to make changes, please contact us directly.</p>`,
    ),
  },
  {
    key: 'booking_new_restaurant',
    audience: 'restaurant',
    subject: '{{count}} new booking(s) at {{restaurantName}}',
    body: baseBlock(
      `New bookings received`,
      `You have {{count}} new reservation(s).`,
      `{{bookingsHtml}}<div style="margin-top:14px;text-align:center;"><a href="{{appUrl}}/table-booking-management" style="display:inline-block;padding:10px 20px;background:#111827;color:#fff;text-decoration:none;border-radius:8px;font-weight:600;font-size:13px;">View bookings</a></div>`,
    ),
  },
  {
    key: 'booking_reminder_customer',
    audience: 'customer',
    subject: 'Reminder: your booking at {{restaurantName}} is in 2 hours',
    body: baseBlock(
      `See you soon!`,
      `Hi {{guestName}}, this is a friendly reminder of your reservation at {{restaurantName}} today at {{time}} for {{partySize}} guests. Reference: {{bookingRef}}.`,
    ),
  },
  {
    key: 'plan_purchased',
    audience: 'restaurant',
    subject: 'Subscription confirmed — {{planName}}',
    body: baseBlock(
      `You're on the {{planName}} plan`,
      `Hi {{name}}, your subscription is active. Thanks for choosing us!`,
    ),
  },
  {
    key: 'plan_trial_ending',
    audience: 'restaurant',
    subject: 'Your {{appName}} trial ends in {{daysLeft}} days',
    body: baseBlock(
      `Your trial is ending soon`,
      `Hi {{name}}, your free trial ends on {{trialEnd}}. Upgrade now to keep your AI agents running without interruption.`,
      `<div style="margin:18px 0;text-align:center;"><a href="{{appUrl}}/billing" style="display:inline-block;padding:12px 24px;background:#111827;color:#fff;text-decoration:none;border-radius:10px;font-weight:600;font-size:14px;">Upgrade plan</a></div>`,
    ),
  },
  {
    key: 'plan_expired',
    audience: 'restaurant',
    subject: 'Your {{appName}} plan has expired',
    body: baseBlock(
      `Your subscription has expired`,
      `Hi {{name}}, AI features have been paused. Reactivate any time to resume service.`,
    ),
  },
  {
    key: 'low_credit_warning',
    audience: 'restaurant',
    subject: 'Low usage credits at {{restaurantName}}',
    body: baseBlock(
      `Heads up — credits running low`,
      `You have {{remaining}} credits left this period. Top up to avoid interruption.`,
    ),
  },
  {
    key: 'weekly_summary',
    audience: 'restaurant',
    subject: 'Your {{restaurantName}} weekly summary',
    body: baseBlock(
      `Last week at {{restaurantName}}`,
      `Here's a quick summary of activity:`,
      `<table cellpadding="0" cellspacing="0" style="width:100%;margin:14px 0;font-size:14px;">
        <tr><td style="padding:8px 0;color:#6b7280;">Orders</td><td style="padding:8px 0;color:#111827;font-weight:600;text-align:right;">{{ordersCount}}</td></tr>
        <tr><td style="padding:8px 0;color:#6b7280;">Bookings</td><td style="padding:8px 0;color:#111827;font-weight:600;text-align:right;">{{bookingsCount}}</td></tr>
        <tr><td style="padding:8px 0;color:#6b7280;">Revenue</td><td style="padding:8px 0;color:#111827;font-weight:600;text-align:right;">{{revenue}}</td></tr>
      </table>`,
    ),
  },
  {
    key: 'gift_card_issued',
    audience: 'customer',
    subject: 'You have a gift card from {{restaurantName}}',
    body: baseBlock(
      `A gift just for you`,
      `Hi {{recipientName}}, {{senderLine}} sent you a gift card for {{restaurantName}}.`,
      `<div style="margin:18px 0;padding:22px;background:linear-gradient(135deg,{{brandColor}}11,{{brandColor}}33);border:1px solid {{brandColor}}55;border-radius:14px;text-align:center;">
        <div style="font-size:13px;color:#6b7280;text-transform:uppercase;letter-spacing:1.5px;font-weight:600;">Gift card</div>
        <div style="font-size:34px;font-weight:800;color:#111827;margin:6px 0 14px 0;letter-spacing:-0.5px;">{{amount}}</div>
        <div style="font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:1.5px;font-weight:600;">Code</div>
        <div style="margin:8px auto 0 auto;padding:12px 18px;background:#fff;border:1px dashed {{brandColor}}88;border-radius:10px;display:inline-block;font-family:'SF Mono',Menlo,Consolas,monospace;font-size:22px;font-weight:700;letter-spacing:4px;color:#111827;">{{code}}</div>
        <div style="margin-top:14px;font-size:13px;color:#6b7280;">{{expiryLine}}</div>
      </div>
      {{messageBlockHtml}}
      <p style="margin:14px 0 0 0;font-size:13px;color:#6b7280;">Use this code at checkout — online or in person — at {{restaurantName}}. The PDF voucher is attached.</p>`,
    ),
    sampleVars: {
      restaurantName: 'Acme Bistro',
      recipientName: 'Alex',
      senderLine: 'Sam',
      amount: '$50.00',
      code: 'GC-ABCD-EFGH',
      brandColor: '#f97316',
      expiryLine: 'Valid until Dec 31, 2026',
      messageBlockHtml: '',
    },
  },
  {
    key: 'loyalty_points_earned',
    audience: 'customer',
    subject: 'You earned {{pointsEarned}} points at {{restaurantName}}',
    body: baseBlock(
      `Thanks for your order!`,
      `Hi {{customerName}}, you've just earned points on order {{orderRef}}.`,
      `<div style="margin:18px 0;padding:22px;background:#fff7ed;border:1px solid #fed7aa;border-radius:14px;text-align:center;">
        <div style="font-size:13px;color:#9a3412;text-transform:uppercase;letter-spacing:1.5px;font-weight:600;">Points earned</div>
        <div style="font-size:38px;font-weight:800;color:#9a3412;margin:6px 0 4px 0;letter-spacing:-0.5px;">+{{pointsEarned}}</div>
        <div style="font-size:13px;color:#6b7280;">New balance: <strong style="color:#111827;">{{newBalance}} points</strong></div>
      </div>
      <p style="margin:14px 0 0 0;font-size:13px;color:#6b7280;">Keep earning to unlock the next tier and reward yourself with discounts on future orders.</p>`,
    ),
    sampleVars: { customerName: 'Alex', pointsEarned: '125', newBalance: '640', orderRef: 'A1B2C3D4' },
  },
  {
    key: 'loyalty_tier_upgraded',
    audience: 'customer',
    subject: "You've reached {{tierName}} at {{restaurantName}}!",
    body: baseBlock(
      `Welcome to {{tierName}}!`,
      `Hi {{customerName}}, congratulations — your loyalty has unlocked a new tier at {{restaurantName}}.`,
      `<div style="margin:18px 0;padding:22px;background:linear-gradient(135deg,#fef3c7,#fde68a);border:1px solid #fcd34d;border-radius:14px;text-align:center;">
        <div style="font-size:13px;color:#92400e;text-transform:uppercase;letter-spacing:1.5px;font-weight:600;">New tier</div>
        <div style="font-size:32px;font-weight:800;color:#78350f;margin:6px 0 4px 0;letter-spacing:-0.5px;">{{tierName}}</div>
      </div>
      {{perksHtml}}
      <p style="margin:14px 0 0 0;font-size:13px;color:#6b7280;">Your new perks apply automatically on your next order.</p>`,
    ),
    sampleVars: { customerName: 'Alex', tierName: 'Gold', perksHtml: '' },
  },
  {
    // Task #295: low-stock owner alert. Fired by the order-decrement path
    // when stock_count crosses low_stock_threshold (rate-limited to once
    // per 24h per item).
    key: 'low_stock_alert',
    audience: 'restaurant',
    subject: 'Low stock at {{restaurantName}} — {{itemName}}',
    body: baseBlock(
      `Inventory running low`,
      `Heads up — <strong>{{itemName}}</strong> is running low at {{restaurantName}}.`,
      `<table cellpadding="0" cellspacing="0" style="width:100%;margin:14px 0;font-size:14px;">
        <tr><td style="padding:8px 0;color:#6b7280;">Stock remaining</td><td style="padding:8px 0;color:#b91c1c;font-weight:700;text-align:right;">{{stockRemaining}}</td></tr>
        <tr><td style="padding:8px 0;color:#6b7280;">Alert threshold</td><td style="padding:8px 0;color:#111827;font-weight:600;text-align:right;">{{threshold}}</td></tr>
      </table>
      <div style="margin-top:14px;text-align:center;"><a href="{{appUrl}}/menu-management" style="display:inline-block;padding:10px 20px;background:#111827;color:#fff;text-decoration:none;border-radius:8px;font-weight:600;font-size:13px;">Manage inventory</a></div>`,
    ),
    sampleVars: { itemName: 'Butter Chicken', stockRemaining: '3', threshold: '5', restaurantName: 'Acme Bistro' },
  },
  {
    // Task #298: sold-out alert. Fired by the order-decrement path when
    // stock_count crosses 0. 24h cooldown per item.
    key: 'sold_out_alert',
    audience: 'restaurant',
    subject: 'Sold out at {{restaurantName}} — {{itemName}}',
    body: baseBlock(
      `Item just sold out`,
      `<strong>{{itemName}}</strong> is sold out at {{restaurantName}}. The item has been auto-disabled until you restock or reset it.`,
      `<table cellpadding="0" cellspacing="0" style="width:100%;margin:14px 0;font-size:14px;">
        <tr><td style="padding:8px 0;color:#6b7280;">Stock remaining</td><td style="padding:8px 0;color:#b91c1c;font-weight:700;text-align:right;">0</td></tr>
      </table>
      <div style="margin-top:14px;text-align:center;"><a href="{{appUrl}}/menu-management" style="display:inline-block;padding:10px 20px;background:#111827;color:#fff;text-decoration:none;border-radius:8px;font-weight:600;font-size:13px;">Manage inventory</a></div>`,
    ),
    sampleVars: { itemName: 'Butter Chicken', restaurantName: 'Acme Bistro' },
  },
  {
    // Task #505: webhook exhausted alert. Fired when all retry attempts for a
    // webhook delivery have been used up — operators need to know so they can
    // fix the integration before data loss accumulates.
    key: 'webhook_delivery_exhausted',
    audience: 'restaurant',
    subject: 'Webhook delivery failed — all retries exhausted at {{restaurantName}}',
    body: baseBlock(
      `Webhook delivery exhausted`,
      `All delivery attempts for a webhook endpoint at {{restaurantName}} have been exhausted. No further retries will be made automatically.`,
      `<table cellpadding="0" cellspacing="0" style="width:100%;margin:14px 0;font-size:14px;">
        <tr><td style="padding:8px 0;color:#6b7280;">Event</td><td style="padding:8px 0;color:#111827;font-weight:600;text-align:right;font-family:'SF Mono',Menlo,Consolas,monospace;">{{eventType}}</td></tr>
        <tr><td style="padding:8px 0;color:#6b7280;">Endpoint</td><td style="padding:8px 0;color:#b91c1c;font-weight:600;text-align:right;word-break:break-all;font-family:'SF Mono',Menlo,Consolas,monospace;">{{endpointUrl}}</td></tr>
      </table>
      <p style="margin:12px 0 0 0;font-size:13px;color:#6b7280;">You can inspect the delivery logs and manually resend from the Webhooks dashboard once the issue is resolved.</p>
      <div style="margin-top:16px;text-align:center;"><a href="{{appUrl}}/webhooks" style="display:inline-block;padding:10px 20px;background:#111827;color:#fff;text-decoration:none;border-radius:8px;font-weight:600;font-size:13px;">View Webhooks dashboard</a></div>`,
    ),
    sampleVars: { eventType: 'order.created', endpointUrl: 'https://example.com/hook', restaurantName: 'Acme Bistro' },
  },
  {
    key: 'gift_card_balance_after_redeem',
    audience: 'customer',
    subject: 'Gift card receipt — {{restaurantName}}',
    body: baseBlock(
      `Gift card applied`,
      `Hi {{recipientName}}, your gift card was used at {{restaurantName}}.`,
      `<table cellpadding="0" cellspacing="0" style="width:100%;margin:14px 0;font-size:14px;">
        <tr><td style="padding:8px 0;color:#6b7280;">Card</td><td style="padding:8px 0;color:#111827;font-weight:600;text-align:right;font-family:'SF Mono',Menlo,Consolas,monospace;">{{maskedCode}}</td></tr>
        <tr><td style="padding:8px 0;color:#6b7280;">Applied</td><td style="padding:8px 0;color:#111827;font-weight:600;text-align:right;">{{appliedAmount}}</td></tr>
        <tr><td style="padding:8px 0;color:#6b7280;">Order</td><td style="padding:8px 0;color:#111827;font-weight:600;text-align:right;">{{orderRef}}</td></tr>
        <tr><td style="padding:12px 0 8px 0;border-top:1px solid #e5e7eb;color:#111827;font-weight:600;">Remaining balance</td><td style="padding:12px 0 8px 0;border-top:1px solid #e5e7eb;color:#111827;font-weight:700;text-align:right;">{{remainingBalance}}</td></tr>
      </table>`,
    ),
  },
];

export function getDefaultTemplate(key: string): TemplateDefault | undefined {
  return DEFAULT_TEMPLATES.find(t => t.key === key);
}
