<?php
require_once '../config/database.php';
require_once '../includes/functions.php';

$pageTitle = 'Available Tasks';
include 'side.php';

$conn   = getConnection();
$userId = $_SESSION['user_id'];

$internalTaskTypes = ['trivia','quiz','blog','survey','meme','transcription'];
$externalTaskTypes = ['video','ads','spin','chat'];

/* ══ HANDLE SUBMISSION ══ */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['submit_task'])) {
    $taskId = intval($_POST['task_id']??0);
    if ($taskId<=0) { setFlash('error','Invalid task!'); header('Location: tasks.php'); exit; }
    $tq=mysqli_prepare($conn,"SELECT * FROM tasks WHERE id=? AND status='active'");
    mysqli_stmt_bind_param($tq,"i",$taskId); mysqli_stmt_execute($tq);
    $task=mysqli_fetch_assoc(mysqli_stmt_get_result($tq)); mysqli_stmt_close($tq);
    if (!$task) { setFlash('error','Task not found or inactive!'); header('Location: tasks.php'); exit; }
    $todayCount=mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) as cnt FROM task_completions WHERE user_id=$userId AND task_id=$taskId AND DATE(created_at)=CURDATE()"))['cnt'];
    if ($todayCount>=$task['daily_limit_per_user']) { setFlash('error','Daily limit reached!'); header('Location: tasks.php'); exit; }
    if ($task['total_limit']) {
        $tc=mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) as cnt FROM task_completions WHERE task_id=$taskId AND status='completed'"))['cnt'];
        if ($tc>=$task['total_limit']) { setFlash('error','Task at maximum completions!'); header('Location: tasks.php'); exit; }
    }
    $screenshotPath=null;
    if ($task['requires_proof'] && isset($_FILES['proof_screenshot']) && $_FILES['proof_screenshot']['error']===UPLOAD_ERR_OK) {
        $ext=strtolower(pathinfo($_FILES['proof_screenshot']['name'],PATHINFO_EXTENSION));
        if (!in_array($ext,['jpg','jpeg','png','gif','webp'])) { setFlash('error','Invalid screenshot type!'); header('Location: tasks.php'); exit; }
        if ($_FILES['proof_screenshot']['size']>2*1024*1024) { setFlash('error','Screenshot too large! Max 2MB.'); header('Location: tasks.php'); exit; }
        $ud='../uploads/task_proofs/'; if (!file_exists($ud)) mkdir($ud,0755,true);
        $nf='proof_'.$userId.'_'.$taskId.'_'.time().'.'.$ext;
        if (move_uploaded_file($_FILES['proof_screenshot']['tmp_name'],$ud.$nf)) $screenshotPath='uploads/task_proofs/'.$nf;
    }
    $sub=[]; $quizScore=null; $passed=true;
    if (in_array($task['task_type'],['quiz','trivia'])&&$task['content_type']==='internal') {
        $qa=$_POST['quiz_answers']??[];
        $qq=mysqli_query($conn,"SELECT * FROM task_quizzes WHERE task_id=$taskId ORDER BY order_number");
        $tp=0; $ep=0;
        while ($q=mysqli_fetch_assoc($qq)) {
            $pts=intval($q['points']); $tp+=$pts;
            $ua=strtoupper(trim($qa[$q['id']]??'')); $ca=strtoupper(trim($q['correct_answer']));
            if ($ua===$ca) $ep+=$pts;
            $sub['answers'][]=['question_id'=>$q['id'],'user_answer'=>$ua,'correct_answer'=>$ca,'is_correct'=>($ua===$ca)];
        }
        $quizScore=$tp>0?round(($ep/$tp)*100,2):0;
        $sub['score']=$quizScore; $sub['earned_points']=$ep; $sub['total_points']=$tp;
        if ($quizScore<$task['pass_percentage']) $passed=false;
    }
    if ($task['task_type']==='survey'&&$task['content_type']==='internal') $sub['survey_responses']=$_POST['survey_answers']??[];
    if ($task['task_type']==='blog'&&$task['content_type']==='internal') {
        $bc=$_POST['blog_content']??''; $wc=str_word_count(strip_tags($bc));
        $sub['blog_content']=$bc; $sub['word_count']=$wc;
        $br=mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM task_blog_requirements WHERE task_id=$taskId"));
        if ($br&&$br['enable_word_count']) {
            if ($wc<$br['min_words']) { setFlash('error','Too short! Min '.$br['min_words'].' words.'); header('Location: tasks.php'); exit; }
            if ($br['max_words']&&$wc>$br['max_words']) { setFlash('error','Too long! Max '.$br['max_words'].' words.'); header('Location: tasks.php'); exit; }
        }
    }
    if ($task['task_type']==='meme'&&$task['content_type']==='internal') {
        if (isset($_FILES['meme_upload'])&&$_FILES['meme_upload']['error']===UPLOAD_ERR_OK) {
            $mr=mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM task_meme_requirements WHERE task_id=$taskId"));
            $af=$mr?explode(',',$mr['allowed_formats']):['jpg','png','gif'];
            $ms=($mr?intval($mr['max_file_size_mb']):5)*1024*1024;
            $ext=strtolower(pathinfo($_FILES['meme_upload']['name'],PATHINFO_EXTENSION));
            if (!in_array($ext,$af)) { setFlash('error','Invalid format! Allowed: '.implode(', ',$af)); header('Location: tasks.php'); exit; }
            if ($_FILES['meme_upload']['size']>$ms) { setFlash('error','File too large!'); header('Location: tasks.php'); exit; }
            $ud='../uploads/task_memes/'; if (!file_exists($ud)) mkdir($ud,0755,true);
            $nf='meme_'.$userId.'_'.$taskId.'_'.time().'.'.$ext;
            if (move_uploaded_file($_FILES['meme_upload']['tmp_name'],$ud.$nf)) $sub['meme_file']='uploads/task_memes/'.$nf;
        }
    }
    if ($task['task_type']==='transcription'&&$task['content_type']==='internal') {
        $tt=$_POST['transcription_text']??''; $sub['transcription']=$tt; $sub['word_count']=str_word_count($tt);
    }
    if ($task['content_type']==='external') $sub['proof_text']=$_POST['proof_text']??'';
    $status='pending';
    if ($task['auto_approve']) $status=$passed?'completed':'failed';
    $rewardEarned=$passed?floatval($task['reward']):0;
    $sj=json_encode($sub);
    $stmt=mysqli_prepare($conn,"INSERT INTO task_completions(task_id,user_id,status,reward_earned,screenshot,submission_data,created_at)VALUES(?,?,?,?,?,?,NOW())");
    mysqli_stmt_bind_param($stmt,"iisdss",$taskId,$userId,$status,$rewardEarned,$screenshotPath,$sj);
    if (mysqli_stmt_execute($stmt)) {
        if ($status==='completed'&&$rewardEarned>0) {
            $wk=$task['task_type']==='quiz'?'trivia':$task['task_type'];
            $desc="Completed: ".$task['title']." (ID:$taskId)";
            $ref="TASK_{$taskId}_".time()."_".mt_rand(100,999);
            $credited=creditWallet($userId,$wk,$rewardEarned,$desc,$ref);
            if ($credited) setFlash('success','🎉 Earned '.($cd['currency_symbol']??'KSh').' '.number_format($rewardEarned,2).'!');
            else setFlash('warning',"Task done but reward pending. Contact support (Task #$taskId)");
        } elseif ($status==='failed') { setFlash('warning',"Failed! Score: $quizScore%. Need ".$task['pass_percentage']."%."); }
        else { setFlash('info','✅ Submitted for review!'); }
    } else { setFlash('error','Submission failed. Please try again.'); }
    mysqli_stmt_close($stmt);
    header('Location: tasks.php'); exit;
}

/* ══ FETCH DATA ══ */
$filter=$_GET['filter']??'all';
$fsql="WHERE t.status='active'";
if ($filter!=='all'&&in_array($filter,['video','survey','trivia','quiz','ads','blog','meme','transcription','chat','spin']))
    $fsql.=" AND t.task_type='".mysqli_real_escape_string($conn,$filter)."'";

$tasks=[];
$tq=mysqli_query($conn,"SELECT t.*,
    (SELECT COUNT(*) FROM task_completions WHERE task_id=t.id AND user_id=$userId AND DATE(created_at)=CURDATE()) as today_completions,
    (SELECT COUNT(*) FROM task_completions WHERE task_id=t.id AND status='completed') as total_completions
    FROM tasks t $fsql ORDER BY t.show_in_sidebar DESC, t.created_at DESC");
while ($r=mysqli_fetch_assoc($tq)) $tasks[]=$r;

$taskContents=[];
foreach ($tasks as $t) {
    $tid=$t['id']; $taskContents[$tid]=['type'=>$t['content_type']];
    if ($t['content_type']==='internal') {
        if (in_array($t['task_type'],['quiz','trivia'])) {
            $taskContents[$tid]['quiz_questions']=[]; $q=mysqli_query($conn,"SELECT * FROM task_quizzes WHERE task_id=$tid ORDER BY order_number"); while ($r=mysqli_fetch_assoc($q)) $taskContents[$tid]['quiz_questions'][]=$r;
        } elseif ($t['task_type']==='survey') {
            $taskContents[$tid]['survey_questions']=[]; $q=mysqli_query($conn,"SELECT * FROM task_survey_questions WHERE task_id=$tid ORDER BY order_number"); while ($r=mysqli_fetch_assoc($q)) $taskContents[$tid]['survey_questions'][]=$r;
        } elseif ($t['task_type']==='blog') {
            $q=mysqli_query($conn,"SELECT * FROM task_blog_requirements WHERE task_id=$tid LIMIT 1"); $taskContents[$tid]['blog_data']=mysqli_fetch_assoc($q);
        } elseif ($t['task_type']==='meme') {
            $q=mysqli_query($conn,"SELECT * FROM task_meme_requirements WHERE task_id=$tid LIMIT 1"); $taskContents[$tid]['meme_data']=mysqli_fetch_assoc($q);
        } elseif ($t['task_type']==='transcription') {
            $q=mysqli_query($conn,"SELECT * FROM task_transcription_content WHERE task_id=$tid LIMIT 1"); $taskContents[$tid]['transcription_data']=mysqli_fetch_assoc($q);
        }
    }
}
$taskContentsJson=json_encode($taskContents);

$taskCounts=[]; $cq=mysqli_query($conn,"SELECT task_type,COUNT(*) as cnt FROM tasks WHERE status='active' GROUP BY task_type"); while ($r=mysqli_fetch_assoc($cq)) $taskCounts[$r['task_type']]=$r['cnt'];
$totalTasks=array_sum($taskCounts);
$myStats=mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) as tot,SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as done,SUM(CASE WHEN status='pending' THEN 1 ELSE 0 END) as pend,SUM(CASE WHEN status='completed' THEN reward_earned ELSE 0 END) as earned FROM task_completions WHERE user_id=$userId"));
$flash=getFlash();
$cs=$cd['currency_symbol']??'KSh';

/* type config */
$typeConfig=[
    'quiz'          =>['#818cf8','fa-brain',         'linear-gradient(135deg,#4f46e5,#8b5cf6)'],
    'trivia'        =>['#818cf8','fa-brain',          'linear-gradient(135deg,#4f46e5,#8b5cf6)'],
    'survey'        =>['#22d3ee','fa-chart-simple',   'linear-gradient(135deg,#0891b2,#06b6d4)'],
    'blog'          =>['#34d399','fa-pen-nib',        'linear-gradient(135deg,#059669,#10b981)'],
    'video'         =>['#f87171','fa-clapperboard',   'linear-gradient(135deg,#dc2626,#f97316)'],
    'chat'          =>['#60a5fa','fa-message',        'linear-gradient(135deg,#2563eb,#3b82f6)'],
    'transcription' =>['#fbbf24','fa-microphone',     'linear-gradient(135deg,#d97706,#f59e0b)'],
    'ads'           =>['#c084fc','fa-rectangle-ad',   'linear-gradient(135deg,#7c3aed,#a855f7)'],
    'meme'          =>['#f472b6','fa-image',          'linear-gradient(135deg,#be185d,#ec4899)'],
    'spin'          =>['#2dd4bf','fa-rotate',         'linear-gradient(135deg,#0d9488,#14b8a6)'],
];
?>
<style>
<style>
/* ═══════════════════════════════════════════════
   TASKS PAGE — Modern responsive layout
   Task list + bottom-sheet modal (scrollable body, pinned footer)
═══════════════════════════════════════════════ */
*,*::before,*::after{box-sizing:border-box}
body{overflow-x:hidden}
.tk-pg{padding:0;width:100%;overflow-x:hidden}

/* ── BANNER ── */
.tk-banner{padding:12px 12px 0}
.tk-banner-inner{
    background:linear-gradient(135deg,#1a0e3d 0%,#0d0922 50%,#001510 100%);
    border-radius:16px;padding:14px 13px 16px;
    border:1px solid rgba(255,255,255,.07);
    position:relative;overflow:hidden;margin-bottom:12px;
}
.tk-banner-inner::before{content:'';position:absolute;inset:0;background:radial-gradient(ellipse 60% 70% at 85% 40%,rgba(99,102,241,.1),transparent);pointer-events:none}
.tk-banner-title{font-size:18px;font-weight:900;letter-spacing:-.4px;color:#fff;margin-bottom:2px;position:relative;z-index:1}
.tk-banner-sub{font-size:11px;color:rgba(255,255,255,.38);margin-bottom:13px;position:relative;z-index:1}
.tk-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;position:relative;z-index:1}
.tks{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.07);border-radius:10px;padding:8px 4px;text-align:center}
.tks-val{font-size:14px;font-weight:900;color:#fff;letter-spacing:-.3px;line-height:1}
.tks-lbl{font-size:8.5px;text-transform:uppercase;letter-spacing:.5px;color:rgba(255,255,255,.38);font-weight:600;margin-top:3px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}

/* ── FLASH ── */
.tk-flash{display:flex;align-items:center;gap:8px;padding:9px 12px;border-radius:10px;font-size:12px;font-weight:600;margin:0 12px 11px;border-left:3px solid}
.tk-flash.success{background:rgba(16,185,129,.08);border-color:#10b981;color:#34d399}
.tk-flash.error{background:rgba(239,68,68,.07);border-color:#ef4444;color:#f87171}
.tk-flash.warning{background:rgba(245,158,11,.08);border-color:#f59e0b;color:#fbbf24}
.tk-flash.info{background:rgba(59,130,246,.08);border-color:#3b82f6;color:#60a5fa}
[data-theme=light] .tk-flash.success{color:#059669}[data-theme=light] .tk-flash.error{color:#dc2626}

/* ── FILTER PILLS ── */
.tk-filters{padding:0 12px;margin-bottom:10px}
.tk-filter-scroll{display:flex;gap:5px;overflow-x:auto;padding-bottom:2px;scrollbar-width:none;-webkit-overflow-scrolling:touch}
.tk-filter-scroll::-webkit-scrollbar{display:none}
.tkf{display:inline-flex;align-items:center;gap:4px;padding:5px 11px;border-radius:20px;font-size:11.5px;font-weight:700;white-space:nowrap;flex-shrink:0;text-decoration:none;border:1.5px solid rgba(255,255,255,.1);background:rgba(255,255,255,.06);color:rgba(255,255,255,.55);transition:all .15s}
.tkf:active,.tkf.on{background:rgba(255,255,255,.14);color:#fff;border-color:rgba(255,255,255,.2)}
.tkf-type.on{border-color:currentColor}
[data-theme=light] .tkf{background:rgba(0,0,0,.04);border-color:rgba(0,0,0,.1);color:rgba(30,10,60,.5)}
[data-theme=light] .tkf.on{background:rgba(0,0,0,.1);color:#1a0035}

/* ── TASK LIST ── */
.tk-body{padding:0 12px}
.tk-section-hdr{display:flex;align-items:center;gap:8px;margin:2px 0 8px}
.tk-section-hdr-txt{font-size:9px;font-weight:800;letter-spacing:1.5px;text-transform:uppercase;color:rgba(255,255,255,.3);white-space:nowrap}
.tk-section-hdr-line{flex:1;height:1px;background:rgba(255,255,255,.07)}
[data-theme=light] .tk-section-hdr-txt{color:rgba(60,20,100,.35)}
[data-theme=light] .tk-section-hdr-line{background:rgba(150,80,200,.1)}

/* ── TASK ROW ── */
.trow{display:flex;align-items:center;gap:10px;padding:10px 11px;background:var(--surf);border:1px solid var(--bdr);border-radius:13px;margin-bottom:7px;cursor:pointer;transition:border-color .15s,transform .15s;position:relative;overflow:hidden;-webkit-tap-highlight-color:transparent}
.trow::before{content:'';position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--trow-color,#818cf8);opacity:0;transition:opacity .15s}
.trow:active{transform:scale(.99);border-color:var(--trow-color)}
.trow:active::before{opacity:1}
.trow.done{opacity:.4;pointer-events:none}
.trow-ico{width:42px;height:42px;border-radius:11px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:17px;color:#fff;position:relative}
.trow-ico-done{position:absolute;inset:0;border-radius:11px;background:rgba(34,197,94,.88);display:flex;align-items:center;justify-content:center;font-size:14px;color:#fff;opacity:0;transition:opacity .15s}
.trow.done .trow-ico-done{opacity:1}
.trow-info{flex:1;min-width:0}
.trow-title{font-size:13px;font-weight:700;color:var(--txt);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-bottom:4px}
.trow-meta{display:flex;align-items:center;gap:5px;overflow:hidden}
.trow-tag{display:inline-flex;align-items:center;padding:2px 6px;border-radius:5px;font-size:8.5px;font-weight:800;text-transform:uppercase;color:#fff;flex-shrink:0}
.trow-diff{padding:2px 6px;border-radius:5px;font-size:8.5px;font-weight:700;flex-shrink:0}
.d-e{background:rgba(16,185,129,.15);color:#34d399}.d-m{background:rgba(245,158,11,.15);color:#fbbf24}.d-h{background:rgba(239,68,68,.12);color:#f87171}
[data-theme=light] .d-e{color:#059669}[data-theme=light] .d-m{color:#b45309}[data-theme=light] .d-h{color:#dc2626}
.trow-count{font-size:9.5px;color:var(--txt3);display:flex;align-items:center;gap:3px;flex-shrink:0}
@media(max-width:340px){.trow-count{display:none}}
.trow-right{text-align:right;flex-shrink:0;min-width:58px;max-width:75px}
.trow-reward{font-size:13px;font-weight:900;color:var(--txt);line-height:1;word-break:break-all}
.trow-reward-lbl{font-size:8.5px;color:var(--txt3);text-transform:uppercase;margin-top:1px}
.trow-cta{display:inline-flex;align-items:center;justify-content:center;margin-top:5px;padding:3px 9px;border-radius:6px;font-size:9.5px;font-weight:800;color:#fff;transition:.15s;white-space:nowrap}
.trow-hot{position:absolute;top:0;right:0;background:linear-gradient(135deg,#f59e0b,#f97316);color:#fff;font-size:8px;font-weight:800;padding:2px 8px;border-radius:0 13px 0 8px;text-transform:uppercase}
.trow-timer{display:inline-flex;align-items:center;gap:3px;font-size:9px;color:var(--txt3);margin-top:2px}
.tk-empty{text-align:center;padding:44px 16px;background:var(--surf);border:1px solid var(--bdr);border-radius:14px}
.tk-empty i{font-size:38px;color:var(--txt3);margin-bottom:11px;display:block}
.tk-empty-t{font-size:14px;font-weight:700;color:var(--txt);margin-bottom:4px}
.tk-empty-s{font-size:12px;color:var(--txt2)}

/* ═══════════════════════════════════════════════
   BOTTOM SHEET — THE FIX
   .bsheet = fixed height flex column
   #taskForm = flex:1 flex-column (KEY!)
   .bsheet-body = flex:1 overflow-y:auto min-height:0 (KEY!)
   .bsheet-ftr = flex-shrink:0 (always visible)
═══════════════════════════════════════════════ */
.bsheet-overlay{
    display:none;
    position:fixed;inset:0;
    background:rgba(0,0,0,.55);
    backdrop-filter:blur(8px) brightness(.55);
    -webkit-backdrop-filter:blur(8px) brightness(.55);
    z-index:9000;
    opacity:0;
    transition:opacity .3s ease;
}
.bsheet-overlay.on{display:block;opacity:1}

.bsheet{
    position:fixed;left:0;bottom:0;width:100%;
    height:88svh;height:88vh; /* fixed height, not max-height */
    background:var(--surf);
    border-radius:18px 18px 0 0;
    z-index:9001;
    display:flex;flex-direction:column;
    overflow:hidden; /* clip at fixed height */
    transform:translateY(110%);
    transition:transform .32s cubic-bezier(.22,1,.36,1);
    box-shadow:0 -8px 36px rgba(0,0,0,.45);
}
.bsheet.on{transform:translateY(0)}
@media(min-width:600px){
    .bsheet{left:50%;width:540px;transform:translateX(-50%) translateY(110%)}
    .bsheet.on{transform:translateX(-50%) translateY(0)}
}

/* Drag handle */
.bsheet-handle{width:34px;height:4px;border-radius:2px;background:rgba(255,255,255,.2);margin:8px auto 0;flex-shrink:0}
[data-theme=light] .bsheet-handle{background:rgba(0,0,0,.15)}

/* Header */
.bsheet-hdr{padding:10px 13px 9px;border-bottom:1px solid var(--bdr);flex-shrink:0;display:flex;align-items:center;gap:9px}
.bsheet-hdr-ico{width:34px;height:34px;border-radius:9px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:14px;color:#fff}
.bsheet-hdr-info{flex:1;min-width:0}
.bsheet-hdr-title{font-size:13px;font-weight:800;color:var(--txt);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.3;margin-bottom:1px}
.bsheet-hdr-sub{font-size:10px;color:var(--txt2)}
.bsheet-cls{width:30px;height:30px;border-radius:8px;flex-shrink:0;background:var(--surf2);border:1px solid var(--bdr);color:var(--txt2);font-size:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:.15s;-webkit-tap-highlight-color:transparent}
.bsheet-cls:active,.bsheet-cls:hover{background:#ef4444;color:#fff;border-color:#ef4444}

/* Reward strip */
.bsheet-reward{display:flex;align-items:center;justify-content:space-between;padding:8px 13px;background:var(--surf2);border-bottom:1px solid var(--bdr);flex-shrink:0;gap:6px}
.bsr-left{display:flex;align-items:center;gap:7px;min-width:0;flex:1}
.bsr-ico{width:26px;height:26px;border-radius:7px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:11px;color:#fff}
.bsr-val{font-size:16px;font-weight:900;color:var(--txt);letter-spacing:-.4px}
.bsr-lbl{font-size:8.5px;color:var(--txt2);text-transform:uppercase;letter-spacing:.4px;font-weight:600}
.bsr-right{display:flex;gap:5px;flex-shrink:0}
.bsr-chip{padding:2px 8px;border-radius:6px;font-size:9px;font-weight:700;background:var(--surf);border:1px solid var(--bdr);color:var(--txt2);white-space:nowrap}

/* ★ CRITICAL FLEX CHAIN ★
   bsheet(flex col overflow:hidden)
     → bsheet-handle (shrink:0)
     → bsheet-hdr    (shrink:0)
     → bsheet-reward (shrink:0)
     → #taskForm     (flex:1 flex-col overflow:hidden min-height:0)
         → bsheet-body (flex:1 overflow-y:auto MIN-HEIGHT:0)
         → bsheet-ftr  (shrink:0) ← ALWAYS VISIBLE
*/
#taskForm{
    flex:1;
    display:flex;
    flex-direction:column;
    overflow:hidden;
    min-height:0;
}
.bsheet-body{
    flex:1;
    overflow-y:auto;
    overflow-x:hidden;
    min-height:0;  /* THIS IS THE KEY — allows shrink below content height */
    padding:11px 13px 6px;
    display:flex;
    flex-direction:column;
    gap:9px;
    -webkit-overflow-scrolling:touch;
    overscroll-behavior:contain;
}
.bsheet-body::-webkit-scrollbar{width:3px}
.bsheet-body::-webkit-scrollbar-thumb{background:var(--bdr);border-radius:2px}

.bsheet-ftr{
    flex-shrink:0;
    display:flex;gap:8px;
    padding:10px 13px;
    padding-bottom:max(10px,env(safe-area-inset-bottom,10px));
    border-top:1px solid var(--bdr);
    background:var(--surf);
}
.bsftr-cancel{height:44px;padding:0 13px;background:var(--surf2);border:1px solid var(--bdr);border-radius:10px;color:var(--txt2);font-size:12px;font-weight:700;cursor:pointer;display:flex;align-items:center;gap:5px;flex-shrink:0;-webkit-tap-highlight-color:transparent;transition:.15s}
.bsftr-cancel:active{opacity:.6}
.bsftr-submit{flex:1;height:44px;border:none;border-radius:10px;font-size:14px;font-weight:900;cursor:pointer;color:#fff;display:flex;align-items:center;justify-content:center;gap:7px;background:var(--a);box-shadow:0 3px 12px rgba(var(--ar),.4);-webkit-tap-highlight-color:transparent;transition:opacity .15s}
.bsftr-submit:active{opacity:.75}
.bsftr-submit:disabled{background:var(--surf2)!important;color:var(--txt3)!important;cursor:not-allowed;box-shadow:none!important;border:1px solid var(--bdr)}

/* ── SHEET CONTENT ── */
.bs-timer{display:none;background:var(--surf2);border:1px solid var(--bdr);border-radius:12px;padding:11px;text-align:center}
.bs-timer.on{display:block}
.bs-timer-lbl{font-size:9px;text-transform:uppercase;letter-spacing:1px;color:var(--txt2);font-weight:600;margin-bottom:4px;display:flex;align-items:center;justify-content:center;gap:5px}
.bs-timer-num{font-size:40px;font-weight:900;letter-spacing:-2px;color:var(--a);font-family:monospace;line-height:1}
.bs-timer.warn .bs-timer-num{color:#fbbf24}
.bs-timer.danger .bs-timer-num{color:#f87171;animation:tpulse .5s ease-in-out infinite alternate}
.bs-timer.expired .bs-timer-num{color:var(--txt3);text-decoration:line-through}
@keyframes tpulse{from{opacity:.5}to{opacity:1}}
.bs-timer-sub{font-size:10.5px;color:var(--txt2);margin-top:4px}

.bs-info{background:var(--surf2);border-radius:11px;padding:11px 13px;border-left:3px solid var(--a)}
.bs-info.grn{border-left-color:#10b981}
.bs-info-hdr{font-size:9.5px;font-weight:800;text-transform:uppercase;letter-spacing:.7px;color:var(--txt2);margin-bottom:4px;display:flex;align-items:center;gap:5px}
.bs-info-body{font-size:12px;color:var(--txt);line-height:1.6}

/* Quiz */
.bs-qblock{background:var(--surf2);border:1px solid var(--bdr);border-radius:11px;padding:11px 12px}
.bs-qnum{display:inline-flex;align-items:center;gap:4px;background:var(--a);color:#fff;padding:2px 8px;border-radius:5px;font-size:9px;font-weight:800;margin-bottom:6px}
.bs-qtxt{font-size:12.5px;font-weight:600;color:var(--txt);margin-bottom:8px;line-height:1.5}
.bs-qopts{display:flex;flex-direction:column;gap:6px}
.bs-qopt{display:flex;align-items:center;gap:9px;padding:10px 11px;background:var(--surf);border:1.5px solid var(--bdr);border-radius:10px;cursor:pointer;transition:.12s;-webkit-tap-highlight-color:transparent}
.bs-qopt:active,.bs-qopt:has(input:checked){border-color:var(--a);background:rgba(var(--ar),.06)}
.bs-qopt input[type=radio]{display:none}
.bs-qopt-ltr{width:28px;height:28px;border-radius:50%;background:var(--surf2);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:800;color:var(--txt2);flex-shrink:0;transition:.12s}
.bs-qopt:has(input:checked) .bs-qopt-ltr{background:var(--a);color:#fff}
.bs-qopt-txt{font-size:12.5px;color:var(--txt);flex:1;line-height:1.4}

/* Survey */
.rating-row{display:flex;gap:6px;margin-top:8px;flex-wrap:wrap}
.ropt label{cursor:pointer}.ropt input[type=radio]{display:none}
.ropt-n{width:38px;height:38px;border-radius:8px;background:var(--surf);border:1.5px solid var(--bdr);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:var(--txt);transition:.12s}
.ropt:has(input:checked) .ropt-n{background:var(--a);color:#fff;border-color:var(--a)}

/* Inputs */
.bs-in,.bs-ta{width:100%;padding:10px 11px;border:1.5px solid var(--bdr);border-radius:10px;background:var(--surf2);color:var(--txt);font-size:13px;transition:.15s;outline:none;-webkit-appearance:none}
.bs-in:focus,.bs-ta:focus{border-color:var(--a);box-shadow:0 0 0 3px rgba(var(--ar),.12)}
.bs-in::placeholder,.bs-ta::placeholder{color:var(--txt3)}
.bs-ta{min-height:120px;resize:vertical;line-height:1.6}
.bs-wc{text-align:right;font-size:10.5px;color:var(--txt2);font-weight:600;margin-top:3px}

/* File upload */
.bs-upload{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:18px 14px;background:var(--surf2);border:2px dashed rgba(var(--ar),.3);border-radius:11px;cursor:pointer;transition:.15s;text-align:center;gap:6px;-webkit-tap-highlight-color:transparent}
.bs-upload:active,.bs-upload:hover{border-color:rgba(var(--ar),.6)}
.bs-upload input{display:none}
.bs-upload i{font-size:24px;color:var(--a)}
.bs-upload span{font-size:11.5px;color:var(--txt2);font-weight:500;line-height:1.5}
.bs-fprev img{max-width:100%;max-height:140px;border-radius:9px;margin-top:8px;border:1px solid var(--bdr)}

/* Video */
.vwrap{position:relative;padding-bottom:56.25%;height:0;overflow:hidden;border-radius:11px}
.vwrap iframe{position:absolute;inset:0;width:100%;height:100%;border:none}
.vwrap.tiktok{padding-bottom:125%}
.vplayer{width:100%;border-radius:11px}
.bs-vprog{width:100%;height:5px;background:var(--surf2);border-radius:3px;overflow:hidden;margin-top:8px}
.bs-vprog-fill{height:100%;background:linear-gradient(90deg,var(--a),#10b981);border-radius:3px;transition:width .3s}
.bs-vstat{display:flex;align-items:center;gap:7px;padding:9px 12px;border-radius:10px;font-size:12px;font-weight:600;margin-top:6px}
.bs-vstat.watching{background:rgba(59,130,246,.1);border:1px solid rgba(59,130,246,.2);color:#60a5fa}
.bs-vstat.done{background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.2);color:#34d399}
@keyframes vSpin{100%{transform:rotate(360deg)}}
.bs-vstat.watching i{animation:vSpin 1.2s linear infinite}
.bs-vnote{display:flex;align-items:center;gap:6px;padding:8px 11px;background:rgba(245,158,11,.07);border:1px solid rgba(245,158,11,.2);border-radius:9px;color:#fbbf24;font-size:11px;margin-top:4px}

/* External link */
.bs-extlink{background:var(--surf2);border-radius:11px;padding:16px 14px;text-align:center;border:1px solid var(--bdr)}
.bs-extlink p{font-size:12px;color:var(--txt2);margin-bottom:12px;line-height:1.6}
.bs-extlink-btn{display:inline-flex;align-items:center;gap:7px;padding:11px 22px;border-radius:10px;font-size:13px;font-weight:800;color:#fff;text-decoration:none;background:var(--a);box-shadow:0 3px 12px rgba(var(--ar),.35);-webkit-tap-highlight-color:transparent}
.bs-extlink-btn:active{opacity:.8}

/* ═══════════════════════════════════
   NOTIFICATION TOAST — bold & visible
═══════════════════════════════════ */
@keyframes ntSlideDown{
    0%{opacity:0;transform:translateX(-50%) translateY(-24px) scale(.92)}
    60%{transform:translateX(-50%) translateY(4px) scale(1.02)}
    100%{opacity:1;transform:translateX(-50%) translateY(0) scale(1)}
}
@keyframes ntSlideUp{
    0%{opacity:1;transform:translateX(-50%) translateY(0) scale(1)}
    100%{opacity:0;transform:translateX(-50%) translateY(-16px) scale(.94)}
}
@keyframes ntProgress{from{width:100%}to{width:0%}}
@keyframes ntPop{0%,100%{transform:scale(1)}50%{transform:scale(1.18)}}
@keyframes ntShake{0%,100%{transform:translateX(-50%) rotate(0)}20%{transform:translateX(calc(-50% - 4px)) rotate(-1deg)}40%{transform:translateX(calc(-50% + 4px)) rotate(1deg)}60%{transform:translateX(calc(-50% - 3px)) rotate(-1deg)}80%{transform:translateX(calc(-50% + 3px)) rotate(1deg)}}

.nt{
    position:fixed;
    top:calc(var(--hh,56px) + 10px);
    left:50%;
    transform:translateX(-50%) translateY(-24px) scale(.92);
    opacity:0;
    min-width:min(340px, 92vw);
    max-width:92vw;
    z-index:99999;
    pointer-events:none;
    border-radius:16px;
    overflow:hidden;
    box-shadow:0 16px 48px rgba(0,0,0,.35), 0 4px 16px rgba(0,0,0,.2);
    font-family:inherit;
}
.nt.nt-show{
    pointer-events:all;
    animation:ntSlideDown .45s cubic-bezier(.22,1,.36,1) forwards;
}
.nt.nt-hide{
    animation:ntSlideUp .3s ease forwards;
}
.nt.nt-err{animation:ntSlideDown .45s cubic-bezier(.22,1,.36,1) forwards, ntShake .45s .45s ease}

/* Inner card */
.nt-inner{
    display:flex;align-items:flex-start;gap:12px;
    padding:14px 14px 10px;
    position:relative;
}
/* Type-based backgrounds */
.nt-success .nt-inner{background:linear-gradient(135deg,#052e16 0%,#064e3b 100%);border:1px solid rgba(52,211,153,.25);border-bottom:none}
.nt-error   .nt-inner{background:linear-gradient(135deg,#450a0a 0%,#7f1d1d 100%);border:1px solid rgba(248,113,113,.25);border-bottom:none}
.nt-warning .nt-inner{background:linear-gradient(135deg,#1c1000 0%,#451a03 100%);border:1px solid rgba(251,191,36,.25);border-bottom:none}
.nt-info    .nt-inner{background:linear-gradient(135deg,#0c1445 0%,#1e3a8a 100%);border:1px solid rgba(96,165,250,.25);border-bottom:none}

/* Icon circle */
.nt-ico{
    width:38px;height:38px;border-radius:50%;flex-shrink:0;
    display:flex;align-items:center;justify-content:center;
    font-size:16px;color:#fff;
    animation:ntPop .4s .3s cubic-bezier(.34,1.56,.64,1) both;
}
.nt-success .nt-ico{background:linear-gradient(135deg,#10b981,#059669);box-shadow:0 0 16px rgba(16,185,129,.5)}
.nt-error   .nt-ico{background:linear-gradient(135deg,#ef4444,#dc2626);box-shadow:0 0 16px rgba(239,68,68,.5)}
.nt-warning .nt-ico{background:linear-gradient(135deg,#f59e0b,#d97706);box-shadow:0 0 16px rgba(245,158,11,.5)}
.nt-info    .nt-ico{background:linear-gradient(135deg,#3b82f6,#2563eb);box-shadow:0 0 16px rgba(59,130,246,.5)}

/* Text area */
.nt-txt{flex:1;min-width:0;padding-top:2px}
.nt-label{
    font-size:10px;font-weight:800;letter-spacing:1.2px;
    text-transform:uppercase;margin-bottom:3px;opacity:.7;
}
.nt-success .nt-label{color:#6ee7b7}
.nt-error   .nt-label{color:#fca5a5}
.nt-warning .nt-label{color:#fde68a}
.nt-info    .nt-label{color:#bfdbfe}
.nt-msg{
    font-size:13.5px;font-weight:700;color:#fff;
    line-height:1.4;word-break:break-word;
}

/* Close button */
.nt-cls{
    width:24px;height:24px;border-radius:6px;flex-shrink:0;
    background:rgba(255,255,255,.1);border:none;
    color:rgba(255,255,255,.6);font-size:13px;cursor:pointer;
    display:flex;align-items:center;justify-content:center;
    transition:.15s;-webkit-tap-highlight-color:transparent;
    margin-top:1px;
}
.nt-cls:active{background:rgba(255,255,255,.22);color:#fff}

/* Progress bar */
.nt-bar{
    height:3px;
    border:1px solid transparent;border-top:none;
}
.nt-bar-fill{
    height:100%;
    border-radius:0 0 16px 16px;
    animation:ntProgress linear forwards;
    transform-origin:left;
}
.nt-success .nt-bar{border-color:rgba(52,211,153,.25);background:rgba(16,185,129,.15)}
.nt-error   .nt-bar{border-color:rgba(248,113,113,.25);background:rgba(239,68,68,.15)}
.nt-warning .nt-bar{border-color:rgba(251,191,36,.25);background:rgba(245,158,11,.15)}
.nt-info    .nt-bar{border-color:rgba(96,165,250,.25);background:rgba(59,130,246,.15)}
.nt-success .nt-bar-fill{background:linear-gradient(90deg,#10b981,#34d399)}
.nt-error   .nt-bar-fill{background:linear-gradient(90deg,#ef4444,#f87171)}
.nt-warning .nt-bar-fill{background:linear-gradient(90deg,#f59e0b,#fbbf24)}
.nt-info    .nt-bar-fill{background:linear-gradient(90deg,#3b82f6,#60a5fa)}
</style>

<div class="tk-pg">

<?php if($flash): ?>
<div class="tk-flash <?= $flash['type'] ?>">
    <i class="fa-solid fa-<?= $flash['type']==='success'?'circle-check':($flash['type']==='error'?'circle-xmark':($flash['type']==='warning'?'triangle-exclamation':'circle-info')) ?>"></i>
    <?= htmlspecialchars($flash['message']) ?>
</div>
<?php endif; ?>

<!-- BANNER -->
<div class="tk-banner">
    <div class="tk-banner-inner">
        <div class="tk-banner-title">💼 Earn Now</div>
        <div class="tk-banner-sub">Complete tasks and get paid instantly</div>
        <div class="tk-stats">
            <div class="tks"><div class="tks-val"><?= number_format($myStats['done']??0) ?></div><div class="tks-lbl">Done</div></div>
            <div class="tks"><div class="tks-val"><?= number_format($myStats['earned']??0,0) ?></div><div class="tks-lbl"><?= $cs ?> Earned</div></div>
            <div class="tks"><div class="tks-val"><?= number_format($myStats['pend']??0) ?></div><div class="tks-lbl">Pending</div></div>
            <div class="tks"><div class="tks-val"><?= $totalTasks ?></div><div class="tks-lbl">Available</div></div>
        </div>
    </div>
</div>

<!-- FILTERS -->
<div class="tk-filters">
    <div class="tk-filter-scroll">
        <a href="?filter=all" class="tkf tkf-all <?= $filter==='all'?'on':'' ?>">
            <i class="fa-solid fa-grid-2"></i> All <strong><?= $totalTasks ?></strong>
        </a>
        <?php
        $ftypes=['video'=>['fa-clapperboard','Video','#f87171'],'survey'=>['fa-chart-simple','Survey','#22d3ee'],'trivia'=>['fa-brain','Trivia','#818cf8'],'quiz'=>['fa-circle-question','Quiz','#818cf8'],'ads'=>['fa-rectangle-ad','Ads','#c084fc'],'blog'=>['fa-pen-nib','Blog','#34d399'],'meme'=>['fa-image','Meme','#f472b6'],'transcription'=>['fa-microphone','Trans','#fbbf24'],'chat'=>['fa-message','Chat','#60a5fa'],'spin'=>['fa-rotate','Spin','#2dd4bf']];
        foreach($ftypes as $fk=>$fi): $cnt=$taskCounts[$fk]??0; if($cnt<1)continue; ?>
        <a href="?filter=<?= $fk ?>" class="tkf tkf-type <?= $filter===$fk?'on':'' ?>" style="--trow-color:<?= $fi[2] ?>;<?= $filter===$fk?'background:rgba(0,0,0,.15);border-color:'.$fi[2]:'' ?>">
            <i class="fa-solid <?= $fi[0] ?>" style="color:<?= $fi[2] ?>"></i>
            <?= $fi[1] ?> <strong style="opacity:.7"><?= $cnt ?></strong>
        </a>
        <?php endforeach; ?>
    </div>
</div>

<!-- TASKS -->
<div class="tk-body">
<?php if(empty($tasks)): ?>
<div class="tk-empty"><i class="fa-solid fa-clipboard-list"></i><div class="tk-empty-t">No Tasks Available</div><div class="tk-empty-s">Check back soon for new earning opportunities!</div></div>
<?php else:
    $hot=[]; $normal=[];
    foreach($tasks as $t){ if($t['show_in_sidebar'])$hot[]=$t; else $normal[]=$t; }
    $all_sorted=array_merge($hot,$normal);

    if(!empty($hot)):?>
<div class="tk-section-hdr"><span class="tk-section-hdr-txt"><i class="fa-solid fa-fire" style="color:#f97316"></i> Featured</span><div class="tk-section-hdr-line"></div></div>
    <?php foreach($hot as $t):
        $cfg=$typeConfig[$t['task_type']]??['#818cf8','fa-circle-dot','linear-gradient(135deg,#6366f1,#8b5cf6)'];
        $clr=$cfg[0]; $ico=$cfg[1]; $grad=$cfg[2];
        $canDo=$t['today_completions']<$t['daily_limit_per_user'];
        $atLim=$t['total_limit']&&$t['total_completions']>=$t['total_limit'];
        if($atLim)$canDo=false;
        $hasTimer=intval($t['enable_timer'])===1&&intval($t['min_duration_seconds'])>0;
    ?>
    <div class="trow <?= !$canDo?'done':'' ?>"
        style="--trow-color:<?= $clr ?>"
        onclick="<?= $canDo?'openSheet(this)':'' ?>"
        data-task-id="<?= $t['id'] ?>"
        data-task-type="<?= htmlspecialchars($t['task_type']) ?>"
        data-content-type="<?= htmlspecialchars($t['content_type']) ?>"
        data-task-title="<?= htmlspecialchars($t['title']) ?>"
        data-task-image="<?= htmlspecialchars($t['task_image']??'') ?>"
        data-task-instructions="<?= htmlspecialchars($t['instructions']??'') ?>"
        data-task-desc="<?= htmlspecialchars($t['description']??'') ?>"
        data-task-url="<?= htmlspecialchars($t['task_url']??'') ?>"
        data-task-reward="<?= $t['reward'] ?>"
        data-enable-timer="<?= $t['enable_timer'] ?>"
        data-timer-duration="<?= $t['min_duration_seconds'] ?>"
        data-requires-proof="<?= $t['requires_proof'] ?>"
        data-pass-pct="<?= $t['pass_percentage'] ?>"
        data-difficulty="<?= htmlspecialchars($t['difficulty']??'') ?>"
        data-can-do="<?= $canDo?1:0 ?>"
        data-today="<?= $t['today_completions'] ?>"
        data-limit="<?= $t['daily_limit_per_user'] ?>"
        data-grad="<?= htmlspecialchars($grad) ?>">
        <div class="trow-hot">🔥 Hot</div>
        <div class="trow-ico" style="background:<?= $grad ?>">
            <i class="fa-solid <?= $ico ?>"></i>
            <div class="trow-ico-done"><i class="fa-solid fa-check"></i></div>
        </div>
        <div class="trow-info">
            <div class="trow-title"><?= htmlspecialchars($t['title']) ?></div>
            <div class="trow-meta">
                <span class="trow-tag" style="background:<?= $grad ?>"><?= strtoupper($t['task_type']) ?></span>
                <?php if(!empty($t['difficulty'])): ?><span class="trow-diff d-<?= $t['difficulty'][0] ?>"><?= ucfirst($t['difficulty']) ?></span><?php endif; ?>
                <span class="trow-count"><i class="fa-solid fa-users"></i><?= number_format($t['total_completions']) ?></span>
            </div>
            <?php if($hasTimer): ?><div class="trow-timer"><i class="fa-solid fa-stopwatch"></i><?= gmdate('i:s',$t['min_duration_seconds']) ?> timer</div><?php endif; ?>
        </div>
        <div class="trow-right">
            <div class="trow-reward"><?= $cs.' '.number_format($t['reward'],2) ?></div>
            <div class="trow-reward-lbl">Reward</div>
            <div class="trow-cta" style="background:<?= $grad ?>"><?= $canDo?'Start':'Done' ?></div>
        </div>
    </div>
    <?php endforeach; endif; ?>

<?php if(!empty($normal)):?>
<div class="tk-section-hdr" style="<?= !empty($hot)?'margin-top:4px':'' ?>"><span class="tk-section-hdr-txt">All Tasks</span><div class="tk-section-hdr-line"></div></div>
    <?php foreach($normal as $t):
        $cfg=$typeConfig[$t['task_type']]??['#818cf8','fa-circle-dot','linear-gradient(135deg,#6366f1,#8b5cf6)'];
        $clr=$cfg[0]; $ico=$cfg[1]; $grad=$cfg[2];
        $canDo=$t['today_completions']<$t['daily_limit_per_user'];
        $atLim=$t['total_limit']&&$t['total_completions']>=$t['total_limit'];
        if($atLim)$canDo=false;
        $hasTimer=intval($t['enable_timer'])===1&&intval($t['min_duration_seconds'])>0;
    ?>
    <div class="trow <?= !$canDo?'done':'' ?>"
        style="--trow-color:<?= $clr ?>"
        onclick="<?= $canDo?'openSheet(this)':'' ?>"
        data-task-id="<?= $t['id'] ?>"
        data-task-type="<?= htmlspecialchars($t['task_type']) ?>"
        data-content-type="<?= htmlspecialchars($t['content_type']) ?>"
        data-task-title="<?= htmlspecialchars($t['title']) ?>"
        data-task-image="<?= htmlspecialchars($t['task_image']??'') ?>"
        data-task-instructions="<?= htmlspecialchars($t['instructions']??'') ?>"
        data-task-desc="<?= htmlspecialchars($t['description']??'') ?>"
        data-task-url="<?= htmlspecialchars($t['task_url']??'') ?>"
        data-task-reward="<?= $t['reward'] ?>"
        data-enable-timer="<?= $t['enable_timer'] ?>"
        data-timer-duration="<?= $t['min_duration_seconds'] ?>"
        data-requires-proof="<?= $t['requires_proof'] ?>"
        data-pass-pct="<?= $t['pass_percentage'] ?>"
        data-difficulty="<?= htmlspecialchars($t['difficulty']??'') ?>"
        data-can-do="<?= $canDo?1:0 ?>"
        data-today="<?= $t['today_completions'] ?>"
        data-limit="<?= $t['daily_limit_per_user'] ?>"
        data-grad="<?= htmlspecialchars($grad) ?>">
        <div class="trow-ico" style="background:<?= $grad ?>">
            <i class="fa-solid <?= $ico ?>"></i>
            <div class="trow-ico-done"><i class="fa-solid fa-check"></i></div>
        </div>
        <div class="trow-info">
            <div class="trow-title"><?= htmlspecialchars($t['title']) ?></div>
            <div class="trow-meta">
                <span class="trow-tag" style="background:<?= $grad ?>"><?= strtoupper($t['task_type']) ?></span>
                <?php if(!empty($t['difficulty'])): ?><span class="trow-diff d-<?= $t['difficulty'][0] ?>"><?= ucfirst($t['difficulty']) ?></span><?php endif; ?>
                <span class="trow-count"><i class="fa-solid fa-users"></i><?= number_format($t['total_completions']) ?></span>
            </div>
            <?php if($hasTimer): ?><div class="trow-timer"><i class="fa-solid fa-stopwatch"></i><?= gmdate('i:s',$t['min_duration_seconds']) ?></div><?php endif; ?>
        </div>
        <div class="trow-right">
            <div class="trow-reward"><?= $cs.' '.number_format($t['reward'],2) ?></div>
            <div class="trow-reward-lbl">Reward</div>
            <div class="trow-cta" style="background:<?= $grad ?>"><?= $canDo?'Start':'Done' ?></div>
        </div>
    </div>
    <?php endforeach; ?>
<?php endif; ?>
<?php endif; ?>
</div><!-- /.tk-body -->
</div><!-- /.tk-pg -->

<!-- ════ BOTTOM SHEET ════ -->
<div class="bsheet-overlay" id="bsOverlay" onclick="closeSheet()"></div>
<div class="bsheet" id="bsheet">
    <div class="bsheet-handle"></div>
    <div class="bsheet-hdr">
        <div class="bsheet-hdr-ico" id="bsIco"></div>
        <div class="bsheet-hdr-info">
            <div class="bsheet-hdr-title" id="bsTitle"></div>
            <div class="bsheet-hdr-sub" id="bsSub"></div>
        </div>
        <button class="bsheet-cls" onclick="closeSheet()"><i class="fa-solid fa-xmark"></i></button>
    </div>
    <div class="bsheet-reward" id="bsReward"></div>
    <form id="taskForm" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="submit_task" value="1">
        <input type="hidden" name="task_id" id="fTaskId">
        <div class="bsheet-body" id="bsBody"></div>
        <div class="bsheet-ftr">
            <button type="button" class="bsftr-cancel" onclick="closeSheet()"><i class="fa-solid fa-xmark"></i> Cancel</button>
            <button type="submit" class="bsftr-submit" id="bsSubmit"><i class="fa-solid fa-paper-plane"></i> Submit Task</button>
        </div>
    </form>
</div>

<!-- NOTIFICATION -->
<div class="nt" id="nt" role="alert" aria-live="assertive">
    <div class="nt-inner">
        <div class="nt-ico" id="nt-ico"></div>
        <div class="nt-txt">
            <div class="nt-label" id="nt-label"></div>
            <div class="nt-msg"  id="nt-msg"></div>
        </div>
        <button class="nt-cls" id="nt-cls" aria-label="Close"><i class="fa-solid fa-xmark"></i></button>
    </div>
    <div class="nt-bar"><div class="nt-bar-fill" id="nt-bar-fill"></div></div>
</div>

<script>
const TC  = <?= $taskContentsJson ?>;
const CS  = '<?= addslashes($cs) ?>';
let timerIv=null, timeLeft=0, vidIv=null, vidDone=false;

/* ── NOTIFICATION ── */
var _ntTimer=null, _ntHideTimer=null;
function toast(msg,type){
    type=type||'success';
    var nt=document.getElementById('nt');
    var ico=document.getElementById('nt-ico');
    var lbl=document.getElementById('nt-label');
    var m=document.getElementById('nt-msg');
    var bar=document.getElementById('nt-bar-fill');
    var cls=document.getElementById('nt-cls');
    // clear pending timers
    clearTimeout(_ntTimer); clearTimeout(_ntHideTimer);
    // reset animation
    nt.className='nt';
    void nt.offsetWidth; // force reflow
    // config per type
    var cfg={
        success:{cls:'nt-success',lbl:'Success',ico:'fa-circle-check',dur:4500},
        error:  {cls:'nt-error',  lbl:'Error',  ico:'fa-circle-xmark', dur:5500},
        warning:{cls:'nt-warning',lbl:'Warning', ico:'fa-triangle-exclamation',dur:5000},
        info:   {cls:'nt-info',   lbl:'Info',    ico:'fa-circle-info', dur:4500},
    }[type]||{cls:'nt-success',lbl:'Notice',ico:'fa-circle-check',dur:4500};
    // apply
    nt.classList.add(cfg.cls);
    ico.innerHTML='<i class="fa-solid '+cfg.ico+'"></i>';
    lbl.textContent=cfg.lbl;
    m.textContent=msg;
    // progress bar
    bar.style.animation='none';
    void bar.offsetWidth;
    bar.style.animation='ntProgress '+cfg.dur+'ms linear forwards';
    // show
    nt.classList.add(type==='error'?'nt-err':'nt-show');
    if(type==='error') setTimeout(()=>nt.classList.add('nt-show'),1);
    // auto hide
    _ntTimer=setTimeout(function(){ntHide();},cfg.dur);
    // close button
    cls.onclick=function(){clearTimeout(_ntTimer);ntHide();};
}
function ntHide(){
    var nt=document.getElementById('nt');
    nt.classList.add('nt-hide');
    _ntHideTimer=setTimeout(function(){nt.className='nt';},320);
}
function fmt(s){return String(Math.floor(s/60)).padStart(2,'0')+':'+String(s%60).padStart(2,'0');}
function esc(t){if(!t)return'';var d=document.createElement('div');d.textContent=t;return d.innerHTML;}

/* ── EMBED ── */
function getEmbed(url){
    if(!url)return null;
    var m;
    m=url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);
    if(m)return'<div class="vwrap"><iframe src="https://www.youtube.com/embed/'+m[1]+'?rel=0&modestbranding=1" allow="autoplay;encrypted-media;fullscreen;picture-in-picture" allowfullscreen></iframe></div>';
    m=url.match(/vimeo\.com\/(\d+)/);
    if(m)return'<div class="vwrap"><iframe src="https://player.vimeo.com/video/'+m[1]+'" allowfullscreen></iframe></div>';
    m=url.match(/tiktok\.com\/@[^/]+\/video\/(\d+)/);
    if(m)return'<div class="vwrap tiktok"><iframe src="https://www.tiktok.com/embed/v2/'+m[1]+'" allowfullscreen></iframe></div>';
    if(url.match(/\.(mp4|webm|ogg|mov)(\?.*)?$/i))return'<video controls class="vplayer"><source src="'+esc(url)+'"></video>';
    return'<div class="vwrap"><iframe src="'+esc(url)+'" allowfullscreen></iframe></div>';
}

/* ── OPEN SHEET ── */
function openSheet(row){
    var d=row.dataset;
    if(parseInt(d.canDo)===0)return;

    // Escape sidebar wrapper — move to body if not already there
    var overlay=document.getElementById('bsOverlay');
    var sheet=document.getElementById('bsheet');
    if(overlay.parentElement!==document.body){
        document.body.appendChild(overlay);
        document.body.appendChild(sheet);
    }
    document.getElementById('fTaskId').value=d.taskId;
    // Header
    document.getElementById('bsIco').style.background=d.grad;
    document.getElementById('bsIco').innerHTML='<i class="fa-solid '+getIcon(d.taskType)+'" style="font-size:18px;color:#fff"></i>';
    document.getElementById('bsTitle').textContent=d.taskTitle;
    document.getElementById('bsSub').textContent=d.taskType.toUpperCase()+' TASK'+(d.difficulty?' · '+d.difficulty.toUpperCase():'');
    // Reward strip
    document.getElementById('bsReward').innerHTML=
        '<div class="bsr-left"><div class="bsr-ico" style="background:'+esc(d.grad)+'"><i class="fa-solid fa-coins"></i></div>'
        +'<div><div class="bsr-val">'+CS+' '+parseFloat(d.taskReward).toFixed(2)+'</div><div class="bsr-lbl">Reward</div></div></div>'
        +'<div class="bsr-right">'
        +'<span class="bsr-chip"><i class="fa-solid fa-rotate-right" style="font-size:9px;margin-right:3px"></i>'+d.today+'/'+d.limit+' today</span>'
        +(d.enableTimer==='1'&&parseInt(d.timerDuration)>0?'<span class="bsr-chip"><i class="fa-solid fa-stopwatch" style="font-size:9px;margin-right:3px"></i>'+fmt(parseInt(d.timerDuration))+'</span>':'')
        +'</div>';
    // Reset
    if(timerIv){clearInterval(timerIv);timerIv=null;}
    if(vidIv){clearInterval(vidIv);vidIv=null;}
    vidDone=false;
    var sb=document.getElementById('bsSubmit');
    sb.disabled=false;sb.innerHTML='<i class="fa-solid fa-paper-plane"></i> Submit Task';

    // Build body
    var body='';
    var hasTimer=d.enableTimer==='1'&&parseInt(d.timerDuration)>0;
    body+='<div class="bs-timer'+(hasTimer?' on':'')+'" id="bs-tw">'
        +'<div class="bs-timer-lbl"><i class="fa-solid fa-stopwatch"></i> Time Remaining</div>'
        +'<div class="bs-timer-num" id="bs-tn">'+(hasTimer?fmt(parseInt(d.timerDuration)):'--:--')+'</div>'
        +'<div class="bs-timer-sub" id="bs-tsub">Complete the task before the timer ends</div></div>';

    if(d.taskDesc)    body+='<div class="bs-info"><div class="bs-info-hdr"><i class="fa-solid fa-circle-info"></i>About</div><div class="bs-info-body">'+esc(d.taskDesc)+'</div></div>';
    if(d.taskInstructions) body+='<div class="bs-info grn"><div class="bs-info-hdr"><i class="fa-solid fa-list-check"></i>Instructions</div><div class="bs-info-body">'+esc(d.taskInstructions)+'</div></div>';

    // Content
    var tc=TC[d.taskId];
    if(d.contentType==='internal'&&tc){
        if((d.taskType==='quiz'||d.taskType==='trivia')&&tc.quiz_questions) body+=renderQuiz(tc.quiz_questions);
        else if(d.taskType==='survey'&&tc.survey_questions) body+=renderSurvey(tc.survey_questions);
        else if(d.taskType==='blog'&&tc.blog_data) body+=renderBlog(tc.blog_data);
        else if(d.taskType==='meme'&&tc.meme_data) body+=renderMeme(tc.meme_data);
        else if(d.taskType==='transcription'&&tc.transcription_data) body+=renderTrans(tc.transcription_data);
    } else {
        body+=renderExternal(d.taskUrl,d.requiresProof==='1',d.taskType);
    }

    document.getElementById('bsBody').innerHTML=body;
    document.getElementById('bsOverlay').classList.add('on');
    document.getElementById('bsheet').classList.add('on');
    document.body.style.overflow='hidden';

    initFilePrev();
    var bt=document.getElementById('blogTA');
    if(bt)bt.addEventListener('input',()=>{var n=document.getElementById('wcNum');if(n)n.textContent=bt.value.trim().split(/\s+/).filter(Boolean).length;});
    var tt=document.getElementById('transTA');
    if(tt)tt.addEventListener('input',()=>{var n=document.getElementById('transWc');if(n)n.textContent=tt.value.trim().split(/\s+/).filter(Boolean).length;});

    if(hasTimer) setTimeout(()=>startTimer(parseInt(d.timerDuration)),80);
    if(d.taskType==='video'||d.taskType==='ads') initVidTrack(parseInt(d.timerDuration)||30);
}

function getIcon(type){
    var icons={quiz:'fa-brain',trivia:'fa-brain',survey:'fa-chart-simple',blog:'fa-pen-nib',video:'fa-clapperboard',chat:'fa-message',transcription:'fa-microphone',ads:'fa-rectangle-ad',meme:'fa-image',spin:'fa-rotate'};
    return icons[type]||'fa-circle-dot';
}

/* ── RENDERERS ── */
function renderQuiz(qs){
    if(!qs||!qs.length)return'<p style="text-align:center;padding:20px;color:var(--txt2)">No questions.</p>';
    var h='';
    qs.forEach((q,i)=>{
        h+='<div class="bs-qblock"><span class="bs-qnum"><i class="fa-solid fa-circle-question" style="font-size:9px"></i> Q'+(i+1)+' of '+qs.length+'</span><div class="bs-qtxt">'+esc(q.question)+'</div><div class="bs-qopts">';
        var opts={A:q.option_a,B:q.option_b};
        if(q.option_c)opts.C=q.option_c; if(q.option_d)opts.D=q.option_d;
        for(var l in opts){if(!opts[l])continue;h+='<label class="bs-qopt"><input type="radio" name="quiz_answers['+q.id+']" value="'+l+'" required><span class="bs-qopt-ltr">'+l+'</span><span class="bs-qopt-txt">'+esc(opts[l])+'</span></label>';}
        h+='</div></div>';
    });
    return h;
}

function renderSurvey(qs){
    if(!qs||!qs.length)return'<p style="text-align:center;padding:20px;color:var(--txt2)">No questions.</p>';
    var h='';
    qs.forEach((q,i)=>{
        var req=q.required==1?'required':'', rm=q.required==1?'<span style="color:#f87171;margin-left:2px">*</span>':'';
        h+='<div class="bs-qblock"><div class="bs-qtxt"><strong>'+(i+1)+'.</strong> '+esc(q.question)+rm+'</div>';
        if(q.question_type==='text') h+='<input type="text" name="survey_answers['+q.id+']" class="bs-in" style="margin-top:8px" '+req+' placeholder="Your answer...">';
        else if(q.question_type==='textarea') h+='<textarea name="survey_answers['+q.id+']" class="bs-ta" style="min-height:80px;margin-top:8px" '+req+' placeholder="Your answer..."></textarea>';
        else if(q.question_type==='multiple_choice'&&q.options){
            h+='<div class="bs-qopts" style="margin-top:8px">';
            q.options.split('|').forEach(o=>{o=o.trim();h+='<label class="bs-qopt"><input type="radio" name="survey_answers['+q.id+']" value="'+esc(o)+'" '+req+'><span class="bs-qopt-txt">'+esc(o)+'</span></label>';});
            h+='</div>';
        }
        else if(q.question_type==='rating'){h+='<div class="rating-row">';for(var r=1;r<=5;r++)h+='<div class="ropt"><label><input type="radio" name="survey_answers['+q.id+']" value="'+r+'" '+req+'><div class="ropt-n">'+r+'</div></label></div>';h+='</div>';}
        else if(q.question_type==='yes_no') h+='<div class="bs-qopts" style="margin-top:8px"><label class="bs-qopt"><input type="radio" name="survey_answers['+q.id+']" value="yes" '+req+'><span class="bs-qopt-txt">Yes</span></label><label class="bs-qopt"><input type="radio" name="survey_answers['+q.id+']" value="no" '+req+'><span class="bs-qopt-txt">No</span></label></div>';
        h+='</div>';
    });
    return h;
}

function renderBlog(d){
    if(!d)return'';
    var h='<div class="bs-info"><div class="bs-info-hdr"><i class="fa-solid fa-pen-nib"></i>Writing Brief</div><div class="bs-info-body"><strong>Topic:</strong> '+esc(d.topic||'Write a blog post')+'<br>';
    if(d.guidelines) h+=esc(d.guidelines)+'<br>';
    if(d.keywords)   h+='<strong>Keywords:</strong> '+esc(d.keywords)+'<br>';
    h+='<strong>Min:</strong> '+(d.min_words||300)+' words'+(d.max_words?' | <strong>Max:</strong> '+d.max_words+' words':'')+' </div></div>';
    h+='<input type="text" name="blog_title" class="bs-in" placeholder="Your blog title…" required>';
    h+='<textarea name="blog_content" class="bs-ta" id="blogTA" placeholder="Write your post here…" required></textarea>';
    h+='<div class="bs-wc">Words: <span id="wcNum">0</span>'+(d.min_words?' / min '+d.min_words:'')+'</div>';
    return h;
}

function renderMeme(d){
    if(!d)return'';
    var h='<div class="bs-info"><div class="bs-info-hdr"><i class="fa-solid fa-image"></i>Theme: '+esc(d.theme)+'</div><div class="bs-info-body">';
    if(d.guidelines) h+=esc(d.guidelines)+'<br>';
    h+='Formats: <strong>'+esc(d.allowed_formats)+'</strong> | Max: <strong>'+(d.max_file_size_mb||5)+'MB</strong></div></div>';
    h+='<label class="bs-upload"><input type="file" name="meme_upload" accept="image/*" required class="fpi"><i class="fa-solid fa-cloud-arrow-up"></i><span>Tap to upload your meme<br><small>'+esc(d.allowed_formats)+' accepted</small></span></label><div class="bs-fprev"></div>';
    return h;
}

function renderTrans(d){
    if(!d)return'';
    var h='';
    if(d.video_url){var m=d.video_url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([^&\n]+)/);h+=m?'<div class="vwrap"><iframe src="https://www.youtube.com/embed/'+m[1]+'" allowfullscreen></iframe></div>':'<video controls class="vplayer"><source src="'+esc(d.video_url)+'"></video>';}
    else if(d.audio_url) h+='<audio controls style="width:100%;border-radius:11px"><source src="'+esc(d.audio_url)+'"></audio>';
    h+='<div class="bs-info"><div class="bs-info-body">Language: <strong>'+esc(d.language||'English')+'</strong>'+(d.duration_seconds?' | Duration: <strong>'+fmt(d.duration_seconds)+'</strong>':'')+'</div></div>';
    h+='<textarea name="transcription_text" class="bs-ta" id="transTA" placeholder="Type your transcription here…" required></textarea>';
    h+='<div class="bs-wc">Words: <span id="transWc">0</span></div>';
    return h;
}

function renderExternal(url,proof,type){
    var h='', isVideo=(type==='video'||type==='ads');
    if(isVideo&&url){
        var emb=getEmbed(url);
        h+=emb?emb:'<div class="bs-info">Could not embed video.</div>';
        h+='<div class="bs-vprog"><div class="bs-vprog-fill" id="vpf" style="width:0%"></div></div>';
        h+='<div class="bs-vstat watching" id="vst"><i class="fa-solid fa-spinner"></i><span id="vstxt">Press play and watch the full '+(type==='ads'?'ad':'video')+'…</span></div>';
        h+='<div class="bs-vnote"><i class="fa-solid fa-circle-info"></i>Stay on this screen until the video completes.</div>';
    } else if(url){
        h+='<div class="bs-extlink"><p>This task is on an external platform. Open the link and complete the task, then submit.</p><a href="'+esc(url)+'" target="_blank" rel="noopener" class="bs-extlink-btn"><i class="fa-solid fa-arrow-up-right-from-square"></i>Open Task Link</a></div>';
    }
    if(proof) h+='<label class="bs-upload"><input type="file" name="proof_screenshot" accept="image/*" required class="fpi"><i class="fa-solid fa-camera"></i><span>Upload proof screenshot<br><small>JPG, PNG or WEBP · Max 2MB</small></span></label><div class="bs-fprev"></div>';
    return h;
}

/* ── VIDEO TRACKING ── */
function initVidTrack(sec){
    var pf=document.getElementById('vpf'),st=document.getElementById('vst'),stxt=document.getElementById('vstxt'),sb=document.getElementById('bsSubmit');
    if(!pf)return;
    sb.disabled=true; vidDone=false;
    var watched=0, total=sec||30;
    if(vidIv)clearInterval(vidIv);
    vidIv=setInterval(()=>{
        watched++; var pct=Math.min(watched/total*100,100);
        if(pf)pf.style.width=pct+'%';
        if(stxt&&total-watched>0) stxt.textContent='Watching… '+fmt(total-watched)+' remaining';
        if(watched>=total&&!vidDone){
            vidDone=true; clearInterval(vidIv); vidIv=null;
            if(pf)pf.style.width='100%';
            if(st){st.className='bs-vstat done';st.innerHTML='<i class="fa-solid fa-circle-check"></i><span>Complete! You can now submit.</span>';}
            sb.disabled=false;
            toast('Video complete! Ready to submit.');
        }
    },1000);
}

/* ── TIMER ── */
function startTimer(sec){
    timeLeft=sec; var total=sec;
    var tw=document.getElementById('bs-tw'),tn=document.getElementById('bs-tn'),ts=document.getElementById('bs-tsub'),sb=document.getElementById('bsSubmit');
    if(tn)tn.textContent=fmt(timeLeft);
    if(timerIv)clearInterval(timerIv);
    timerIv=setInterval(()=>{
        timeLeft--;
        if(tn)tn.textContent=fmt(timeLeft);
        if(tw){var p=timeLeft/total;tw.className='bs-timer on'+(p<=.1?' danger':p<=.3?' warn':'');}
        if(timeLeft<=0){
            clearInterval(timerIv); timerIv=null;
            if(tw)tw.className='bs-timer on expired';
            if(ts)ts.textContent='⛔ Time expired — cannot submit';
            if(sb){sb.disabled=true;sb.innerHTML='<i class="fa-solid fa-ban"></i> Time Expired';}
            toast('⏰ Time expired!','error');
        }
    },1000);
}

/* ── CLOSE ── */
function closeSheet(){
    if(timerIv){clearInterval(timerIv);timerIv=null;}
    if(vidIv){clearInterval(vidIv);vidIv=null;}
    vidDone=false; timeLeft=0;
    var sb=document.getElementById('bsSubmit');
    if(sb){sb.disabled=false;sb.innerHTML='<i class="fa-solid fa-paper-plane"></i> Submit Task';}
    var bs=document.getElementById('bsheet');
    if(bs){bs.querySelectorAll('iframe').forEach(f=>f.src='');bs.querySelectorAll('video,audio').forEach(v=>{v.pause();v.src='';});}
    document.getElementById('taskForm').reset();
    document.getElementById('bsheet').classList.remove('on');
    var ov=document.getElementById('bsOverlay');
    ov.style.opacity='0';
    // wait for fade-out then hide so blur clears cleanly
    setTimeout(function(){
        ov.classList.remove('on');
        ov.style.opacity='';
        document.getElementById('bsBody').innerHTML='';
    },300);
    document.body.style.overflow='';
}

/* ── FILE PREVIEW ── */
function initFilePrev(){
    document.querySelectorAll('.fpi').forEach(inp=>{
        inp.addEventListener('change',function(){
            var p=this.closest('.bsheet-body').querySelector('.bs-fprev');
            if(p&&this.files[0]){var r=new FileReader();r.onload=e=>p.innerHTML='<img src="'+e.target.result+'">';r.readAsDataURL(this.files[0]);}
        });
    });
}

/* ── FORM SUBMIT ── */
document.getElementById('taskForm').addEventListener('submit',function(e){
    var hasTW=document.getElementById('bs-tw')&&document.getElementById('bs-tw').classList.contains('on');
    if(hasTW&&timeLeft<=0){e.preventDefault();toast('Time expired!','error');return;}
    var vst=document.getElementById('vst');
    if(vst&&vst.classList.contains('watching')&&!vidDone){e.preventDefault();toast('Watch the full video first!','warning');return;}
    var qs=document.querySelectorAll('.bs-qblock');
    for(var i=0;i<qs.length;i++){
        var name=qs[i].querySelector('input[type=radio]')?.name;
        if(name&&!document.querySelector('input[name="'+name+'"]:checked')){
            e.preventDefault(); toast('Please answer all questions!','warning');
            qs[i].scrollIntoView({behavior:'smooth',block:'center'}); return;
        }
    }
    var sb=document.getElementById('bsSubmit');
    sb.disabled=true; sb.innerHTML='<i class="fa-solid fa-spinner fa-spin"></i> Submitting…';
});

/* ── ESC ── */
document.addEventListener('keydown',e=>{if(e.key==='Escape')closeSheet();});

/* ── AUTO-OPEN FROM URL ── */
(function(){
    var p=new URLSearchParams(location.search),oid=p.get('open');
    if(oid){
        var row=document.querySelector('.trow[data-task-id="'+oid+'"]');
        if(row&&parseInt(row.dataset.canDo)){setTimeout(()=>{openSheet(row);row.scrollIntoView({behavior:'smooth',block:'center'});},350);}
        else toast('Task not available!','warning');
        history.replaceState({},'',location.pathname+(p.has('filter')?'?filter='+p.get('filter'):''));
    }
})();

<?php if($flash): ?>
toast(<?= json_encode($flash['message']) ?>, <?= json_encode($flash['type']==='success'?'success':($flash['type']==='error'?'error':'warning')) ?>);
<?php endif; ?>
</script>
<?php include 'footer.php'; ?>