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

// RSS Feeds (same as frontend)
const RSS_FEEDS = [
    { name: 'The Hacker News', url: 'https://feeds.feedburner.com/TheHackersNews' },
    { name: 'Krebs on Security', url: 'https://krebsonsecurity.com/feed/' },
    { name: 'Dark Reading', url: 'https://www.darkreading.com/rss.xml' },
    { name: 'BleepingComputer', url: 'https://www.bleepingcomputer.com/feed/' },
    { name: 'SecurityWeek', url: 'https://feeds.feedburner.com/securityweek' },
    { name: 'Schneier on Security', url: 'https://www.schneier.com/feed/atom/' },
    { name: 'WeLiveSecurity', url: 'https://www.welivesecurity.com/feed/' },
    { name: 'CISA Current Activity', url: 'https://www.cisa.gov/uscert/ncas/current-activity.xml' },
    { name: 'Graham Cluley', url: 'https://grahamcluley.com/feed/' }
];

// Fetch RSS feed
const fetchRSS = async (feed) => {
    try {
        const response = await axios.get(`https://api.rss2json.com/v1/api.json?rss_url=${encodeURIComponent(feed.url)}`, {
            timeout: 10000
        });
        
        if (response.data.status === 'ok') {
            return response.data.items.map(item => {
                // Extract image from various possible locations
                let image = null;
                if (item.enclosure && item.enclosure.link) {
                    image = item.enclosure.link;
                } else if (item.thumbnail) {
                    image = item.thumbnail;
                } else if (item.content) {
                    // Try to extract first img from content
                    const imgMatch = item.content.match(/<img[^>]+src=["']([^"']+)["']/);
                    if (imgMatch) image = imgMatch[1];
                }
                
                return {
                    source: feed.name,
                    title: item.title,
                    link: item.link,
                    date: new Date(item.pubDate),
                    description: item.description ? item.description.replace(/<[^>]*>/g, '').substring(0, 300) : '',
                    image: image
                };
            });
        }
        return [];
    } catch (error) {
        console.error(`Error fetching ${feed.name}:`, error.message);
        return [];
    }
};

// Fetch all news from RSS feeds
const fetchAllNews = async () => {
    const promises = RSS_FEEDS.map(feed => fetchRSS(feed));
    const results = await Promise.all(promises);
    const allNews = results.flat();
    
    // Sort by date (newest first)
    allNews.sort((a, b) => b.date - a.date);
    
    // Return only last 7 days of news
    const cutoff = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
    return allNews.filter(n => n.date >= cutoff);
};

// AI: Select top 5 critical stories
const selectCriticalNews = async (articles, apiKey) => {
    if (!apiKey || articles.length === 0) {
        // Fallback: just return first 5
        return articles.slice(0, 5);
    }

    const articlesSummary = articles.slice(0, 50).map((a, i) => 
        `[${i}] "${a.title}" (${a.source}) - ${a.description.substring(0, 150)}`
    ).join('\n');

    const prompt = `You are a cybersecurity news editor selecting the TOP 5 most critical stories for a weekly TL;DR newsletter.

AVAILABLE ARTICLES (last 48 hours):
${articlesSummary}

SELECTION CRITERIA (prioritize in order):
1. Zero-day vulnerabilities or critical CVEs
2. Major ransomware attacks or data breaches
3. Nation-state / APT activity
4. Critical infrastructure threats
5. Significant malware campaigns
6. Important security patches or updates

OUTPUT: Return JSON with key "selected_indices" containing array of 5 integers (the indices of articles to include).
Example: {"selected_indices": [0, 3, 7, 12, 15]}

Select DIVERSE topics - avoid 5 stories about the same thing.`;

    try {
        const response = await axios.post('https://api.openai.com/v1/chat/completions', {
            model: "gpt-4o-mini",
            messages: [
                { role: "system", content: "You are a cybersecurity news curator. Return valid JSON only." },
                { role: "user", content: prompt }
            ],
            response_format: { type: "json_object" },
            temperature: 0.3
        }, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            timeout: 30000
        });

        const result = JSON.parse(response.data.choices[0].message.content);
        const indices = result.selected_indices || [];
        
        return indices.map(i => articles[i]).filter(Boolean).slice(0, 5);
    } catch (error) {
        console.error('AI Selection Error:', error.message);
        return articles.slice(0, 5);
    }
};

// AI: Generate TL;DR summaries
const generateSummaries = async (articles, apiKey) => {
    if (!apiKey || articles.length === 0) {
        return articles.map(a => ({ ...a, tldr: a.description.substring(0, 100) + '...' }));
    }

    const articlesList = articles.map((a, i) => 
        `[${i}] TITLE: ${a.title}\nSOURCE: ${a.source}\nDESCRIPTION: ${a.description}`
    ).join('\n\n');

    const prompt = `Generate TL;DR summaries for these cybersecurity news articles.

ARTICLES:
${articlesList}

For each article, write a 2-sentence TL;DR that:
1. States what happened/was discovered
2. Explains why it matters to security professionals

OUTPUT: Return JSON with key "summaries" containing array of objects:
[{"index": 0, "tldr": "Two sentence summary here."}, ...]`;

    try {
        const response = await axios.post('https://api.openai.com/v1/chat/completions', {
            model: "gpt-4o-mini",
            messages: [
                { role: "system", content: "You are a cybersecurity journalist writing concise summaries. Return valid JSON only." },
                { role: "user", content: prompt }
            ],
            response_format: { type: "json_object" },
            temperature: 0.5
        }, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            timeout: 30000
        });

        const result = JSON.parse(response.data.choices[0].message.content);
        const summaries = result.summaries || [];
        
        return articles.map((article, i) => {
            const summary = summaries.find(s => s.index === i);
            return { ...article, tldr: summary?.tldr || article.description.substring(0, 100) + '...' };
        });
    } catch (error) {
        console.error('AI Summary Error:', error.message);
        return articles.map(a => ({ ...a, tldr: a.description.substring(0, 100) + '...' }));
    }
};

// Generate newsletter content (preview)
exports.generateNewsletter = async (req, res) => {
    try {
        // Get API key from settings
        const settingsResult = await db.query("SELECT value FROM system_settings WHERE `key` = 'ai_api_key'");
        const apiKey = settingsResult.rows[0]?.value;

        console.log('[Newsletter] Fetching news...');
        const allNews = await fetchAllNews();
        console.log(`[Newsletter] Found ${allNews.length} articles from last 48 hours`);

        if (allNews.length === 0) {
            return res.status(400).json({ message: 'No news articles found. Try again later.' });
        }

        console.log('[Newsletter] AI selecting top 5 critical stories...');
        const selectedArticles = await selectCriticalNews(allNews, apiKey);
        
        console.log('[Newsletter] AI generating summaries...');
        const articlesWithSummaries = await generateSummaries(selectedArticles, apiKey);

        // Check if newsletter column exists
        const columnCheck = await db.query("SHOW COLUMNS FROM users LIKE 'is_subscribed_newsletter'");
        const hasColumn = columnCheck.rows && columnCheck.rows.length > 0;
        
        // Get subscriber count based on column availability
        // Get subscriber count (check JSON preferences)
        let subscriberCount = 0;
        let users = [];
        
        if (hasColumn) {
            const result = await db.query(
                "SELECT email_preferences FROM users WHERE (is_subscribed_newsletter = 1 OR is_subscribed_newsletter IS NULL) AND is_verified = 1"
            );
            users = result.rows;
        } else {
            const result = await db.query("SELECT email_preferences FROM users WHERE is_verified = 1");
            users = result.rows;
        }

        // Filter in JS
        subscriberCount = users.filter(u => {
            if (!u.email_preferences) return true;
            try {
                const prefs = typeof u.email_preferences === 'string' ? JSON.parse(u.email_preferences) : u.email_preferences;
                return prefs.newsletter !== false && prefs.newsletter !== 0;
            } catch (e) { return true; }
        }).length;

        res.json({
            message: 'Newsletter generated successfully',
            articles: articlesWithSummaries,
            subscriber_count: subscriberCount,
            generated_at: new Date().toISOString()
        });
    } catch (error) {
        console.error('Error generating newsletter:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

// Preview newsletter HTML
exports.previewNewsletter = async (req, res) => {
    try {
        const { articles } = req.body;
        
        if (!articles || articles.length === 0) {
            return res.status(400).json({ message: 'No articles provided' });
        }

        const html = generateNewsletterHTML(articles);
        res.json({ html, subject: generateSubjectLine(articles) });
    } catch (error) {
        console.error('Error previewing newsletter:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

// Send newsletter to all subscribers (or single test email)
exports.sendNewsletter = async (req, res) => {
    try {
        const { articles, customSubject, testEmail } = req.body;
        const { sendEmail } = require('../utils/emailService');

        if (!articles || articles.length === 0) {
            return res.status(400).json({ message: 'No articles provided' });
        }

        const subject = customSubject || generateSubjectLine(articles);
        const html = generateNewsletterHTML(articles);

        // If test email provided, send only to that email
        if (testEmail) {
            try {
                const personalizedHtml = html.replace('{{name}}', 'Test User');
                await sendEmail(testEmail, subject, personalizedHtml);
                return res.json({ message: 'Test email sent', sent: 1, total: 1, testEmail });
            } catch (err) {
                return res.status(500).json({ message: 'Failed to send test email: ' + err.message });
            }
        }

        // Check if newsletter column exists
        const columnCheck = await db.query("SHOW COLUMNS FROM users LIKE 'is_subscribed_newsletter'");
        const hasColumn = columnCheck.rows && columnCheck.rows.length > 0;
        
        // Get registered user subscribers
        // Get registered user subscribers
        let registeredSubscribers = [];
        let rawUsers = [];

        if (hasColumn) {
            const subscribersResult = await db.query(
                "SELECT email, name, email_preferences FROM users WHERE (is_subscribed_newsletter = 1 OR is_subscribed_newsletter IS NULL) AND is_verified = 1"
            );
            rawUsers = subscribersResult.rows;
        } else {
            // Column doesn't exist, get all verified users
            const allUsersResult = await db.query("SELECT email, name, email_preferences FROM users WHERE is_verified = 1");
            rawUsers = allUsersResult.rows;
        }

        // Filter based on JSON preferences
        registeredSubscribers = rawUsers.filter(u => {
            if (!u.email_preferences) return true;
            try {
                const prefs = typeof u.email_preferences === 'string' ? JSON.parse(u.email_preferences) : u.email_preferences;
                return prefs.newsletter !== false && prefs.newsletter !== 0;
            } catch (e) { return true; }
        });

        // Get external subscribers from newsletter_subscribers table
        let externalSubscribers = [];
        try {
            const externalResult = await db.query(
                "SELECT email, NULL as name FROM newsletter_subscribers WHERE is_active = 1"
            );
            externalSubscribers = externalResult.rows || [];
        } catch (e) {
            // Table might not exist yet
            console.log('[Newsletter] No external subscribers table found');
        }

        // Merge and deduplicate (registered users take priority for name)
        const emailMap = new Map();
        for (const sub of registeredSubscribers) {
            emailMap.set(sub.email.toLowerCase(), { email: sub.email, name: sub.name, source: 'registered' });
        }
        for (const sub of externalSubscribers) {
            const email = sub.email.toLowerCase();
            if (!emailMap.has(email)) {
                emailMap.set(email, { email: sub.email, name: null, source: 'external' });
            }
        }
        
        const subscribers = Array.from(emailMap.values());

        if (subscribers.length === 0) {
            return res.json({ message: 'No subscribers found', sent: 0 });
        }

        let sentCount = 0;
        let errors = [];

        for (const subscriber of subscribers) {
            try {
                // Personalize with name
                const personalizedHtml = html.replace('{{name}}', subscriber.name || 'Security Pro');
                await sendEmail(subscriber.email, subject, personalizedHtml);
                sentCount++;
            } catch (err) {
                errors.push({ email: subscriber.email, error: err.message });
            }
        }

        res.json({
            message: 'Newsletter sent successfully',
            sent: sentCount,
            total: subscribers.length,
            registered: registeredSubscribers.length,
            external: externalSubscribers.length,
            errors: errors.length > 0 ? errors : undefined
        });
    } catch (error) {
        console.error('Error sending newsletter:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

// Get newsletter schedule settings
exports.getNewsletterSettings = async (req, res) => {
    try {
        const result = await db.query(
            "SELECT `key`, value FROM system_settings WHERE `key` IN ('newsletter_enabled', 'newsletter_day', 'newsletter_hour')"
        );
        const settings = {};
        result.rows.forEach(row => {
            settings[row.key] = row.value;
        });
        res.json({
            enabled: settings.newsletter_enabled === '1',
            day: settings.newsletter_day || 'friday',
            hour: settings.newsletter_hour || '9'
        });
    } catch (error) {
        console.error('Error getting newsletter settings:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

// Update newsletter schedule settings
exports.updateNewsletterSettings = async (req, res) => {
    try {
        const { enabled, day, hour } = req.body;
        
        // Upsert settings
        await db.query(
            "INSERT INTO system_settings (`key`, value) VALUES ('newsletter_enabled', ?) ON DUPLICATE KEY UPDATE value = ?",
            [enabled ? '1' : '0', enabled ? '1' : '0']
        );
        await db.query(
            "INSERT INTO system_settings (`key`, value) VALUES ('newsletter_day', ?) ON DUPLICATE KEY UPDATE value = ?",
            [day, day]
        );
        await db.query(
            "INSERT INTO system_settings (`key`, value) VALUES ('newsletter_hour', ?) ON DUPLICATE KEY UPDATE value = ?",
            [hour, hour]
        );

        res.json({ message: 'Newsletter settings updated', enabled, day, hour });
    } catch (error) {
        console.error('Error updating newsletter settings:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

// Public: Subscribe to newsletter (no auth required)
exports.publicSubscribe = async (req, res) => {
    try {
        const { email } = req.body;
        
        if (!email || !email.includes('@')) {
            return res.status(400).json({ message: 'Please enter a valid email address' });
        }

        // Check if newsletter_subscribers table exists, create if not
        await db.query(`
            CREATE TABLE IF NOT EXISTS newsletter_subscribers (
                id INT AUTO_INCREMENT PRIMARY KEY,
                email VARCHAR(255) UNIQUE NOT NULL,
                subscribed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                is_active BOOLEAN DEFAULT TRUE
            )
        `);

        // Try to insert the email
        try {
            await db.query(
                "INSERT INTO newsletter_subscribers (email) VALUES (?)",
                [email.toLowerCase().trim()]
            );
            res.json({ message: 'Successfully subscribed!', email });
        } catch (err) {
            if (err.code === 'ER_DUP_ENTRY') {
                // Already subscribed - reactivate if inactive
                await db.query(
                    "UPDATE newsletter_subscribers SET is_active = TRUE WHERE email = ?",
                    [email.toLowerCase().trim()]
                );
                res.json({ message: 'You\'re already subscribed!', email });
            } else {
                throw err;
            }
        }
    } catch (error) {
        console.error('Error subscribing to newsletter:', error);
        res.status(500).json({ message: 'Subscription failed. Please try again.' });
    }
};

// Admin: Get all subscribers (merged list)
exports.getSubscribers = async (req, res) => {
    try {
        // Get registered users subscribed
        const columnCheck = await db.query("SHOW COLUMNS FROM users LIKE 'is_subscribed_newsletter'");
        const hasColumn = columnCheck.rows && columnCheck.rows.length > 0;
        
        let registeredUsers = [];
        let rawUsers = [];

        if (hasColumn) {
            const result = await db.query(
                "SELECT email, name, 'registered' as source, created_at as subscribed_at, email_preferences FROM users WHERE (is_subscribed_newsletter = 1 OR is_subscribed_newsletter IS NULL) AND is_verified = 1 ORDER BY created_at DESC"
            );
            rawUsers = result.rows || [];
        } else {
            const result = await db.query(
                "SELECT email, name, 'registered' as source, created_at as subscribed_at, email_preferences FROM users WHERE is_verified = 1 ORDER BY created_at DESC"
            );
            rawUsers = result.rows || [];
        }

        registeredUsers = rawUsers.filter(u => {
            if (!u.email_preferences) return true;
            try {
                const prefs = typeof u.email_preferences === 'string' ? JSON.parse(u.email_preferences) : u.email_preferences;
                return prefs.newsletter !== false && prefs.newsletter !== 0;
            } catch (e) { return true; }
        });

        // Get external subscribers
        let externalSubscribers = [];
        try {
            const result = await db.query(
                "SELECT email, NULL as name, 'external' as source, subscribed_at FROM newsletter_subscribers WHERE is_active = 1 ORDER BY subscribed_at DESC"
            );
            externalSubscribers = result.rows || [];
        } catch (e) {
            // Table doesn't exist
        }

        // Merge and deduplicate
        const emailMap = new Map();
        for (const sub of registeredUsers) {
            emailMap.set(sub.email.toLowerCase(), sub);
        }
        for (const sub of externalSubscribers) {
            const email = sub.email.toLowerCase();
            if (!emailMap.has(email)) {
                emailMap.set(email, sub);
            }
        }

        const subscribers = Array.from(emailMap.values());

        res.json({
            total: subscribers.length,
            registered: registeredUsers.length,
            external: externalSubscribers.length,
            subscribers
        });
    } catch (error) {
        console.error('Error getting subscribers:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

// Admin: Unsubscribe an email
exports.unsubscribeEmail = async (req, res) => {
    try {
        const { email } = req.body;
        if (!email) {
            return res.status(400).json({ message: 'Email required' });
        }

        const emailLower = email.toLowerCase().trim();
        let unsubscribed = false;

        // Try to unsubscribe from users table
        const columnCheck = await db.query("SHOW COLUMNS FROM users LIKE 'is_subscribed_newsletter'");
        if (columnCheck.rows && columnCheck.rows.length > 0) {
            const result = await db.query(
                "UPDATE users SET is_subscribed_newsletter = 0 WHERE LOWER(email) = ?",
                [emailLower]
            );
            if (result.affectedRows > 0) unsubscribed = true;
        }

        // Always try to update email_preferences JSON as fallback/primary
        try {
             const result = await db.query(
                "UPDATE users SET email_preferences = JSON_SET(COALESCE(email_preferences, '{}'), '$.newsletter', false) WHERE LOWER(email) = ?",
                [emailLower]
            );
            if (result.affectedRows > 0) unsubscribed = true;
        } catch (err) {
            console.error('Error updating email_preferences:', err);
        }

        // Try to unsubscribe from external subscribers
        try {
            const result = await db.query(
                "UPDATE newsletter_subscribers SET is_active = 0 WHERE LOWER(email) = ?",
                [emailLower]
            );
            if (result.affectedRows > 0) unsubscribed = true;
        } catch (e) {
            // Table doesn't exist
        }

        if (unsubscribed) {
            res.json({ message: 'Email unsubscribed', email });
        } else {
            res.status(404).json({ message: 'Email not found' });
        }
    } catch (error) {
        console.error('Error unsubscribing:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

// Admin: Import subscribers in bulk
exports.importSubscribers = async (req, res) => {
    const { emails } = req.body;

    if (!emails || (!Array.isArray(emails) && typeof emails !== 'string')) {
        return res.status(400).json({ message: 'Invalid format. Provide an array of emails or a comma/newline separated string.' });
    }

    let emailList = [];
    if (typeof emails === 'string') {
        emailList = emails.split(/[\n,]+/).map(e => e.trim()).filter(e => e);
    } else {
        emailList = emails;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    let imported = 0;
    let errors = 0;
    
    try {
        for (const email of emailList) {
            if (!emailRegex.test(email)) {
                errors++;
                continue;
            }

            try {
                const check = await db.query('SELECT id FROM newsletter_subscribers WHERE email = ?', [email]);
                if (check.rows.length === 0) {
                    await db.query('INSERT INTO newsletter_subscribers (email, is_active) VALUES (?, 1)', [email]);
                    imported++;
                } else {
                    await db.query('UPDATE newsletter_subscribers SET is_active = 1 WHERE email = ?', [email]);
                }
            } catch (err) {
                console.error('Import error for ' + email, err);
                errors++;
            }
        }

        res.json({ 
            message: `Import complete.`, 
            stats: { processed: emailList.length, imported, duplicates_or_errors: errors } 
        });
    } catch (error) {
        console.error('Import Subscribers Error:', error);
        res.status(500).json({ message: 'Server error during import' });
    }
};

// Admin: Get Beta Signups
exports.getBetaSignups = async (req, res) => {
    try {
        // Check if table exists first prevents 500 error if migration hasn't run
        const tableCheck = await db.query("SHOW TABLES LIKE 'beta_signups'");
        if (tableCheck.rows.length === 0) {
             return res.json([]);
        }
        
        const result = await db.query("SELECT * FROM beta_signups ORDER BY created_at DESC");
        res.json(result.rows || []);
    } catch (error) {
        console.error('Error fetching beta signups:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

// Admin: Delete Beta Signup
exports.deleteBetaSignup = async (req, res) => {
    try {
        const { id } = req.params;
        const result = await db.query("DELETE FROM beta_signups WHERE id = ?", [id]);
        
        if (result.affectedRows === 0) {
            return res.status(404).json({ message: 'Signup not found' });
        }
        
        res.json({ message: 'Beta signup removed' });
    } catch (error) {
        console.error('Error deleting beta signup:', error);
        res.status(500).json({ message: 'Server error: ' + error.message });
    }
};

// Public: Beta Signup
exports.signupBeta = async (req, res) => {
    try {
        const { email } = req.body;
        const ip_address = req.ip || req.connection.remoteAddress;
        const user_agent = req.headers['user-agent'];
        const source = 'web';

        if (!email || !email.includes('@')) {
            return res.status(400).json({ message: 'Please enter a valid email address' });
        }

        // Check if table exists (migration safety)
        const tableCheck = await db.query("SHOW TABLES LIKE 'beta_signups'");
        if (tableCheck.rows.length === 0) {
             return res.status(503).json({ message: 'Beta signup system is initializing. Please try again later.' });
        }

        try {
            await db.query(
                "INSERT INTO beta_signups (email, ip_address, user_agent, source) VALUES (?, ?, ?, ?)",
                [email.toLowerCase().trim(), ip_address, user_agent, source]
            );
            res.json({ message: 'Successfully joined the waitlist!', email });
        } catch (err) {
            if (err.code === 'ER_DUP_ENTRY') {
                res.json({ message: 'You are already on the waitlist!', email });
            } else {
                throw err;
            }
        }
    } catch (error) {
        console.error('Error in beta signup:', error);
        res.status(500).json({ message: 'Signup failed. Please try again.' });
    }
};

// Generate subject line
const generateSubjectLine = (articles) => {
    const today = new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    const topStory = articles[0]?.title?.substring(0, 40) || 'Security Updates';
    return `🔒 Weekly Intel (${today}): ${topStory}...`;
};

// Generate newsletter HTML
const generateNewsletterHTML = (articles) => {
    const articlesHtml = articles.map((article, index) => {
        const imageHtml = article.image 
            ? `<td style="width: 120px; vertical-align: top; padding-right: 15px;">
                    <a href="${article.link}">
                        <img src="${article.image}" alt="" style="width: 120px; height: 80px; object-fit: cover; border-radius: 8px; border: 1px solid #2a2a3e;" />
                    </a>
               </td>`
            : `<td style="width: 50px; vertical-align: top; padding-right: 15px;">
                    <div style="width: 40px; height: 40px; background: linear-gradient(135deg, #b026ff, #6366f1); border-radius: 8px; text-align: center; line-height: 40px; color: white; font-weight: bold; font-size: 18px;">
                        ${index + 1}
                    </div>
               </td>`;
        
        return `
        <tr>
            <td style="padding: 20px 0; border-bottom: 1px solid #2a2a3e;">
                <table width="100%" cellpadding="0" cellspacing="0">
                    <tr>
                        ${imageHtml}
                        <td style="vertical-align: top;">
                            <a href="${article.link}" style="color: #ffffff; text-decoration: none; font-size: 16px; font-weight: 600; line-height: 1.4; display: block; margin-bottom: 6px;">
                                ${article.title}
                            </a>
                            <p style="color: #a0a0b0; font-size: 13px; line-height: 1.5; margin: 0 0 8px 0;">
                                ${article.tldr}
                            </p>
                            <div>
                                <span style="color: #b026ff; font-size: 11px; font-weight: 600;">${article.source}</span>
                                <span style="color: #666; font-size: 11px; margin: 0 5px;">•</span>
                                <a href="${article.link}" style="color: #6366f1; font-size: 11px; text-decoration: none;">Read more →</a>
                            </div>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    `;
    }).join('');

    return `
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; background-color: #0e0f11; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #0e0f11; padding: 40px 20px;">
        <tr>
            <td align="center">
                <table width="600" cellpadding="0" cellspacing="0" style="max-width: 600px;">
                    <!-- Header -->
                    <tr>
                        <td style="text-align: center; padding-bottom: 30px;">
                            <img src="https://infoseclabs.io/logo.png?v=2" alt="InfoSecLabs" style="height: 40px; margin-bottom: 20px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;">
                            <h1 style="color: #ffffff; font-size: 28px; margin: 0 0 10px 0;">Weekly Security Intel</h1>
                            <p style="color: #888; font-size: 14px; margin: 0;">Your TL;DR cybersecurity briefing</p>
                        </td>
                    </tr>
                    
                    <!-- Greeting -->
                    <tr>
                        <td style="padding: 20px 0;">
                            <p style="color: #cccccc; font-size: 15px; margin: 0;">
                                Hey {{name}}, 👋<br><br>
                                Here are this week's top 5 security stories you need to know:
                            </p>
                        </td>
                    </tr>
                    
                    <!-- Articles -->
                    <tr>
                        <td style="background-color: #1a1b1e; border-radius: 12px; padding: 10px 25px;">
                            <table width="100%" cellpadding="0" cellspacing="0">
                                ${articlesHtml}
                            </table>
                        </td>
                    </tr>
                    
                    <!-- CTA -->
                    <tr>
                        <td style="text-align: center; padding: 40px 0;">
                            <a href="https://infoseclabs.io/news" style="display: inline-block; background: linear-gradient(135deg, #b026ff, #6366f1); color: white; text-decoration: none; padding: 14px 30px; border-radius: 8px; font-weight: 600; font-size: 15px;">
                                Read More News →
                            </a>
                        </td>
                    </tr>
                    
                    <!-- Footer -->
                    <tr>
                        <td style="text-align: center; padding-top: 30px; border-top: 1px solid #2a2a3e;">
                            <p style="color: #666; font-size: 12px; margin: 0;">
                                You're receiving this because you subscribed to InfoSecLabs updates.<br>
                                <a href="https://infoseclabs.io/dashboard" style="color: #b026ff; text-decoration: none;">Manage preferences</a>
                            </p>
                            <p style="color: #444; font-size: 11px; margin: 15px 0 0 0;">
                                © ${new Date().getFullYear()} InfoSecLabs. All rights reserved.
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>
    `;
};
