
/**
 * Utility functions for building professional email templates.
 */

/**
 * Wraps HTML body content in a professional email template layout.
 * Supports both positional arguments and an options object for backwards compatibility.
 * 
 * @param {string|Object} bodyContentOrParams - The HTML body content OR an object containing parameters.
 * @param {string} [associationName] - The name of the association.
 * @param {string} [associationLogo] - The URL of the association's logo.
 * @param {string} [footerText] - Custom footer text.
 * @returns {string} The fully formatted HTML email string.
 */
export const wrapEmailContent = (bodyContentOrParams, associationName, associationLogo, footerText) => {
  let body = '';
  let name = 'Homeowner Association';
  let logo = '';
  let footer = '© 2026 Avria Community Management, LLC. All rights reserved. Powered by Avria Community Management';
  let title = 'Notification';

  if (typeof bodyContentOrParams === 'object' && bodyContentOrParams !== null) {
    // Handle object params used by EmailComposer and NotifyOwnersContext
    body = bodyContentOrParams.bodyHtml || bodyContentOrParams.bodyContent || '';
    name = bodyContentOrParams.clientInfo?.name || bodyContentOrParams.associationName || name;
    logo = bodyContentOrParams.clientInfo?.logo_url || bodyContentOrParams.clientInfo?.notice_logo || bodyContentOrParams.associationLogo || logo;
    footer = bodyContentOrParams.footerText || footer;
    title = bodyContentOrParams.title || title;
  } else {
    // Handle positional arguments as explicitly requested
    body = bodyContentOrParams || '';
    if (associationName) name = associationName;
    if (associationLogo) logo = associationLogo;
    if (footerText) footer = footerText;
  }

  if (!body) {
    console.warn("wrapEmailContent: Missing body content parameter.");
  }

  // Fallback logo if none is provided
  const safeLogo = logo || 'https://horizons-cdn.hostinger.com/126c5dbc-827f-4c3e-9c76-35f3b3c26024/overlayacmfull-Qhx65.png';

  return `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>${title}</title>
      <style>
        body { 
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 
          background-color: #f1f3f7; 
          margin: 0; 
          padding: 0; 
          -webkit-font-smoothing: antialiased;
        }
        .wrapper { 
          width: 100%; 
          table-layout: fixed; 
          background-color: #f1f3f7; 
          padding: 40px 0; 
        }
        .container { 
          max-width: 600px; 
          margin: 0 auto; 
          background-color: #ffffff; 
          border-radius: 8px; 
          overflow: hidden; 
          box-shadow: 0 4px 15px rgba(0,0,0,0.05); 
        }
        .header { 
          background-color: #2C3E50; 
          padding: 35px 20px; 
          text-align: center; 
        }
        .header img { 
          max-height: 65px; 
          margin-bottom: 16px; 
          display: inline-block; 
        }
        .header h1 { 
          margin: 0; 
          font-size: 24px; 
          font-weight: 600; 
          color: #ffffff; 
          letter-spacing: 0.5px; 
        }
        .body { 
          padding: 40px 35px; 
          color: #334155; 
          line-height: 1.6; 
          font-size: 16px; 
          background-color: #ffffff; 
        }
        .body h1, .body h2, .body h3 { 
          color: #1e293b; 
          margin-top: 0; 
          margin-bottom: 16px;
        }
        .body p {
          margin-top: 0;
          margin-bottom: 16px;
        }
        .body a {
          color: #2563eb;
          text-decoration: underline;
        }
        .footer { 
          background-color: #f1f3f7; 
          padding: 24px 35px; 
          text-align: center; 
          color: #64748b; 
          font-size: 13px; 
          border-top: 1px solid #e2e8f0; 
        }
        .footer p { 
          margin: 4px 0; 
        }
        @media screen and (max-width: 600px) {
          .wrapper { padding: 0; }
          .container { border-radius: 0; width: 100%; box-shadow: none; }
          .body { padding: 25px 20px; }
          .header { padding: 25px 20px; }
        }
      </style>
    </head>
    <body>
      <div class="wrapper">
        <div class="container">
          <div class="header">
            ${safeLogo ? `<img src="${safeLogo}" alt="${name} Logo" />` : ''}
            <h1>${name}</h1>
          </div>
          <div class="body">
            ${body}
          </div>
          <div class="footer">
            <p>${footer}</p>
          </div>
        </div>
      </div>
    </body>
    </html>
  `;
};

/**
 * Generates an email template for Homeowner Requests.
 * Supports both explicit positional arguments and legacy object inputs.
 * 
 * @param {string|Object} subjectOrRequest - The subject line OR a request object for backward compatibility.
 * @param {string|Object} bodyOrClientInfo - The body text OR client info object.
 * @param {string} [associationNameOrEmail] - The association name OR recipient email string.
 * @param {string} [associationLogo] - The association logo URL.
 * @returns {string} The fully generated HTML email.
 */
export const generateHomeownerRequestEmail = (...args) => {
  let subject, body, associationName, associationLogo;

  if (!args || args.length === 0) {
    console.error("generateHomeownerRequestEmail: Missing required parameters.");
    return '';
  }

  // Check if it's being called via the legacy pattern: (request, clientInfo, recipientEmail)
  if (typeof args[0] === 'object' && args[0] !== null && 'title' in args[0]) {
    const [request, clientInfo] = args;
    subject = request.title || 'New Homeowner Request';
    
    body = `
      <h2 style="margin-top: 0; color: #0f172a;">Homeowner Request Notification</h2>
      <p>A new homeowner request has been submitted for your review.</p>
      <div style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 15px; margin-bottom: 20px;">
        <p style="margin: 4px 0;"><strong>Status:</strong> <span style="text-transform:capitalize;">${request.status}</span></p>
        ${request.address_selected ? `<p style="margin: 4px 0;"><strong>Property:</strong> ${request.address_selected}</p>` : ''}
      </div>
      <div style="margin-bottom: 25px;">
        <h3 style="margin-top: 0; font-size: 16px; color: #334155;">${request.title}</h3>
        <p>${request.description || 'No summary provided.'}</p>
        ${request.content ? `<div style="margin-top:15px; border-top:1px dashed #e2e8f0; padding-top:15px; font-size: 14px; color: #475569;">${request.content}</div>` : ''}
      </div>
      <div style="text-align: center; margin: 30px 0;">
        <a href="https://avria.cloud/login" style="background-color: #0f172a; color: #ffffff; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold; display: inline-block;">View Request Details</a>
      </div>
    `;

    associationName = clientInfo?.name || 'Homeowner Association';
    associationLogo = clientInfo?.logo_url || clientInfo?.notice_logo || '';
  } else {
    // Handling as requested: (subject, body, associationName, associationLogo)
    [subject, body, associationName, associationLogo] = args;
  }

  if (!subject || !body) {
    console.warn("generateHomeownerRequestEmail: Missing subject or body.");
  }

  return wrapEmailContent(
    body || '',
    associationName || 'Homeowner Association',
    associationLogo || '',
    '© 2026 Avria Community Management, LLC. All rights reserved. Powered by Avria Community Management'
  );
};

/**
 * Extracts template variables wrapped in double curly braces (e.g. {{name}}).
 * 
 * @param {string} text - The text to extract from.
 * @returns {string[]} An array of variable names.
 */
export const extractVariables = (text) => {
  if (!text) return [];
  const matches = text.match(/{{([^}]+)}}/g);
  if (!matches) return [];
  return [...new Set(matches.map(m => m.replace(/[{}]/g, '')))];
};

/**
 * Replaces double curly brace variables with values from a context object.
 * 
 * @param {string} text - The text containing variables.
 * @param {Object} context - Dictionary of variable values.
 * @returns {string} The text with variables replaced.
 */
export const replaceTemplateVariables = (text, context) => {
  if (!text) return '';
  return text.replace(/{{([^}]+)}}/g, (match, key) => {
      return context[key] !== undefined ? context[key] : match;
  });
};

/**
 * Generates an email specifically for Notify Board operations.
 * 
 * @param {string} subject - Email subject line.
 * @param {string} bodyContent - Core email body content containing variables.
 * @param {Object} variables - Key-value pair of variables to replace.
 * @param {Object} client - Client info object.
 * @returns {string} Fully structured HTML email.
 */
export const generateNotifyBoardEmail = (subject, bodyContent, variables = {}, client = null) => {
  let finalBody = bodyContent || '';
  Object.keys(variables).forEach(key => {
    const regex = new RegExp(`{{${key}}}`, 'g');
    finalBody = finalBody.replace(regex, variables[key] || '');
  });
  
  return wrapEmailContent({
      title: subject,
      bodyContent: finalBody,
      clientInfo: client
  });
};
