<?php
require_once dirname(__DIR__).'/config.php';
$u = current_user();
if (!$u) { header('Location: ' . url('?login=1')); exit; }
$firstName = explode(' ', trim($u['full_name'] ?? 'مستخدم'))[0];
$plan      = $u['plan_key'] ?? $u['subscription_tier'] ?? 'free';
$planLabel = ['free'=>'مجاني','plus'=>'Plus','pro'=>'Pro','corp'=>'شركات'][$plan] ?? $plan;
$planColor = ['free'=>'#64748b','plus'=>'#00d97e','pro'=>'#f59e0b','corp'=>'#a78bfa'][$plan] ?? '#64748b';
?><!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <title>مساعدك الشخصي — سودانا</title>
  <style>
    :root{--g:#00d97e;--g2:#059669;--dark:#073328;--bg:#f0fdf4;--card:#fff;
          --text:#1e293b;--muted:#64748b;--border:#e2e8f0;--gold:#f59e0b;
          --safe-bottom:env(safe-area-inset-bottom,0px)}
    *{box-sizing:border-box;margin:0;padding:0;-webkit-tap-highlight-color:transparent}
    body{font-family:'Cairo','Noto Sans Arabic',system-ui,sans-serif;
         background:var(--bg);color:var(--text);min-height:100vh;
         padding-bottom:calc(70px + var(--safe-bottom))}
    .hdr{background:var(--dark);height:56px;display:flex;align-items:center;
         justify-content:space-between;padding:0 16px;position:sticky;top:0;z-index:100}
    .logo{color:#fff;font-weight:900;font-size:1rem}
    .hdr-right{display:flex;align-items:center;gap:10px}
    .notif-btn{background:rgba(255,255,255,.1);border:none;border-radius:50%;
               width:36px;height:36px;color:#fff;cursor:pointer;position:relative;
               display:flex;align-items:center;justify-content:center;font-size:1rem}
    .notif-badge{position:absolute;top:-2px;right:-2px;background:#ef4444;color:#fff;
                 border-radius:50%;width:16px;height:16px;font-size:.6rem;
                 display:none;align-items:center;justify-content:center}
    .avatar{width:34px;height:34px;background:linear-gradient(135deg,var(--g),#0ea5e9);
            border-radius:50%;display:flex;align-items:center;justify-content:center;
            color:#fff;font-weight:900;font-size:.9rem;text-decoration:none}
    .hero{background:linear-gradient(135deg,var(--dark),#0a2a1a);padding:20px 16px 0;position:relative}
    .hero::after{content:'';position:absolute;bottom:-1px;left:0;right:0;height:20px;
                 background:var(--bg);border-radius:20px 20px 0 0}
    .hero-top{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:14px}
    .hero-greeting{color:rgba(255,255,255,.7);font-size:.78rem;margin-bottom:3px}
    .hero-name{color:#fff;font-size:1.2rem;font-weight:900}
    .plan-badge{border-radius:20px;padding:4px 12px;font-size:.72rem;font-weight:700;border:1px solid}
    .chat-wrap{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:16px;overflow:hidden}
    .chat-msgs{height:220px;overflow-y:scroll;-webkit-overflow-scrolling:touch;
               padding:14px;display:flex;flex-direction:column;gap:8px;scroll-behavior:smooth}
    .cmsg-bot{background:rgba(255,255,255,.1);border-radius:12px 12px 12px 3px;
              padding:10px 13px;font-size:.83rem;line-height:1.65;
              color:rgba(255,255,255,.92);max-width:88%;animation:msgIn .3s ease}
    .cmsg-user{background:rgba(0,217,126,.2);border:1px solid rgba(0,217,126,.3);
               border-radius:12px 12px 3px 12px;padding:10px 13px;font-size:.83rem;
               line-height:1.65;color:#fff;max-width:88%;margin-right:auto;margin-left:0;animation:msgIn .3s ease}
    .ctyping{display:flex;gap:5px;align-items:center;padding:10px 13px;
             background:rgba(255,255,255,.08);border-radius:12px 12px 12px 3px;width:fit-content}
    .ctyping span{width:7px;height:7px;border-radius:50%;background:rgba(255,255,255,.6);
                  animation:tdot 1.2s infinite;display:inline-block}
    .ctyping span:nth-child(2){animation-delay:.2s}.ctyping span:nth-child(3){animation-delay:.4s}
    @keyframes tdot{0%,100%{opacity:.3;transform:translateY(0)}50%{opacity:1;transform:translateY(-3px)}}
    @keyframes msgIn{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:translateY(0)}}
    .chat-choices{display:flex;gap:6px;flex-wrap:wrap;margin-top:6px}
    .chat-choice{background:rgba(255,255,255,.1);border:1.5px solid rgba(255,255,255,.2);
                 border-radius:20px;padding:6px 13px;font-size:.77rem;color:rgba(255,255,255,.9);
                 font-family:inherit;cursor:pointer;transition:.2s;touch-action:manipulation}
    .chat-choice:active{background:rgba(0,217,126,.2);border-color:rgba(0,217,126,.5)}
    .chat-input-row{display:flex;gap:8px;padding:10px 12px;border-top:1px solid rgba(255,255,255,.08)}
    .chat-input{flex:1;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.15);
                border-radius:10px;padding:10px 13px;color:#fff;font-family:inherit;
                font-size:16px;outline:none}
    .chat-input::placeholder{color:rgba(255,255,255,.4)}
    .chat-input:focus{border-color:rgba(0,217,126,.5)}
    .chat-send{background:var(--g);border:none;border-radius:10px;width:40px;height:40px;
               color:#000;cursor:pointer;font-size:1.1rem;flex-shrink:0;touch-action:manipulation}
    .container{max-width:800px;margin:0 auto;padding:16px}
    .stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:16px}
    .stat-card{background:var(--card);border:1px solid var(--border);border-radius:12px;
               padding:12px 8px;text-align:center;box-shadow:0 1px 4px rgba(0,0,0,.04)}
    .stat-val{font-size:1.4rem;font-weight:900;color:var(--g)}
    .stat-lbl{font-size:.65rem;color:var(--muted);margin-top:3px}
    .stat-bar{height:4px;background:rgba(0,217,126,.1);border-radius:2px;margin-top:8px;overflow:hidden}
    .stat-bar-fill{height:100%;background:linear-gradient(90deg,#00d97e,#00b76d);border-radius:2px;transition:width .4s}
    .stat-bar-fill.warn{background:linear-gradient(90deg,#f59e0b,#dc2626)}
    .stat-bar-fill.critical{background:linear-gradient(90deg,#ef4444,#991b1b)}
    .alert-card{background:#3a1010;border:1px solid #ef4444;border-radius:10px;padding:10px 14px;margin-bottom:10px;font-size:.85rem;color:#fca5a5;display:flex;align-items:center;gap:8px}
    .alert-card.warn{background:#3a2a10;border-color:#f59e0b;color:#fcd34d}
    .section{background:var(--card);border:1px solid var(--border);border-radius:16px;
             padding:16px;margin-bottom:14px;box-shadow:0 1px 6px rgba(0,0,0,.04)}
    .sec-title{font-size:.9rem;font-weight:800;color:var(--dark);margin-bottom:12px;display:flex;align-items:center;gap:6px}
    .row-item{display:flex;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid var(--border);font-size:.8rem}
    .row-item:last-child{border:none}
    .row-icon{width:34px;height:34px;background:linear-gradient(135deg,var(--g),#0ea5e9);
              border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:.9rem;flex-shrink:0}
    .row-sub{font-size:.7rem;color:var(--muted);margin-top:2px}
    .svc-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
    .svc-btn{background:#f8fafc;border:1.5px solid var(--border);border-radius:12px;
             padding:12px 6px;text-align:center;text-decoration:none;color:inherit;
             display:block;transition:.15s;touch-action:manipulation}
    .svc-btn:active{border-color:var(--g);background:#f0fdf4}
    .svc-icon{font-size:1.4rem;display:block;margin-bottom:4px}
    .svc-lbl{font-size:.65rem;font-weight:700}
    .nudge-card{background:linear-gradient(135deg,var(--dark),#0a2a1a);border-radius:14px;
                padding:16px;color:#fff;margin-bottom:14px;border:1px solid rgba(0,217,126,.2)}
    .nudge-msg{font-size:.83rem;line-height:1.65;margin-bottom:12px;color:rgba(255,255,255,.9)}
    .nudge-btns{display:flex;gap:8px;flex-wrap:wrap}
    .nudge-yes{background:var(--g);color:#000;border:none;border-radius:10px;
               padding:8px 16px;font-family:inherit;font-weight:800;font-size:.8rem;cursor:pointer}
    .nudge-skip{background:rgba(255,255,255,.1);color:rgba(255,255,255,.6);border:none;
                border-radius:10px;padding:8px 14px;font-family:inherit;font-size:.78rem;cursor:pointer}
    .bottom-nav{position:fixed;bottom:0;left:0;right:0;background:#fff;
                border-top:1px solid var(--border);display:flex;
                padding:8px 0 calc(8px + var(--safe-bottom));z-index:100}
    .nav-item{flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;
              text-decoration:none;color:var(--muted);font-size:.62rem;padding:4px 0}
    .nav-item.active{color:var(--g)}
    .nav-icon{font-size:1.2rem}
    .skel{background:linear-gradient(90deg,#f0f0f0 25%,#e8e8e8 50%,#f0f0f0 75%);
          background-size:200% 100%;animation:skel 1.4s infinite;border-radius:8px;height:14px;margin-bottom:8px}
    @keyframes skel{0%{background-position:200% 0}100%{background-position:-200% 0}}
    .fade-in{animation:fi .35s ease}@keyframes fi{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
    @media(max-width:480px){.stats-row{grid-template-columns:repeat(2,1fr)}}
  </style>
</head>
<body>
<header class="hdr">
  <div class="logo">🧠 سودانا</div>
  <div class="hdr-right">
    <button class="notif-btn" onclick="window.location='/app/notifications.php'">
      🔔<span class="notif-badge" id="notif-badge">0</span>
    </button>
    <a href="/app/profile.php" class="avatar"><?php echo mb_substr($firstName,0,1); ?></a>
  </div>
</header>

<div class="hero">
  <div class="hero-top">
    <div>
      <div class="hero-greeting" id="time-greeting">أهلاً</div>
      <div class="hero-name"><?php echo htmlspecialchars($firstName); ?> 👋</div>
    </div>
    <div class="plan-badge" style="color:<?php echo $planColor;?>;border-color:<?php echo $planColor;?>"><?php echo $planLabel;?></div>
  </div>
  <div class="chat-wrap">
    <div class="chat-msgs" id="chat-msgs"></div>
    <div class="chat-input-row">
      <input type="text" class="chat-input" id="chat-q" placeholder="اسألني أي شيء..."
             autocomplete="off" autocorrect="off" onkeydown="if(event.key==='Enter')sendChat()">
      <button class="chat-send" onclick="sendChat()">↑</button>
    </div>
  </div>
</div>

<div class="container">
  <div class="stats-row fade-in">
    <div class="stat-card">
      <div class="stat-val" id="s-ai">-</div>
      <div class="stat-lbl">AI اليوم <span id="s-ai-limit" style="color:#94a3b8;font-size:.7rem"></span></div>
      <div class="stat-bar"><div class="stat-bar-fill" id="s-ai-bar" style="width:0%"></div></div>
    </div>
    <div class="stat-card">
      <div class="stat-val" id="s-bal">-</div>
      <div class="stat-lbl">رصيد SDG</div>
      <div style="font-size:.65rem;color:#94a3b8;margin-top:2px" id="s-credit"></div>
    </div>
    <div class="stat-card"><div class="stat-val" id="s-bk">-</div><div class="stat-lbl">حجوزاتي</div></div>
    <div class="stat-card"><div class="stat-val" id="s-pts">-</div><div class="stat-lbl">نقاطي</div></div>
  </div>

  <div id="alerts-section" style="display:none"></div>
  <div id="nudge-section" style="display:none"></div>

  <div class="section fade-in" id="upcoming-section" style="display:none">
    <div class="sec-title">📅 مواعيدك القادمة</div>
    <div id="upcoming-list"></div>
  </div>

  <div class="section fade-in">
    <div class="sec-title">⚡ الخدمات السريعة</div>
    <div class="svc-grid">
      <a href="/app/medical.php"     class="svc-btn"><span class="svc-icon">⚕️</span><div class="svc-lbl">طبي</div></a>
      <a href="/app/legal.php"       class="svc-btn"><span class="svc-icon">⚖️</span><div class="svc-lbl">قانوني</div></a>
      <a href="/app/education.php"   class="svc-btn"><span class="svc-icon">🎓</span><div class="svc-lbl">تعليم</div></a>
      <a href="/app/pharmacy.php"    class="svc-btn"><span class="svc-icon">💊</span><div class="svc-lbl">صيدلية</div></a>
      <a href="/app/jobs.php"        class="svc-btn"><span class="svc-icon">💼</span><div class="svc-lbl">وظائف</div></a>
      <a href="/app/market.php"      class="svc-btn"><span class="svc-icon">🛒</span><div class="svc-lbl">سوق</div></a>
      <a href="/app/suggestions.php" class="svc-btn"><span class="svc-icon">💡</span><div class="svc-lbl">اقتراح</div></a>
      <a href="/wallet.php"          class="svc-btn"><span class="svc-icon">💰</span><div class="svc-lbl">محفظة</div></a>
      <a href="/app/corporate-solutions.php" class="svc-btn"><span class="svc-icon">🏢</span><div class="svc-lbl">شركات</div></a>
    </div>
  </div>

  <div class="section fade-in">
    <div class="sec-title">📋 آخر نشاطاتك</div>
    <div id="activity-list">
      <div class="skel"></div><div class="skel"></div><div class="skel"></div>
    </div>
  </div>
</div>

<nav class="bottom-nav">
  <a href="/app/dashboard.php"   class="nav-item active"><span class="nav-icon">🏠</span><span>الرئيسية</span></a>
  <a href="/app/services.php"    class="nav-item"><span class="nav-icon">⚡</span><span>الخدمات</span></a>
  <a href="/app/suggestions.php" class="nav-item"><span class="nav-icon">💡</span><span>اقتراح</span></a>
  <a href="/app/notifications.php" class="nav-item"><span class="nav-icon">🔔</span><span>إشعارات</span></a>
  <a href="/app/profile.php"     class="nav-item"><span class="nav-icon">👤</span><span>حسابي</span></a>
</nav>

<script>
const USER_NAME = '<?php echo addslashes($firstName); ?>';
const USER_PLAN = '<?php echo $plan; ?>';
let CTX = null;

// الوقت
(function(){
  const h = new Date().getHours();
  const g = h<7?'الفجر بركة 🌅':h<12?'صباح الخير ☀️':h<14?'سلام الظهيرة 🕛':h<18?'مساء النشاط ✨':h<21?'مساء النور 🌆':'الليل هادي 🌙';
  document.getElementById('time-greeting').textContent = g;
})();

function addMsg(text, isUser=false) {
  const chat = document.getElementById('chat-msgs');
  const div  = document.createElement('div');
  div.className = isUser ? 'cmsg-user' : 'cmsg-bot';
  div.innerHTML = text.replace(/\n/g,'<br>');
  chat.appendChild(div);
  chat.scrollTop = chat.scrollHeight;
  return div;
}

function addTyping() {
  const chat = document.getElementById('chat-msgs');
  const div  = document.createElement('div');
  div.className = 'ctyping';
  div.innerHTML = '<span></span><span></span><span></span>';
  chat.appendChild(div);
  chat.scrollTop = chat.scrollHeight;
  return div;
}

function addChoices(choices, cb) {
  const chat = document.getElementById('chat-msgs');
  const row  = document.createElement('div');
  row.className = 'chat-choices';
  choices.forEach(c => {
    const btn = document.createElement('button');
    btn.className   = 'chat-choice';
    btn.textContent = c.label;
    btn.onclick     = () => { row.remove(); addMsg(c.label, true); setTimeout(()=>cb(c.value,c.label), 300); };
    row.appendChild(btn);
  });
  chat.appendChild(row);
  chat.scrollTop = chat.scrollHeight;
}

function sleep(ms){ return new Promise(r=>setTimeout(r,ms)); }

async function typeMsg(text, delay=700) {
  const t = addTyping();
  await sleep(delay);
  t.remove();
  addMsg(text);
}

function fmtNum(n){ return Number(n||0).toLocaleString('ar-SA'); }
function fmtDate(dt){
  if (!dt) return '';
  const d = new Date(dt.replace(' ','T'));
  const diffH = Math.round((new Date()-d)/3600000);
  if (diffH<1) return 'منذ دقائق';
  if (diffH<24) return 'منذ '+diffH+' ساعة';
  return d.toLocaleDateString('ar-SA',{day:'numeric',month:'short'});
}

async function loadContext() {
  try {
    const r = await fetch('/api/user/context.php');
    CTX = await r.json();

    // AI usage with limit + bar
    const aiUsed = CTX.stats?.ai_today ?? CTX.usage?.ai_today ?? 0;
    const aiLim  = CTX.limits?.ai_daily ?? 20;
    const aiPct  = CTX.usage?.ai_pct_used ?? 0;
    document.getElementById('s-ai').textContent       = aiUsed;
    document.getElementById('s-ai-limit').textContent = ' / ' + aiLim;
    const bar = document.getElementById('s-ai-bar');
    bar.style.width = aiPct + '%';
    bar.classList.remove('warn','critical');
    if (aiPct >= 100) bar.classList.add('critical');
    else if (aiPct >= 80) bar.classList.add('warn');

    document.getElementById('s-bal').textContent = fmtNum(CTX.wallet?.balance);

    // Show credit if active
    const credit = CTX.wallet?.credit_remaining ?? 0;
    if (credit > 0) {
      document.getElementById('s-credit').textContent = '+' + fmtNum(credit) + ' وثائق';
    }

    document.getElementById('s-bk').textContent  = CTX.stats?.bookings_total ?? 0;
    document.getElementById('s-pts').textContent = fmtNum(CTX.user?.points);

    // Render alerts (limit warnings, low credit, etc.)
    if (CTX.alerts?.length > 0) {
      const aSec = document.getElementById('alerts-section');
      aSec.style.display = 'block';
      aSec.innerHTML = CTX.alerts.map(a =>
        `<div class="alert-card ${a.severity==='critical'?'':'warn'}">
           <span style="font-size:1.1rem">${a.severity==='critical'?'🚨':'⚠️'}</span>
           <span>${a.message}</span>
         </div>`
      ).join('');
    }

    const unread = CTX.notifications?.unread ?? 0;
    if (unread > 0) {
      const b = document.getElementById('notif-badge');
      b.textContent = unread > 9 ? '9+' : unread;
      b.style.display = 'flex';
    }

    if (CTX.upcoming?.length > 0) {
      document.getElementById('upcoming-section').style.display = 'block';
      const icons = {medical:'⚕️',legal:'⚖️',education:'🎓',general:'📋'};
      document.getElementById('upcoming-list').innerHTML = CTX.upcoming.map(b=>`
        <div class="row-item">
          <div class="row-icon">${icons[b.service_type]||'📋'}</div>
          <div><div style="font-weight:700">${b.provider_name||'المزود'}</div>
          <div class="row-sub">${fmtDate(b.slot_time)}</div></div>
        </div>`).join('');
    }

    const actEl = document.getElementById('activity-list');
    if (CTX.recent?.length > 0) {
      const si = {medical:'⚕️',legal:'⚖️',education:'🎓',platform:'🧠',market:'🛒',general:'💬'};
      actEl.innerHTML = CTX.recent.map(a=>`
        <div class="row-item">
          <div class="row-icon" style="background:rgba(0,217,126,.15)">${si[a.sector]||'💬'}</div>
          <div style="flex:1;min-width:0">
            <div style="font-size:.8rem;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${a.question||''}</div>
            <div class="row-sub">${fmtDate(a.created_at)}</div>
          </div>
        </div>`).join('');
    } else {
      actEl.innerHTML = '<p style="color:var(--muted);font-size:.82rem;text-align:center;padding:10px">لا نشاط بعد — ابدأ بسؤال!</p>';
    }

    if (CTX.nudge) showNudge(CTX.nudge);
  } catch(e) {}
  startAssistant();
}

async function startAssistant() {
  document.getElementById('chat-msgs').innerHTML = '';

  if (CTX?.upcoming?.length > 0) {
    const b = CTX.upcoming[0];
    await typeMsg('أهلاً '+USER_NAME+' 🙂\n\nعندك موعد قريب مع '+( b.provider_name||'المزود')+'\nتبي تذكير؟', 700);
    addChoices([
      {label:'نعم، ذكِّرني',value:'remind'},
      {label:'شكراً، أعرف',value:'dismiss'},
    ], async (v) => {
      if (v==='remind') { await typeMsg('تمام ✅\nهنبعثلك إشعار قبل الموعد بساعة.',600); }
      enableFree();
    });
    return;
  }

  if (CTX?.recent?.length > 0) {
    const last = CTX.recent[0];
    const sa = {medical:'الطب',legal:'القانون',education:'التعليم',market:'السوق',general:'عام'};
    await typeMsg('أهلاً '+USER_NAME+' 🙂\n\nآخر مرة سألت عن '+(sa[last.sector]||last.sector)+'\nنكمل؟', 700);
    addChoices([
      {label:'نعم',value:'c_'+last.sector},
      {label:'موضوع جديد',value:'new'},
    ], async (v) => {
      if (v.startsWith('c_')) {
        const dest={medical:'/app/medical.php',legal:'/app/legal.php',education:'/app/education.php'};
        const d = dest[v.replace('c_','')];
        if (d) { window.location.href=d; return; }
      }
      await typeMsg('شنو الموضوع الجديد؟',400); enableFree();
    });
    return;
  }

  await typeMsg('أهلاً '+USER_NAME+' 🌟\n\nأنا مساعدك الشخصي في سودانا.\nشنو نبدأ معك اليوم؟', 700);
  addChoices([
    {label:'⚕️ صحي',    value:'medical'},
    {label:'⚖️ قانوني', value:'legal'},
    {label:'📚 تعليمي', value:'education'},
    {label:'💡 عمل',    value:'business'},
  ], async (v) => {
    const d={medical:'/app/medical.php',legal:'/app/legal.php',education:'/app/education.php'};
    if (d[v]) { window.location.href=d[v]; return; }
    await typeMsg('ممتاز 💼\nاكتب عن فكرتك وأنا أساعدك.',500);
    enableFree();
  });
}

function enableFree() {
  const inp = document.getElementById('chat-q');
  if (inp) { inp.placeholder='اكتب سؤالك...'; inp.focus(); }
}

async function sendChat() {
  const inp = document.getElementById('chat-q');
  const q   = inp?.value.trim();
  if (!q) return;
  inp.value = '';
  addMsg(q, true);
  const t = addTyping();
  try {
    const r = await fetch('/api/visitor_ask.php', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({question:q, lang:'ar'})
    });
    const d = await r.json();
    t.remove();
    addMsg((d.answer||'تعذّر الرد.').replace(/\n/g,'<br>').replace(/\*\*(.*?)\*\*/g,'<strong>$1</strong>'));
  } catch(e) { t.remove(); addMsg('تعذّر الاتصال. جرب مرة أخرى.'); }
}

function showNudge(nudge) {
  if (!nudge?.message) return;
  const s = document.getElementById('nudge-section');
  s.style.display = 'block';
  s.innerHTML = '<div class="nudge-card">' +
    '<div class="nudge-msg">'+nudge.message.replace(/\n/g,'<br>')+'</div>' +
    '<div class="nudge-btns">' +
    (nudge.show_register_btn
      ? '<button class="nudge-yes" onclick="window.location=\'/app/provider-register.php\'">سجِّل كمزود ←</button>'
      : '<button class="nudge-yes" onclick="replyNudge(\'positive\')">نعم، أخبرني أكثر</button>') +
    '<button class="nudge-skip" onclick="replyNudge(\'ignored\')">ربما لاحقاً</button>' +
    '</div></div>';
}

async function replyNudge(resp) {
  document.getElementById('nudge-section').style.display='none';
  try { await fetch('/api/user/nudge_response.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({response:resp})}); } catch(e){}
  if (resp==='positive') {
    await typeMsg('ممتاز 🎯\n\nالتسجيل كمزود بسيط جداً.\nأنت من تحدد وقتك وسعرك.\nتبي نبدأ؟', 400);
    addChoices([{label:'نعم، ابدأ',value:'go'},{label:'لاحقاً',value:'later'}],
      (v) => { if (v==='go') window.location.href='/app/provider-register.php'; else enableFree(); });
  }
}

if (window.visualViewport) {
  window.visualViewport.addEventListener('resize', () => {
    const c = document.getElementById('chat-msgs');
    if (c) c.scrollTop = c.scrollHeight;
  });
}

loadContext();

// ── Sudanna Pay Balance ──────────────────────────────────────
(async function loadPayBalance(){
  try {
    const r = await fetch('/api/pay/dashboard.php');
    const d = await r.json();
    const bal = d.data?.available ?? d.data?.balance ?? 0;
    const el = document.getElementById('pay-balance-widget');
    if (el) el.innerHTML = Number(bal).toLocaleString('ar-SA') + ' SDG';
    const el2 = document.getElementById('pay-balance-mini');
    if (el2) el2.textContent = Number(bal).toLocaleString('ar-SA') + ' SDG';
  } catch(e) {}
})();
</script>
<script src="/assets/pricing-loader.js" defer></script>
</body>
</html>