// =============================================
// sp-ui.js — UI rendering, audio, badges, toasts
// =============================================
import { state } from './sp-state.js';

let _messagesEl, _statusText, _chatInput, _getSendMessage;
let audioCtx = null;
let _alertTimeout = null;
let _toastContainer = null;

export function showToast(message, type = 'info', duration = 5000) {
    if (!_toastContainer) {
        _toastContainer = document.createElement('div');
        _toastContainer.id = 'pidgey-toast-container';
        _toastContainer.style.cssText = 'position:fixed;top:12px;right:12px;z-index:99999;display:flex;flex-direction:column;gap:8px;pointer-events:none;max-width:340px;';
        document.body.appendChild(_toastContainer);
    }

    const colors = {
        success: { bg: 'linear-gradient(135deg,#059669,#10b981)', icon: '\u2705', border: '#059669' },
        error:   { bg: 'linear-gradient(135deg,#dc2626,#ef4444)', icon: '\u274c', border: '#dc2626' },
        warning: { bg: 'linear-gradient(135deg,#d97706,#f59e0b)', icon: '\u26a0\ufe0f', border: '#d97706' },
        info:    { bg: 'linear-gradient(135deg,#2563eb,#3b82f6)', icon: '\ud83d\udc26', border: '#2563eb' }
    };
    const c = colors[type] || colors.info;

    const toast = document.createElement('div');
    toast.style.cssText = `pointer-events:auto;background:${c.bg};color:white;padding:10px 14px;border-radius:10px;font-size:12px;font-weight:600;line-height:1.4;box-shadow:0 8px 24px rgba(0,0,0,0.25);display:flex;align-items:flex-start;gap:8px;animation:pidgeyToastIn 0.3s ease;cursor:pointer;max-width:340px;word-wrap:break-word;`;
    toast.innerHTML = `<span style="font-size:16px;flex-shrink:0;">${c.icon}</span><div style="flex:1;">${message}</div>`;
    toast.addEventListener('click', () => dismissToast(toast));

    _toastContainer.appendChild(toast);

    const styleId = 'pidgey-toast-keyframes';
    if (!document.getElementById(styleId)) {
        const style = document.createElement('style');
        style.id = styleId;
        style.textContent = '@keyframes pidgeyToastIn{from{opacity:0;transform:translateX(40px)}to{opacity:1;transform:translateX(0)}}@keyframes pidgeyToastOut{from{opacity:1;transform:translateX(0)}to{opacity:0;transform:translateX(40px)}}';
        document.head.appendChild(style);
    }

    if (duration > 0) {
        setTimeout(() => dismissToast(toast), duration);
    }
    return toast;
}

function dismissToast(toast) {
    if (!toast || !toast.parentNode) return;
    toast.style.animation = 'pidgeyToastOut 0.25s ease forwards';
    setTimeout(() => toast.remove(), 260);
}

export function initUI(els, getSendMessage) {
    _messagesEl = els.messagesEl;
    _statusText = els.statusText;
    _chatInput = els.chatInput;
    _getSendMessage = getSendMessage;
    document.addEventListener('click', initAudio, { once: true });
    document.addEventListener('keydown', initAudio, { once: true });
    window.addEventListener('focus', clearAlertBadge);
    document.addEventListener('click', clearAlertBadge);
    document.addEventListener('keydown', clearAlertBadge);
    document.addEventListener('mousemove', () => {
        clearTimeout(_alertTimeout);
        _alertTimeout = setTimeout(clearAlertBadge, 300);
    });
}

export function setStatus(text) { if (_statusText) _statusText.textContent = text; }

export function escapeHtml(str) {
    const d = document.createElement('div');
    d.textContent = str;
    return d.innerHTML;
}

export function formatMessage(text) {
    text = text.replace(/\[FOLLOWUP:[^\]]*\]/g, '').trim();
    const links = [];
    const codeBlocks = [];

    let withPH = text.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) => {
        const i = codeBlocks.length;
        codeBlocks.push(`<pre style="background:#1e293b;color:#e2e8f0;padding:14px 16px;border-radius:8px;overflow-x:auto;font-size:12px;line-height:1.5;margin:8px 0;border-left:3px solid #3b82f6;"><code>${escapeHtml(code.trim())}</code></pre>`);
        return `\x00C${i}\x00`;
    });

    withPH = withPH.replace(/!\[(.*?)\]\((https?:\/\/[^)]+)\)/g, (_, alt, url) => {
        const i = links.length;
        links.push(`<img src="${url}" alt="${escapeHtml(alt)}" style="max-width:100%; border-radius:8px; margin-top:8px; margin-bottom:8px;" />`);
        return `\x00L${i}\x00`;
    });
    withPH = withPH.replace(/\[(.*?)\]\((https?:\/\/[^)]+)\)/g, (_, label, url) => {
        const i = links.length;
        links.push(`<a href="${url}" target="_blank" rel="noopener" style="color:#3b82f6;text-decoration:underline;">${escapeHtml(label)}</a>`);
        return `\x00L${i}\x00`;
    });

    let r = escapeHtml(withPH);

    r = r.replace(/^(#{1,4})\s+(.+)$/gm, (_, hashes, content) => {
        const level = hashes.length;
        const sizes = { 1: '1.5em', 2: '1.25em', 3: '1.1em', 4: '1em' };
        const colors = { 1: '#0f172a', 2: '#1e40af', 3: '#334155', 4: '#475569' };
        const borders = { 1: 'border-bottom:2px solid #3b82f6;padding-bottom:6px;', 2: 'border-bottom:1px solid #e2e8f0;padding-bottom:4px;', 3: '', 4: '' };
        return `<div style="font-size:${sizes[level]};font-weight:800;color:${colors[level]};margin:16px 0 8px 0;${borders[level]}">${content}</div>`;
    });

    r = r.replace(/^---+$/gm, '<hr style="border:none;border-top:2px solid #e2e8f0;margin:16px 0;">');

    r = r.replace(/^&gt;\s?(.+)$/gm, '<div style="border-left:4px solid #3b82f6;padding:8px 12px;margin:8px 0;background:#eff6ff;border-radius:0 8px 8px 0;color:#1e40af;font-style:italic;">$1</div>');

    const tableBlocks = [];
    r = r.replace(/(\|.+\|[\s\S]*?\|.+\|)(?:\n|$)/g, (match) => {
        const rows = match.trim().split('\n').filter(row => row.trim());
        const isAlignRow = (row) => /^\|[\s:|-]+\|$/.test(row.trim());
        let headerRow = null;
        const dataRows = [];
        for (let i = 0; i < rows.length; i++) {
            if (isAlignRow(rows[i])) continue;
            const cells = rows[i].split('|').slice(1, -1).map(c => c.trim());
            if (!headerRow && i < 2) { headerRow = cells; } else { dataRows.push(cells); }
        }
        if (!headerRow || dataRows.length === 0) return match;
        const thHtml = headerRow.map(h => `<th style="padding:8px 12px;background:#1e40af;color:white;font-weight:700;text-align:left;font-size:12px;text-transform:uppercase;letter-spacing:0.5px;">${h}</th>`).join('');
        const trHtml = dataRows.map((row, idx) => {
            const bg = idx % 2 === 0 ? '#f8fafc' : '#ffffff';
            return `<tr style="background:${bg};">${row.map(c => `<td style="padding:8px 12px;border-bottom:1px solid #e2e8f0;font-size:13px;">${c}</td>`).join('')}</tr>`;
        }).join('');
        const tIdx = tableBlocks.length;
        tableBlocks.push(`<div style="overflow-x:auto;margin:12px 0;border-radius:8px;border:1px solid #e2e8f0;"><table style="width:100%;border-collapse:collapse;">${thHtml ? `<thead><tr>${thHtml}</tr></thead>` : ''}<tbody>${trHtml}</tbody></table></div>`);
        return `\x00T${tIdx}\x00`;
    });

    r = r
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code style="background:#dbeafe;color:#1e40af;padding:2px 6px;border-radius:4px;font-size:12px;font-weight:600;">$1</code>');

    r = r.replace(/\n/g, '<br>');

    r = r.replace(/\x00L(\d+)\x00/g, (_, i) => links[+i]);
    r = r.replace(/\x00C(\d+)\x00/g, (_, i) => codeBlocks[+i]);
    r = r.replace(/\x00T(\d+)\x00/g, (_, i) => tableBlocks[+i]);
    return r;
}

export function formatReport(text, title) {
    const body = formatMessage(text);
    return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${escapeHtml(title || 'Pidgey Report')}</title>
<style>
:root {
    --blue-50: #eff6ff; --blue-100: #dbeafe; --blue-500: #3b82f6; --blue-600: #2563eb; --blue-700: #1d4ed8; --blue-900: #1e3a5f;
    --slate-50: #f8fafc; --slate-100: #f1f5f9; --slate-200: #e2e8f0; --slate-300: #cbd5e1; --slate-600: #475569; --slate-700: #334155; --slate-800: #1e293b; --slate-900: #0f172a;
    --green-50: #f0fdf4; --green-500: #22c55e; --green-700: #15803d;
    --amber-50: #fffbeb; --amber-500: #f59e0b; --amber-700: #b45309;
    --red-50: #fef2f2; --red-500: #ef4444; --red-700: #b91c1c;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
    background: linear-gradient(135deg, var(--slate-100) 0%, var(--blue-50) 100%);
    color: var(--slate-800); line-height: 1.7; padding: 40px 20px;
    min-height: 100vh;
}
.report-wrapper {
    max-width: 900px; margin: 0 auto;
}
.report-header {
    background: linear-gradient(135deg, var(--blue-700) 0%, var(--slate-900) 100%);
    color: white; padding: 32px 40px; border-radius: 16px 16px 0 0;
    position: relative; overflow: hidden;
}
.report-header::before {
    content: ''; position: absolute; top: -50%; right: -20%; width: 300px; height: 300px;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
    border-radius: 50%;
}
.report-header h1 {
    font-size: 1.8em; font-weight: 800; margin-bottom: 4px; position: relative;
}
.report-header .subtitle {
    font-size: 0.85em; opacity: 0.8; font-weight: 400; position: relative;
}
.report-header .pidgey-badge {
    position: absolute; top: 24px; right: 32px; background: rgba(255,255,255,0.15);
    padding: 6px 14px; border-radius: 20px; font-size: 12px; font-weight: 700;
    backdrop-filter: blur(4px); letter-spacing: 0.5px;
}
.report-body {
    background: white; padding: 40px; border-radius: 0 0 16px 16px;
    box-shadow: 0 20px 60px rgba(0,0,0,0.08);
}
.report-body strong { color: var(--slate-900); }
.report-body a { color: var(--blue-600); text-decoration: none; border-bottom: 1px solid var(--blue-100); transition: border-color 0.2s; }
.report-body a:hover { border-bottom-color: var(--blue-500); }
.report-body hr { border: none; border-top: 2px solid var(--slate-200); margin: 24px 0; }
.report-body pre {
    background: var(--slate-900) !important; color: #e2e8f0 !important;
    padding: 20px !important; border-radius: 10px !important; margin: 16px 0 !important;
    border-left: 4px solid var(--blue-500) !important; font-size: 13px !important;
    overflow-x: auto;
}
.report-body code {
    background: var(--blue-100) !important; color: var(--blue-700) !important;
    padding: 2px 8px !important; border-radius: 4px !important;
    font-weight: 600 !important; font-size: 13px !important;
}
.report-body table {
    width: 100%; border-collapse: collapse; margin: 16px 0;
    border-radius: 8px; overflow: hidden; border: 1px solid var(--slate-200);
}
.report-body table th {
    background: linear-gradient(135deg, var(--blue-700), var(--blue-600));
    color: white; padding: 10px 14px; text-align: left; font-size: 12px;
    text-transform: uppercase; letter-spacing: 0.5px; font-weight: 700;
}
.report-body table td { padding: 10px 14px; border-bottom: 1px solid var(--slate-100); font-size: 13px; }
.report-body table tr:nth-child(even) { background: var(--slate-50); }
.report-body table tr:hover { background: var(--blue-50); }

.metric-row { display: flex; gap: 16px; margin: 16px 0; flex-wrap: wrap; }
.metric-card {
    flex: 1; min-width: 140px; padding: 16px; border-radius: 10px;
    text-align: center; border: 1px solid var(--slate-200);
    background: linear-gradient(to bottom, white, var(--slate-50));
}
.metric-card .metric-value { font-size: 1.8em; font-weight: 800; color: var(--blue-700); line-height: 1.2; }
.metric-card .metric-label { font-size: 11px; color: var(--slate-600); text-transform: uppercase; letter-spacing: 0.5px; margin-top: 4px; }

.status-green { color: var(--green-700); background: var(--green-50); padding: 2px 8px; border-radius: 4px; font-weight: 700; font-size: 12px; }
.status-amber { color: var(--amber-700); background: var(--amber-50); padding: 2px 8px; border-radius: 4px; font-weight: 700; font-size: 12px; }
.status-red { color: var(--red-700); background: var(--red-50); padding: 2px 8px; border-radius: 4px; font-weight: 700; font-size: 12px; }

.bar-chart { margin: 16px 0; }
.bar-row { display: flex; align-items: center; margin: 6px 0; }
.bar-label { width: 120px; font-size: 12px; font-weight: 600; color: var(--slate-700); text-align: right; padding-right: 12px; }
.bar-track { flex: 1; height: 24px; background: var(--slate-100); border-radius: 6px; overflow: hidden; position: relative; }
.bar-fill { height: 100%; border-radius: 6px; background: linear-gradient(90deg, var(--blue-500), var(--blue-700)); transition: width 0.6s ease; display: flex; align-items: center; justify-content: flex-end; padding-right: 8px; }
.bar-value { font-size: 11px; font-weight: 700; color: white; }

.section-card {
    background: var(--slate-50); border: 1px solid var(--slate-200);
    border-radius: 10px; padding: 20px; margin: 16px 0;
    border-left: 4px solid var(--blue-500);
}
.section-card.green { border-left-color: var(--green-500); background: var(--green-50); }
.section-card.amber { border-left-color: var(--amber-500); background: var(--amber-50); }
.section-card.red { border-left-color: var(--red-500); background: var(--red-50); }

.report-footer {
    text-align: center; padding: 20px; color: var(--slate-300);
    font-size: 11px; margin-top: 12px;
}
@media print {
    body { background: white; padding: 0; }
    .report-header { border-radius: 0; }
    .report-body { box-shadow: none; border-radius: 0; }
}
</style>
</head>
<body>
<div class="report-wrapper">
    <div class="report-header">
        <div class="pidgey-badge">PIDGEY REPORT</div>
        <h1>${escapeHtml(title || 'Report')}</h1>
        <div class="subtitle">Generated ${new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })} by Pidgey Assist</div>
    </div>
    <div class="report-body">
        ${body}
    </div>
    <div class="report-footer">
        Pidgey Assist &mdash; Your AI-Powered Browser Companion
    </div>
</div>
</body>
</html>`;
}

export function scrollToBottom() {
    requestAnimationFrame(() => { _messagesEl.scrollTop = _messagesEl.scrollHeight; });
}

export function addUserMessage(text) {
    const div = document.createElement('div');
    div.className = 'message user';
    div.innerHTML = `<div class="message-bubble">${escapeHtml(text)}</div>`;
    _messagesEl.appendChild(div);
    scrollToBottom();
}

export function addBotMessage(text, { followups = [], saveResearch = false } = {}) {
    const cleanText = text.replace(/\[FOLLOWUP:[^\]]*\]/g, '').trim();
    const fuMatch = text.match(/\[FOLLOWUP:([^\]]+)\]/);
    const chips = followups.length ? followups
        : (fuMatch ? fuMatch[1].split('|').map(q => q.trim()).filter(Boolean) : []);

    const div = document.createElement('div');
    div.className = 'message bot';
    let html = `
        <div class="message-bubble" style="position:relative; padding-right: 32px;">
            ${formatMessage(cleanText)}
            <div style="position:absolute; top:8px; right:6px; display:flex; flex-direction:column; gap:4px;">
                <button class="copy-btn" title="Copy text" style="background:rgba(255,255,255,0.4); border:none; cursor:pointer; font-size:12px; border-radius:4px; padding:3px; transition:all 0.2s;">📋</button>
                <button class="share-btn" title="Share to X (Twitter)" data-text="${escapeHtml(cleanText)}" style="background:rgba(255,255,255,0.4); border:none; cursor:pointer; font-size:12px; border-radius:4px; padding:3px; transition:all 0.2s;">🐦</button>
                <button class="medium-btn" title="Publish to Medium/Substack" data-text="${escapeHtml(cleanText)}" style="background:rgba(255,255,255,0.4); border:none; cursor:pointer; font-size:12px; border-radius:4px; padding:3px; transition:all 0.2s;">✍️</button>
            </div>
        </div>`;
    if (chips.length) {
        html += `<div class="followup-chips">${chips.map(q =>
            `<button class="followup-chip" data-q="${escapeHtml(q)}">${escapeHtml(q)}</button>`
        ).join('')}</div>`;
    }
    div.innerHTML = html;
    div.querySelectorAll('.copy-btn').forEach(btn => {
        btn.addEventListener('mouseover', () => btn.style.background = 'white');
        btn.addEventListener('mouseout', () => btn.style.background = 'rgba(255,255,255,0.4)');
        btn.addEventListener('click', () => {
            navigator.clipboard.writeText(btn.parentElement.parentElement.innerText.replace('📋', '').replace('✅', '').replace('🐦', '').replace('⏳', '').replace('❌', '').trim());
            btn.innerHTML = '✅';
            setTimeout(() => btn.innerHTML = '📋', 2000);
        });
    });
    div.querySelectorAll('.share-btn').forEach(btn => {
        btn.addEventListener('mouseover', () => btn.style.background = 'white');
        btn.addEventListener('mouseout', () => btn.style.background = 'rgba(255,255,255,0.4)');
        btn.addEventListener('click', async () => {
            btn.innerHTML = '⏳';
            try { 
                await generateTwitterCardImage(btn.getAttribute('data-text') || cleanText); 
                btn.innerHTML = '✅'; 
            } catch(e) { 
                btn.innerHTML = '❌'; 
            }
            setTimeout(() => btn.innerHTML = '🐦', 3000);
        });
    });
    div.querySelectorAll('.followup-chip').forEach(btn => {
        btn.addEventListener('click', () => {
            _chatInput.value = btn.dataset.q;
            _chatInput.focus();
            _getSendMessage()();
        });
    });
    _messagesEl.appendChild(div);
    scrollToBottom();

    if (saveResearch && cleanText.length > 100) {
        try {
            chrome.storage.local.get(['pidgey_research_history'], res => {
                const h = res.pidgey_research_history || [];
                h.unshift({ date: new Date().toISOString(), url: state.currentUrl || '', summary: cleanText.substring(0, 500) });
                chrome.storage.local.set({ pidgey_research_history: h.slice(0, 20) });
            });
        } catch { }
    }
    try {
        if (chrome.action && !document.hasFocus()) {
            chrome.action.setBadgeText({ text: '1' });
            chrome.action.setBadgeBackgroundColor({ color: '#2563eb' });
            chrome.action.setTitle({ title: `Pidgey: ${cleanText.replace(/[*_#>]/g, '').trim().substring(0, 60)}...` });
        }
    } catch { }
}

export function addErrorMessage(text) {
    const div = document.createElement('div');
    div.className = 'message bot error';
    div.innerHTML = `<div class="message-bubble">${formatMessage(text)}</div>`;
    _messagesEl.appendChild(div);
    scrollToBottom();
}

export function addThinking() {
    const div = document.createElement('div');
    div.className = 'message bot';
    div.innerHTML = `<div class="message-bubble thinking"><span></span><span></span><span></span></div>`;
    _messagesEl.appendChild(div);
    scrollToBottom();
    return div;
}

export function renderSavedMessages(history) {
    _messagesEl.innerHTML = '';
    for (const msg of history) {
        const text = msg.parts?.[0]?.text || '';
        if (!text) continue;
        const div = document.createElement('div');
        div.className = `message ${msg.role === 'user' ? 'user' : 'bot'}`;

        let htmlContent = msg.role === 'user' ? escapeHtml(text) : formatMessage(text);
        if (msg.role === 'model' || msg.role === 'bot') {
            htmlContent = `
            <div style="position:relative; padding-right: 32px;">
                ${htmlContent}
                <div style="position:absolute; top:8px; right:6px; display:flex; flex-direction:column; gap:4px;">
                    <button class="copy-btn" title="Copy text" style="background:rgba(255,255,255,0.4); border:none; cursor:pointer; font-size:12px; border-radius:4px; padding:3px; transition:all 0.2s;">📋</button>
                    <button class="share-btn" title="Share to X (Twitter)" data-text="${escapeHtml(text)}" style="background:rgba(255,255,255,0.4); border:none; cursor:pointer; font-size:12px; border-radius:4px; padding:3px; transition:all 0.2s;">🐦</button>
                    <button class="medium-btn" title="Publish to Medium/Substack" data-text="${escapeHtml(text)}" style="background:rgba(255,255,255,0.4); border:none; cursor:pointer; font-size:12px; border-radius:4px; padding:3px; transition:all 0.2s;">✍️</button>
                </div>
            </div>`;
        }

        div.innerHTML = `<div class="message-bubble">${htmlContent}</div>`;
        div.querySelectorAll('.copy-btn').forEach(btn => {
            btn.addEventListener('mouseover', () => btn.style.background = 'white');
            btn.addEventListener('mouseout', () => btn.style.background = 'rgba(255,255,255,0.4)');
            btn.addEventListener('click', () => {
                navigator.clipboard.writeText(btn.parentElement.parentElement.innerText.replace('📋', '').replace('✅', '').replace('🐦', '').replace('⏳', '').replace('❌', '').trim());
                btn.innerHTML = '✅';
                setTimeout(() => btn.innerHTML = '📋', 2000);
            });
        });
        div.querySelectorAll('.share-btn').forEach(btn => {
            btn.addEventListener('mouseover', () => btn.style.background = 'white');
            btn.addEventListener('mouseout', () => btn.style.background = 'rgba(255,255,255,0.4)');
            btn.addEventListener('click', async () => {
                btn.innerHTML = '⏳';
                try { 
                    await generateTwitterCardImage(btn.getAttribute('data-text') || text); 
                    btn.innerHTML = '✅'; 
                } catch(e) { 
                    btn.innerHTML = '❌'; 
                }
                setTimeout(() => btn.innerHTML = '🐦', 3000);
            });
        });
        div.querySelectorAll('.medium-btn').forEach(btn => {
            btn.addEventListener('mouseover', () => btn.style.background = 'white');
            btn.addEventListener('mouseout', () => btn.style.background = 'rgba(255,255,255,0.4)');
            btn.addEventListener('click', () => {
                const txt = btn.getAttribute('data-text') || text;
                const article = txt.replace(/\[FOLLOWUP:[^\]]*\]/g, '').trim() + '\n\n---\n*Written in 3 minutes with [Pidgey Assist AI](https://pidgeyassist.com).*';
                navigator.clipboard.writeText(article);
                btn.innerHTML = '✅';
                setTimeout(() => btn.innerHTML = '✍️', 2000);
                chrome.tabs.create({ url: 'https://medium.com/new-story' });
            });
        });
        _messagesEl.appendChild(div);
    }
    scrollToBottom();
}

export function initAudio() {
    if (!audioCtx) {
        const AC = window.AudioContext || window.webkitAudioContext;
        if (AC) audioCtx = new AC();
    }
    if (audioCtx?.state === 'suspended') audioCtx.resume();
}

export function playAudioAlert(type) {
    try {
        if (!audioCtx) initAudio();
        if (!audioCtx || audioCtx.state === 'suspended') return;
        const osc = audioCtx.createOscillator(), gain = audioCtx.createGain();
        osc.connect(gain); gain.connect(audioCtx.destination);
        if (type === 'chirp') {
            osc.type = 'sine';
            osc.frequency.setValueAtTime(800, audioCtx.currentTime);
            osc.frequency.exponentialRampToValueAtTime(1200, audioCtx.currentTime + 0.1);
            gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.1);
            osc.start(); osc.stop(audioCtx.currentTime + 0.1);
        } else if (type === 'action') {
            osc.type = 'triangle';
            osc.frequency.setValueAtTime(600, audioCtx.currentTime);
            gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.1);
            osc.start();
            setTimeout(() => {
                try {
                    const o2 = audioCtx.createOscillator(), g2 = audioCtx.createGain();
                    o2.connect(g2); g2.connect(audioCtx.destination);
                    o2.type = 'triangle'; o2.frequency.setValueAtTime(900, audioCtx.currentTime);
                    g2.gain.setValueAtTime(0.1, audioCtx.currentTime);
                    g2.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.1);
                    o2.start(); o2.stop(audioCtx.currentTime + 0.1);
                } catch { }
            }, 100);
            osc.stop(audioCtx.currentTime + 0.1);
        } else if (type === 'success') {
            osc.type = 'sine';
            [440, 554.37, 659.25, 880].forEach((f, i) => osc.frequency.setValueAtTime(f, audioCtx.currentTime + i * 0.1));
            gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
            gain.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 0.5);
            osc.start(); osc.stop(audioCtx.currentTime + 0.5);
        }
    } catch { }
}

function clearAlertBadge() {
    try { if (chrome.action) { chrome.action.setBadgeText({ text: '' }); chrome.action.setTitle({ title: 'Pidgey Assist' }); } } catch { }
}

export async function generateTwitterCardImage(text) {
    const canvas = document.createElement('canvas');
    canvas.width = 1200;
    canvas.height = 630;
    const ctx = canvas.getContext('2d');
    
    // Background
    const grd = ctx.createLinearGradient(0, 0, 1200, 630);
    grd.addColorStop(0, '#0f172a'); 
    grd.addColorStop(1, '#020617');
    ctx.fillStyle = grd;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // Watermark
    ctx.shadowColor = '#38bdf8';
    ctx.shadowBlur = 40;
    ctx.fillStyle = '#38bdf8';
    ctx.font = 'bold 36px "Segoe UI", system-ui, sans-serif';
    ctx.fillText('🦅 Pidgey Assist', 60, 60);
    ctx.shadowBlur = 0;
    
    // Clean text
    let cleanText = text.replace(/\[FOLLOWUP:[^\]]*\]/g, '').replace(/[*_#>`]/g, '').trim();
    if (cleanText.length > 800) cleanText = cleanText.substring(0, 800) + '...';

    // Wrap text
    ctx.fillStyle = '#f8fafc';
    ctx.font = '32px "Segoe UI", system-ui, sans-serif';
    const maxWidth = 1080;
    const lineHeight = 46;
    let y = 140;
    
    const paragraphs = cleanText.split('\n');
    for (let p = 0; p < paragraphs.length; p++) {
        let words = paragraphs[p].split(' ');
        let line = '';
        for (let n = 0; n < words.length; n++) {
            let testLine = line + words[n] + ' ';
            let metrics = ctx.measureText(testLine);
            if (metrics.width > maxWidth && n > 0) {
                ctx.fillText(line, 60, y);
                line = words[n] + ' ';
                y += lineHeight;
            } else {
                line = testLine;
            }
        }
        ctx.fillText(line, 60, y);
        y += lineHeight + 20; 
        if (y > 520) break;
    }
    
    // Footer
    ctx.fillStyle = '#64748b';
    ctx.font = '24px "Segoe UI", system-ui, sans-serif';
    ctx.fillText('No subscriptions. Bring your own API key. pidgeyassist.com', 60, 580);

    return new Promise((resolve, reject) => {
        canvas.toBlob(async blob => {
            if (!blob) return reject("Blob failed");
            try {
                const item = new ClipboardItem({ "image/png": blob });
                await navigator.clipboard.write([item]);
                const tweetText = encodeURIComponent("🦅 Analyzed by @PidgeyAssist.\nNo monthly subs, bring your own API key.\n\nhttps://pidgeyassist.com");
                chrome.tabs.create({ url: `https://twitter.com/intent/tweet?text=${tweetText}` });
                resolve();
            } catch (err) { reject(err); }
        });
    });
}
