<?php
// Resources/views/pages/leads/show.php
?>
<div class="dashboard-container">
    <header class="dashboard-header">
        <div class="header-content">
            <div class="welcome-section">
                <h1>
                    <?= htmlspecialchars($lead['full_name'] ?: ($lead['first_name'] ?? 'Lead')) ?>
                </h1>
                <p>Lead profile, AI insights, and recent activity.</p>
            </div>
            <div class="header-actions">
                <a href="/lead-management/public/app/leads"
                    style="margin-right:.5rem; text-decoration:none; font-size:.85rem; color:var(--sky-700);">
                    <i class="fas fa-arrow-left"></i> Back to Leads
                </a>
                <a href="/lead-management/public/app/leads/<?= (int)$lead['id'] ?>/edit"
                    class="btn-primary"
                    style="padding:.55rem 1.2rem; background:var(--primary); color:#fff; border-radius:var(--radius); font-weight:600; text-decoration:none; border:none; display:inline-flex; align-items:center; gap:.4rem;">
                    <i class="fas fa-pen"></i> Edit
                </a>
            </div>
        </div>
    </header>

    <div class="dashboard-grid" style="margin-top:1.5rem;">
        <!-- Left: lead info + timeline -->
        <div class="left-column">
            <!-- Lead Profile -->
            <section class="tasks-section">
                <div class="section-header">
                    <h2><i class="fas fa-user-circle"></i> Lead Profile</h2>
                </div>

                <div style="display:grid; grid-template-columns: minmax(0,1.4fr) minmax(0,1fr); gap:1.5rem;">
                    <!-- Contact info -->
                    <div>
                        <h3 style="font-size:1rem; margin-bottom:.5rem; color:var(--sky-800);">Contact</h3>
                        <div style="display:flex; flex-direction:column; gap:.3rem; font-size:.9rem;">
                            <?php if (!empty($lead['email'])): ?>
                                <div>
                                    <span style="font-weight:600; color:var(--sky-700);">Email:</span>
                                    <a href="mailto:<?= htmlspecialchars($lead['email']) ?>"
                                        style="color:var(--primary); text-decoration:none;">
                                        <?= htmlspecialchars($lead['email']) ?>
                                    </a>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($lead['phone'])): ?>
                                <div>
                                    <span style="font-weight:600; color:var(--sky-700);">Phone:</span>
                                    <span><?= htmlspecialchars($lead['phone']) ?></span>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($lead['source'])): ?>
                                <div>
                                    <span style="font-weight:600; color:var(--sky-700);">Source:</span>
                                    <span><?= htmlspecialchars($lead['source']) ?></span>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($lead['form_name'])): ?>
                                <div>
                                    <span style="font-weight:600; color:var(--sky-700);">Form:</span>
                                    <span><?= htmlspecialchars($lead['form_name']) ?></span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Company info -->
                    <div>
                        <h3 style="font-size:1rem; margin-bottom:.5rem; color:var(--sky-800);">Company</h3>
                        <div style="display:flex; flex-direction:column; gap:.3rem; font-size:.9rem;">
                            <div>
                                <span style="font-weight:600; color:var(--sky-700);">Name:</span>
                                <span>
                                    <?= $lead['company']
                                        ? htmlspecialchars($lead['company'])
                                        : '<span style="color:var(--sky-600);">Not provided</span>' ?>
                                </span>
                            </div>
                            <div>
                                <span style="font-weight:600; color:var(--sky-700);">Industry:</span>
                                <span>
                                    <?= $lead['industry']
                                        ? htmlspecialchars($lead['industry'])
                                        : '<span style="color:var(--sky-600);">Not provided</span>' ?>
                                </span>
                            </div>
                            <div>
                                <span style="font-weight:600; color:var(--sky-700);">Status:</span>
                                <?php
                                $status = $lead['status'] ?? 'new';
                                $statusClass = 'status-pill status-new';
                                if ($status === 'converted') $statusClass = 'status-pill status-converted';
                                elseif ($status === 'active') $statusClass = 'status-pill status-active';
                                elseif ($status === 'lost') $statusClass = 'status-pill status-lost';
                                ?>
                                <span class="<?= $statusClass ?>"
                                    style="display:inline-flex; align-items:center; padding:.2rem .6rem; border-radius:999px; font-size:.75rem; font-weight:600;">
                                    <?= htmlspecialchars(ucfirst($status)) ?>
                                </span>
                            </div>
                            <div>
                                <span style="font-weight:600; color:var(--sky-700);">Created:</span>
                                <span>
                                    <?= !empty($lead['created_at'])
                                        ? htmlspecialchars(date('M d, Y H:i', strtotime($lead['created_at'])))
                                        : '—' ?>
                                </span>
                            </div>
                            <div>
                                <span style="font-weight:600; color:var(--sky-700);">Last updated:</span>
                                <span>
                                    <?= !empty($lead['updated_at'])
                                        ? htmlspecialchars(date('M d, Y H:i', strtotime($lead['updated_at'])))
                                        : '—' ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Notes -->
                <div style="margin-top:1.5rem;">
                    <h3 style="font-size:1rem; margin-bottom:.5rem; color:var(--sky-800);">Internal Notes</h3>
                    <div style="border-radius:12px; border:1px solid var(--sky-200); background:#fff; padding:.75rem; font-size:.9rem; color:var(--sky-800); min-height:60px;">
                        <?= $lead['notes']
                            ? nl2br(htmlspecialchars($lead['notes']))
                            : '<span style="color:var(--sky-600);">No notes yet.</span>' ?>
                    </div>
                </div>
            </section>

            <!-- Activity Timeline -->
            <section class="reports-section">
                <div class="section-header">
                    <h2><i class="fas fa-stream"></i> Activity Timeline</h2>
                </div>

                <?php if (empty($timeline)): ?>
                    <p style="color:var(--sky-600); font-size:.9rem;">No activity recorded yet for this lead.</p>
                <?php else: ?>
                    <ul style="list-style:none; margin:0; padding:0; position:relative;">
                        <?php foreach ($timeline as $event): ?>
                            <li style="display:flex; gap:.75rem; margin-bottom:.75rem; position:relative;">
                                <div style="width:10px; display:flex; justify-content:center;">
                                    <span style="width:10px; height:10px; border-radius:999px; background:var(--primary); margin-top:4px;"></span>
                                </div>
                                <div>
                                    <div style="font-weight:600; color:var(--sky-800); font-size:.9rem;">
                                        <?= htmlspecialchars($event['label']) ?>
                                    </div>
                                    <div style="font-size:.8rem; color:var(--sky-600);">
                                        <?= htmlspecialchars(date('M d, Y H:i', strtotime($event['at']))) ?>
                                    </div>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </section>
        </div>

        <!-- Right: AI Insights -->
        <div class="right-column">
            <!-- AI Score -->
            <section class="quick-actions-section">
                <div class="section-header">
                    <h2><i class="fas fa-brain"></i> AI Lead Score</h2>
                </div>

                <?php
                $score = $lead['ai_score'] ?? null;
                $category = $lead['ai_score_category'] ?? null;
                $confidence = $lead['ai_confidence'] ?? null;

                $scoreClass = 'score-pill score-none';
                if ($score !== null) {
                    if ($score >= 80) $scoreClass = 'score-pill score-high';
                    elseif ($score >= 50) $scoreClass = 'score-pill score-medium';
                    else $scoreClass = 'score-pill score-low';
                }
                ?>
                <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:1rem;">
                    <div>
                        <div class="<?= $scoreClass ?>"
                            id="lead-score-pill"
                            style="display:inline-flex; flex-direction:column; align-items:flex-start; gap:2px; padding:.35rem .8rem; border-radius:999px; font-size:.85rem; font-weight:600;">
                            <?php if ($score !== null): ?>
                                <span><?= (int)$score ?>/100</span>
                                <?php if ($category): ?>
                                    <span style="font-size:.75rem; opacity:.8;">
                                        <?= htmlspecialchars($category) ?>
                                    </span>
                                <?php endif; ?>
                            <?php else: ?>
                                <span>No score yet</span>
                            <?php endif; ?>
                        </div>
                        <?php if ($confidence !== null): ?>
                            <div style="font-size:.8rem; color:var(--sky-600); margin-top:.3rem;">
                                Confidence: <?= round($confidence * 100) ?>%
                            </div>
                        <?php endif; ?>
                        <?php if (!empty($lead['ai_model_used'])): ?>
                            <div style="font-size:.75rem; color:var(--sky-600);">
                                Model: <?= htmlspecialchars($lead['ai_model_used']) ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div>
                        <button type="button"
                            id="btn-ai-score-detail"
                            style="border:none; background:var(--primary); color:#fff; padding:.4rem .75rem; border-radius:999px; font-size:.8rem; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:.35rem;">
                            <i class="fas fa-sync"></i> Score with AI
                        </button>
                    </div>
                </div>

                <div id="ai-score-reasoning"
                    style="border-radius:10px; border:1px dashed var(--sky-200); background:#fff; padding:.75rem; font-size:.85rem; color:var(--sky-800); min-height:60px;">
                    <?= !empty($lead['ai_score_reasoning'])
                        ? nl2br(htmlspecialchars($lead['ai_score_reasoning']))
                        : '<span style="color:var(--sky-600);">No AI reasoning yet. Click "Score with AI" to generate.</span>' ?>
                </div>
            </section>

            <!-- AI Email + Behavior -->
            <section class="progress-section">
                <div class="section-header">
                    <h2><i class="fas fa-magic"></i> AI Tools</h2>
                </div>

                <div style="display:flex; flex-direction:column; gap:1rem;">
                    <!-- Generate Email -->
                    <div>
                        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:.4rem;">
                            <div style="font-weight:600; color:var(--sky-800); font-size:.9rem;">
                                Smart Email Draft
                            </div>
                            <button type="button"
                                id="btn-ai-email-detail"
                                style="border:none; background:rgba(14,165,233,0.1); color:var(--sky-700); padding:.35rem .7rem; border-radius:999px; font-size:.8rem; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:.3rem;">
                                <i class="fas fa-envelope"></i> Generate
                            </button>
                        </div>
                        <textarea id="ai-email-detail"
                            placeholder="Click Generate to create an email draft for this lead…"
                            style="width:100%; min-height:140px; border-radius:10px; border:1px solid var(--sky-200); padding:.6rem; font-size:.85rem; resize:vertical;"></textarea>
                        <?php if (!empty($lead['last_email_generated'])): ?>
                            <div style="font-size:.75rem; color:var(--sky-600); margin-top:.25rem;">
                                Last AI email: <?= htmlspecialchars(date('M d, Y H:i', strtotime($lead['last_email_generated']))) ?>
                                (<?= (int)($lead['email_generation_count'] ?? 0) ?> total)
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Behavior Analysis -->
                    <div>
                        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:.4rem;">
                            <div style="font-weight:600; color:var(--sky-800); font-size:.9rem;">
                                Behavior & Follow-up Ideas
                            </div>
                            <button type="button"
                                id="btn-ai-behavior-detail"
                                style="border:none; background:rgba(16,185,129,0.1); color:var(--success); padding:.35rem .7rem; border-radius:999px; font-size:.8rem; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:.3rem;">
                                <i class="fas fa-lightbulb"></i> Analyze
                            </button>
                        </div>
                        <div id="ai-behavior-detail"
                            style="border-radius:10px; border:1px dashed var(--sky-200); background:#fff; padding:.6rem; font-size:.85rem; color:var(--sky-800); min-height:100px;">
                            <span style="color:var(--sky-600);">
                                Click "Analyze" to let AI summarize this lead’s behavior and suggest next steps.
                            </span>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const leadId = <?= (int)$lead['id'] ?>;
        const baseUrl = '/lead-management/public';

        const btnScore = document.getElementById('btn-ai-score-detail');
        const scorePill = document.getElementById('lead-score-pill');
        const scoreReason = document.getElementById('ai-score-reasoning');

        const btnEmail = document.getElementById('btn-ai-email-detail');
        const emailArea = document.getElementById('ai-email-detail');

        const btnBehavior = document.getElementById('btn-ai-behavior-detail');
        const behaviorBox = document.getElementById('ai-behavior-detail');

        function setScoreUI(scorePayload) {
            const s = scorePayload.score ?? scorePayload?.data?.score ?? null;
            const category = scorePayload.category ?? scorePayload?.data?.category ?? null;
            const reasoning = scorePayload.reasoning ?? scorePayload?.data?.reasoning ?? 'No reasoning provided';

            let scoreVal = s;
            if (typeof s === 'object' && s.score !== undefined) {
                scoreVal = s.score;
            }

            const score = Number(scoreVal);
            scorePill.textContent = '';

            if (!isNaN(score)) {
                const main = document.createElement('span');
                main.textContent = Math.round(score) + '/100';
                scorePill.appendChild(main);

                if (category) {
                    const cat = document.createElement('span');
                    cat.textContent = category;
                    cat.style.fontSize = '.75rem';
                    cat.style.opacity = '0.8';
                    scorePill.appendChild(cat);
                }
            } else {
                scorePill.textContent = 'No score yet';
            }

            scorePill.className = 'score-pill';
            if (isNaN(score)) {
                scorePill.classList.add('score-none');
            } else if (score >= 80) {
                scorePill.classList.add('score-high');
            } else if (score >= 50) {
                scorePill.classList.add('score-medium');
            } else {
                scorePill.classList.add('score-low');
            }

            scoreReason.innerHTML = reasoning ?
                reasoning.replace(/\n/g, '<br>') :
                '<span style="color:var(--sky-600);">No reasoning provided.</span>';
        }

        // Score with AI
        if (btnScore) {
            btnScore.addEventListener('click', async () => {
                btnScore.disabled = true;
                const original = btnScore.textContent;
                btnScore.textContent = 'Scoring…';

                try {
                    const res = await fetch(`${baseUrl}/app/leads/${leadId}/score`, {
                        method: 'POST'
                    });
                    const data = await res.json();

                    if (!data.success || !data.score) {
                        alert(data.error || 'Failed to score lead');
                    } else {
                        setScoreUI(data.score);
                    }
                } catch (e) {
                    alert('Error calling AI scoring');
                } finally {
                    btnScore.disabled = false;
                    btnScore.textContent = original;
                }
            });
        }

        // Generate email
        if (btnEmail) {
            btnEmail.addEventListener('click', async () => {
                btnEmail.disabled = true;
                const original = btnEmail.textContent;
                btnEmail.textContent = 'Generating…';

                try {
                    const res = await fetch(`${baseUrl}/app/leads/${leadId}/generate-email`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            email_type: 'follow_up'
                        })
                    });
                    const data = await res.json();

                    if (!data.success) {
                        alert(data.error || 'Failed to generate email');
                    } else {
                        const content = data.email_content || {};
                        const body = content.body || JSON.stringify(content, null, 2);
                        emailArea.value = body;
                        emailArea.focus();
                    }
                } catch (e) {
                    alert('Error generating email');
                } finally {
                    btnEmail.disabled = false;
                    btnEmail.textContent = original;
                }
            });
        }

        // Behavior analysis
        if (btnBehavior) {
            btnBehavior.addEventListener('click', async () => {
                btnBehavior.disabled = true;
                const original = btnBehavior.textContent;
                btnBehavior.textContent = 'Analyzing…';

                try {
                    const res = await fetch(`${baseUrl}/app/leads/${leadId}/analyze-behavior`);
                    const data = await res.json();

                    if (!data.success) {
                        alert(data.error || 'Failed to analyze behavior');
                    } else {
                        const analysis = data.analysis || {};
                        let text = '';

                        if (typeof analysis === 'string') {
                            text = analysis;
                        } else if (analysis.summary || analysis.next_steps) {
                            if (analysis.summary) {
                                text += 'Summary:\n' + analysis.summary + '\n\n';
                            }
                            if (analysis.next_steps) {
                                text += 'Suggested next steps:\n' + analysis.next_steps;
                            }
                        } else {
                            text = JSON.stringify(analysis, null, 2);
                        }

                        behaviorBox.innerHTML = text ?
                            text.replace(/\n/g, '<br>') :
                            '<span style="color:var(--sky-600);">No analysis provided.</span>';
                    }
                } catch (e) {
                    alert('Error analyzing behavior');
                } finally {
                    btnBehavior.disabled = false;
                    btnBehavior.textContent = original;
                }
            });
        }
    });
</script>

<style>
    /* reuse small pill helpers here too */
    .status-pill {
        background: var(--sky-100);
        color: var(--sky-700);
    }

    .status-new {
        background: rgba(59, 130, 246, 0.1);
        color: var(--primary);
    }

    .status-active {
        background: rgba(14, 165, 233, 0.12);
        color: var(--sky-700);
    }

    .status-converted {
        background: rgba(16, 185, 129, 0.12);
        color: var(--success);
    }

    .status-lost {
        background: rgba(239, 68, 68, 0.12);
        color: var(--danger);
    }

    .score-pill {
        background: var(--sky-100);
        color: var(--sky-700);
    }

    .score-high {
        background: rgba(16, 185, 129, 0.1);
        color: var(--success);
    }

    .score-medium {
        background: rgba(245, 158, 11, 0.1);
        color: var(--warning);
    }

    .score-low {
        background: rgba(239, 68, 68, 0.1);
        color: var(--danger);
    }

    .score-none {
        background: var(--sky-100);
        color: var(--sky-600);
    }
</style>