/**
 * Email templates store a Handlebars shell: header/footer partials + optional primary_cta (portal button).
 * Admins edit only the inner HTML; shell is stripped for the editor and reassembled on save/preview.
 */

function decodeHandlebarsEntities(html: string): string {
  const hb = /\{\{\{[\s\S]*?\}\}\}|\{\{[\s\S]*?\}\}/g;
  return html.replace(hb, (block) =>
    block
      .replace(/&amp;lt;/gi, '<')
      .replace(/&amp;gt;/gi, '>')
      .replace(/&amp;quot;/gi, '"')
      .replace(/&amp;#39;/g, "'")
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'")
      .replace(/&amp;/g, '&')
  );
}

const HDR = /\{\{\s*>\s*email_header\s*\}\}/i;
const FTR = /\{\{\s*>\s*email_footer\s*\}\}/i;
const CTA = /\{\{\s*>\s*primary_cta\s*\}\}/i;

/** Wrapped partial tag — optional surrounding block element from rich text export */
const HDR_BLOCK =
  /^[\s\r\n]*(?:<(?:p|div)[^>]*>)?\s*\{\{\s*>\s*email_header\s*\}\}\s*(?:<\/(?:p|div)>)?[\s\r\n]*/i;
const FTR_BLOCK =
  /[\s\r\n]*(?:<(?:p|div)[^>]*>)?\s*\{\{\s*>\s*email_footer\s*\}\}\s*(?:<\/(?:p|div)>)?[\s\r\n]*$/i;
const CTA_BLOCK =
  /(?:<(?:p|div)[^>]*>)?\s*\{\{\s*>\s*primary_cta\s*\}\}\s*(?:<\/(?:p|div)>)?/gi;

export type ParsedEmailShell = {
  isShellTemplate: boolean;
  editableHtml: string;
  includesCta: boolean;
};

export function parseEmailLayoutShell(html: string): ParsedEmailShell {
  const raw = html || '';
  const decoded = decodeHandlebarsEntities(raw);
  if (!HDR.test(decoded) || !FTR.test(decoded)) {
    return { isShellTemplate: false, editableHtml: raw, includesCta: false };
  }
  const includesCta = CTA.test(decoded);
  let inner = decoded.replace(HDR_BLOCK, '').replace(FTR_BLOCK, '').replace(CTA_BLOCK, '');
  inner = inner.trim();
  return { isShellTemplate: true, editableHtml: inner, includesCta };
}

/** Rebuild stored body for API; CTA URL/label come from backend at send time only. */
export function composeEmailLayoutShell(editableHtml: string, includesCta: boolean): string {
  const inner = (editableHtml || '').trim();
  const mid = includesCta ? `\n{{> primary_cta}}\n` : '\n';
  return `{{> email_header}}\n${inner}${mid}{{> email_footer}}`;
}
