/**
 * ReEngagement.tsx — win-back email for inactive buyers.
 */

import {
  Html,
  Head,
  Body,
  Container,
  Section,
  Text,
  Link,
  Hr,
  Preview,
} from '@/server/email/primitives.js';
import { dirForLocale, type Locale } from '@/lib/i18n/index.js';
import { fonts, spacing, tokens } from '@/server/email/tokens/index.js';
import { formatAgorotWhole } from '@/lib/money';

export type ReEngagementTone = '30d' | '60d' | '90d';

export interface ReEngagementDeal {
  title: string;
  slug: string;
  priceAgorot: number;
  originalPriceAgorot: number;
}

export interface ReEngagementProps {
  buyerName?: string;
  deals: ReEngagementDeal[];
  tone: ReEngagementTone;
  siteUrl: string;
  unsubscribeUrl: string;
  locale?: Locale;
}

const tones = {
  he: {
    '30d': {
      preview: 'התגעגענו — יש דילים חדשים',
      heading: 'התגעגענו אליך',
      body: 'כמה זמן לא ראינו אותך. ראה מה חדש:',
    },
    '60d': {
      preview: 'דילים בלעדיים רק בשבילך',
      heading: 'דילים שנבחרו בשבילך',
      body: 'שמנו עינינו על כמה דילים שיכולים לעניין אותך:',
    },
    '90d': {
      preview: 'ההצעה האחרונה שלנו',
      heading: 'רגע לפני שנלך...',
      body: 'לפני שנסגור את הדיל — הנה 3 דילים שלא כדאי לפספס:',
    },
  },
  en: {
    '30d': {
      preview: 'We miss you — there are new deals',
      heading: 'We missed you',
      body: "It's been a while. See what's new:",
    },
    '60d': {
      preview: 'Exclusive deals just for you',
      heading: 'Deals picked for you',
      body: "We've been keeping an eye on some deals you might like:",
    },
    '90d': {
      preview: 'Our last offer to you',
      heading: 'Before we say goodbye...',
      body: "Before we close the deal — here are 3 deals you shouldn't miss:",
    },
  },
} as const;

const copy = {
  he: {
    dealLink: 'לצפייה',
    cta: 'לכל הדילים',
    unsub: 'הסרה מרשימת התפוצה',
    greeting: (name: string) => `היי ${name},`,
  },
  en: {
    dealLink: 'View',
    cta: 'Browse all deals',
    unsub: 'Unsubscribe',
    greeting: (name: string) => `Hi ${name},`,
  },
} as const;

export function ReEngagement({
  buyerName,
  deals,
  tone,
  siteUrl,
  unsubscribeUrl,
  locale = 'he',
}: ReEngagementProps) {
  const t = tones[locale]?.[tone] ?? tones.he[tone];
  const c = copy[locale] ?? copy.he;
  const dir = dirForLocale(locale);
  const fontFamily = locale === 'he' ? fonts.he : fonts.en;
  const topDeals = deals.slice(0, 3);

  return (
    <Html lang={locale} dir={dir}>
      <Head />
      <Preview>{t.preview}</Preview>
      <Body
        style={{
          backgroundColor: tokens.neutral50,
          fontFamily: fontFamily,
          margin: 0,
          padding: spacing.marginBlock32,
        }}
      >
        <Container
          style={{
            maxWidth: spacing.cardMaxWide,
            backgroundColor: tokens.neutral0,
            borderRadius: '8px',
            padding: '0',
            overflow: 'hidden',
          }}
        >
          {/* Header */}
          <Section
            style={{
              backgroundColor: tokens.brandPrimary700,
              padding: spacing.padHeaderWide,
              textAlign: locale === 'he' ? 'right' : 'left',
            }}
          >
            <Text
              style={{
                fontSize: spacing.px22,
                fontWeight: 700,
                color: tokens.brandOnPrimary,
                margin: 0,
                fontFamily,
              }}
            >
              {t.heading}
            </Text>
          </Section>

          {/* Body */}
          <Section
            style={{
              padding: spacing.padHeaderLg,
              direction: dir,
              textAlign: locale === 'he' ? 'right' : 'left',
            }}
          >
            {buyerName && (
              <Text
                style={{
                  fontSize: spacing.px16,
                  color: tokens.textSecondary,
                  margin: '0 0 8px',
                  fontFamily,
                }}
              >
                {c.greeting(buyerName)}
              </Text>
            )}
            <Text
              style={{
                fontSize: spacing.px16,
                color: tokens.textSecondary,
                lineHeight: '1.6',
                margin: spacing.marginBottom20,
                fontFamily,
              }}
            >
              {t.body}
            </Text>

            {topDeals.map((deal) => (
              <div
                key={deal.slug}
                style={{
                  padding: spacing.padCompact,
                  marginBottom: spacing.px12,
                  backgroundColor: tokens.surfaceRaised,
                  borderRadius: '6px',
                  border: `1px solid ${tokens.borderDefault}`,
                }}
              >
                <Text
                  style={{
                    fontSize: spacing.px15,
                    fontWeight: 600,
                    color: tokens.textPrimary,
                    margin: '0 0 4px',
                    fontFamily,
                  }}
                >
                  {deal.title}
                </Text>
                <Text
                  style={{
                    fontSize: spacing.px13,
                    color: tokens.textSecondary,
                    margin: '0 0 6px',
                    fontFamily,
                  }}
                >
                  {formatAgorotWhole(deal.priceAgorot)}{' '}
                  <span style={{ textDecoration: 'line-through', color: tokens.textMuted }}>
                    {formatAgorotWhole(deal.originalPriceAgorot)}
                  </span>
                </Text>
                <Link
                  href={`${siteUrl}/deals/${deal.slug}`}
                  style={{
                    color: tokens.textLink,
                    fontSize: spacing.px13,
                    fontWeight: 600,
                    textDecoration: 'none',
                    fontFamily,
                  }}
                >
                  {c.dealLink}
                </Link>
              </div>
            ))}

            <div style={{ textAlign: 'center', marginTop: spacing.px20 }}>
              <Link
                href={siteUrl}
                style={{
                  display: 'inline-block',
                  backgroundColor: tokens.brandPrimary600,
                  color: tokens.brandOnPrimary,
                  padding: spacing.padTagMd,
                  borderRadius: '6px',
                  textDecoration: 'none',
                  fontWeight: 600,
                  fontFamily,
                  fontSize: spacing.px14,
                }}
              >
                {c.cta}
              </Link>
            </div>
          </Section>

          {/* Footer */}
          <Section
            style={{
              padding: spacing.padBodyWide,
              backgroundColor: tokens.surfaceRaised,
              borderTop: `1px solid ${tokens.borderDefault}`,
            }}
          >
            <Hr style={{ borderColor: tokens.borderDefault, margin: spacing.marginBottom12 }} />
            <Text
              style={{
                fontSize: spacing.px12,
                color: tokens.textMuted,
                textAlign: 'center',
                fontFamily,
              }}
            >
              <Link href={unsubscribeUrl} style={{ color: tokens.textMuted }}>
                {c.unsub}
              </Link>
            </Text>
          </Section>
        </Container>
      </Body>
    </Html>
  );
}

export default ReEngagement;
