<?php
$callsList        = $calls ?? [];
$callBaseUrl      = $callInitiateUrl ?? site_url('/leads/call/initiate');
$askAiUrl         = $askAiUrl ?? site_url('/chat/ask-call-transcript');
$cloudtalkReady   = $cloudtalkConfigured ?? true;
$syncUrl          = $syncCallsUrl ?? '';
$statusBadgeMap   = [
    'initiated' => 'bg-blue-100 text-blue-700 border-blue-200',
    'ringing'   => 'bg-amber-100 text-amber-700 border-amber-200',
    'answered'  => 'bg-sky-100 text-sky-700 border-sky-200',
    'ended'     => 'bg-emerald-100 text-emerald-700 border-emerald-200',
    'missed'    => 'bg-rose-100 text-rose-700 border-rose-200',
    'failed'    => 'bg-red-100 text-red-700 border-red-200',
    'canceled'  => 'bg-slate-100 text-slate-700 border-slate-200',
];

$callsDeduped = [];
$seen = [];
foreach ($callsList as $rowOrig) {
    $c = (array) ($rowOrig['call'] ?? $rowOrig);
    $dest = preg_replace('/\D+/', '', (string)($c['destination_number'] ?? ''));
    $tsStr = (string)($c['started_at'] ?? $c['created_at'] ?? '');
    $minuteKey = $tsStr !== '' ? date('YmdHi', strtotime($tsStr) ?: 0) : '0';
    $ctId = (string)($c['cloudtalk_call_id'] ?? '');
    $richness = 0;
    $richness += !empty($c['talk_time_seconds']) ? 5 : 0;
    $richness += !empty($c['duration_seconds']) ? 2 : 0;
    $richness += !empty($c['result']) ? 2 : 0;
    $richness += !empty($c['ended_at']) ? 1 : 0;
    $richness += !empty($rowOrig['transcript']) && !empty($rowOrig['transcript']['transcript_text']) ? 10 : 0;
    $richness += !empty($rowOrig['recording']) && !empty($rowOrig['recording']['recording_url']) ? 8 : 0;
    $sRaw = (string)($c['status'] ?? '');
    $numericStatus = ctype_digit($sRaw);
    $richness += $numericStatus ? -3 : 0;

    if ($ctId !== '') {
        $key = 'ct|' . $ctId;
        if (!isset($seen[$key]) || $richness > $seen[$key]['r']) {
            $seen[$key] = ['i' => count($callsDeduped), 'r' => $richness];
            $callsDeduped[] = $rowOrig;
            continue;
        }
        if ($richness > $seen[$key]['r']) {
            $callsDeduped[$seen[$key]['i']] = $rowOrig;
        }
        continue;
    }
    if ($dest !== '' && $minuteKey !== '0') {
        $key = 'p|' . $dest . '|' . $minuteKey;
        if (!isset($seen[$key]) || $richness > $seen[$key]['r']) {
            $seen[$key] = ['i' => count($callsDeduped), 'r' => $richness];
            $callsDeduped[] = $rowOrig;
            continue;
        }
        if ($richness > $seen[$key]['r']) {
            $callsDeduped[$seen[$key]['i']] = $rowOrig;
        }
        continue;
    }
    $callsDeduped[] = $rowOrig;
}
$callsList = $callsDeduped;

$sanitizeStatus = static function ($raw, $default = 'initiated') {
    $s = trim((string)$raw);
    if ($s === '' || ctype_digit($s)) return $default;
    $sLower = strtolower($s);
    if (str_contains($sLower, 'start') || str_contains($sLower, 'initiated') || str_contains($sLower, 'queue')) return 'ringing';
    if (str_contains($sLower, 'answer')) return 'answered';
    if (str_contains($sLower, 'end') || str_contains($sLower, 'hangup') || str_contains($sLower, 'complete') || str_contains($sLower, 'success') || str_contains($sLower, 'done') || str_contains($sLower, 'finish')) return 'ended';
    if (str_contains($sLower, 'miss') || str_contains($sLower, 'no_answer')) return 'missed';
    if (str_contains($sLower, 'fail') || str_contains($sLower, 'error')) return 'failed';
    if (str_contains($sLower, 'cancel')) return 'canceled';
    if (str_contains($sLower, 'in_progress') || str_contains($sLower, 'active')) return 'answered';
    return in_array($sLower, ['ringing','answered','ended','missed','failed','canceled','initiated'], true) ? $sLower : $default;
};
?>
<div class="glass rounded-2xl p-6 shadow-sm border border-slate-200/60">
    <div class="flex items-center justify-between mb-5 flex-wrap gap-3">
        <div class="flex items-center gap-3">
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-sky-500 to-indigo-600 flex items-center justify-center shadow-sm">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                </svg>
            </div>
            <div>
                <h4 class="text-sm font-bold text-slate-800">Call History</h4>
                <p class="text-xs text-slate-500"><?= count($callsList) ?> call<?= count($callsList) !== 1 ? 's' : '' ?> logged</p>
            </div>
        </div>
        <div class="flex items-center gap-2 flex-wrap">
            <?php if ($cloudtalkReady && $syncUrl !== ''): ?>
                <button type="button" id="btn-sync-calls"
                    class="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold text-white bg-gradient-to-r from-sky-500 to-indigo-600 hover:from-sky-600 hover:to-indigo-700 shadow-sm shadow-sky-500/20 transition disabled:opacity-60 disabled:cursor-not-allowed">
                    <svg id="btn-sync-icon" xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                    </svg>
                    <span id="btn-sync-label">Sync Call History</span>
                </button>
            <?php endif; ?>
            <?php if (empty($cloudtalkReady)): ?>
                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold bg-amber-50 border border-amber-200 text-amber-700">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                    </svg>
                    CloudTalk not configured yet
                </span>
            <?php endif; ?>
        </div>
    </div>

    <?php if (empty($callsList)): ?>
        <div class="py-14 text-center">
            <div class="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center mx-auto mb-4">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
                </svg>
            </div>
            <p class="text-sm font-semibold text-slate-700">No calls yet</p>
            <p class="text-xs text-slate-500 mt-1">Click <span class="font-semibold text-emerald-600">Call Lead</span> above to start the first call.</p>
        </div>
    <?php else: ?>
        <div class="space-y-4">
            <?php foreach ($callsList as $idx => $row): ?>
                <?php
                    $call       = $row['call'] ?? [];
                    $transcript = $row['transcript'] ?? null;
                    $recording  = $row['recording'] ?? null;
                    $callId     = (int) ($call['id'] ?? 0);
                    $rawStatus  = (string) ($call['status'] ?? 'initiated');
                    $status     = $sanitizeStatus($rawStatus, 'initiated');
                    $badgeClass = $statusBadgeMap[$status] ?? 'bg-slate-100 text-slate-700 border-slate-200';
                    $duration   = (int) ($call['talk_time_seconds'] ?? $call['duration_seconds'] ?? 0);
                    $durMin     = floor($duration / 60);
                    $durSec     = $duration % 60;
                    $startedAt  = !empty($call['started_at'] ?? $call['created_at']) ? strtotime((string)($call['started_at'] ?? $call['created_at'])) : null;
                    $summary    = trim((string) ($transcript['ai_summary'] ?? ''));
                    $summaryStatus = (string) ($transcript['ai_summary_status'] ?? 'pending');
                    $audioDirectUrl = (string) ($recording['recording_url'] ?? '');
                    $recordingDbId  = (int) ($recording['id'] ?? 0);
                    $ctCallId       = trim((string) ($call['cloudtalk_call_id'] ?? ''));
                    $audioProxyUrl  = '';
                    if ($recordingDbId > 0) {
                        $audioProxyUrl = site_url('/call/recording/' . $recordingDbId);
                    } elseif ($ctCallId !== '') {
                        $audioProxyUrl = site_url('/call/recording/ct/' . rawurlencode($ctCallId));
                    }
                    $audioUrl = $audioProxyUrl !== '' ? $audioProxyUrl : $audioDirectUrl;
                    $audioUrlForExternal = $audioProxyUrl !== '' ? $audioProxyUrl : $audioDirectUrl;
                    $segments   = [];
                    if (!empty($transcript['speaker_segments'])) {
                        $dec = json_decode((string)$transcript['speaker_segments'], true);
                        if (is_array($dec)) {
                            $segments = $dec;
                        }
                    }
                    $raw = null;
                    $ciSentiment = '';
                    $ciSentimentScore = null;
                    $ciTopics = [];
                    $ciSmartNotes = [];
                    $ciTalkListen = [];
                    if (!empty($transcript['raw_json'])) {
                        $decRaw = json_decode((string)$transcript['raw_json'], true);
                        if (is_array($decRaw)) {
                            $raw = $decRaw;
                            if (!empty($decRaw['sentiment']) && is_array($decRaw['sentiment'])) {
                                $ciSentiment = trim((string) ($decRaw['sentiment']['overall_sentiment'] ?? ''));
                                if (isset($decRaw['sentiment']['sentiment_score'])) $ciSentimentScore = (int)$decRaw['sentiment']['sentiment_score'];
                            }
                            if (!empty($decRaw['topics']) && is_array($decRaw['topics'])) {
                                $ciTopics = $decRaw['topics'];
                            }
                            if (!empty($decRaw['smart_notes']) && is_array($decRaw['smart_notes'])) {
                                $ciSmartNotes = $decRaw['smart_notes'];
                            }
                            if (!empty($decRaw['talk_listen_ratio']) && is_array($decRaw['talk_listen_ratio'])) {
                                $ciTalkListen = $decRaw['talk_listen_ratio'];
                            }
                            if ($segments === [] && !empty($decRaw['transcript_raw']['data']['segments']) && is_array($decRaw['transcript_raw']['data']['segments'])) {
                                $rawSegs = $decRaw['transcript_raw']['data']['segments'];
                                $callers = $decRaw['transcript_raw']['data']['callers'] ?? [];
                                $callerMap = [];
                                if (is_array($callers)) {
                                    foreach ($callers as $cc) {
                                        if (is_array($cc) && isset($cc['localIdentifier']) && isset($cc['type'])) {
                                            $callerMap[(string)$cc['localIdentifier']] = (string)$cc['type'];
                                        }
                                    }
                                }
                                foreach ($rawSegs as $rs) {
                                    if (!is_array($rs)) continue;
                                    $speakerId = (string) ($rs['caller'] ?? '');
                                    $speakerType = $callerMap[$speakerId] ?? $speakerId;
                                    $speakerLabel = $speakerType === 'agent' ? 'Agent' : ($speakerType === 'contact' ? 'Contact' : ucfirst($speakerType));
                                    $segments[] = [
                                        'speaker' => $speakerLabel,
                                        'speaker_type' => $speakerType,
                                        'start'   => $rs['start'] ?? 0,
                                        'end'     => $rs['end']   ?? 0,
                                        'text'    => (string) ($rs['text'] ?? ''),
                                        'caller_id' => $speakerId,
                                    ];
                                }
                            }
                        }
                    }
                    $sentimentBadge = '';
                    if ($ciSentiment !== '') {
                        $sMap = [
                            'very positive' => 'bg-emerald-100 text-emerald-700 border-emerald-200',
                            'positive'      => 'bg-emerald-50  text-emerald-700 border-emerald-200',
                            'neutral'       => 'bg-slate-100   text-slate-700   border-slate-200',
                            'negative'      => 'bg-rose-50     text-rose-700    border-rose-200',
                            'very negative' => 'bg-rose-100   text-rose-700    border-rose-200',
                        ];
                        $cls = $sMap[mb_strtolower($ciSentiment)] ?? 'bg-slate-100 text-slate-700 border-slate-200';
                        $sentimentBadge = '<span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider border ' . $cls . '" title="CI Overall Sentiment: ' . esc($ciSentiment) . '">' . esc($ciSentiment) . '</span>';
                    }
                    $ciSummaryBadge = '';
                    if ($summaryStatus === 'cloudtalk') {
                        $ciSummaryBadge = '<span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-indigo-50 text-indigo-700 border border-indigo-200" title="Generated by CloudTalk Conversation Intelligence">CI Summary</span>';
                    } elseif ($summaryStatus === 'done') {
                        $ciSummaryBadge = '<span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-violet-50 text-violet-700 border border-violet-200">Assistant</span>';
                    }
                ?>
                <div class="border border-slate-200 rounded-2xl bg-white/60 hover:bg-white transition overflow-hidden">
                    <div class="px-5 py-4 flex flex-wrap items-center gap-3 justify-between">
                        <div class="flex items-center gap-3 min-w-0 flex-1">
                            <div class="w-10 h-10 rounded-xl bg-slate-100 flex items-center justify-center flex-shrink-0">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-slate-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                            </div>
                            <div class="min-w-0">
                                <div class="flex flex-wrap items-center gap-2">
                                    <span class="text-sm font-semibold text-slate-800">
                                        <?= esc(ucfirst((string)($call['direction'] ?? 'outbound'))) ?> call
                                        to <span class="font-mono text-slate-700"><?= esc($call['destination_number'] ?? '—') ?></span>
                                    </span>
                                    <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold border <?= $badgeClass ?>">
                                        <?= esc(ucfirst($status)) ?>
                                    </span>
                                </div>
                                <div class="flex flex-wrap items-center gap-x-3 gap-y-1 mt-0.5 text-xs text-slate-500">
                                    <?php if ($startedAt): ?>
                                        <span><?= date('M j, Y g:i A', $startedAt) ?></span>
                                    <?php endif; ?>
                                    <span>
                                        Agent: <span class="font-medium text-slate-700"><?= esc($call['agent_name'] ?? $call['agent_username'] ?? 'Unknown') ?></span>
                                    </span>
                                    <?php if ($duration > 0): ?>
                                        <span>Talk: <span class="font-medium text-slate-700"><?= $durMin ?>m <?= str_pad((string)$durSec, 2, '0', STR_PAD_LEFT) ?>s</span></span>
                                    <?php endif; ?>
                                    <?php if (!empty($call['result'])): ?>
                                        <span>Result: <span class="font-medium text-slate-700"><?= esc($call['result']) ?></span></span>
                                    <?php endif; ?>
                                    <?php if (!empty($call['disposition'])): ?>
                                        <span>Disposition: <span class="font-medium text-slate-700"><?= esc($call['disposition']) ?></span></span>
                                    <?php endif; ?>
                                    <?php if ($sentimentBadge !== ''): ?>
                                        <span class="ml-1"><?= $sentimentBadge ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <button type="button" data-toggle="call-expand-<?= $callId ?>"
                                class="call-expand inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 bg-slate-100 hover:bg-slate-200 transition">
                            <span data-toggle-label="call-expand-<?= $callId ?>">Show details</span>
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 transition-transform" data-toggle-arrow="call-expand-<?= $callId ?>" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                            </svg>
                        </button>
                    </div>

                    <div id="call-expand-<?= $callId ?>" class="border-t border-slate-100 p-5 space-y-5 hidden">

                        <?php if ($audioUrl !== ''): ?>
                            <div>
                                <div class="flex items-center gap-2 mb-2">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-rose-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15.536a5 5 0 011.414 1.414m2.828-9.9a9 9 0 012.828 12.728" />
                                    </svg>
                                    <h6 class="text-xs font-bold text-slate-700 uppercase tracking-wider">Recording</h6>
                                    <?php if ($audioDirectUrl !== '' && $audioProxyUrl !== '' && $audioDirectUrl !== $audioProxyUrl): ?>
                                        <span class="text-[10px] font-semibold text-slate-400 uppercase tracking-wider ml-auto" title="Proxied through local server to avoid CORS/auth issues">via proxy</span>
                                    <?php endif; ?>
                                </div>
                                <audio controls preload="auto" class="w-full h-11 rounded-xl bg-slate-50 border border-slate-200">
                                    <source src="<?= esc($audioUrl) ?>" type="audio/wav">
                                    <source src="<?= esc($audioUrl) ?>" type="audio/mpeg">
                                    <source src="<?= esc($audioUrl) ?>" type="application/octet-stream">
                                </audio>
                                <div class="mt-1 flex justify-between items-center gap-3 flex-wrap">
                                    <div class="text-[11px] text-slate-500 leading-snug">
                                        If the player shows 0:00, click “Open in new tab” or the “Sync Call History” button above to refresh the recording link.
                                    </div>
                                    <a href="<?= esc($audioUrlForExternal) ?>" target="_blank" rel="noopener noreferrer" class="text-[11px] text-blue-600 font-medium hover:underline whitespace-nowrap">Open recording in new tab →</a>
                                </div>
                            </div>
                        <?php elseif (($call['enable_recording'] ?? 1) && $status === 'ended'): ?>
                            <div class="p-3 rounded-xl bg-slate-50 border border-slate-100 text-xs text-slate-500 flex items-center gap-2">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                Recording not available yet. CloudTalk is probably still processing.
                            </div>
                        <?php endif; ?>

                        <div>
                            <div class="flex items-center gap-2 mb-2">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-indigo-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                </svg>
                                <h6 class="text-xs font-bold text-slate-700 uppercase tracking-wider">Transcript</h6>
                                <?php if (!empty($transcript)): ?>
                                    <span class="text-[10px] font-semibold text-slate-400 uppercase tracking-wider ml-auto">
                                        <?= esc(strtoupper($transcript['language'] ?? 'EN')) ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                            <?php if (!empty($transcript) && trim((string)$transcript['transcript_text']) !== ''): ?>
                                <div class="max-h-80 overflow-y-auto rounded-xl bg-slate-50/80 border border-slate-100 p-4 scrollbar-thin">
                                    <?php if (!empty($segments)): ?>
                                        <div class="space-y-3">
                                            <?php foreach ($segments as $seg):
                                                $speaker = (string) ($seg['speaker'] ?? $seg['role'] ?? 'Agent');
                                                $text    = (string) ($seg['text'] ?? $seg['content'] ?? '');
                                                $time    = (string) ($seg['time'] ?? $seg['start'] ?? '');
                                                $isAgent = (stripos($speaker, 'agent') !== false || stripos($speaker, 'user') !== false);
                                            ?>
                                                <div class="flex gap-3">
                                                    <div class="w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center text-[11px] font-bold text-white <?= $isAgent ? 'bg-sky-500' : 'bg-violet-500' ?>">
                                                        <?= esc(strtoupper(substr($speaker, 0, 1))) ?>
                                                    </div>
                                                    <div class="flex-1 min-w-0">
                                                        <div class="flex items-center gap-2 text-[11px] font-semibold text-slate-500 mb-0.5">
                                                            <span><?= esc($speaker) ?></span>
                                                            <?php if ($time !== ''): ?>
                                                                <span class="text-slate-400 font-mono"><?= esc($time) ?></span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <p class="text-sm text-slate-700 leading-relaxed whitespace-pre-wrap"><?= esc($text) ?></p>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <p class="text-sm text-slate-700 leading-relaxed whitespace-pre-wrap"><?= esc((string)$transcript['transcript_text']) ?></p>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <div class="p-3 rounded-xl bg-slate-50 border border-slate-100 text-xs text-slate-600 space-y-2">
                                    <div class="flex items-start gap-2">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-amber-500 mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                        </svg>
                                        <div>
                                            <div class="font-semibold text-slate-700">Transcript & AI not generated yet for this call</div>
                                            <div class="mt-1 leading-relaxed">
                                                Conversation Intelligence (transcript, summary, sentiment, topics, smart notes, talk/listen ratio) comes from CloudTalk. If it's missing:
                                                <ul class="mt-1 ml-4 list-disc space-y-0.5">
                                                    <li>Enable <b>Conversation Intelligence</b> in your CloudTalk plan (Settings → Add-ons → Conversational AI / Speech Analytics).</li>
                                                    <li>Wait 20 seconds to 20 minutes <b>after the call ends</b> for CloudTalk's post-call processing.</li>
                                                    <li>Make sure <b>Recording</b> is turned on — CI never runs for missed or non-recorded calls.</li>
                                                    <li>Then click <b>Sync Call History</b> above to pull the new data.</li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="border-t border-dashed border-slate-200 pt-5">
                            <div class="flex items-center gap-2 mb-3">
                                <div class="w-8 h-8 rounded-lg bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-sm">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                                    </svg>
                                </div>
                                <div>
                                    <h6 class="text-xs font-bold text-slate-700 uppercase tracking-wider">Ask AI About This Call</h6>
                                    <p class="text-[11px] text-slate-500">Query the transcript: summarize, detect sentiment, extract next steps.</p>
                                </div>
                                <?php if ($summary !== ''): ?>
                                    <span class="ml-auto inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-semibold bg-violet-50 text-violet-700 border border-violet-200">
                                        Summary saved
                                    </span>
                                <?php elseif ($summaryStatus === 'processing'): ?>
                                    <span class="ml-auto inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-semibold bg-sky-50 text-sky-700 border border-sky-200 animate-pulse">
                                        Generating summary…
                                    </span>
                                <?php endif; ?>
                            </div>

                            <div class="flex flex-wrap gap-2 mb-3">
                                <button type="button" class="ai-presets inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-white border border-slate-200 text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:border-slate-300 transition"
                                        data-call-id="<?= $callId ?>" data-preset="summarize">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-violet-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                    </svg>
                                    Summarize
                                </button>
                                <button type="button" class="ai-presets inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-white border border-slate-200 text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:border-slate-300 transition"
                                        data-call-id="<?= $callId ?>" data-preset="what_happened">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-sky-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                    What happened?
                                </button>
                                <button type="button" class="ai-presets inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-white border border-slate-200 text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:border-slate-300 transition"
                                        data-call-id="<?= $callId ?>" data-preset="next_steps">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M13 7l5 5m0 0l-5 5m5-5H6" />
                                    </svg>
                                    Next Steps
                                </button>
                                <button type="button" class="ai-presets inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-white border border-slate-200 text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:border-slate-300 transition"
                                        data-call-id="<?= $callId ?>" data-preset="sentiment">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-rose-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                    Sentiment
                                </button>
                            </div>

                            <div class="flex gap-2 items-start">
                                <div class="flex-1">
                                    <textarea data-ai-input="<?= $callId ?>" rows="2" placeholder="Ask anything about this call (e.g. \"Did the customer mention pricing?\")"
                                        class="w-full px-3.5 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-700 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-violet-500/20 focus:border-violet-400 transition resize-y"></textarea>
                                </div>
                                <button type="button" data-ask="<?= $callId ?>"
                                        class="ai-ask-btn shrink-0 inline-flex items-center justify-center px-4 py-2.5 h-[52px] rounded-xl bg-gradient-to-r from-violet-600 to-fuchsia-600 text-white text-sm font-semibold hover:from-violet-700 hover:to-fuchsia-700 transition shadow-md shadow-violet-500/20 disabled:opacity-60 disabled:cursor-not-allowed"
                                        data-call-id="<?= $callId ?>">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                                    </svg>
                                </button>
                            </div>

                            <div data-ai-output="<?= $callId ?>" class="mt-3 hidden">
                                <div class="rounded-2xl border border-violet-100 bg-gradient-to-br from-violet-50/80 to-fuchsia-50/80 p-4">
                                    <div class="flex items-center gap-2 mb-2">
                                        <div class="w-6 h-6 rounded-md bg-violet-600 text-white flex items-center justify-center">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                                            </svg>
                                        </div>
                                        <span class="text-[11px] font-semibold uppercase tracking-wider text-violet-700" data-ai-qlabel="<?= $callId ?>">AI Answer</span>
                                    </div>
                                    <div data-ai-answer="<?= $callId ?>" class="text-sm text-slate-800 leading-relaxed whitespace-pre-wrap"></div>
                                </div>
                            </div>

                            <?php if ($summary !== ''): ?>
                                <div class="mt-3 rounded-2xl border border-violet-200 bg-violet-50/60 p-4">
                                    <div class="flex items-center gap-2 mb-2 flex-wrap">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-violet-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                        </svg>
                                        <span class="text-[11px] font-bold uppercase tracking-wider text-violet-700">AI Summary</span>
                                        <?php if ($ciSummaryBadge !== ''): ?>
                                            <?= $ciSummaryBadge ?>
                                        <?php else: ?>
                                            <span class="ml-auto inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-semibold bg-violet-50 text-violet-700 border border-violet-200">
                                                Summary saved
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="text-sm text-slate-800 leading-relaxed whitespace-pre-wrap"><?= esc($summary) ?></div>
                                </div>
                            <?php endif; ?>

                            <div class="mt-4 pt-4 border-t border-dashed border-slate-200">
                                <div class="flex items-center gap-2 mb-3">
                                    <div class="w-8 h-8 rounded-lg bg-gradient-to-br from-sky-500 to-emerald-500 flex items-center justify-center shadow-sm">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                                        </svg>
                                    </div>
                                    <div>
                                        <h6 class="text-xs font-bold text-slate-700 uppercase tracking-wider">Conversation Intelligence</h6>
                                        <p class="text-[11px] text-slate-500">Sentiment, Topics, Smart Notes, Talk/Listen — pulled from CloudTalk after each recorded call.</p>
                                    </div>
                                </div>

                                <?php if ($ciTopics !== [] || $ciSmartNotes !== [] || $ciTalkListen !== [] || $ciSentiment !== ''): ?>
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                                        <?php if ($ciSentiment !== '' || $ciSentimentScore !== null): ?>
                                            <div class="rounded-2xl border border-violet-100 bg-violet-50/40 p-3.5">
                                                <div class="flex items-center gap-2 mb-2">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-violet-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                    </svg>
                                                    <h6 class="text-[11px] font-bold uppercase tracking-wider text-violet-700">CI Sentiment</h6>
                                                </div>
                                                <div class="flex flex-wrap items-center gap-2">
                                                    <?php if ($ciSentiment !== ''): ?>
                                                        <?= $sentimentBadge !== '' ? $sentimentBadge : '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-slate-100 text-slate-700 border border-slate-200">' . esc($ciSentiment) . '</span>' ?>
                                                    <?php endif; ?>
                                                    <?php if ($ciSentimentScore !== null): ?>
                                                        <span class="text-[11px] font-semibold text-slate-600">Score <span class="font-mono"><?= (int)$ciSentimentScore ?></span></span>
                                                    <?php endif; ?>
                                                    <?php if ($ciSentiment === '' && $ciSentimentScore === null): ?>
                                                        <span class="text-[11px] text-slate-500 italic">No sentiment yet.</span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                        <?php if ($ciTopics !== []): ?>
                                        <div class="rounded-2xl border border-sky-100 bg-sky-50/40 p-3.5">
                                            <div class="flex items-center gap-2 mb-2">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-sky-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M7 7h.01M7 3h5a1.99 1.99 0 011.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.99 1.99 0 013 12V7a4 4 0 014-4z" />
                                                </svg>
                                                <h6 class="text-[11px] font-bold uppercase tracking-wider text-sky-700">CI Topics</h6>
                                            </div>
                                            <div class="flex flex-wrap gap-1.5">
                                                <?php
                                                    $topicsFlat = [];
                                                    $walk = static function ($arr) use (&$walk, &$topicsFlat) {
                                                        if (!is_array($arr)) return;
                                                        foreach ($arr as $k => $v) {
                                                            if (is_array($v)) {
                                                                if (isset($v['topic']) && is_string($v['topic'])) $topicsFlat[] = $v['topic'];
                                                                if (isset($v['name']) && is_string($v['name'])) $topicsFlat[] = $v['name'];
                                                                $walk($v);
                                                            } elseif (is_string($v) && in_array(mb_strtolower((string)$k), ['topic','topics','name','label','text','title'], true)) {
                                                                $topicsFlat[] = $v;
                                                            } elseif (is_string($v) && is_numeric($k) && trim($v) !== '') {
                                                                $topicsFlat[] = $v;
                                                            }
                                                        }
                                                    };
                                                    $walk($ciTopics);
                                                    $topicsFlat = array_values(array_unique(array_filter(array_map('strval', $topicsFlat), static fn($s) => trim($s) !== '')));
                                                    if ($topicsFlat === []):
                                                ?>
                                                    <span class="text-[11px] text-slate-500 italic">No topics tagged yet.</span>
                                                <?php else: ?>
                                                    <?php foreach (array_slice($topicsFlat, 0, 15) as $t): ?>
                                                        <span class="inline-block px-2 py-0.5 rounded-full text-[10.5px] font-semibold text-sky-800 bg-white border border-sky-200 shadow-sm shadow-sky-500/5">
                                                            #<?= esc(trim($t)) ?>
                                                        </span>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($ciSmartNotes !== []): ?>
                                        <div class="rounded-2xl border border-amber-100 bg-amber-50/40 p-3.5">
                                            <div class="flex items-center gap-2 mb-2">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-amber-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                </svg>
                                                <h6 class="text-[11px] font-bold uppercase tracking-wider text-amber-800">CI Smart Notes</h6>
                                            </div>
                                            <?php
                                                $notesFlat = [];
                                                $walkN = static function ($arr) use (&$walkN, &$notesFlat) {
                                                    if (!is_array($arr)) return;
                                                    foreach ($arr as $k => $v) {
                                                        if (is_array($v)) {
                                                            if (isset($v['note']) && is_string($v['note'])) $notesFlat[] = $v['note'];
                                                            elseif (isset($v['text']) && is_string($v['text'])) $notesFlat[] = $v['text'];
                                                            elseif (isset($v['content']) && is_string($v['content'])) $notesFlat[] = $v['content'];
                                                            else $walkN($v);
                                                        } elseif (is_string($v) && trim($v) !== '' && is_numeric($k)) {
                                                            $notesFlat[] = $v;
                                                        }
                                                    }
                                                };
                                                $walkN($ciSmartNotes);
                                                $notesFlat = array_values(array_unique(array_filter(array_map('strval', $notesFlat), static fn($s) => trim($s) !== '')));
                                            ?>
                                            <?php if ($notesFlat === []): ?>
                                                <p class="text-[11px] text-slate-500 italic">No smart notes available.</p>
                                            <?php else: ?>
                                                <ul class="space-y-1.5">
                                                    <?php foreach (array_slice($notesFlat, 0, 10) as $nt): ?>
                                                        <li class="flex gap-2 text-[12px] text-amber-900">
                                                            <span class="text-amber-600 mt-0.5">•</span>
                                                            <span class="leading-snug"><?= esc(trim($nt)) ?></span>
                                                        </li>
                                                    <?php endforeach; ?>
                                                </ul>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($ciTalkListen !== []): ?>
                                        <div class="rounded-2xl border border-emerald-100 bg-emerald-50/40 p-3.5">
                                            <div class="flex items-center gap-2 mb-2">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-emerald-700" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                </svg>
                                                <h6 class="text-[11px] font-bold uppercase tracking-wider text-emerald-800">Talk / Listen Ratio</h6>
                                            </div>
                                            <?php
                                                $ratioRows = [];
                                                foreach ($ciTalkListen as $rr) {
                                                    if (!is_array($rr)) continue;
                                                    $caller = (string) ($rr['caller'] ?? '');
                                                    $talking = (float) ($rr['talkingTime'] ?? $rr['talking_time'] ?? 0);
                                                    $ratio = (float) ($rr['ratio'] ?? 0);
                                                    if ($caller === '' && $talking <= 0) continue;
                                                    $ratioRows[] = ['caller' => $caller, 'talking' => $talking, 'ratio' => $ratio];
                                                }
                                            ?>
                                            <?php if ($ratioRows === []): ?>
                                                <p class="text-[11px] text-slate-500 italic">No ratio data available.</p>
                                            <?php else: ?>
                                                <div class="space-y-2">
                                                    <?php foreach ($ratioRows as $ri => $row):
                                                        $who = $row['caller'] === 'caller1' ? 'Agent' : ($row['caller'] === 'caller2' ? 'Contact' : ucfirst((string)$row['caller']));
                                                        $agentLike = stripos($who, 'agent') !== false || $row['caller'] === 'caller1';
                                                        $pct = max(0, min(100, (float)$row['ratio']));
                                                        $cls = $agentLike ? 'bg-sky-500' : 'bg-emerald-500';
                                                        $secs = (int) round((float)$row['talking']);
                                                    ?>
                                                        <div>
                                                            <div class="flex justify-between text-[11px] font-semibold text-emerald-900 mb-0.5">
                                                                <span><?= esc($who) ?></span>
                                                                <span class="font-mono"><?= round($pct, 1) ?>% · <?= (int)($secs/60) ?>m <?= str_pad((string)($secs%60), 2, '0', STR_PAD_LEFT) ?>s</span>
                                                            </div>
                                                            <div class="w-full h-2 bg-white/70 rounded-full overflow-hidden border border-emerald-100">
                                                                <div class="h-full <?= $cls ?> rounded-full" style="width:<?= $pct ?>%"></div>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="rounded-2xl border border-slate-100 bg-slate-50/60 p-4">
                                        <div class="flex items-start gap-3">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-sky-500 mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                            </svg>
                                            <div class="text-xs text-slate-600 leading-relaxed">
                                                <div class="font-semibold text-slate-700 mb-1">No Conversation Intelligence data yet</div>
                                                For each <b>recorded</b> call, CloudTalk generates:
                                                <ul class="mt-1 ml-4 list-disc space-y-0.5">
                                                    <li><b>Transcript</b> — full call text with speaker segments</li>
                                                    <li><b>AI Summary</b> — short call recap</li>
                                                    <li><b>Sentiment</b> — overall tone (positive / neutral / negative)</li>
                                                    <li><b>Topics</b> — auto-tagged subjects discussed</li>
                                                    <li><b>Smart Notes</b> — key facts & follow-ups extracted</li>
                                                    <li><b>Talk/Listen Ratio</b> — who spoke, and for how long</li>
                                                </ul>
                                                <div class="mt-2">
                                                    If the items above are missing:
                                                    <ol class="mt-1 ml-4 list-decimal space-y-0.5">
                                                        <li>Make sure <b>Conversation Intelligence</b> is enabled in your CloudTalk plan (Settings → Add-ons).</li>
                                                        <li>Wait up to <b>20 minutes</b> after a recorded call ends for CloudTalk processing.</li>
                                                        <li>Click <b>Sync Call History</b> at the top of this card to re-pull data.</li>
                                                        <li>Missed / unanswered calls never produce transcripts or CI data.</li>
                                                    </ol>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<script>
(function(){
    var CALL_URL = <?= json_encode($callBaseUrl) ?>;
    var AI_URL   = <?= json_encode($askAiUrl) ?>;
    var SYNC_URL = <?= json_encode($syncUrl) ?>;

    var syncBtn = document.getElementById('btn-sync-calls');
    if (syncBtn && SYNC_URL) {
        syncBtn.addEventListener('click', function(){
            var btn   = syncBtn;
            var label = document.getElementById('btn-sync-label');
            var icon  = document.getElementById('btn-sync-icon');
            btn.disabled = true;
            var originalLabel = label ? label.textContent : '';
            if (label) label.textContent = 'Syncing…';
            if (icon) icon.classList.add('animate-spin');
            fetch(SYNC_URL, {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            }).then(function(r){ return r.json().catch(function(){ return {ok:false, error:'Invalid JSON response'}; }); }).then(function(j){
                btn.disabled = false;
                if (icon) icon.classList.remove('animate-spin');
                if (label) label.textContent = originalLabel || 'Sync Call History';
                if (j && j.ok) {
                    var msg = 'Synced ' + (j.matched || 0) + ' call(s) from CloudTalk: inserted ' + (j.inserted||0) + ', updated ' + (j.updated||0) + ', recordings ' + (j.recordings||0) + '.';
                    if ((j.transcripts|0) + (j.summaries|0) + (j.sentiments|0) > 0) {
                        msg += '  Conversation Intelligence: transcripts ' + (j.transcripts|0) + ', summaries ' + (j.summaries|0) + ', sentiments ' + (j.sentiments|0) + '.';
                    }
                    if (j.ci_errors|0) {
                        msg += '  CI endpoints returning 404: ' + (j.ci_errors|0) + ' (data not yet generated).';
                    }
                    if (j.searched === 0) {
                        msg += ' (No calls found in CloudTalk for date_from=' + (j.date_from || '') + ' / phone=' + (j.phone||'') + ')';
                    }
                    if (j.warnings && Array.isArray(j.warnings) && j.warnings.length) {
                        msg += '\n\nWarnings:\n- ' + j.warnings.slice(0,5).join('\n- ');
                    }
                    alert(msg);
                    window.location.reload();
                } else {
                    alert('Sync failed: ' + ((j && j.error) ? j.error : 'Unknown error'));
                }
            }).catch(function(err){
                btn.disabled = false;
                if (icon) icon.classList.remove('animate-spin');
                if (label) label.textContent = originalLabel || 'Sync Call History';
                alert('Request error: ' + err);
            });
        });
    }

    var profileBtn = document.getElementById('profile-call-btn');
    if (profileBtn) {
        profileBtn.addEventListener('click', function(){
            var btn = profileBtn;
            var leadId  = parseInt(btn.getAttribute('data-lead-id') || '0', 10);
            var phone   = btn.getAttribute('data-lead-phone') || '';
            var name    = btn.getAttribute('data-lead-name') || '';
            var email   = btn.getAttribute('data-lead-email') || '';
            var company = btn.getAttribute('data-lead-company') || '';
            if (!phone) { alert('This lead has no phone number.'); return; }
            btn.disabled = true;
            btn.classList.add('opacity-70');
            var fd = new FormData();
            fd.append('lead_id', leadId);
            fd.append('phone',   phone);
            fd.append('name',    name);
            fd.append('email',   email);
            fd.append('company', company);
            fetch(CALL_URL, {
                method: 'POST',
                body: fd,
                credentials: 'same-origin',
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            }).then(function(r){ return r.json(); }).then(function(j){
                btn.disabled = false;
                btn.classList.remove('opacity-70');
                if (j && j.ok) {
                    alert('Call initiated! Check your CloudTalk phone/softphone. Call ID: ' + (j.cloudtalk_call_id || 'n/a'));
                    setTimeout(function(){ window.location.reload(); }, 1200);
                } else {
                    alert('Failed to initiate call: ' + ((j && j.error) ? j.error : 'Unknown error'));
                }
            }).catch(function(err){
                btn.disabled = false;
                btn.classList.remove('opacity-70');
                alert('Request error: ' + err);
            });
        });
    }

    document.addEventListener('click', function(e){
        var toggleBtn = e.target.closest && e.target.closest('[data-toggle]');
        if (toggleBtn) {
            var id = toggleBtn.getAttribute('data-toggle');
            if (!id) return;
            var box = document.getElementById(id);
            if (!box) return;
            var isHidden = box.classList.contains('hidden');
            box.classList.toggle('hidden');
            var label = document.querySelector('[data-toggle-label="' + id + '"]');
            if (label) label.textContent = isHidden ? 'Hide details' : 'Show details';
            var arrow = document.querySelector('[data-toggle-arrow="' + id + '"]');
            if (arrow) arrow.style.transform = isHidden ? 'rotate(180deg)' : '';
            return;
        }

        var preset = e.target.closest && e.target.closest('.ai-presets');
        if (preset) {
            var callId = preset.getAttribute('data-call-id');
            var pr     = preset.getAttribute('data-preset');
            if (callId) runAi(callId, pr, '');
            return;
        }

        var ask = e.target.closest && e.target.closest('.ai-ask-btn');
        if (ask) {
            var cid = ask.getAttribute('data-call-id');
            var inp = document.querySelector('[data-ai-input="' + cid + '"]');
            var q = inp ? inp.value.trim() : '';
            if (!q) { alert('Type your question first, or pick one of the presets above.'); return; }
            if (cid) runAi(cid, '', q);
            return;
        }
    });

    document.addEventListener('keydown', function(e){
        var inp = e.target.closest && e.target.closest('[data-ai-input]');
        if (inp && e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
            var cid = inp.getAttribute('data-ai-input');
            var q = inp.value.trim();
            if (q && cid) runAi(cid, '', q);
        }
    });

    function runAi(callId, preset, question) {
        var out = document.querySelector('[data-ai-output="' + callId + '"]');
        var ans = document.querySelector('[data-ai-answer="' + callId + '"]');
        var qlb = document.querySelector('[data-ai-qlabel="' + callId + '"]');
        var btn = document.querySelector('[data-ask="' + callId + '"]');
        if (!out || !ans) return;
        out.classList.remove('hidden');
        ans.textContent = 'Thinking…';
        if (btn) btn.disabled = true;
        if (qlb) {
            if (preset) {
                var labels = { summarize:'AI Summary', what_happened:'What Happened', next_steps:'Next Steps', sentiment:'Sentiment Analysis' };
                qlb.textContent = labels[preset] || 'AI Answer';
            } else {
                qlb.textContent = 'AI Answer';
            }
        }
        var fd = new FormData();
        fd.append('call_id',  callId);
        if (preset)   fd.append('preset',   preset);
        if (question) fd.append('question', question);
        fetch(AI_URL, {
            method: 'POST',
            body: fd,
            credentials: 'same-origin',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function(r){ return r.json(); }).then(function(j){
            if (btn) btn.disabled = false;
            if (j && j.success) {
                ans.textContent = j.answer || '(no answer)';
            } else {
                ans.textContent = 'Error: ' + ((j && j.error) ? j.error : 'Unknown error');
            }
        }).catch(function(err){
            if (btn) btn.disabled = false;
            ans.textContent = 'Request error: ' + err;
        });
    }
})();
</script>
