import emailjs from "@emailjs/browser";

// ── EmailJS Configuration ──────────────────────────────────────────
const SERVICE_ID = process.env.NEXT_PUBLIC_EMAILJS_SERVICE_ID ?? "";
const CONTACT_TEMPLATE_ID =
    process.env.NEXT_PUBLIC_EMAILJS_CONTACT_TEMPLATE_ID ?? "";
const NEWSLETTER_TEMPLATE_ID =
    process.env.NEXT_PUBLIC_EMAILJS_NEWSLETTER_TEMPLATE_ID ?? "";
const PUBLIC_KEY = process.env.NEXT_PUBLIC_EMAILJS_PUBLIC_KEY ?? "";

// ── Types ──────────────────────────────────────────────────────────
export interface ContactFormData {
    firstName: string;
    lastName: string;
    email: string;
    subject: string;
    message: string;
}

export interface NewsletterFormData {
    name?: string;
    email: string;
}

// ── Contact Email ──────────────────────────────────────────────────
export async function sendContactEmail(data: ContactFormData) {
    const templateParams = {
        firstName: data.firstName,  // Updated: first_name se firstName kar diya
        lastName: data.lastName,    // Updated: last_name se lastName kar diya
        email: data.email,          // Updated: from_email se email kar diya
        subject: data.subject,
        message: data.message,
    };

    return emailjs.send(SERVICE_ID, CONTACT_TEMPLATE_ID, templateParams, {
        publicKey: PUBLIC_KEY,
    });
}

// ── Newsletter Subscription ────────────────────────────────────────
export async function sendNewsletterSubscription(data: NewsletterFormData) {
    const templateParams = {
        name: data.name ?? "",   // Updated: subscriber_name ko name kar diya
        email: data.email,       // Updated: subscriber_email ko email kar diya
    };

    return emailjs.send(SERVICE_ID, NEWSLETTER_TEMPLATE_ID, templateParams, {
        publicKey: PUBLIC_KEY,
    });
}

// ── Validation Helpers ─────────────────────────────────────────────
export function isValidEmail(email: string): boolean {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
