import { analytics } from './analytics';
import { sendContactEmail, type ContactEmailData } from '../api/emailClient';

interface EmailData {
  name: string;
  email: string;
  phone?: string;
  company?: string;
  message: string;
}

export function validateEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

export function formatEmailContent(data: EmailData, type: 'contact' | 'offset'): { subject: string, body: string } {
  const subject = type === 'contact'
    ? `Contact from ${data.name} - Puffin Offset`
    : `Offset Request - ${data.name}`;

  const body = `
Name: ${data.name}
Email: ${data.email}
Phone: ${data.phone || 'Not provided'}
Company: ${data.company || 'Not provided'}

Message:
${data.message}
  `.trim();

  return { subject, body };
}

export function sendEmail(to: string, subject: string, body: string): void {
  const mailtoUrl = `mailto:${to}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  window.location.href = mailtoUrl;
}

/**
 * Send contact form email via SMTP backend
 * @param data Contact form data
 * @param type Email type (contact or offset) - currently only 'contact' is supported
 */
export async function sendContactFormEmail(data: EmailData, type: 'contact' | 'offset' = 'contact'): Promise<void> {
  try {
    const contactData: ContactEmailData = {
      name: data.name,
      email: data.email,
      phone: data.phone,
      company: data.company,
      message: data.message,
    };

    await sendContactEmail(contactData);
    analytics.event('email', 'sent', type);
  } catch (error) {
    analytics.error(error as Error, 'Email sending failed');
    throw error;
  }
}