const nodemailer = require('nodemailer');
const db = require('../db');

// SendGrid setup (optional - used if SENDGRID_API_KEY is set)
let sgMail = null;
try {
    sgMail = require('@sendgrid/mail');
    if (process.env.SENDGRID_API_KEY) {
        sgMail.setApiKey(process.env.SENDGRID_API_KEY);
        console.log('✅ SendGrid API configured');
    }
} catch (e) {
    // SendGrid not installed, will use SMTP
}

const getTransporter = async () => {
    try {
        // Fetch settings from DB
        const result = await db.query("SELECT `key`, value FROM system_settings WHERE category = 'email'");
        const settings = {};
        result.rows.forEach(row => {
            settings[row.key] = row.value;
        });

        // Helper to clean quotes if stored as JSON strings
        const clean = (val) => {
            if (typeof val !== 'string') return val;
            // Remove outer quotes and handle escaped internal quotes
            let cleaned = val.replace(/^"|"$/g, '').trim();
            // Handle cases where double-escaped quotes might exist (e.g. \"host\")
            return cleaned.replace(/\\"/g, '"');
        };

        // Use DB settings if available, otherwise fallback to env vars
        const host = clean(settings['smtp_host']) || process.env.SMTP_HOST;
        const port = clean(settings['smtp_port']) || process.env.SMTP_PORT;
        const user = clean(settings['smtp_user']) || process.env.SMTP_USER;
        const pass = clean(settings['smtp_pass']) || process.env.SMTP_PASS;
        const secure = String(settings['smtp_secure']).replace(/^"|"$/g, '') === 'true' || String(process.env.SMTP_SECURE) === 'true';

        if (!host || !user || !pass) {
            console.warn('SMTP settings not configured. Missing: ' + 
                (!host ? 'host ' : '') + 
                (!user ? 'user ' : '') + 
                (!pass ? 'pass' : '')
            );
            console.warn('Env vars: SMTP_HOST=' + process.env.SMTP_HOST + ', SMTP_PORT=' + process.env.SMTP_PORT + ', SMTP_USER=' + (process.env.SMTP_USER ? '***' : 'missing'));
            return null;
        }

        return nodemailer.createTransport({
            host,
            port,
            secure, // true for 465, false for other ports
            auth: { user, pass },
            tls: {
                rejectUnauthorized: false // Fix for cPanel self-signed certs
            }
        });
    } catch (error) {
        console.error('Error creating transporter:', error);
        return null;
    }
};

// function removed

const logEmailEvent = async (to, subject, status, body = null, errorMessage = null, userId = null) => {
    try {
        await db.query(
            "INSERT INTO email_logs (recipient_email, subject, status, body, error_message, user_id) VALUES (?, ?, ?, ?, ?, ?)",
            [to, subject, status, body, errorMessage, userId]
        );
    } catch (e) {
        console.error('Failed to log email event:', e);
    }
};

const sendEmail = async (to, subject, html, userId = null) => {
    const fromEmail = 'noreply@infoseclabs.io';
    const fromName = process.env.FROM_NAME || 'InfoSecLabs';

    // Try SendGrid first if configured
    if (sgMail && process.env.SENDGRID_API_KEY) {
        try {
            const msg = {
                to,
                from: { email: fromEmail, name: fromName },
                subject,
                html,
            };
            await sgMail.send(msg);
            console.log('📧 Email sent via SendGrid to:', to);
            // Fire and forget logging (with userId)
            logEmailEvent(to, subject, 'sent', html, null, userId).catch(e => console.error(e));
            return { messageId: 'sendgrid-' + Date.now() };
        } catch (error) {
            console.error('SendGrid error:', error.response?.body || error.message);
            logEmailEvent(to, subject, 'failed', html, error.message, userId).catch(e => console.error(e));
            // Fall through to SMTP if SendGrid fails
        }
    }

    // Fallback to SMTP
    try {
        const transporter = await getTransporter();
        if (!transporter) {
            console.log('Email not sent: SMTP not configured.');
            return null;
        }

        const info = await transporter.sendMail({
            from: `"${fromName}" <${fromEmail}>`,
            to,
            subject,
            html,
        });
        console.log('📧 Email sent via SMTP:', info.messageId);
        // Await logging for critical emails or keep it fire-and-forget but with userId
        logEmailEvent(to, subject, 'sent', html, null, userId).catch(e => console.error(e));
        return info;
    } catch (error) {
        console.error('Error sending email:', error);
        logEmailEvent(to, subject, 'failed', html, error.message, userId).catch(e => console.error(e));
        throw error;
    }
};

// Bulk send for newsletters (with rate limiting for SendGrid)
const sendBulkEmail = async (recipients, subject, htmlTemplate, nameKey = 'name') => {
    const results = { sent: 0, failed: 0, errors: [] };
    const fromEmail = 'noreply@infoseclabs.io';
    const fromName = process.env.FROM_NAME || 'InfoSecLabs';

    // SendGrid bulk sending (up to 1000 per request)
    if (sgMail && process.env.SENDGRID_API_KEY) {
        const batchSize = 100; // Send in batches of 100
        const delayBetweenBatches = 1000; // 1 second delay between batches

        for (let i = 0; i < recipients.length; i += batchSize) {
            const batch = recipients.slice(i, i + batchSize);
            
            const messages = batch.map(recipient => ({
                to: recipient.email,
                from: { email: fromEmail, name: fromName },
                subject,
                html: htmlTemplate.replace(/\{\{name\}\}/g, recipient[nameKey] || 'there'),
            }));

            try {
                await sgMail.send(messages);
                results.sent += messages.length;
                console.log(`📧 Batch ${Math.floor(i/batchSize) + 1}: Sent ${messages.length} emails via SendGrid`);
                
                // Log all successes
                Promise.all(batch.map(recipient => {
                    const personalizedHtml = htmlTemplate.replace(/\{\{name\}\}/g, recipient[nameKey] || 'there');
                    return logEmailEvent(recipient.email, subject, 'sent', personalizedHtml);
                })).catch(e => console.error(e));
            } catch (error) {
                results.failed += messages.length;
                results.errors.push(error.message);
                console.error('SendGrid batch error:', error.response?.body || error.message);
                
                // Log all failures
                Promise.all(batch.map(recipient => {
                    const personalizedHtml = htmlTemplate.replace(/\{\{name\}\}/g, recipient[nameKey] || 'there');
                    return logEmailEvent(recipient.email, subject, 'failed', personalizedHtml, error.message);
                })).catch(e => console.error(e));
            }

            // Delay between batches to avoid rate limits
            if (i + batchSize < recipients.length) {
                await new Promise(resolve => setTimeout(resolve, delayBetweenBatches));
            }
        }
        return results;
    }

    // Fallback: SMTP one-by-one (slower but works)
    for (const recipient of recipients) {
        try {
            const personalizedHtml = htmlTemplate.replace(/\{\{name\}\}/g, recipient[nameKey] || 'there');
            await sendEmail(recipient.email, subject, personalizedHtml, recipient.id || recipient.user_id || null);
            results.sent++;
            // Small delay to avoid overwhelming SMTP server
            await new Promise(resolve => setTimeout(resolve, 100));
        } catch (error) {
            results.failed++;
            results.errors.push(`${recipient.email}: ${error.message}`);
        }
    }

    return results;
};

const sendVerificationEmail = async (email, token) => {
    const verificationUrl = `${process.env.CLIENT_ORIGIN || 'http://localhost:5173'}/verify-email/${token}`;
    const subject = 'Verify your email address';
    const html = `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Verify Email</title>
        <style>
            body { margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #0d0d0d; }
            table { border-spacing: 0; }
            td { padding: 0; }
            .wrapper { width: 100%; table-layout: fixed; background-color: #0d0d0d; padding-bottom: 40px; }
            .webkit { max-width: 600px; background-color: #1a1a1a; margin: 0 auto; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.5); border: 1px solid #333; }
            .header { background-color: #111; padding: 20px; text-align: center; border-bottom: 1px solid #333; }
            .content { padding: 40px 30px; text-align: center; color: #e0e0e0; }
            .button { display: inline-block; padding: 14px 32px; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: #ffffff !important; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 16px; margin: 25px 0; box-shadow: 0 4px 6px rgba(59, 130, 246, 0.3); }
            .footer { background-color: #111; padding: 20px; text-align: center; color: #666; font-size: 12px; border-top: 1px solid #333; }
            .link-text { color: #3b82f6; word-break: break-all; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <table class="webkit" role="presentation">
                <tr>
                    <td class="header">
                        <img src="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/logo.png" alt="InfoSecLabs" style="height: 40px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;">
                    </td>
                </tr>
                <tr>
                    <td class="content">
                        <h2 style="color: #ffffff; margin-top: 0; font-size: 22px;">Verify your Email</h2>
                        <p style="color: #b0b0b0; font-size: 16px; line-height: 1.6; margin-bottom: 25px;">
                            Welcome to <strong>InfoSecLabs</strong>! To activate your account and access the platform, please verify your email address.
                        </p>
                        
                        <a href="${verificationUrl}" class="button">Verify Email Address</a>
                        
                        <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #333;">
                            <p style="color: #666; font-size: 13px; margin-bottom: 10px;">Or copy this link to your browser:</p>
                            <a href="${verificationUrl}" class="link-text" style="font-size: 13px;">${verificationUrl}</a>
                        </div>

                        <div style="margin-top: 30px; padding: 25px; background: rgba(59, 130, 246, 0.05); border-radius: 12px; border: 1px solid rgba(59, 130, 246, 0.2);">
                            <h3 style="color: #ffffff; margin-top: 0; font-size: 16px; margin-bottom: 10px;">Take your training anywhere!</h3>
                            <p style="color: #b0b0b0; font-size: 13px; margin-bottom: 20px;">Download our mobile app to complete daily missions and threat briefings on the go.</p>
                            
                            <div style="display: flex; justify-content: center; gap: 15px;">
                                <a href="https://apps.apple.com/us/app/infoseclabs-soc-analyst-lab/id6759411974" style="display: inline-block;">
                                    <img src="https://infoseclabs.io/assets/app_store_badge.png" alt="Download on App Store" style="height: 40px;">
                                </a>
                                <a href="https://play.google.com/store/apps/details?id=io.infoseclabs.mobile" style="display: inline-block;">
                                    <img src="https://infoseclabs.io/assets/google_play_badge.png" alt="Get it on Google Play" style="height: 40px;">
                                </a>
                            </div>
                        </div>

                        <div style="margin-top: 20px; padding: 25px; background: rgba(88, 101, 242, 0.05); border-radius: 12px; border: 1px solid rgba(88, 101, 242, 0.2);">
                            <h3 style="color: #ffffff; margin-top: 0; font-size: 16px; margin-bottom: 10px;">Join our Community</h3>
                            <p style="color: #b0b0b0; font-size: 13px; margin-bottom: 20px;">Connect with thousands of other analysts, share findings, and get help on Discord.</p>
                            <div style="text-align: center;">
                                <a href="https://discord.gg/G6AAV744Ux" style="display: inline-block; padding: 12px 25px; background-color: #5865F2; color: #ffffff !important; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 15px;">Join InfoSecLabs Discord</a>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="footer">
                        &copy; ${new Date().getFullYear()} InfoSecLabs. All rights reserved.<br>
                        Security Training & SOC Simulations
                    </td>
                </tr>
            </table>
        </div>
    </body>
    </html>
    `;
    return sendEmail(email, subject, html, null); // userId not available on signup yet
};

const sendOrganizationInviteEmail = async (email, orgName, token, role, inviterId = null) => {
    const inviteUrl = `${process.env.CLIENT_ORIGIN || 'http://localhost:5173'}/join-team/${token}`;
    const subject = `Invitation to join ${orgName} on InfoSecLabs`;
    const html = `
        <div style="background-color: #0e0f11; color: #ffffff; padding: 40px; font-family: sans-serif;">
            <div style="text-align: center; margin-bottom: 30px;">
                <img src="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/logo.png" alt="InfoSecLabs Business" style="height: 40px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;">
            </div>
            <div style="background-color: #1a1b1e; padding: 30px; border-radius: 8px; border: 1px solid #333;">
                <h2 style="color: #ffffff; margin-top: 0;">You've been invited!</h2>
                <p style="color: #cccccc;">You have been invited to join the <strong>${orgName}</strong> organization as a <strong>${role}</strong>.</p>
                <p style="color: #999; margin: 20px 0;">Join your team to collaborate on investigations, access shared training resources, and track progress together.</p>
                <div style="text-align: center; margin: 30px 0;">
                    <a href="${inviteUrl}" style="display: inline-block; padding: 12px 30px; background-color: #3b82f6; color: #ffffff; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 16px; box-shadow: 0 0 15px rgba(59, 130, 246, 0.5);">Accept Invitation</a>
                </div>
                <p style="color: #999999; font-size: 12px;">Or copy this link to your browser:</p>
                <p style="background-color: #000; padding: 10px; border-radius: 4px; overflow-wrap: break-word;"><a href="${inviteUrl}" style="color: #3b82f6;">${inviteUrl}</a></p>
            </div>
            <div style="text-align: center; margin-top: 20px; color: #666; font-size: 12px;">
                &copy; ${new Date().getFullYear()} InfoSecLabs. All rights reserved.
            </div>
        </div>
    `;
    return sendEmail(email, subject, html, null);
};

const sendPasswordResetEmail = async (email, token, userId = null) => {
    const resetUrl = `${process.env.CLIENT_ORIGIN || 'http://localhost:5173'}/reset-password/${token}`;
    const subject = 'Password Reset Request';
    const html = `
        <h1>Password Reset</h1>
        <p>You requested a password reset. Please click the link below to reset your password:</p>
        <a href="${resetUrl}">${resetUrl}</a>
        <p>This link will expire in 1 hour.</p>
        <p>If you did not request this, please ignore this email.</p>
    `;
    return sendEmail(email, subject, html, userId);
};

const sendProfileUpdateEmail = async (email, updateType, userId = null) => {
    const subject = 'Account Updated';
    const html = `
        <h1>Account Updated</h1>
        <p>Your ${updateType} has been successfully updated.</p>
        <p>If you did not make this change, please contact support immediately.</p>
    `;
    return sendEmail(email, subject, html, userId);
};

const getTemplate = async (key) => {
    try {
        const result = await db.query("SELECT value FROM system_settings WHERE `key` = ?", [key]);
        if (result.rows.length > 0) {
            let val = result.rows[0].value;
            if (typeof val === 'string' && val.startsWith('"') && val.endsWith('"')) {
                try {
                    val = JSON.parse(val);
                } catch (e) {
                    val = val.replace(/^"|"$/g, '');
                }
            }
            return val;
        }
        return null;
    } catch (error) {
        console.error(`Error fetching template ${key}:`, error);
        return null;
    }
};

const getBaseUrl = () => process.env.CLIENT_ORIGIN || 'https://infoseclabs.io';

const sendAccountDeletedEmail = async (email, name, userId = null) => {
    let subject = await getTemplate('account_deleted_subject') || 'Account Deleted';
    let body = await getTemplate('account_deleted_body') || `<h1>Account Deleted</h1><p>Hello ${name},</p><p>Your account has been deleted.</p>`;

    body = body.replace('{{name}}', name).replace(/{{baseUrl}}/g, getBaseUrl());
    return sendEmail(email, subject, body, userId);
};

const sendAwardEmail = async (email, name, awardType, userId = null) => {
    let subjectKey = `award_${awardType}_subject`;
    let bodyKey = `award_${awardType}_body`;

    let subject = await getTemplate(subjectKey) || `Congratulations! You Won the ${awardType.charAt(0).toUpperCase() + awardType.slice(1)} Award!`;
    let body = await getTemplate(bodyKey) || `<h1>Congratulations!</h1><p>Dear ${name},</p><p>You have won the ${awardType} award.</p>`;

    body = body.replace('{{name}}', name).replace(/{{baseUrl}}/g, getBaseUrl());
    return sendEmail(email, subject, body, userId);
};

const sendAlertAssignedEmail = async (email, name, alertTitle, userId = null) => {
    let subject = await getTemplate('alert_assigned_subject') || `New Alert Assigned: ${alertTitle}`;
    let body = await getTemplate('alert_assigned_body') || `<h1>New Alert Assigned</h1><p>Hello ${name},</p><p>Alert <strong>${alertTitle}</strong> has been assigned to you.</p>`;

    subject = subject.replace('{{title}}', alertTitle);
    body = body.replace('{{name}}', name)
        .replace('{{title}}', alertTitle)
        .replace(/{{baseUrl}}/g, getBaseUrl());

    return sendEmail(email, subject, body, userId);
};

const sendInvestigationGradedEmail = async (email, name, alertTitle, grade, feedback, userId = null) => {
    let subject = await getTemplate('investigation_graded_subject') || `Investigation Graded: ${alertTitle}`;
    let body = await getTemplate('investigation_graded_body') || `<h1>Investigation Graded</h1><p>Hello ${name},</p><p>Your investigation for <strong>${alertTitle}</strong> has been graded.</p><p>Grade: ${grade}</p><p>Feedback: ${feedback}</p>`;

    let gradeColor = 'ef4444'; // Red (Low)
    const gradeNum = parseInt(grade);
    if (gradeNum >= 80) gradeColor = '00ff41'; // Green (High)
    else if (gradeNum >= 50) gradeColor = 'f59e0b'; // Yellow (Med)

    subject = subject.replace('{{title}}', alertTitle);
    body = body.replace('{{name}}', name)
        .replace('{{title}}', alertTitle)
        .replace('{{grade}}', grade)
        .replace('{{gradeColor}}', gradeColor)
        .replace('{{feedback}}', feedback)
        .replace(/{{baseUrl}}/g, getBaseUrl());

    return sendEmail(email, subject, body, userId);
};

const sendAccountLockedEmail = async (email, name) => {
    // ... existing ...
    return sendEmail(email, 'Security Alert: Account Locked', `...`);
};

const sendSubscriptionUpgradedEmail = async (email, name, planType = 'monthly', isUpgrade = false) => {
    const subject = isUpgrade ? `🚀 Your InfoSecLabs Plan has been Updated!` : `🚀 Welcome to InfoSecLabs Pro!`;
    const html = `
        <div style="background-color: #0e0f11; color: #ffffff; padding: 40px; font-family: sans-serif;">
            <div style="text-align: center; margin-bottom: 30px;">
                <img src="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/logo.png" alt="InfoSecLabs Pro" style="height: 40px; margin-bottom: 10px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;"><br>
                <h1 style="color: #3b82f6; margin: 0;">InfoSecLabs <span style="color: #ffffff;">Pro</span></h1>
            </div>
            <div style="background-color: #1a1b1e; padding: 30px; border-radius: 8px; border: 1px solid #333;">
                <h2 style="color: #ffffff; margin-top: 0;">${isUpgrade ? 'Plan Successfully Updated' : 'Deployment Authorized'}, ${name}! 🏆</h2>
                <p style="color: #cccccc;">
                    ${isUpgrade 
                        ? `Your subscription has been successfully updated to the <strong>Pro ${planType === 'yearly' ? 'Yearly' : 'Monthly'}</strong> plan. Your journey towards mastering cybersecurity continues with even more dedication!`
                        : `Your account has been successfully upgraded to <strong>Pro (${planType === 'yearly' ? 'Yearly' : 'Monthly'})</strong>. You now have unlimited access to all realistic SOC missions, live threat briefings, and our AI Senior Analyst features.`
                    }
                </p>
                
                <p style="color: #cccccc; margin-top: 20px;">What's yours now:</p>
                <ul style="color: #cccccc; padding-left: 20px;">
                    <li style="margin: 8px 0;">✅ <strong>Unlimited missions:</strong> Practice without boundaries.</li>
                    <li style="margin: 8px 0;">✅ <strong>AI Coaching:</strong> Get instant, expert feedback on your investigations.</li>
                    <li style="margin: 8px 0;">✅ <strong>Zero-Day Briefings:</strong> Stay ahead of the latest real-world threats.</li>
                </ul>

                <div style="text-align: center; margin: 30px 0;">
                    <a href="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/dashboard" style="display: inline-block; padding: 12px 30px; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: #ffffff; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 16px; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);">Access Command Center</a>
                </div>

                <div style="margin-top: 40px; padding: 25px; background: rgba(59, 130, 246, 0.05); border-radius: 12px; border: 1px solid rgba(59, 130, 246, 0.2); text-align: center;">
                    <h3 style="color: #ffffff; margin-top: 0; font-size: 16px; margin-bottom: 10px;">Take your training anywhere!</h3>
                    <p style="color: #cccccc; font-size: 13px; margin-bottom: 20px;">Download our mobile app to track real-world threats on the go.</p>
                    
                    <div style="display: flex; justify-content: center; gap: 15px;">
                        <a href="https://apps.apple.com/us/app/infoseclabs-soc-analyst-lab/id6759411974" style="display: inline-block;">
                            <img src="https://infoseclabs.io/assets/app_store_badge.png" alt="Download on App Store" style="height: 36px;">
                        </a>
                        <a href="https://play.google.com/store/apps/details?id=io.infoseclabs.mobile" style="display: inline-block;">
                            <img src="https://infoseclabs.io/assets/google_play_badge.png" alt="Get it on Google Play" style="height: 36px;">
                        </a>
                    </div>
                </div>

                <div style="margin-top: 20px; padding: 25px; background: rgba(88, 101, 242, 0.05); border-radius: 12px; border: 1px solid rgba(88, 101, 242, 0.2); text-align: center;">
                    <h3 style="color: #ffffff; margin-top: 0; font-size: 16px; margin-bottom: 10px;">The Inner Circle</h3>
                    <p style="color: #cccccc; font-size: 13px; margin-bottom: 20px;">As a Pro member, you have direct access to our exclusive community of elite analysts.</p>
                    <a href="https://discord.gg/G6AAV744Ux" style="display: inline-block; padding: 12px 25px; background-color: #5865F2; color: #ffffff !important; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 15px;">Join Elite Discord Channel</a>
                </div>
            </div>
            <div style="text-align: center; margin-top: 20px; color: #666; font-size: 12px;">
                &copy; ${new Date().getFullYear()} InfoSecLabs. All rights reserved.
            </div>
        </div>
    `;
    return sendEmail(email, subject, html);
};

const sendAdminUpgradeNotification = async (userEmail, userName, planType, isUpgrade = false) => {
    const subject = `💰 ${isUpgrade ? 'Plan Updated' : 'New Upgrade'}: ${userName} (${planType})`;
    const html = `
        <div style="background-color: #f3f4f6; padding: 40px; font-family: sans-serif;">
            <div style="background-color: #ffffff; padding: 30px; border-radius: 12px; border: 1px solid #e5e7eb; box-shadow: 0 4px 6px rgba(0,0,0,0.05);">
                <h2 style="color: #111827; margin-top: 0; border-bottom: 2px solid #3b82f6; padding-bottom: 10px;">${isUpgrade ? 'Subscription Updated' : 'New Pro Subscription'}! 🚀</h2>
                
                <div style="margin: 20px 0; font-size: 16px; color: #374151;">
                    <p><strong>User:</strong> ${userName}</p>
                    <p><strong>Email:</strong> <a href="mailto:${userEmail}">${userEmail}</a></p>
                    <p><strong>Plan Details:</strong> <span style="text-transform: uppercase; font-weight: bold; color: #059669;">${planType}</span></p>
                    <p><strong>Status:</strong> ${isUpgrade ? 'Upgraded/Modified Existing Sub' : 'New Conversion from Free'}</p>
                    <p><strong>Date:</strong> ${new Date().toLocaleString()}</p>
                </div>

                <div style="margin-top: 30px; text-align: center;">
                    <a href="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/dashboard?view=users" style="display: inline-block; padding: 10px 20px; background-color: #111827; color: #ffffff; text-decoration: none; border-radius: 6px; font-weight: 500;">View in Admin Panel</a>
                </div>
            </div>
        </div>
    `;
    return sendEmail('support@infoseclabs.io', subject, html);
};

const sendWeeklyReport = async (email, name, stats, userId = null) => {
    let subject = await getTemplate('weekly_report_subject') || 'Weekly Analyst Report';
    let body = await getTemplate('weekly_report_body') || `<h1>Weekly Report</h1><p>Assigned: {{assigned}}</p>`;

    body = body.replace('{{name}}', name)
        .replace('{{assigned}}', stats.assigned)
        .replace('{{graded}}', stats.graded)
        .replace('{{avgScore}}', stats.avgScore)
        .replace('{{totalScore}}', stats.totalScore)
        .replace('{{totalInvestigations}}', stats.totalInvestigations || 0)
        .replace('{{totalXP}}', (stats.totalXP || 0).toLocaleString())
        .replace('{{lifetimeAvg}}', stats.lifetimeAvg || 0)
        .replace('{{bestScore}}', stats.bestScore || 0)
        .replace('{{rank}}', typeof stats.rank === 'number' ? `#${stats.rank}` : (stats.rank || 'Unranked'))
        .replace(/{{baseUrl}}/g, getBaseUrl());

    // Clean up raw \n characters that appear in email previews
    body = body.replace(/\\n/g, '').replace(/[\r\n]+/g, ' ').replace(/\s{2,}/g, ' ');

    return sendEmail(email, subject, body, userId);
};

const sendContactEmail = async (name, email, message) => {
    const subject = `[Contact Form] Message from ${name}`;
    const html = `
        <div style="background-color: #f3f4f6; padding: 20px;">
            <div style="background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
                <h2 style="color: #333; margin-top:0;">New Contact Form Submission</h2>
                <hr style="border: 0; border-top: 1px solid #eee; margin: 20px 0;">
                <p><strong>Name:</strong> ${name}</p>
                <p><strong>Email:</strong> <a href="mailto:${email}">${email}</a></p>
                <p><strong>Message:</strong></p>
                <div style="background-color: #f9fafb; padding: 15px; border-left: 4px solid #b026ff; border-radius: 4px;">
                    ${message.replace(/\n/g, '<br>')}
                </div>
                <p style="font-size: 12px; color: #999; margin-top: 20px;">Sent via InfoSecLabs Contact Form</p>
            </div>
        </div>
    `;
    // Send to support email (hardcoded as requested)
    return sendEmail('support@infoseclabs.io', subject, html);
};

const sendVerificationReminderEmail = async (email, name, token, userId = null) => {
    const verificationUrl = `${process.env.CLIENT_ORIGIN || 'http://localhost:5173'}/verify-email/${token}`;
    const subject = '⚠️ Action Required: Verify Your Email Within 24 Hours';
    const html = `
        <div style="background-color: #0e0f11; color: #ffffff; padding: 40px; font-family: sans-serif;">
            <div style="text-align: center; margin-bottom: 30px;">
                <img src="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/logo.png" alt="InfoSecLabs" style="height: 40px; margin-bottom: 20px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;"><br>
                <h1 style="color: #ff4444; margin: 0;">⚠️ Account Deletion Warning</h1>
            </div>
            <div style="background-color: #1a1b1e; padding: 30px; border-radius: 8px; border: 1px solid #ff4444;">
                <h2 style="color: #ffffff; margin-top: 0;">Hello ${name || 'User'},</h2>
                <p style="color: #cccccc;">Your account email has not been verified yet. <strong style="color: #ff4444;">Your account will be permanently deleted in 24 hours</strong> if you do not verify your email address.</p>
                <p style="color: #cccccc;">Click the button below to verify your email and keep your account:</p>
                <div style="text-align: center; margin: 30px 0;">
                    <a href="${verificationUrl}" style="display: inline-block; padding: 12px 30px; background-color: #b026ff; color: #ffffff; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 16px; box-shadow: 0 0 15px rgba(176, 38, 255, 0.5);">Verify Email Now</a>
                </div>
                <p style="background-color: #000; padding: 10px; border-radius: 4px; overflow-wrap: break-word;"><a href="${verificationUrl}" style="color: #b026ff;">${verificationUrl}</a></p>

                <div style="margin-top: 30px; padding: 25px; background: rgba(176, 38, 255, 0.05); border-radius: 12px; border: 1px solid rgba(176, 38, 255, 0.2); text-align: center;">
                    <h3 style="color: #ffffff; margin-top: 0; font-size: 16px; margin-bottom: 10px;">Don't miss out on your daily training!</h3>
                    <p style="color: #cccccc; font-size: 13px; margin-bottom: 20px;">Download the mobile app to ensure you never miss a threat briefing.</p>
                    
                    <div style="display: flex; justify-content: center; gap: 15px;">
                        <a href="https://apps.apple.com/us/app/infoseclabs-soc-analyst-lab/id6759411974" style="display: inline-block;">
                            <img src="https://infoseclabs.io/assets/app_store_badge.png" alt="Download on App Store" style="height: 36px;">
                        </a>
                        <a href="https://play.google.com/store/apps/details?id=io.infoseclabs.mobile" style="display: inline-block;">
                            <img src="https://infoseclabs.io/assets/google_play_badge.png" alt="Get it on Google Play" style="height: 36px;">
                        </a>
                    </div>
                </div>

                <div style="margin-top: 20px; padding: 25px; background: rgba(88, 101, 242, 0.05); border-radius: 12px; border: 1px solid rgba(88, 101, 242, 0.2); text-align: center;">
                    <h3 style="color: #ffffff; margin-top: 0; font-size: 16px; margin-bottom: 10px;">Need Help?</h3>
                    <p style="color: #cccccc; font-size: 13px; margin-bottom: 20px;">Having trouble verifying? Join our Discord for instant support from our staff.</p>
                    <a href="https://discord.gg/G6AAV744Ux" style="display: inline-block; padding: 12px 25px; background-color: #5865F2; color: #ffffff !important; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 15px;">Join Support Discord</a>
                </div>
            </div>
            <div style="text-align: center; margin-top: 20px; color: #666; font-size: 12px;">
                &copy; ${new Date().getFullYear()} InfoSecLabs. All rights reserved.
            </div>
        </div>
    `;
    return sendEmail(email, subject, html, userId);
};

const sendLimitReachedEmail = async (email, name, usageCount, userId = null) => {
    const subject = '🚀 Maximize Your Security Training - InfoSecLabs Pro';
    const html = `
        <div style="background-color: #0e0f11; color: #ffffff; padding: 40px; font-family: sans-serif;">
            <div style="text-align: center; margin-bottom: 30px;">
                <img src="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/logo.png" alt="InfoSecLabs Pro" style="height: 40px; margin-bottom: 10px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;"><br>
                <h1 style="color: #3b82f6; margin: 0;">InfoSecLabs <span style="color: #ffffff;">Pro</span></h1>
            </div>
            <div style="background-color: #1a1b1e; padding: 30px; border-radius: 8px; border: 1px solid #333;">
                <h2 style="color: #ffffff; margin-top: 0;">You're on fire, ${name}! 🔥</h2>
                <p style="color: #cccccc;">You've hit your <strong>monthly limit</strong> of <strong>${usageCount} alerts</strong> on the Free Plan. This shows your dedication to mastering SOC skills!</p>
                
                <p style="color: #cccccc;">Don't let limits slow down your career trajectory. Upgrade to <strong>Pro</strong> to unlock:</p>
                
                <ul style="color: #cccccc; list-style-type: none; padding: 0;">
                    <li style="margin: 10px 0;">✅ <strong>Unlimited</strong> Alert Investigations & Missions</li>
                    <li style="margin: 10px 0;">✅ <strong>Advanced</strong> Threat Scenarios (APT, Ransomware)</li>
                    <li style="margin: 10px 0;">✅ <strong>AI Assistant</strong> Coaching & Feedback</li>
                </ul>

                <div style="text-align: center; margin: 30px 0;">
                    <a href="${process.env.CLIENT_ORIGIN || 'http://localhost:5173'}/pricing" style="display: inline-block; padding: 12px 30px; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: #ffffff; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 16px; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);">Upgrade to Pro Now</a>
                </div>
                
                <p style="color: #999999; font-size: 12px; text-align: center;">Or verify your account settings to see current usage.</p>

                <div style="margin-top: 30px; padding: 25px; background: rgba(88, 101, 242, 0.05); border-radius: 12px; border: 1px solid rgba(88, 101, 242, 0.2); text-align: center;">
                    <h3 style="color: #ffffff; margin-top: 0; font-size: 16px; margin-bottom: 10px;">Join our Community</h3>
                    <p style="color: #cccccc; font-size: 13px; margin-bottom: 20px;">Connect with other analysts and share tips on how to master the labs.</p>
                    <a href="https://discord.gg/G6AAV744Ux" style="display: inline-block; padding: 12px 25px; background-color: #5865F2; color: #ffffff !important; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 15px;">Join the Conversation</a>
                </div>
            </div>
            <div style="text-align: center; margin-top: 20px; color: #666; font-size: 12px;">
                &copy; ${new Date().getFullYear()} InfoSecLabs. All rights reserved.
            </div>
        </div>
    `;
    return sendEmail(email, subject, html, userId);
};

const sendReportNotificationEmail = async (user, alert, reason) => {
    const subject = `⚠️ Alert Report/Appeal: ${alert.title} (ID: ${alert.id})`;
    const html = `
        <div style="background-color: #0e0f11; color: #ffffff; padding: 40px; font-family: sans-serif;">
            <div style="text-align: center; margin-bottom: 30px;">
                <img src="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/logo.png" alt="InfoSecLabs Support" style="height: 40px; margin-bottom: 20px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;"><br>
                <h1 style="color: #ff4444; margin: 0;">New Alert Report / Appeal</h1>
            </div>
            <div style="background-color: #1a1b1e; padding: 30px; border-radius: 8px; border: 1px solid #333;">
                <h2 style="color: #ffffff; margin-top: 0; border-bottom: 1px solid #333; padding-bottom: 10px;">Investigation Details</h2>
                
                <div style="margin: 20px 0; display: grid; gap: 10px;">
                    <p style="margin: 5px 0;"><strong style="color: #3b82f6;">Investigator:</strong> ${user.name} (${user.email})</p>
                    <p style="margin: 5px 0;"><strong style="color: #3b82f6;">Alert Title:</strong> ${alert.title}</p>
                    <p style="margin: 5px 0;"><strong style="color: #3b82f6;">Alert ID:</strong> ${alert.id}</p>
                    <p style="margin: 5px 0;"><strong style="color: #3b82f6;">Severity:</strong> ${alert.severity}</p>
                </div>

                <div style="margin-top: 30px; padding: 20px; background-color: #000; border-radius: 8px; border-left: 4px solid #ff4444;">
                    <h3 style="color: #ff4444; margin-top: 0; font-size: 14px; text-transform: uppercase;">Submission Reason</h3>
                    <p style="color: #ffffff; margin-bottom: 0; white-space: pre-wrap;">${reason}</p>
                </div>

                <div style="text-align: center; margin: 30px 0;">
                    <a href="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/dashboard?view=reported" style="display: inline-block; padding: 12px 30px; background-color: #3b82f6; color: #ffffff; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 16px;">View in Admin Console</a>
                </div>
            </div>
            <div style="text-align: center; margin-top: 20px; color: #666; font-size: 12px;">
                Incoming Support Request via InfoSecLabs Platform
            </div>
        </div>
    `;
    return sendEmail('support@infoseclabs.io', subject, html);
};

const sendReferralRewardEmail = async (email, name, referredName, userId = null) => {
    const subject = '🎉 You Earned 1 Month of InfoSecLabs Pro!';
    const html = `
        <div style="background-color: #0e0f11; color: #ffffff; padding: 40px; font-family: sans-serif;">
            <div style="text-align: center; margin-bottom: 30px;">
                 <img src="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/logo.png" alt="InfoSecLabs Pro" style="height: 40px; margin-bottom: 10px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;"><br>
                 <h1 style="color: #3b82f6; margin: 0;">InfoSecLabs <span style="color: #ffffff;">Pro</span></h1>
            </div>
            <div style="background-color: #1a1b1e; padding: 30px; border-radius: 8px; border: 1px solid #3b82f6;">
                <h2 style="color: #ffffff; margin-top: 0;">Congratulations, ${name || 'User'}! 🏆</h2>
                <p style="color: #cccccc;">Your invited friend, <strong>${referredName || 'a new user'}</strong>, just subscribed to InfoSecLabs Pro. As a thank you for growing our community, we've added <strong style="color: #3b82f6;">+30 Days of Pro Membership</strong> completely free to your account!</p>
                <div style="text-align: center; margin: 30px 0;">
                    <a href="${process.env.CLIENT_ORIGIN || 'https://infoseclabs.io'}/dashboard" style="display: inline-block; padding: 12px 30px; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: #ffffff; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 16px; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);">View Dashboard</a>
                </div>

                <div style="margin-top: 20px; padding: 25px; background: rgba(88, 101, 242, 0.05); border-radius: 12px; border: 1px solid rgba(88, 101, 242, 0.2); text-align: center;">
                    <h3 style="color: #ffffff; margin-top: 0; font-size: 16px; margin-bottom: 10px;">Celebrate with us!</h3>
                    <p style="color: #cccccc; font-size: 13px; margin-bottom: 20px;">Share your reward and connect with our team on Discord.</p>
                    <a href="https://discord.gg/G6AAV744Ux" style="display: inline-block; padding: 12px 25px; background-color: #5865F2; color: #ffffff !important; text-decoration: none; font-weight: bold; border-radius: 8px; font-size: 15px;">Join Community Discord</a>
                </div>
            </div>
            <div style="text-align: center; margin-top: 20px; color: #666; font-size: 12px;">
                &copy; ${new Date().getFullYear()} InfoSecLabs. All rights reserved.
            </div>
        </div>
    `;
    return sendEmail(email, subject, html, userId);
};

const sendComplimentaryWelcomeEmail = async (email, name, expiryDate, userId = null) => {
    let subject = await getTemplate('complimentary_welcome_subject') || 'DEPLOYMENT AUTHORIZED: 30-Day Pro Complimentary Access';
    let body = await getTemplate('complimentary_welcome_body');
    
    // Fallback body
    if (!body) {
        body = `<h1>Deployment Authorized</h1><p>Hello ${name},</p><p>You have been granted 30 days of complimentary Pro access.</p><p>Expires: ${expiryDate}</p>`;
    }

    body = body.replace('{{name}}', name)
        .replace('{{expiryDate}}', expiryDate)
        .replace(/{{baseUrl}}/g, getBaseUrl());

    return sendEmail(email, subject, body, userId);
};

const sendComplimentaryReminderEmail = async (email, name, userId = null) => {
    let subject = await getTemplate('complimentary_reminder_subject') || '24-HOURS REMAINING: Subscription Renewal Required';
    let body = await getTemplate('complimentary_reminder_body');
    
    // Fallback body
    if (!body) {
        body = `<h1>Heads up, Agent!</h1><p>Hello ${name},</p><p>Your complimentary Pro access expires in 24 hours.</p>`;
    }

    body = body.replace('{{name}}', name)
        .replace(/{{baseUrl}}/g, getBaseUrl());

    return sendEmail(email, subject, body, userId);
};

module.exports = {
    sendVerificationEmail,
    sendOrganizationInviteEmail,
    sendPasswordResetEmail,
    sendProfileUpdateEmail,
    sendAccountDeletedEmail,
    sendAwardEmail,
    sendAlertAssignedEmail,
    sendInvestigationGradedEmail,
    sendAccountLockedEmail,
    sendSubscriptionUpgradedEmail,
    sendWeeklyReport,
    sendContactEmail,
    sendEmail,
    sendBulkEmail,
    sendVerificationReminderEmail,
    sendLimitReachedEmail,
    sendReportNotificationEmail,
    sendReferralRewardEmail,
    sendComplimentaryWelcomeEmail,
    sendComplimentaryReminderEmail,
    sendAdminUpgradeNotification
};
