export default async function handler(req, res) {
  // Set CORS headers for local development if needed
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  if (req.method === 'OPTIONS') {
    return res.status(200).end();
  }

  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method Not Allowed' });
  }

  const { type, name, email, phone, mobile, designation, dateTime, interests, resumeName } = req.body;

  const serviceId = process.env.EMAILJS_SERVICE_ID || 'vishva_cavintest';
  const publicKey = process.env.EMAILJS_PUBLIC_KEY || 'YOUR_EMAILJS_PUBLIC_KEY';
  
  let templateId = '';
  if (type === 'careers') {
    templateId = process.env.EMAILJS_TEMPLATE_ID_CAREERS || 'YOUR_EMAILJS_TEMPLATE_ID_CAREERS';
  } else {
    templateId = process.env.EMAILJS_TEMPLATE_ID_STRATEGY || 'YOUR_EMAILJS_TEMPLATE_ID_STRATEGY';
  }

  const templateParams = {
    type: type,
    name: name,
    email: email,
    phone: phone || mobile || '',
    mobile: mobile || phone || '',
    designation: designation || 'N/A',
    dateTime: dateTime || 'N/A',
    interests: interests || 'N/A',
    resumeName: resumeName || 'None'
  };

  try {
    const response = await fetch('https://api.emailjs.com/api/v1.0/email/send', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        service_id: serviceId,
        template_id: templateId,
        user_id: publicKey,
        template_params: templateParams
      }),
    });

    const data = await response.text();
    if (!response.ok) {
      return res.status(response.status).json({ error: data });
    }
    return res.status(200).json({ success: true, message: data });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
}
