/**
 * Landing Page Generator
 * Generates beautiful, compliant HTML pages from templates
 */

import Handlebars from 'handlebars';
import { optInTemplate, privacyPolicyTemplate, termsTemplate } from './templates';
import type { LandingPageConfig, CampaignInfo, BusinessInfo } from '../types';

export interface GeneratedPages {
  optInHtml: string;
  privacyPolicyHtml: string;
  termsHtml: string;
  slug: string;
}

/**
 * Generate a URL-safe slug from business name
 */
export function generateSlug(businessName: string): string {
  return businessName
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .substring(0, 50);
}

/**
 * Get business initial (first letter) for logo placeholder
 */
function getBusinessInitial(businessName: string): string {
  return businessName.charAt(0).toUpperCase();
}

/**
 * Format current date as "Month DD, YYYY"
 */
function getCurrentDate(): string {
  const now = new Date();
  return now.toLocaleDateString('en-US', { 
    month: 'long', 
    day: 'numeric', 
    year: 'numeric' 
  });
}

/**
 * Get current year for copyright
 */
function getCurrentYear(): number {
  return new Date().getFullYear();
}

/**
 * Convert campaign use case to friendly display name
 */
function formatUseCase(useCase: string): string {
  return useCase
    .split('_')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(' ');
}

/**
 * Generate all three compliant landing pages
 */
export function generateLandingPages(
  config: LandingPageConfig,
  campaign: CampaignInfo,
  business: BusinessInfo
): GeneratedPages {
  
  // Generate slug if not provided
  const slug = config.businessSlug || generateSlug(config.businessName);
  
  // Default brand color if not provided
  const brandColor = config.brandColor || '#3B82F6'; // Blue-500
  
  // Prepare template data
  const templateData = {
    // Config data
    businessName: config.businessName,
    businessSlug: slug,
    useCase: formatUseCase(config.useCase),
    useCaseDescription: config.useCaseDescription,
    messageFrequency: config.messageFrequency,
    privacyPolicyUrl: config.privacyPolicyUrl,
    termsUrl: config.termsUrl,
    contactEmail: config.contactEmail,
    contactPhone: config.contactPhone,
    brandColor: brandColor,
    logoUrl: config.logoUrl || null,
    
    // Derived data
    businessInitial: getBusinessInitial(config.businessName),
    currentDate: getCurrentDate(),
    currentYear: getCurrentYear(),
    
    // Campaign-specific
    campaignDescription: campaign.description,
    sampleMessages: campaign.sampleMessages,
    optInMessage: campaign.optInMessage,
    optOutMessage: campaign.optOutMessage,
    helpMessage: campaign.helpMessage,
    
    // Business info
    websiteUrl: business.websiteUrl,
    businessType: business.businessType,
  };
  
  // Compile templates
  const optInCompiled = Handlebars.compile(optInTemplate);
  const privacyCompiled = Handlebars.compile(privacyPolicyTemplate);
  const termsCompiled = Handlebars.compile(termsTemplate);
  
  // Generate HTML
  const optInHtml = optInCompiled(templateData);
  const privacyPolicyHtml = privacyCompiled(templateData);
  const termsHtml = termsCompiled(templateData);
  
  return {
    optInHtml,
    privacyPolicyHtml,
    termsHtml,
    slug,
  };
}

/**
 * Create LandingPageConfig from business and campaign data
 * Helper function to simplify config creation
 */
export function createLandingPageConfig(
  business: BusinessInfo,
  campaign: CampaignInfo,
  contactEmail: string,
  contactPhone: string,
  baseUrl: string,
  options?: {
    brandColor?: string;
    logoUrl?: string;
    messageFrequency?: string;
  }
): LandingPageConfig {
  
  const slug = generateSlug(business.businessName);
  
  return {
    businessName: business.businessName,
    businessSlug: slug,
    useCase: campaign.useCase,
    useCaseDescription: campaign.description,
    messageFrequency: options?.messageFrequency || 'up to 5 messages per week',
    privacyPolicyUrl: `${baseUrl}/${slug}/privacy-policy.html`,
    termsUrl: `${baseUrl}/${slug}/terms.html`,
    contactEmail,
    contactPhone,
    brandColor: options?.brandColor,
    logoUrl: options?.logoUrl,
  };
}
