<?php
// Expected from controller (all optional, view is defensive):
// $lead          = [...]
// $events        = [...] (behavior timeline)
// $scoreHistory  = [['date' => 'YYYY-MM-DD', 'score' => 82], ...]
// $aiInsights    = "string from AI"
// $aiNextActions = ["Bullet 1", "Bullet 2", ...]

$lead  = $lead  ?? [];
$events = $events ?? [];
$scoreHistory = $scoreHistory ?? [];
$aiInsights = $aiInsights ?? '';
$aiNextActions = $aiNextActions ?? [];

$leadName  = trim(($lead['first_name'] ?? '') . ' ' . ($lead['last_name'] ?? ''));
if ($leadName === '') {
    $leadName = $lead['full_name'] ?? 'Lead #'.($lead['id'] ?? '');
}
$leadEmail = $lead['email'] ?? $lead['email_address'] ?? null;
$currentScore = $lead['ai_score'] ?? $lead['score'] ?? null;
?>
<div class="dashboard-container">
    <style>
        .lead-header {
            background: rgba(255,255,255,0.9);
            backdrop-filter: blur(18px);
            border-radius: 16px;
            padding: 1.5rem 2rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 8px 20px rgba(15, 23, 42, 0.08);
            border: 1px solid rgba(255,255,255,0.9);
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 1rem;
        }
        .lead-header-main {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        .lead-avatar {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1.1rem;
        }
        .lead-header-title {
            font-size: 1.4rem;
            font-weight: 700;
            color: var(--sky-900);
        }
        .lead-header-subtitle {
            color: var(--sky-700);
            font-size: 0.9rem;
        }
        .lead-header-actions .btn-primary {
            padding: 0.6rem 1.3rem;
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: 999px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }
        .lead-header-actions .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
            box-shadow: 0 8px 18px rgba(37,99,235,0.35);
        }

        .lead-layout {
            display: grid;
            grid-template-columns: 1.2fr 2fr;
            gap: 1.5rem;
        }
        @media (max-width: 1024px) {
            .lead-layout {
                grid-template-columns: 1fr;
            }
        }

        .lead-card {
            background: linear-gradient(135deg, rgba(255,255,255,0.98), rgba(240,249,255,0.98));
            border-radius: 16px;
            padding: 1.5rem 1.75rem;
            box-shadow: 0 8px 24px rgba(15,23,42,0.08);
            border: 1px solid rgba(255,255,255,0.9);
            position: relative;
            overflow: hidden;
        }
        .lead-card::before {
            content: "";
            position: absolute;
            top: 0; left: 0;
            width: 100%; height: 4px;
            background: linear-gradient(90deg, var(--primary-light), var(--primary));
            background-size: 200% 100%;
            animation: leadGradientShift 4s ease infinite;
        }
        .lead-card h2 {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--sky-800);
            margin-bottom: 0.75rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .lead-card h2 i {
            color: var(--primary);
        }

        .lead-detail-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.9rem;
        }
        @media (max-width: 700px) {
            .lead-detail-grid {
                grid-template-columns: 1fr;
            }
        }
        .lead-detail-item {
            background: rgba(255,255,255,0.98);
            border-radius: 12px;
            padding: 0.8rem 0.9rem;
            border: 1px solid var(--sky-100);
        }
        .lead-detail-label {
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: .06em;
            color: var(--sky-600);
            margin-bottom: 0.15rem;
        }
        .lead-detail-value {
            font-size: 0.95rem;
            font-weight: 600;
            color: var(--sky-900);
        }

        .lead-score-pill {
            display: inline-flex;
            align-items: center;
            gap: 0.35rem;
            padding: 0.25rem 0.7rem;
            border-radius: 999px;
            font-size: 0.8rem;
            font-weight: 700;
        }
        .lead-score-high {
            background: rgba(16,185,129,0.12);
            color: #059669;
        }
        .lead-score-medium {
            background: rgba(245,158,11,0.12);
            color: #b45309;
        }
        .lead-score-low {
            background: rgba(239,68,68,0.12);
            color: #b91c1c;
        }

        .lead-score-chart {
            margin-top: 1rem;
        }
        .score-bars {
            display: flex;
            align-items: flex-end;
            gap: 0.3rem;
            height: 130px;
            padding-bottom: 0.4rem;
        }
        .score-bar {
            flex: 1;
            min-width: 6px;
            border-radius: 999px 999px 0 0;
            background: var(--sky-200);
            position: relative;
            overflow: hidden;
        }
        .score-bar-inner {
            position: absolute;
            left: 0; right: 0; bottom: 0;
            height: 0;
            border-radius: inherit;
            background: linear-gradient(180deg, var(--primary-light), var(--primary));
            transform-origin: bottom;
            transform: scaleY(0);
        }
        .score-bar-labels {
            display: flex;
            justify-content: space-between;
            gap: 0.3rem;
            font-size: 0.7rem;
            color: var(--sky-700);
        }

        .timeline-card::before {
            background: linear-gradient(90deg, var(--sky-400), var(--sky-600));
        }
        .timeline {
            position: relative;
            margin-top: 0.5rem;
        }
        .timeline::before {
            content: "";
            position: absolute;
            left: 12px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: var(--sky-200);
        }
        .timeline-item {
            position: relative;
            padding-left: 2.2rem;
            padding-bottom: 1rem;
        }
        .timeline-dot {
            position: absolute;
            left: 7px;
            width: 10px;
            height: 10px;
            border-radius: 999px;
            background: var(--primary);
            box-shadow: 0 0 0 4px rgba(59,130,246,0.18);
            top: 4px;
        }
        .timeline-title {
            font-weight: 600;
            color: var(--sky-900);
            font-size: 0.9rem;
        }
        .timeline-meta {
            font-size: 0.78rem;
            color: var(--sky-600);
            margin-top: 0.15rem;
        }
        .timeline-note {
            font-size: 0.8rem;
            color: var(--sky-700);
            margin-top: 0.25rem;
        }

        .ai-insights-card::before {
            background: linear-gradient(90deg, var(--success), var(--primary));
        }
        .ai-insights-body {
            font-size: 0.9rem;
            color: var(--sky-800);
            white-space: pre-wrap;
        }
        .ai-actions-list {
            margin-top: 0.75rem;
            padding-left: 1rem;
            font-size: 0.88rem;
            color: var(--sky-800);
        }
        .ai-actions-list li {
            margin-bottom: 0.35rem;
        }

        .lead-empty {
            padding: 1rem;
            text-align: center;
            color: var(--sky-700);
            font-size: 0.9rem;
        }

        @keyframes leadGradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
    </style>

    <header class="lead-header">
        <div class="lead-header-main">
            <div class="lead-avatar">
                <?php
                    $initials = '';
                    $parts = explode(' ', $leadName);
                    foreach ($parts as $p) {
                        $p = trim($p);
                        if ($p !== '') $initials .= mb_strtoupper(mb_substr($p, 0, 1));
                        if (mb_strlen($initials) >= 2) break;
                    }
                    echo htmlspecialchars($initials ?: 'L');
                ?>
            </div>
            <div>
                <div class="lead-header-title">
                    <?= htmlspecialchars($leadName) ?>
                </div>
                <div class="lead-header-subtitle">
                    <?= $leadEmail ? htmlspecialchars($leadEmail) : 'No email on record' ?>
                </div>
            </div>
        </div>
        <div class="lead-header-actions">
            <button type="button" class="btn-primary"
                    onclick="window.location.href='/lead-management/public/app/leads'">
                ← Back to Leads
            </button>
        </div>
    </header>

    <div class="lead-layout">
        <!-- LEFT: lead snapshot & score history -->
        <section class="lead-card">
            <h2><i class="fas fa-user-circle"></i> Lead snapshot</h2>
            <div class="lead-detail-grid">
                <div class="lead-detail-item">
                    <div class="lead-detail-label">Lead ID</div>
                    <div class="lead-detail-value">
                        <?= htmlspecialchars((string)($lead['id'] ?? '—')) ?>
                    </div>
                </div>
                <div class="lead-detail-item">
                    <div class="lead-detail-label">Status</div>
                    <div class="lead-detail-value">
                        <?= htmlspecialchars(ucfirst($lead['status'] ?? 'unknown')) ?>
                    </div>
                </div>
                <div class="lead-detail-item">
                    <div class="lead-detail-label">AI score</div>
                    <div class="lead-detail-value">
                        <?php if ($currentScore !== null): ?>
                            <?php
                                $scoreInt = (int)$currentScore;
                                if ($scoreInt >= 80) {
                                    $cls = 'lead-score-pill lead-score-high';
                                    $label = 'High priority';
                                } elseif ($scoreInt >= 50) {
                                    $cls = 'lead-score-pill lead-score-medium';
                                    $label = 'Warm';
                                } else {
                                    $cls = 'lead-score-pill lead-score-low';
                                    $label = 'Low priority';
                                }
                            ?>
                            <span class="<?= $cls ?>">
                                <?= $scoreInt ?> / 100 · <?= $label ?>
                            </span>
                        <?php else: ?>
                            —
                        <?php endif; ?>
                    </div>
                </div>
                <div class="lead-detail-item">
                    <div class="lead-detail-label">Source</div>
                    <div class="lead-detail-value">
                        <?= htmlspecialchars($lead['source'] ?? $lead['utm_source'] ?? '—') ?>
                    </div>
                </div>
                <div class="lead-detail-item">
                    <div class="lead-detail-label">Created</div>
                    <div class="lead-detail-value">
                        <?= htmlspecialchars($lead['created_at'] ?? '—') ?>
                    </div>
                </div>
                <div class="lead-detail-item">
                    <div class="lead-detail-label">Last updated</div>
                    <div class="lead-detail-value">
                        <?= htmlspecialchars($lead['updated_at'] ?? '—') ?>
                    </div>
                </div>
            </div>

            <div class="lead-score-chart">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.4rem;">
                    <div style="font-size:0.86rem;font-weight:600;color:var(--sky-800);">
                        Score history
                    </div>
                    <div style="font-size:0.78rem;color:var(--sky-600);">
                        Based on previous AI scoring runs
                    </div>
                </div>

                <?php if (!empty($scoreHistory)): ?>
                    <?php
                        if (count($scoreHistory) > 14) {
                            $scoreHistory = array_slice($scoreHistory, -14);
                        }
                        $maxScore = 0;
                        foreach ($scoreHistory as $p) {
                            $v = (int)($p['score'] ?? 0);
                            if ($v > $maxScore) $maxScore = $v;
                        }
                        if ($maxScore < 1) $maxScore = 100; // avoid div by zero
                    ?>
                    <div class="score-bars" id="score-bars" data-max="<?= (int)$maxScore ?>">
                        <?php foreach ($scoreHistory as $p): ?>
                            <?php $v = (int)($p['score'] ?? 0); ?>
                            <div class="score-bar" data-score="<?= $v ?>">
                                <div class="score-bar-inner"></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="score-bar-labels">
                        <?php foreach ($scoreHistory as $p): ?>
                            <?php
                                $label = $p['date'] ?? $p['created_at'] ?? '';
                                $label = substr((string)$label, 5);
                            ?>
                            <span><?= htmlspecialchars($label) ?></span>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="lead-empty">
                        No score history yet. Try running AI scoring for this lead a couple of times.
                    </div>
                <?php endif; ?>
            </div>
        </section>

        <!-- RIGHT: timeline + AI insights -->
        <section class="lead-card timeline-card">
            <h2><i class="fas fa-stream"></i> Behavior timeline</h2>
            <?php if (empty($events)): ?>
                <div class="lead-empty">
                    No behavior events recorded for this lead yet.  
                    Once tracking is wired (page views, email opens, form interactions), they’ll appear here.
                </div>
            <?php else: ?>
                <div class="timeline">
                    <?php foreach ($events as $evt): ?>
                        <?php
                            $etype = $evt['type'] ?? $evt['event_type'] ?? 'event';
                            $when  = $evt['occurred_at'] ?? $evt['created_at'] ?? $evt['time'] ?? '';
                            $note  = $evt['description'] ?? $evt['detail'] ?? $evt['note'] ?? '';
                            $meta  = [];
                            foreach (['url', 'page', 'source', 'campaign'] as $mk) {
                                if (!empty($evt[$mk])) $meta[] = ucfirst($mk).': '.$evt[$mk];
                            }
                        ?>
                        <div class="timeline-item">
                            <div class="timeline-dot"></div>
                            <div class="timeline-title">
                                <?= htmlspecialchars(ucfirst(str_replace('_', ' ', $etype))) ?>
                            </div>
                            <div class="timeline-meta">
                                <?= htmlspecialchars($when ?: 'Unknown time') ?>
                                <?php if (!empty($meta)): ?>
                                    · <?= htmlspecialchars(implode(' · ', $meta)) ?>
                                <?php endif; ?>
                            </div>
                            <?php if ($note): ?>
                                <div class="timeline-note">
                                    <?= htmlspecialchars($note) ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>

        <section class="lead-card ai-insights-card" style="grid-column: 1 / -1;">
            <h2><i class="fas fa-brain"></i> AI behavior analysis</h2>

            <?php if ($aiInsights): ?>
                <div class="ai-insights-body">
                    <?= nl2br(htmlspecialchars($aiInsights)) ?>
                </div>
            <?php else: ?>
                <div class="lead-empty" style="text-align:left;">
                    No AI analysis text provided yet.  
                    You can have <code>LeadsController@analyzeBehavior</code> call your <code>AIService</code>
                    and pass a summary string as <code>$aiInsights</code>.
                </div>
            <?php endif; ?>

            <?php if (!empty($aiNextActions)): ?>
                <ul class="ai-actions-list">
                    <?php foreach ($aiNextActions as $item): ?>
                        <li><?= htmlspecialchars($item) ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php else: ?>
                <div class="ai-actions-list" style="list-style:none;padding-left:0;">
                    <div style="font-size:0.8rem;color:var(--sky-600);margin-top:0.5rem;">
                        Tip: pass an array of recommended next steps in <code>$aiNextActions</code>
                        to show a prioritized playbook here.
                    </div>
                </div>
            <?php endif; ?>
        </section>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const barsContainer = document.getElementById('score-bars');
    if (!barsContainer) return;
    const max = parseInt(barsContainer.dataset.max || '100', 10) || 100;
    const bars = barsContainer.querySelectorAll('.score-bar');

    bars.forEach(bar => {
        const s = parseInt(bar.dataset.score || '0', 10);
        const pct = Math.max(0, Math.min(100, (s / max) * 100));
        const inner = bar.querySelector('.score-bar-inner');
        if (!inner) return;
        setTimeout(() => {
            inner.style.height = pct + '%';
            inner.style.transform = 'scaleY(1)';
        }, 200);
    });
});
</script>
