// email.jsx — Email sender via EmailJS

// Enviar email via EmailJS (Gmail relay)
const sendViaEmailJS = async ({ to, subject, html, pdfBase64 }) => {
  // Inicializar EmailJS si no está inicializado
  if (!window.emailjs) {
    throw new Error('EmailJS not loaded');
  }

  // Nota: necesitas configurar tu cuenta de EmailJS y obtener:
  // - Service ID (tu conexión de Gmail)
  // - Template ID
  // - Public Key
  
  emailjs.init("YOUR_PUBLIC_KEY"); // Reemplazar con tu public key de EmailJS
  
  const templateParams = {
    to_email: to,
    from_name: window.APP_CONFIG.COMPANY_NAME,
    subject: subject,
    message_html: html,
    // EmailJS no soporta attachments en el plan gratuito
    // El PDF debe enviarse como link o usar servicio pago
  };

  return emailjs.send(
    "YOUR_SERVICE_ID", // Gmail service
    "YOUR_TEMPLATE_ID", // Template que creaste
    templateParams
  );
};

// Fallback: usar mailto: link (abre cliente de email local)
const sendViaMailto = ({ to, subject, html }) => {
  const body = html.replace(/<[^>]*>/g, ''); // Strip HTML tags para texto plano
  const mailtoLink = `mailto:${to}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  window.location.href = mailtoLink;
};

// Wrapper principal — usa mailto como fallback simple
const sendEmail = async ({ to, subject, html, pdfBlob }) => {
  // Por ahora usamos mailto (abre Gmail/Outlook del usuario)
  // El PDF se descarga por separado y el usuario lo adjunta manualmente
  
  try {
    // Descargar PDF primero
    if (pdfBlob) {
      const url = URL.createObjectURL(pdfBlob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'invoice.pdf';
      a.click();
      URL.revokeObjectURL(url);
    }
    
    // Abrir email draft
    const body = `
${window.APP_CONFIG.COMPANY_NAME}

Please find attached the invoice for services rendered.

---

${html.replace(/<[^>]*>/g, '\n').replace(/\n\n+/g, '\n\n')}

---

${window.APP_CONFIG.COMPANY_EMAIL}
${window.APP_CONFIG.COMPANY_PHONE}
    `.trim();
    
    const mailtoLink = `mailto:${to}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    window.open(mailtoLink);
    
    return { success: true };
  } catch (error) {
    console.error('Email error:', error);
    throw error;
  }
};

// Template de email para invoice
const buildInvoiceEmail = ({ invoice, client, total, lang }) => {
  const t = makeT(lang);
  return `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; line-height: 1.6; color: #1f2937; margin: 0; padding: 0; }
  .container { max-width: 600px; margin: 0 auto; padding: 40px 20px; }
  .header { text-align: center; margin-bottom: 40px; }
  .header h1 { margin: 0; font-size: 28px; color: #0f172a; }
  .header p { margin: 8px 0 0; color: #64748b; font-size: 14px; }
  .card { background: #f8fafc; border-radius: 12px; padding: 24px; margin: 24px 0; }
  .amount { font-size: 36px; font-weight: 700; color: #0f172a; margin: 0; }
  .label { font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em; color: #64748b; margin-bottom: 4px; }
  .info { display: flex; justify-content: space-between; margin: 16px 0; }
  .info div { flex: 1; }
  .btn { display: inline-block; background: #2563eb; color: white; padding: 14px 32px; border-radius: 8px; text-decoration: none; font-weight: 600; margin: 20px 0; }
  .footer { text-align: center; color: #94a3b8; font-size: 12px; margin-top: 40px; border-top: 1px solid #e2e8f0; padding-top: 24px; }
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1>${window.APP_CONFIG.COMPANY_NAME}</h1>
    <p>${window.APP_CONFIG.COMPANY_TAGLINE}</p>
  </div>
  
  <p>${lang === 'es' ? 'Hola' : 'Hi'} ${client.contact || client.name},</p>
  
  <p>${lang === 'es' 
    ? `Adjunto encontrarás la factura <strong>${invoice.number}</strong> por los servicios prestados.`
    : `Please find attached invoice <strong>${invoice.number}</strong> for services rendered.`
  }</p>
  
  <div class="card">
    <div class="label">${t('total')}</div>
    <div class="amount">${fmtMoney(total)}</div>
    <div class="info">
      <div>
        <div class="label">${t('issued')}</div>
        <div style="font-weight: 500;">${invoice.issued}</div>
      </div>
      <div>
        <div class="label">${t('due')}</div>
        <div style="font-weight: 500; color: #dc2626;">${invoice.due}</div>
      </div>
    </div>
  </div>
  
  <p>${lang === 'es'
    ? 'Si tienes alguna pregunta sobre esta factura, no dudes en contactarnos.'
    : 'If you have any questions about this invoice, please don\'t hesitate to reach out.'
  }</p>
  
  <p>${lang === 'es' ? 'Gracias por tu confianza.' : 'Thank you for your business.'}</p>
  
  <p style="margin-top: 32px;">
    <strong>${window.APP_CONFIG.COMPANY_NAME}</strong><br>
    ${window.APP_CONFIG.COMPANY_EMAIL}<br>
    ${window.APP_CONFIG.COMPANY_PHONE}
  </p>
  
  <div class="footer">
    ${window.APP_CONFIG.COMPANY_ADDRESS}, ${window.APP_CONFIG.COMPANY_CITY}<br>
    ${window.APP_CONFIG.COMPANY_EIN}
  </div>
</div>
</body>
</html>
  `.trim();
};

Object.assign(window, { sendEmail, buildInvoiceEmail });
