<?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)'],
];

// Support both flat array (new UserProfileEngine) and grouped (old AdvisorEngine)
$allInsights = is_array($insights) && isset($insights['all']) ? $insights['all'] : (array)$insights;
$grouped     = [];
foreach ($allInsights as $sig) {
    $cat = $sig['category'] ?? 'cross';
    $grouped[$cat][] = $sig;
}
$top  = array_slice($allInsights, 0, 2);

// Counts
$criticalCount = count(array_filter($allInsights, fn($s)=> in_array(strtolower($s['severity']??''), ['critical'])));
$warningCount  = count(array_filter($allInsights, fn($s)=> in_array(strtolower($s['severity']??''), ['warning'])));
$positiveCount = count(array_filter($allInsights, fn($s)=> in_array(strtolower($s['severity']??''), ['positive'])));

// Decisions (from UserProfileEngine)
$decisions       = $decisions ?? [];
$discipline_score = $discipline_score ?? 100;

// Gauge color
$gaugeColor = $discipline_score >= 75 ? '#22c55e' : ($discipline_score >= 50 ? '#f59e0b' : '#ef4444');
$gaugeLabel = $discipline_score >= 75 ? 'قوي' : ($discipline_score >= 50 ? 'متوسط' : 'طوارئ');
?>


<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 — Decision Engine Dashboard -->
<div class="advisor-hero text-white mb-4">
    <div class="row align-items-center g-4" style="position:relative; z-index:1;">

        <!-- Discipline Score Gauge -->
        <div class="col-md-3 text-center">
            <div style="position:relative; width:130px; height:130px; margin:0 auto;">
                <svg viewBox="0 0 36 36" style="width:100%; transform:rotate(-90deg);">
                    <circle cx="18" cy="18" r="15.9" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="3.5"/>
                    <circle cx="18" cy="18" r="15.9" fill="none" stroke="<?= $gaugeColor ?>" stroke-width="3.5"
                        stroke-dasharray="<?= $discipline_score ?> <?= 100 - $discipline_score ?>"
                        stroke-linecap="round" style="filter: drop-shadow(0 0 6px <?= $gaugeColor ?>);"/>
                </svg>
                <div style="position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center;">
                    <span class="fw-black" style="font-size:2rem; color:<?= $gaugeColor ?>; line-height:1;"><?= $discipline_score ?></span>
                    <span style="font-size:10px; color:rgba(255,255,255,0.6);">/ 100</span>
                </div>
            </div>
            <div class="mt-2">
                <span class="fw-bold" style="font-size:13px; color:<?= $gaugeColor ?>;"><?= $gaugeLabel ?></span>
                <div style="font-size:10px; color:rgba(255,255,255,0.5);">مؤشر الانضباط الكلي</div>
            </div>
        </div>

        <!-- Title + Stats + Active Decisions -->
        <div class="col-md-9">
            <h1 class="h3 fw-bold mb-1">
                <i class="fa-solid fa-robot me-2" style="color:#818cf8;"></i>
                النواة الذكية — صانع القرار
            </h1>
            <p class="mb-3" style="color:rgba(255,255,255,0.5); font-size:13px;">
                <span class="ai-pulse me-2"></span>
                تحليل شامل محدّث للبيانات — <?= count($allInsights) ?> إشارة نشطة
            </p>

            <!-- Stats Pills -->
            <div class="d-flex flex-wrap gap-2 mb-3">
                <?php if ($criticalCount > 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> <?= $criticalCount ?> حرج
                </span>
                <?php endif; ?>
                <?php if ($warningCount > 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> <?= $warningCount ?> تحذير
                </span>
                <?php endif; ?>
                <?php if ($positiveCount > 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> <?= $positiveCount ?> إيجابي
                </span>
                <?php endif; ?>
                <?php if (!empty($decisions['recovery_mode'])): ?>
                <span class="stat-pill" style="background:rgba(239,68,68,0.25); color:#fca5a5; border:1px solid rgba(239,68,68,0.4);">
                    <i class="fa-solid fa-shield-exclamation"></i> وضع التعافي مفعّل
                </span>
                <?php endif; ?>
                <?php if (!empty($decisions['xp_multiplier']) && $decisions['xp_multiplier'] > 1.0): ?>
                <span class="stat-pill" style="background:rgba(250,204,21,0.2); color:#fde68a; border:1px solid rgba(250,204,21,0.3);">
                    <i class="fa-solid fa-bolt"></i> مضاعف XP: <?= number_format($decisions['xp_multiplier'], 1) ?>x
                </span>
                <?php endif; ?>
            </div>

            <!-- Active Decisions Grid -->
            <?php if (!empty($decisions)): ?>
            <div class="d-flex flex-wrap gap-2">
                <?php if (!empty($decisions['high_risk_finance'])): ?>
                <a href="<?= BASE_URL ?>/finance" class="text-decoration-none">
                    <div class="rounded-3 px-3 py-2 d-flex align-items-center gap-2" style="background:rgba(239,68,68,0.15); border:1px solid rgba(239,68,68,0.3); font-size:12px; color:#fca5a5;">
                        <i class="fa-solid fa-wallet"></i> <span class="fw-bold">ماليتك في خطر — راجع الإنفاق</span>
                    </div>
                </a>
                <?php endif; ?>
                <?php if (!empty($decisions['highlight_weak_habits'])): ?>
                <a href="<?= BASE_URL ?>/habits" class="text-decoration-none">
                    <div class="rounded-3 px-3 py-2 d-flex align-items-center gap-2" style="background:rgba(239,68,68,0.12); border:1px solid rgba(239,68,68,0.25); font-size:12px; color:#fca5a5;">
                        <i class="fa-solid fa-fire"></i> <span class="fw-bold">عادات ضعيفة — تدخل فوري</span>
                    </div>
                </a>
                <?php endif; ?>
                <?php if (!empty($decisions['budget_lock_suggested'])): ?>
                <div class="rounded-3 px-3 py-2 d-flex align-items-center gap-2" style="background:rgba(253,126,20,0.15); border:1px solid rgba(253,126,20,0.3); font-size:12px; color:#fb923c;">
                    <i class="fa-solid fa-lock"></i> <span class="fw-bold">يُقترح تجميد الميزانية</span>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>

    </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'] ?? 'fa-lightbulb' ?>" style="color: <?= $sig['color'] ?? '#818cf8' ?>;"></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['msg'] ?? $sig['message'] ?? '') ?>
                    </p>
                    <?php $w = $sig['weight'] ?? 5; ?>
                    <div class="weight-bar mt-3">
                        <div class="weight-bar-fill" style="width: <?= min(100, ($w/10)*100) ?>%; background: <?= $sig['color'] ?? '#818cf8' ?>;"></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 = strtolower($sig['severity'] ?? $sig['type'] ?? 'info');
            $sc  = $severityConfig[$sev] ?? $severityConfig['info'];
            $sigIcon  = $sig['icon']  ?? 'fa-lightbulb';
            $sigColor = $sig['color'] ?? '#6c757d';
            $sigWeight = (float)($sig['weight'] ?? 5);
            $sigMsg   = htmlspecialchars($sig['msg'] ?? $sig['message'] ?? '');
        ?>
        <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: <?= $sigColor ?>20;">
                    <i class="fa-solid <?= $sigIcon ?>" style="color: <?= $sigColor ?>;"></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>
                        <?php if ($sigWeight > 0): ?>
                        <span class="text-muted" style="font-size:11px;">درجة: <?= number_format($sigWeight, 1) ?></span>
                        <?php endif; ?>
                    </div>
                    <p class="mb-0 fw-bold lh-base" style="font-size: 14px;">
                        <?= $sigMsg ?>
                    </p>
                    <div class="weight-bar">
                        <div class="weight-bar-fill" style="width: <?= min(100, ($sigWeight/10)*100) ?>%; background: <?= $sigColor ?>;"></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>
