<style>
/* Identity & Discipline Engine UI */
.fade-in { animation: fadeIn 0.4s ease-in-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.hover-opacity:hover { opacity: 0.7; }
.transition-all { transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }

/* Heatmap Grid */
.heatmap-grid {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
    align-content: flex-start;
}
.heatmap-cell {
    width: 14px;
    height: 14px;
    border-radius: 3px;
    background-color: #ebedf0;
    transition: transform 0.1s;
}
.heatmap-cell:hover { transform: scale(1.2); z-index: 10; position:relative;}
.heatmap-level-1 { background-color: #9be9a8; }
.heatmap-level-2 { background-color: #40c463; }
.heatmap-level-3 { background-color: #30a14e; }
.heatmap-level-4 { background-color: #216e39; }
.heatmap-level-neg-1 { background-color: #fca5a5; } /* Light red for failures */
.heatmap-level-neg-2 { background-color: #ef4444; }
.heatmap-level-neg-3 { background-color: #b91c1c; }

/* Custom Checkboxes */
.check-build input, .check-break input { position: absolute; opacity: 0; cursor: pointer; height: 100%; width: 100%; z-index: 2;}
.check-build .checkmark { display: inline-flex; align-items: center; justify-content: center; background-color: #f8fafc; border: 2px solid #cbd5e1; transition: all 0.2s; position: relative;}
.check-build:hover input ~ .checkmark { background-color: #f0fdf4; border-color: #86efac; }
.check-build input:checked ~ .checkmark { border-color: #22c55e; background-color: #22c55e; }
.check-build .checkmark:after { content: ""; position: absolute; display: none; left: 8px; top: 4px; width: 6px; height: 12px; border: solid white; border-width: 0 2px 2px 0; transform: rotate(45deg); }
.check-build input:checked ~ .checkmark:after { display: block; }

.check-break .checkmark { display: inline-flex; align-items: center; justify-content: center; background-color: #f8fafc; border: 2px solid #cbd5e1; transition: all 0.2s; position: relative;}
.check-break:hover input ~ .checkmark { background-color: #fef2f2; border-color: #fca5a5; }
.check-break input:checked ~ .checkmark { border-color: #ef4444; background-color: #ef4444; }
.check-break .checkmark:after { content: "×"; position: absolute; display: none; color: white; font-weight: bold; font-size: 20px; line-height: 1; top:-1px; }
.check-break input:checked ~ .checkmark:after { display: block; }

.focus-card:hover { transform: translateY(-2px); box-shadow: 0 10px 25px rgba(0,0,0,0.05) !important; z-index:10;}

/* Toggle switch for form */
.habit-switch { appearance: none; width: 50px; height: 26px; background: #ef4444; border-radius: 50px; position: relative; cursor: pointer; outline: none; transition: background 0.3s; }
.habit-switch::after { content: ''; position: absolute; top: 3px; left: 3px; width: 20px; height: 20px; background: white; border-radius: 50%; transition: transform 0.3s; }
.habit-switch:checked { background: #22c55e; }
.habit-switch:checked::after { transform: translateX(24px); }
</style>

<!-- HEADER: IDENTITY ENGINE -->
<div class="row fade-in mb-4 pb-3 border-bottom">
    <div class="col-md-8">
        <h1 class="h2 fw-bold text-dark mb-2" style="letter-spacing:-0.5px;">
            <i class="fa-solid fa-fingerprint text-primary me-2"></i> <?= htmlspecialchars($intelligence['identity']) ?>
        </h1>
        <div class="d-flex align-items-center gap-3">
            <div class="progress flex-grow-1" style="height: 14px; border-radius: 10px; background-color: #e2e8f0; width: 300px;">
                <div class="progress-bar progress-bar-striped progress-bar-animated <?= $intelligence['score'] >= 75 ? 'bg-success' : ($intelligence['score'] >= 50 ? 'bg-warning' : 'bg-danger') ?>" role="progressbar" style="width: <?= $intelligence['score'] ?>%;"></div>
            </div>
            <span class="fw-bold text-secondary">مؤشر الانضباط: <?= $intelligence['score'] ?>/100</span>
        </div>
    </div>
    <div class="col-md-4 text-md-end mt-3 mt-md-0 align-self-center">
        <button class="btn btn-dark rounded-pill px-4 fw-bold shadow-sm py-2" type="button" data-bs-toggle="collapse" data-bs-target="#addBehaviorForm">
            <i class="fa-solid fa-plus me-1"></i> تشكيل سلوك جديد
        </button>
    </div>
</div>

<!-- PRE-FAILURE & INSIGHTS (INTERVENTION) -->
<div class="row g-3 mb-4 fade-in">
    <?php if(!empty($warnings)): foreach($warnings as $w): ?>
    <div class="col-md-6">
        <div class="alert alert-danger border-danger border-2 shadow-sm rounded-4 py-3 px-4 fw-bold d-flex align-items-center mb-0 h-100">
            <div class="bg-danger text-white rounded-circle p-2 me-3 d-flex align-items-center justify-content-center" style="width:40px;height:40px;"><i class="fa-solid fa-triangle-exclamation"></i></div>
            <span class="text-dark"><?= htmlspecialchars($w) ?></span>
        </div>
    </div>
    <?php endforeach; endif; ?>

    <?php if(!empty($behaviorInsights)): foreach($behaviorInsights as $insight): ?>
    <div class="col-md-6">
        <div class="alert bg-white border shadow-sm rounded-4 py-3 px-4 fw-bold d-flex align-items-center mb-0 h-100">
            <div class="bg-primary text-white rounded-circle p-2 me-3 d-flex align-items-center justify-content-center" style="width:40px;height:40px;"><i class="fa-solid fa-brain"></i></div>
            <span class="text-secondary"><?= htmlspecialchars($insight) ?></span>
        </div>
    </div>
    <?php endforeach; endif; ?>
</div>

<!-- HEATMAP: DISCIPLINE CONSTELLATION -->
<div class="row fade-in mb-4">
    <div class="col-12">
        <div class="card border-0 shadow-sm rounded-4 bg-white p-4">
            <h6 class="fw-bold text-secondary mb-3"><i class="fa-solid fa-calendar-days me-2"></i> خريطة الانضباط (آخر 90 يوماً)</h6>
            <div class="heatmap-grid" dir="ltr">
                <?php 
                if(isset($heatmapData)): 
                    foreach($heatmapData as $date => $score): 
                        $class = "heatmap-cell";
                        if ($score > 3) $class .= " heatmap-level-4";
                        elseif ($score > 1) $class .= " heatmap-level-3";
                        elseif ($score == 1) $class .= " heatmap-level-2";
                        elseif ($score <= -3) $class .= " heatmap-level-neg-3";
                        elseif ($score <= -1) $class .= " heatmap-level-neg-2";
                ?>
                <div class="<?= $class ?>" title="<?= $date ?> | التقييم: <?= $score ?>"></div>
                <?php endforeach; endif; ?>
            </div>
            <div class="d-flex align-items-center justify-content-end gap-2 mt-3 fs-7 text-muted">
                <span>انتكاس حاد</span>
                <div class="heatmap-cell heatmap-level-neg-3"></div>
                <div class="heatmap-cell heatmap-level-neg-2"></div>
                <div class="heatmap-cell"></div>
                <div class="heatmap-cell heatmap-level-2"></div>
                <div class="heatmap-cell heatmap-level-3"></div>
                <div class="heatmap-cell heatmap-level-4"></div>
                <span>انضباط حاد</span>
            </div>
        </div>
    </div>
</div>

<!-- ADD HABIT FORM -->
<div class="row fade-in mb-4">
    <div class="col-12">
        <div class="collapse" id="addBehaviorForm">
            <div class="card card-body shadow-sm border-0 rounded-4 bg-white p-4" style="border-top: 4px solid #1e293b !important;">
                <h5 class="fw-bold mb-3" id="behaviorFormTitle"><i class="fa-solid fa-code-branch text-dark me-2"></i> توجيه سلوك جديد</h5>
                <form action="<?= BASE_URL ?>/behavior/storeHabit" method="POST" class="row g-3 align-items-end" id="habitForm">
                    <input type="hidden" name="habit_id" id="habit_id" value="">
                    <div class="col-md-2 text-center border-end">
                        <label class="form-label fs-7 fw-bold text-secondary d-block">هدم أم بناء؟</label>
                        <div class="d-flex align-items-center justify-content-center gap-2">
                            <span class="fs-7 fw-bold text-danger">هدم 🚫</span>
                            <input type="checkbox" name="habit_type" id="habit_type" value="build" class="habit-switch" title="بناء (أخضر) / هدم (أحمر)">
                            <span class="fs-7 fw-bold text-success">بناء 🚀</span>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fs-7 fw-bold text-secondary">اسم السلوك / العادة</label>
                        <input type="text" name="name" id="habit_name" class="form-control bg-light border-0 shadow-none fw-bold" placeholder="مثال: القراءة اليومية، أو التوقف عن التدخين" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fs-7 fw-bold text-secondary">الوزن بصمة (1-3)</label>
                        <input type="number" name="intensity" id="habit_intensity" min="1" max="3" value="1" class="form-control bg-light border-0 shadow-none">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label fs-7 fw-bold text-secondary">درجة التأثير</label>
                        <select name="severity" id="habit_severity" class="form-select border-0 shadow-none bg-light fw-bold">
                            <option value="high">جذري 🔥</option>
                            <option value="medium" selected>مؤثر</option>
                            <option value="low">طفيف</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-light w-100 fw-bold shadow-sm py-2 mb-2 d-none" id="btnCancelEdit" onclick="cancelEditHabit()">إلغاء</button>
                        <button type="submit" class="btn btn-dark w-100 fw-bold shadow-sm py-2" id="btnSubmitHabit">تشكيل</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- BEHAVIORS SPLIT -->
<?php 
$buildHabits = array_filter($dailyBehaviors, fn($b) => $b->habit_type === 'build');
$breakHabits = array_filter($dailyBehaviors, fn($b) => $b->habit_type === 'break');
?>

<div class="row g-4 fade-in">
    <!-- SECTION: CONSTRUCTIVE HABITS (BUILD) -->
    <div class="col-md-6">
        <div class="card border-0 shadow-sm rounded-4 h-100" style="background-color: #f8fafc;">
            <div class="card-header bg-transparent border-0 p-4 pb-2">
                <h5 class="fw-bold text-success mb-0"><i class="fa-solid fa-rocket me-2"></i> مسار البناء (اكتساب)</h5>
                <p class="text-secondary fs-7 mt-1">تأشير المربع يعني الإنجاز! حاول الحفاظ على السلسلة مستمرة.</p>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush bg-transparent">
                    <?php if(empty($buildHabits)): ?>
                        <li class="list-group-item bg-transparent text-center py-4 border-0">
                            <p class="text-muted fw-bold mb-0">لا يوجد سلوكيات إيجابية لتتبعها.</p>
                        </li>
                    <?php endif; ?>
                    <?php foreach($buildHabits as $b): ?>
                        <li class="list-group-item p-3 focus-card transition-all bg-transparent border-bottom">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="d-flex align-items-center gap-3 w-100">
                                    <label class="check-build flex-shrink-0" style="width:28px;height:28px;" title="تم إنجازه؟">
                                        <input type="checkbox" onchange="toggleBehavior(<?= $b->id ?>, 'build', this)" <?= $b->today_status == 1 ? 'checked' : '' ?>>
                                        <span class="checkmark w-100 h-100 rounded"></span>
                                    </label>
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1 fw-bold text-dark d-flex align-items-center justify-content-between">
                                            <?= htmlspecialchars($b->name) ?>
                                            <span id="behavior-loader-<?= $b->id ?>" style="display:none;" class="spinner-border spinner-border-sm text-success ms-2"></span>
                                        </h6>
                                        <div class="d-flex align-items-center gap-2 mt-1">
                                            <span class="badge bg-white border text-dark shadow-sm">🔥 صمود: <?= $b->current_streak ?> يوم</span>
                                            <div class="d-flex gap-1 ms-auto">
                                                <?php foreach($b->last_7_days as $dayData): $color = ($dayData['status'] == 1) ? '#22c55e' : '#e2e8f0'; ?>
                                                <div style="width: 8px; height: 8px; border-radius: 2px; background-color: <?= $color ?>;"></div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <a href="javascript:void(0)" class="text-primary opacity-50 hover-opacity flex-shrink-0 me-2" onclick='editHabit(<?= json_encode($b) ?>)'><i class="fa-solid fa-pen"></i></a>
                                    <a href="javascript:void(0)" class="text-danger opacity-50 hover-opacity flex-shrink-0" onclick="deleteBehavior(<?= $b->id ?>, this)"><i class="fa-solid fa-xmark"></i></a>
                                </div>
                            </div>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>

    <!-- SECTION: DESTRUCTIVE HABITS (BREAK) -->
    <div class="col-md-6">
        <div class="card border-0 shadow-sm rounded-4 h-100" style="background-color: #fef2f2;">
            <div class="card-header bg-transparent border-0 p-4 pb-2">
                <h5 class="fw-bold text-danger mb-0"><i class="fa-solid fa-shield-halved me-2"></i> مسار الهدم (تخلص)</h5>
                <p class="text-secondary fs-7 mt-1">تأشير المربع يعني <strong class="text-danger">الانتكاس</strong>. اتركها فارغة لتعزيز الانضباط.</p>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush bg-transparent">
                    <?php if(empty($breakHabits)): ?>
                        <li class="list-group-item bg-transparent text-center py-4 border-0">
                            <p class="text-muted fw-bold mb-0">لا يوجد سلوكيات سلبية تتتبعها.</p>
                        </li>
                    <?php endif; ?>
                    <?php foreach($breakHabits as $b): ?>
                        <li class="list-group-item p-3 focus-card transition-all bg-transparent border-bottom">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="d-flex align-items-center gap-3 w-100">
                                    <label class="check-break flex-shrink-0" style="width:28px;height:28px;" title="وقعت في الانتكاسة؟">
                                        <input type="checkbox" onchange="toggleBehavior(<?= $b->id ?>, 'break', this)" <?= $b->today_status == 1 ? 'checked' : '' ?>>
                                        <span class="checkmark w-100 h-100 rounded"></span>
                                    </label>
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1 fw-bold text-dark d-flex align-items-center justify-content-between">
                                            <?= htmlspecialchars($b->name) ?>
                                            <span id="behavior-loader-<?= $b->id ?>" style="display:none;" class="spinner-border spinner-border-sm text-danger ms-2"></span>
                                        </h6>
                                        <div class="d-flex align-items-center gap-2 mt-1">
                                            <span class="badge bg-white border text-dark shadow-sm">🛡️ حماية: <?= $b->current_streak ?> يوم</span>
                                            <div class="d-flex gap-1 ms-auto">
                                                <?php foreach($b->last_7_days as $dayData): $color = ($dayData['status'] == 0) ? '#ef4444' : '#e2e8f0'; /* For visual 0 is fail */ ?>
                                                <div style="width: 8px; height: 8px; border-radius: 2px; background-color: <?= $color ?>;"></div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <a href="javascript:void(0)" class="text-primary opacity-50 hover-opacity flex-shrink-0 me-2" onclick='editHabit(<?= json_encode($b) ?>)'><i class="fa-solid fa-pen"></i></a>
                                    <a href="javascript:void(0)" class="text-danger opacity-50 hover-opacity flex-shrink-0" onclick="deleteBehavior(<?= $b->id ?>, this)"><i class="fa-solid fa-xmark"></i></a>
                                </div>
                            </div>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<script>
function toggleBehavior(habitId, type, checkbox) {
    const status = checkbox.checked ? 1 : 0; 
    const loader = document.getElementById('behavior-loader-' + habitId);
    if(loader) loader.style.display = 'inline-block';
    
    let triggerReason = null;

    // Zero-friction check: Only ask for trigger if they "failed"
    // Fail for break = checked (1). Fail for build = unchecked (0).
    const isFailure = (type === 'break' && status === 1) || (type === 'build' && status === 0);
    
    if (isFailure) {
        triggerReason = prompt('سجلت انتكاسة مؤقتة! ما هو المحفز أو السبب الخفي؟ (اختياري - سيساعدنا في كشف الأنماط)');
    }

    fetch(`<?= BASE_URL ?>/behavior/toggleLog`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ habit_id: habitId, status: status, trigger_reason: triggerReason })
    })
    .then(res => res.json())
    .then(data => {
        if(loader) loader.style.display = 'none';
        if(data.success) {
            checkbox.closest('.list-group-item').style.animation = 'pulse 0.5s';
        } else {
            alert('فشل الحفظ. تأكد من الجلسة.');
            checkbox.checked = !status; 
        }
    })
    .catch(err => {
        if(loader) loader.style.display = 'none';
        checkbox.checked = !status; 
    });
}

function deleteBehavior(id, btn) {
    if(!confirm('هل تريد حذف هذا المسار نهائياً؟ ستفقد جميع السجلات والتراكمات المرتبطة به.')) return;
    
    // UI Feedback
    const li = btn.closest('li');
    li.style.opacity = '0.5';
    
    fetch('<?= BASE_URL ?>/behavior/deleteHabit/' + id, { method: 'POST' })
    .then(() => li.remove())
    .catch(() => alert('حدث خطأ.'));
}

function editHabit(habit) {
    // Open collapse if closed
    const collapseEl = document.getElementById('addBehaviorForm');
    const bsCollapse = bootstrap.Collapse.getOrCreateInstance(collapseEl);
    bsCollapse.show();
    
    // Fill the fields
    document.getElementById('habit_id').value = habit.id;
    document.getElementById('habit_name').value = habit.name;
    document.getElementById('habit_intensity').value = habit.intensity;
    document.getElementById('habit_severity').value = habit.severity;
    document.getElementById('habit_type').checked = habit.habit_type === 'build';
    
    // Update UI elements
    document.getElementById('behaviorFormTitle').innerHTML = '<i class="fa-solid fa-pen text-primary me-2"></i> تعديل السلوك';
    document.getElementById('btnSubmitHabit').innerText = 'تحديث';
    document.getElementById('btnSubmitHabit').classList.replace('btn-dark', 'btn-primary');
    document.getElementById('btnCancelEdit').classList.remove('d-none');
}

function cancelEditHabit() {
    // Reset form
    document.getElementById('habitForm').reset();
    document.getElementById('habit_id').value = '';
    
    // Update UI elements
    document.getElementById('behaviorFormTitle').innerHTML = '<i class="fa-solid fa-code-branch text-dark me-2"></i> توجيه سلوك جديد';
    document.getElementById('btnSubmitHabit').innerText = 'تشكيل';
    document.getElementById('btnSubmitHabit').classList.replace('btn-primary', 'btn-dark');
    document.getElementById('btnCancelEdit').classList.add('d-none');
}
</script>
