<script>
(function () {
    const BASE = '/lead-management/public';

    // Simple toast
    function showToast(message, type = 'info') {
        let container = document.getElementById('ai-toast-container');
        if (!container) {
            container = document.createElement('div');
            container.id = 'ai-toast-container';
            container.style.position = 'fixed';
            container.style.right = '1.5rem';
            container.style.bottom = '1.5rem';
            container.style.zIndex = '9999';
            container.style.display = 'flex';
            container.style.flexDirection = 'column';
            container.style.gap = '.5rem';
            document.body.appendChild(container);
        }

        const toast = document.createElement('div');
        toast.textContent = message;
        toast.style.padding = '.6rem .9rem';
        toast.style.borderRadius = '999px';
        toast.style.fontSize = '.82rem';
        toast.style.fontWeight = '600';
        toast.style.boxShadow = '0 8px 18px rgba(15,23,42,0.25)';
        toast.style.color = '#0f172a';
        toast.style.background = type === 'error'
            ? '#fee2e2'
            : (type === 'success' ? '#dcfce7' : '#e0f2fe');
        container.appendChild(toast);

        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(4px)';
            toast.style.transition = 'all .25s ease';
            setTimeout(() => toast.remove(), 260);
        }, 2500);
    }

    // Minimal email modal
    function ensureEmailModal() {
        let modal = document.getElementById('ai-email-modal');
        if (modal) return modal;

        modal = document.createElement('div');
        modal.id = 'ai-email-modal';
        modal.style.position = 'fixed';
        modal.style.inset = '0';
        modal.style.background = 'rgba(15,23,42,0.45)';
        modal.style.display = 'none';
        modal.style.alignItems = 'center';
        modal.style.justifyContent = 'center';
        modal.style.zIndex = '9998';

        modal.innerHTML = `
            <div style="
                background:#ffffff;
                max-width:640px;
                width:94%;
                border-radius:16px;
                box-shadow:0 20px 45px rgba(15,23,42,0.35);
                padding:1.4rem 1.6rem;
                display:flex;
                flex-direction:column;
                gap:.75rem;
                max-height:80vh;
            ">
                <div style="display:flex;justify-content:space-between;align-items:center;gap:.5rem;">
                    <div style="font-weight:700;color:#0f172a;">AI-generated follow-up email</div>
                    <button type="button" id="ai-email-close"
                        style="border:none;background:transparent;font-size:1.1rem;cursor:pointer;color:#64748b;">
                        ✕
                    </button>
                </div>
                <textarea id="ai-email-body" readonly
                    style="flex:1;min-height:260px;border-radius:12px;border:1px solid #e2e8f0;
                           padding:.75rem .9rem;font-size:.9rem;resize:vertical;"></textarea>
                <div style="display:flex;justify-content:flex-end;gap:.5rem;">
                    <button type="button" id="ai-email-copy"
                        style="border:none;border-radius:999px;padding:.4rem .9rem;font-size:.82rem;
                               font-weight:600;cursor:pointer;background:#e0f2fe;color:#0369a1;">
                        Copy to clipboard
                    </button>
                    <button type="button" id="ai-email-ok"
                        style="border:none;border-radius:999px;padding:.4rem 1rem;font-size:.82rem;
                               font-weight:600;cursor:pointer;background:#3b82f6;color:white;">
                        Close
                    </button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        const close = () => { modal.style.display = 'none'; };

        modal.addEventListener('click', e => {
            if (e.target === modal) close();
        });
        modal.querySelector('#ai-email-close').addEventListener('click', close);
        modal.querySelector('#ai-email-ok').addEventListener('click', close);
        modal.querySelector('#ai-email-copy').addEventListener('click', async () => {
            const ta = modal.querySelector('#ai-email-body');
            try {
                await navigator.clipboard.writeText(ta.value);
                showToast('Email copied to clipboard', 'success');
            } catch {
                ta.select();
                showToast('Select + copy manually (clipboard blocked)', 'info');
            }
        });

        return modal;
    }

    async function postJSON(url, data = {}) {
        const res = await fetch(url, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json'
            },
            credentials: 'same-origin',
            body: JSON.stringify(data)
        });
        let json;
        try {
            json = await res.json();
        } catch (e) {
            throw new Error('Invalid JSON response');
        }
        if (!res.ok || json.success === false) {
            throw new Error(json.error || 'Request failed');
        }
        return json;
    }

    function attachLeadAiHandlers() {
        const scoreButtons = document.querySelectorAll('.btn-score-lead');
        const emailButtons = document.querySelectorAll('.btn-generate-email');

        scoreButtons.forEach(btn => {
            if (btn.dataset.aiBound === '1') return;
            btn.dataset.aiBound = '1';

            btn.addEventListener('click', async () => {
                const id = btn.getAttribute('data-lead-id');
                if (!id) return;

                const originalText = btn.textContent;
                btn.disabled = true;
                btn.textContent = 'Scoring…';

                try {
                    const url = `${BASE}/app/leads/${id}/score`;
                    const json = await postJSON(url, {});
                    const score = json.score ?? json.ai_score ?? null;

                    if (score !== null) {
                        const scoreSpan = document.querySelector(
                            `.lead-score-value[data-lead-score-id="${id}"]`
                        );
                        if (scoreSpan) {
                            scoreSpan.textContent = parseInt(score, 10);
                        }
                        showToast(`Lead #${id} scored: ${score}/100`, 'success');
                    } else {
                        showToast('Scored, but response did not contain score field.', 'info');
                    }
                } catch (err) {
                    console.error(err);
                    showToast(err.message || 'Failed to score lead.', 'error');
                } finally {
                    btn.disabled = false;
                    btn.textContent = originalText;
                }
            });
        });

        emailButtons.forEach(btn => {
            if (btn.dataset.aiBound === '1') return;
            btn.dataset.aiBound = '1';

            btn.addEventListener('click', async () => {
                const id = btn.getAttribute('data-lead-id');
                if (!id) return;

                const originalText = btn.textContent;
                btn.disabled = true;
                btn.textContent = 'Generating…';

                try {
                    const url = `${BASE}/app/leads/${id}/generate-email`;
                    const json = await postJSON(url, {});
                    const emailText =
                        json.email_html ||
                        json.email_text ||
                        json.email ||
                        '';

                    if (!emailText) {
                        showToast('No email text returned from server.', 'error');
                    } else {
                        const modal = ensureEmailModal();
                        modal.querySelector('#ai-email-body').value = emailText;
                        modal.style.display = 'flex';
                        showToast(`Email generated for lead #${id}`, 'success');
                    }
                } catch (err) {
                    console.error(err);
                    showToast(err.message || 'Failed to generate email.', 'error');
                } finally {
                    btn.disabled = false;
                    btn.textContent = originalText;
                }
            });
        });
    }

    document.addEventListener('DOMContentLoaded', attachLeadAiHandlers);
})();
</script>
