<div class="analytics-page">
    <!-- Header Block -->
    <div class="d-flex align-items-center justify-content-between mb-4 pb-3" style="border-bottom: 1px solid #e2e8f0;">
        <div>
            <h2 class="analytics-title mb-1">Аналитическая панель</h2>
            <div class="analytics-subtitle"><i class="fa fa-bar-chart me-1"></i> Детальная эффективность операторов и статистика обращений пользователей</div>
        </div>
        <div class="text-muted small">
            <span class="badge bg-light text-dark border px-3 py-2 rounded-3"><i class="fa fa-refresh me-1 text-primary"></i> Обновлено только что</span>
        </div>
    </div>

    <!-- 1. Stats Row -->
    <div class="row g-4 mb-4">
        <!-- Card 1: Total Chats -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="card metric-card p-4">
                <div style="height: 4px; background: linear-gradient(90deg, #6366f1, #818cf8); position: absolute; top:0; left:0; right:0;"></div>
                <div class="d-flex align-items-center justify-content-between">
                    <div>
                        <div class="text-uppercase text-muted font-monospace small mb-1 fw-bold" style="font-size: 11px; letter-spacing: 0.5px;">Всего диалогов</div>
                        <h2 class="fw-bold mb-0 text-dark" style="font-family: 'Outfit', sans-serif;"><?php echo $stats['total_chats']; ?></h2>
                    </div>
                    <div class="metric-icon-box bg-icon-indigo">
                        <i class="fa fa-comments"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 2: Operator Messages -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="card metric-card p-4">
                <div style="height: 4px; background: linear-gradient(90deg, #a855f7, #c084fc); position: absolute; top:0; left:0; right:0;"></div>
                <div class="d-flex align-items-center justify-content-between">
                    <div>
                        <div class="text-uppercase text-muted font-monospace small mb-1 fw-bold" style="font-size: 11px; letter-spacing: 0.5px;">Ответов операторов</div>
                        <h2 class="fw-bold mb-0 text-dark" style="font-family: 'Outfit', sans-serif;"><?php echo $stats['operator_msg']; ?></h2>
                    </div>
                    <div class="metric-icon-box bg-icon-purple">
                        <i class="fa fa-user-circle-o"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 3: AI Messages -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="card metric-card p-4">
                <div style="height: 4px; background: linear-gradient(90deg, #10b981, #34d399); position: absolute; top:0; left:0; right:0;"></div>
                <div class="d-flex align-items-center justify-content-between">
                    <div>
                        <div class="text-uppercase text-muted font-monospace small mb-1 fw-bold" style="font-size: 11px; letter-spacing: 0.5px;">Ответов ИИ-помощника</div>
                        <h2 class="fw-bold mb-0 text-dark" style="font-family: 'Outfit', sans-serif;"><?php echo $stats['ai_msg']; ?></h2>
                    </div>
                    <div class="metric-icon-box bg-icon-emerald">
                        <i class="fa fa-android"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 4: FRT -->
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="card metric-card p-4">
                <div style="height: 4px; background: linear-gradient(90deg, #f59e0b, #fbbf24); position: absolute; top:0; left:0; right:0;"></div>
                <div class="d-flex align-items-center justify-content-between">
                    <div>
                        <div class="text-uppercase text-muted font-monospace small mb-1 fw-bold" style="font-size: 11px; letter-spacing: 0.5px;">Ср. скорость ответа</div>
                        <h2 class="fw-bold mb-0 text-dark" style="font-family: 'Outfit', sans-serif;"><?php echo $stats['formatted_frt']; ?></h2>
                    </div>
                    <div class="metric-icon-box bg-icon-amber">
                        <i class="fa fa-bolt"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 2. Chart Grid Row 1 -->
    <div class="row mb-4">
        <!-- Daily Conversations Line Chart -->
        <div class="col-12 col-xl-8">
            <div class="chart-panel">
                <div class="chart-header">
                    <span><i class="fa fa-line-chart me-2"></i>Динамика обращений по дням (за 30 дней)</span>
                    <i class="fa fa-info-circle" title="Показывает общее количество созданных диалогов за каждый день."></i>
                </div>
                <div style="position: relative; height: 320px;">
                    <canvas id="dailyChatsChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Humans vs AI Share Doughnut Chart -->
        <div class="col-12 col-xl-4">
            <div class="chart-panel">
                <div class="chart-header">
                    <span><i class="fa fa-pie-chart me-2"></i>Доля поддержки: Люди vs ИИ</span>
                    <i class="fa fa-info-circle" title="Соотношение ответов, отправленных менеджерами вручную, и ответов ИИ-консультанта."></i>
                </div>
                <div style="position: relative; height: 320px; display: flex; align-items: center; justify-content: center;">
                    <canvas id="aiShareChart" style="max-height: 280px; max-width: 280px;"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 3. Chart Grid Row 2 -->
    <div class="row mb-4">
        <!-- Messages Sent by Operator Bar Chart -->
        <div class="col-12 col-xl-4 col-lg-6">
            <div class="chart-panel">
                <div class="chart-header">
                    <span><i class="fa fa-users me-2"></i>Нагрузка по менеджерам (ответы)</span>
                    <i class="fa fa-info-circle" title="Общее число ответов, отправленных каждым оператором за все время."></i>
                </div>
                <div style="position: relative; height: 300px;">
                    <canvas id="operatorLoadChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Dialogue Sources Doughnut Chart -->
        <div class="col-12 col-xl-4 col-lg-6">
            <div class="chart-panel">
                <div class="chart-header">
                    <span><i class="fa fa-share-alt me-2"></i>Источники обращений (диалоги)</span>
                    <i class="fa fa-info-circle" title="Распределение созданных диалогов по различным каналам связи."></i>
                </div>
                <div style="position: relative; height: 300px; display: flex; align-items: center; justify-content: center;">
                    <canvas id="dialogueSourcesChart" style="max-height: 250px; max-width: 250px;"></canvas>
                </div>
            </div>
        </div>

        <!-- Hourly Peak Activity Bar Chart -->
        <div class="col-12 col-xl-4 col-lg-12">
            <div class="chart-panel">
                <div class="chart-header">
                    <span><i class="fa fa-clock-o me-2"></i>Пиковые часы суток (активность)</span>
                    <i class="fa fa-info-circle" title="Распределение входящих чатов по времени суток для планирования смен операторов."></i>
                </div>
                <div style="position: relative; height: 300px;">
                    <canvas id="hourlyPeakChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 4. Table Row: Leaderboard -->
    <div class="table-panel">
        <div class="chart-header border-bottom pb-3 mb-3">
            <span class="fs-5"><i class="fa fa-trophy text-amber me-2"></i> Эффективность и рейтинг операторов</span>
            <span class="badge bg-indigo-subtle text-indigo px-3 py-1.5 rounded-pill" style="background: rgba(99, 102, 241, 0.08); color: #6366f1; font-size: 12px;">Лидерборд</span>
        </div>
        
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light text-muted uppercase font-monospace" style="font-size: 11px;">
                    <tr>
                        <th class="ps-4 py-3">Оператор</th>
                        <th class="py-3 text-center">Сеть</th>
                        <th class="py-3 text-center">Активных диалогов</th>
                        <th class="py-3 text-center">Всего ответов</th>
                        <th class="pe-4 py-3 text-end">Ср. время ответа (FRT)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($leaderboard)) { ?>
                        <?php foreach ($leaderboard as $op) { ?>
                            <tr>
                                <td class="ps-4 py-3">
                                    <div class="d-flex align-items-center">
                                        <?php if ($op['avatar']) { ?>
                                            <img src="<?php echo $op['avatar']; ?>" alt="Avatar" class="rounded-circle me-3 border" style="width: 32px; height: 32px; object-fit: cover;">
                                        <?php } else { 
                                            $parts = preg_split('/\s+/', trim($op['name']));
                                            $initials = '';
                                            if (count($parts) >= 2) {
                                                $initials = mb_substr($parts[0], 0, 1, 'UTF-8') . mb_substr($parts[1], 0, 1, 'UTF-8');
                                            } else {
                                                $initials = mb_substr($op['name'], 0, 1, 'UTF-8');
                                            }
                                            ?>
                                            <div class="avatar-circle me-3"><?php echo htmlspecialchars(mb_strtoupper($initials, 'UTF-8')); ?></div>
                                        <?php } ?>
                                        <span class="fw-semibold text-dark"><?php echo htmlspecialchars($op['name']); ?></span>
                                    </div>
                                </td>
                                <td class="py-3 text-center">
                                    <?php if ($op['status'] === 1) { ?>
                                        <span class="badge bg-emerald-subtle text-emerald rounded-pill px-2.5 py-1" style="background: rgba(16, 185, 129, 0.1) !important; color: #10b981 !important; font-size: 11px;">В сети</span>
                                    <?php } else { ?>
                                        <span class="badge bg-secondary-subtle text-muted rounded-pill px-2.5 py-1" style="background: rgba(148, 163, 184, 0.1) !important; color: #64748b !important; font-size: 11px;">Офлайн</span>
                                    <?php } ?>
                                </td>
                                <td class="py-3 text-center fw-medium text-dark"><?php echo $op['active_chats']; ?></td>
                                <td class="py-3 text-center fw-medium text-indigo"><?php echo $op['total_messages']; ?></td>
                                <td class="pe-4 py-3 text-end font-monospace text-muted fw-bold"><?php echo $op['formatted_frt']; ?></td>
                            </tr>
                        <?php } ?>
                    <?php } else { ?>
                        <tr>
                            <td colspan="5" class="text-center py-4 text-muted">Нет данных для составления рейтинга операторов.</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script type="text/javascript">
window.EasyChatAnalyticsConfig = {
    dailyLabels: <?php echo $charts['daily_labels']; ?>,
    dailyData: <?php echo $charts['daily_data']; ?>,
    operatorMsg: <?php echo $stats['operator_msg']; ?>,
    aiMsg: <?php echo $stats['ai_msg']; ?>,
    operatorLabels: <?php echo $charts['operator_labels']; ?>,
    operatorData: <?php echo $charts['operator_data']; ?>,
    hourlyLabels: <?php echo $charts['hourly_labels']; ?>,
    hourlyData: <?php echo $charts['hourly_data']; ?>,
    sourceLabels: <?php echo $charts['source_labels']; ?>,
    sourceData: <?php echo $charts['source_data']; ?>
};
</script>
<?php echo easychat_script_tag('js/views/analytics.js'); ?>
