<?php
// Map categories to Arabic names
$catNames = [
    'health'    => ['label' => 'الصحة', 'icon' => 'fa-heart-pulse', 'color' => '#dc3545'],
    'finance'   => ['label' => 'المالية', 'icon' => 'fa-wallet', 'color' => '#f59e0b'],
    'behavior'  => ['label' => 'السلوكيات', 'icon' => 'fa-brain', 'color' => '#8b5cf6'],
    'habits'    => ['label' => 'العادات', 'icon' => 'fa-fire', 'color' => '#ef4444'],
    'journal'   => ['label' => 'اليومية', 'icon' => 'fa-book-open', 'color' => '#06b6d4'],
    'spiritual' => ['label' => 'الروحانيات', 'icon' => 'fa-kaaba', 'color' => '#10b981'],
    'education' => ['label' => 'التعليم', 'icon' => 'fa-graduation-cap', 'color' => '#3b82f6'],
    'calendar'  => ['label' => 'التقويم', 'icon' => 'fa-calendar-days', 'color' => '#0ea5e9'],
    'cross'     => ['label' => 'تحليل متقاطع', 'icon' => 'fa-circle-nodes', 'color' => '#a855f7'],
];

$severityConfig = [
    'critical' => ['label' => 'حرج', 'badge' => 'danger', 'border' => '#dc3545', 'bg' => 'rgba(220,53,69,0.08)'],
    'warning'  => ['label' => 'تحذير', 'badge' => 'warning', 'border' => '#fd7e14', 'bg' => 'rgba(253,126,20,0.08)'],
    'info'     => ['label' => 'معلومة', 'badge' => 'info', 'border' => '#0d6efd', 'bg' => 'rgba(13,110,253,0.06)'],
    'positive' => ['label' => 'إيجابي', 'badge' => 'success', 'border' => '#198754', 'bg' => 'rgba(25,135,84,0.07)'],
];

$stats    = $insights['stats'] ?? [];
$grouped  = $insights['grouped'] ?? [];
$top      = $insights['top'] ?? [];
$genAt    = $insights['generated_at'] ?? date('Y-m-d H:i:s');
?>

<style>
/* === Advisor 2.0 Styles === */
.advisor-hero {
    background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 50%, #0f172a 100%);
    border-radius: 20px;
    padding: 40px;
    margin-bottom: 28px;
    position: relative;
    overflow: hidden;
    border: 1px solid rgba(255,255,255,0.07);
}
.advisor-hero::before {
    content: '';
    position: absolute;
    top: -60px; right: -60px;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(139,92,246,0.3) 0%, transparent 70%);
    pointer-events: none;
}
.advisor-hero::after {
    content: '';
    position: absolute;
    bottom: -40px; left: -40px;
    width: 150px; height: 150px;
    background: radial-gradient(circle, rgba(14,165,233,0.2) 0%, transparent 70%);
    pointer-events: none;
}
.stat-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 18px;
    border-radius: 999px;
    font-size: 13px;
    font-weight: 700;
    backdrop-filter: blur(10px);
}
.insight-card {
    border-radius: 14px;
    padding: 20px 22px;
    margin-bottom: 14px;
    border-left: 4px solid;
    transition: transform 0.2s, box-shadow 0.2s;
    position: relative;
    overflow: hidden;
}
.insight-card:hover {
    transform: translateX(-4px);
    box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}
body.dark-mode .insight-card { background: #1e293b !important; }
.insight-card .insight-icon {
    width: 42px; height: 42px;
    border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
    font-size: 18px;
}
.cat-section { margin-bottom: 32px; }
.cat-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 14px;
    padding-bottom: 10px;
    border-bottom: 2px solid;
}
.cat-label-text { font-size: 15px; font-weight: 800; }
.refresh-btn {
    border: none;
    background: linear-gradient(135deg, #6366f1, #8b5cf6);
    color: white;
    padding: 10px 24px;
    border-radius: 999px;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.3s;
}
.refresh-btn:hover { transform: scale(1.04); box-shadow: 0 4px 15px rgba(99,102,241,0.4); }
.refresh-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.top-insight-banner {
    background: linear-gradient(135deg, #1e1b4b, #2d1b54);
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 16px;
    border: 1px solid rgba(139,92,246,0.3);
    position: relative;
    overflow: hidden;
}
.top-insight-banner.critical {
    background: linear-gradient(135deg, #1e0a0a, #3b0f0f);
    border-color: rgba(220,53,69,0.4);
}
.top-insight-banner.positive {
    background: linear-gradient(135deg, #0a1e14, #0f3b23);
    border-color: rgba(25,135,84,0.4);
}
.ai-pulse {
    display: inline-block;
    width: 8px; height: 8px;
    background: #22c55e;
    border-radius: 50%;
    animation: aiPulse 1.5s ease-in-out infinite;
}
@keyframes aiPulse { 0%,100%{box-shadow:0 0 0 0 rgba(34,197,94,0.4)} 50%{box-shadow:0 0 0 8px rgba(34,197,94,0)} }
.no-insights-msg {
    text-align: center;
    padding: 40px;
    color: #64748b;
}
.weight-bar {
    height: 3px;
    border-radius: 999px;
    margin-top: 12px;
    background: rgba(0,0,0,0.08);
}
.weight-bar-fill {
    height: 100%;
    border-radius: 999px;
    transition: width 0.8s ease-out;
}
</style>

<!-- HERO HEADER -->
<div class="advisor-hero text-white mb-4">
    <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
        <div>
            <h1 class="h2 fw-bold mb-2">
                <i class="fa-solid fa-robot me-2" style="color:#818cf8;"></i>
                المستشار الذكي 2.0
            </h1>
            <p class="text-secondary mb-3" style="font-size:14px;">
                <span class="ai-pulse me-2"></span>
                تحليل شامل لجميع وحدات النظام — <?= $stats['total'] ?? 0 ?> إشارة <span class="text-info fw-bold"><?= date('H:i') ?></span>
            </p>
            <div class="d-flex flex-wrap gap-2">
                <?php if (($stats['critical'] ?? 0) > 0): ?>
                <span class="stat-pill" style="background:rgba(220,53,69,0.2); color:#f87171; border:1px solid rgba(220,53,69,0.3);">
                    <i class="fa-solid fa-triangle-exclamation"></i> <?= $stats['critical'] ?> حرج
                </span>
                <?php endif; ?>
                <?php if (($stats['warning'] ?? 0) > 0): ?>
                <span class="stat-pill" style="background:rgba(253,126,20,0.2); color:#fb923c; border:1px solid rgba(253,126,20,0.3);">
                    <i class="fa-solid fa-bell"></i> <?= $stats['warning'] ?> تحذير
                </span>
                <?php endif; ?>
                <?php if (($stats['positive'] ?? 0) > 0): ?>
                <span class="stat-pill" style="background:rgba(25,135,84,0.2); color:#4ade80; border:1px solid rgba(25,135,84,0.3);">
                    <i class="fa-solid fa-thumbs-up"></i> <?= $stats['positive'] ?> إيجابي
                </span>
                <?php endif; ?>
            </div>
        </div>
        <button class="refresh-btn" id="refreshBtn" onclick="refreshInsights()">
            <i class="fa-solid fa-rotate-right me-2" id="refreshIcon"></i>تحديث التحليل
        </button>
    </div>
</div>

<!-- TOP 2 PRIORITY INSIGHTS -->
<?php if (!empty($top)): ?>
<h5 class="fw-bold text-dark mb-3">
    <i class="fa-solid fa-fire-flame-curved text-danger me-2"></i>
    الإشارات الأولوية
</h5>
<div class="row g-3 mb-4">
    <?php foreach ($top as $i => $sig):
        $sev = $sig['severity'] ?? 'info';
        $sc  = $severityConfig[$sev] ?? $severityConfig['info'];
        $bClass = $i === 0 ? ($sev === 'critical' ? 'critical' : ($sev === 'positive' ? 'positive' : '')) : '';
    ?>
    <div class="col-md-6">
        <div class="top-insight-banner <?= $bClass ?> text-white h-100">
            <div class="d-flex align-items-start gap-3">
                <div style="font-size: 28px; flex-shrink:0;">
                    <i class="fa-solid <?= $sig['icon'] ?>" style="color: <?= $sig['color'] ?>;"></i>
                </div>
                <div class="flex-grow-1">
                    <span class="badge bg-<?= $sc['badge'] ?> mb-2 rounded-pill" style="font-size:10px;">
                        <?= $i === 0 ? '🥇 الأعلى أولوية' : '🥈 ثانياً' ?> • <?= $sc['label'] ?>
                    </span>
                    <p class="mb-0 fw-bold lh-base" style="font-size: 14px; color: #e2e8f0;">
                        <?= htmlspecialchars($sig['message']) ?>
                    </p>
                    <div class="weight-bar mt-3">
                        <div class="weight-bar-fill" style="width: <?= min(100, ($sig['weight']/10)*100) ?>%; background: <?= $sig['color'] ?>;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- ALL INSIGHTS GROUPED BY CATEGORY -->
<?php if (!empty($grouped)): ?>
<div id="insightsContainer">
    <?php foreach ($grouped as $cat => $catSignals):
        $catInfo = $catNames[$cat] ?? ['label' => $cat, 'icon' => 'fa-lightbulb', 'color' => '#6c757d'];
    ?>
    <div class="cat-section">
        <div class="cat-header" style="border-color: <?= $catInfo['color'] ?>40;">
            <div style="width:34px; height:34px; background: <?= $catInfo['color'] ?>20; border-radius:10px; display:flex; align-items:center; justify-content:center;">
                <i class="fa-solid <?= $catInfo['icon'] ?>" style="color: <?= $catInfo['color'] ?>; font-size:15px;"></i>
            </div>
            <span class="cat-label-text" style="color: <?= $catInfo['color'] ?>;"><?= $catInfo['label'] ?></span>
            <span class="badge rounded-pill ms-auto" style="background: <?= $catInfo['color'] ?>20; color: <?= $catInfo['color'] ?>; font-size:11px;">
                <?= count($catSignals) ?> إشارة
            </span>
        </div>

        <?php foreach ($catSignals as $sig):
            $sev = $sig['severity'] ?? 'info';
            $sc  = $severityConfig[$sev] ?? $severityConfig['info'];
        ?>
        <div class="insight-card" style="background: <?= $sc['bg'] ?>; border-left-color: <?= $sc['border'] ?>;">
            <div class="d-flex align-items-start gap-3">
                <div class="insight-icon" style="background: <?= $sig['color'] ?>20;">
                    <i class="fa-solid <?= $sig['icon'] ?>" style="color: <?= $sig['color'] ?>;"></i>
                </div>
                <div class="flex-grow-1">
                    <div class="d-flex align-items-center gap-2 mb-2">
                        <span class="badge bg-<?= $sc['badge'] ?> rounded-pill" style="font-size:10px;"><?= $sc['label'] ?></span>
                        <span class="text-muted" style="font-size:11px;">درجة: <?= number_format($sig['weight'], 1) ?></span>
                    </div>
                    <p class="mb-0 fw-bold lh-base" style="font-size: 14px;">
                        <?= htmlspecialchars($sig['message']) ?>
                    </p>
                    <div class="weight-bar">
                        <div class="weight-bar-fill" style="width: <?= min(100, ($sig['weight']/10)*100) ?>%; background: <?= $sig['color'] ?>;"></div>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endforeach; ?>
</div>
<?php else: ?>
<div class="no-insights-msg">
    <i class="fa-solid fa-check-circle fa-3x text-success mb-3 d-block"></i>
    <h5 class="fw-bold">كل شيء على ما يرام!</h5>
    <p class="text-muted">لا توجد إشارات طارئة اليوم. استمر في الانضباط.</p>
</div>
<?php endif; ?>

<script>
async function refreshInsights() {
    const btn = document.getElementById('refreshBtn');
    const icon = document.getElementById('refreshIcon');
    btn.disabled = true;
    icon.className = 'fa-solid fa-spinner fa-spin me-2';

    try {
        const res = await fetch('<?= BASE_URL ?>/advisor/refresh', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json' },
            body: JSON.stringify({})
        });
        const data = await res.json();
        if (data.success) {
            // Reload via PJAX
            if (typeof OTIS !== 'undefined') {
                await OTIS.pjaxLoad(window.location.href, false);
            } else {
                window.location.reload();
            }
        }
    } catch(e) {
        window.location.reload();
    }

    btn.disabled = false;
    icon.className = 'fa-solid fa-rotate-right me-2';
}
</script>
