// ── Provider Dashboard v23 — سودانا ─────────────────────────────────

async function loadProviderDashboard(){
  if(!currentUser){ return; }
  const c = document.getElementById('app-content');
  c.innerHTML = '<div style="text-align:center;padding:30px;color:var(--text2)"><div style="font-size:2rem;margin-bottom:8px">⏳</div>جاري تحميل لوحة المزود...</div>';

  const [bkResp, svcResp, earnResp] = await Promise.allSettled([
    fetch('/api/booking/status.php', {method:'POST', headers:{'Content-Type':'application/json'},
          body: JSON.stringify({action:'list', as_provider:true})}),
    fetch('/api/provider/services.php?action=list'),
    fetch('/api/provider/earnings.php?period=month'),
  ]);

  const bkData   = bkResp.status==='fulfilled'   ? await bkResp.value.json().catch(()=>({bookings:[]}))   : {bookings:[]};
  const svcData  = svcResp.status==='fulfilled'  ? await svcResp.value.json().catch(()=>({services:[]}))  : {services:[]};
  const earnData = earnResp.status==='fulfilled' ? await earnResp.value.json().catch(()=>({summary:{}})) : {summary:{}};

  const bookings = bkData.bookings || [];
  const services = svcData.services || [];
  const summary  = earnData.summary || {};
  const pending  = bookings.filter(b=>b.status==='pending').length;
  const active   = bookings.filter(b=>['confirmed','in_progress'].includes(b.status)).length;
  const u = currentUser;

  // ── PROVIDER JOURNEY: not verified yet ──────────────────────────
  if(!u.provider_verified) {
    c.innerHTML = `
    <div style="max-width:500px;margin:0 auto;padding:20px">
      <div style="background:linear-gradient(135deg,#073328,#0d4030);border-radius:16px;padding:24px;color:#fff;text-align:center;margin-bottom:20px">
        <div style="font-size:2.5rem;margin-bottom:10px">🏅</div>
        <div style="font-size:1.1rem;font-weight:900;margin-bottom:6px">حسابك المهني قيد المراجعة</div>
        <div style="opacity:.75;font-size:.85rem">سيتم التواصل معك خلال 48 ساعة بعد مراجعة بياناتك</div>
      </div>
      <div style="background:#fff;border-radius:12px;border:1.5px solid var(--border);padding:18px;margin-bottom:14px">
        <div style="font-weight:800;color:var(--g1);margin-bottom:12px">ما يحدث الآن:</div>
        <div style="display:grid;gap:10px">
          ${['✅ تم استلام طلبك','🔍 مراجعة بيانات التخصص','📞 التحقق من الشهادات','🎯 تفعيل الحساب المهني'].map((s,i)=>`
          <div style="display:flex;align-items:center;gap:10px;padding:8px;border-radius:8px;background:${i===0?'#e8f5e9':i===1?'#fff3e0':'#f5f5f5'};border:1px solid ${i===0?'#a5d6a7':i===1?'#ffcc80':'#eee'}">
            <span style="font-size:.9rem">${s}</span>
          </div>`).join('')}
        </div>
      </div>
      <button onclick="switchTab('profile')" style="width:100%;background:#073328;color:#fff;border:none;border-radius:12px;padding:14px;font-family:Cairo,sans-serif;font-weight:700;font-size:.9rem;cursor:pointer">تحديث بياناتي ←</button>
    </div>`;
    return;
  }

  // ── FULL PROVIDER DASHBOARD ──────────────────────────────────────
  let html = `<div style="max-width:560px;margin:0 auto;padding:16px 16px 50px">

    <!-- ── Header ─────────────────────────────────── -->
    <div style="background:linear-gradient(135deg,#1b5e20,#2e7d32);border-radius:16px;padding:18px;color:#fff;margin-bottom:14px">
      <div style="display:flex;align-items:center;gap:12px;margin-bottom:14px">
        <div style="width:52px;height:52px;background:rgba(255,255,255,.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.5rem">🏅</div>
        <div>
          <div style="font-weight:900;font-size:1rem">${h(u.name||'')}</div>
          <div style="font-size:.72rem;opacity:.75;margin-top:2px">${h(u.user_type||'')} · ${u.state||''}${u.city?' · '+u.city:''}</div>
          <div style="margin-top:4px;display:flex;gap:5px;flex-wrap:wrap">
            <span style="background:rgba(255,255,255,.15);border-radius:6px;padding:2px 8px;font-size:.68rem">✅ موثّق</span>
            <span style="background:rgba(255,255,255,.1);border-radius:6px;padding:2px 8px;font-size:.68rem">⭐ ${(u.avg_rating||0).toFixed?Number(u.avg_rating||0).toFixed(1):'—'}</span>
          </div>
        </div>
      </div>
      <!-- KPI Row -->
      <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px">
        <div style="background:rgba(0,0,0,.2);border-radius:10px;padding:10px;text-align:center">
          <div style="font-size:1.2rem;font-weight:900">${pending}</div>
          <div style="font-size:.62rem;opacity:.8">⏳ انتظار</div>
        </div>
        <div style="background:rgba(0,0,0,.2);border-radius:10px;padding:10px;text-align:center">
          <div style="font-size:1.2rem;font-weight:900">${active}</div>
          <div style="font-size:.62rem;opacity:.8">🔵 نشطة</div>
        </div>
        <div style="background:rgba(0,0,0,.2);border-radius:10px;padding:10px;text-align:center">
          <div style="font-size:1.2rem;font-weight:900">${Number(summary.total_net||0).toLocaleString()}</div>
          <div style="font-size:.62rem;opacity:.8">💰 SDG</div>
        </div>
        <div style="background:rgba(0,0,0,.2);border-radius:10px;padding:10px;text-align:center">
          <div style="font-size:1.2rem;font-weight:900">${services.length}</div>
          <div style="font-size:.62rem;opacity:.8">🛠️ خدمة</div>
        </div>
      </div>
    </div>

    <!-- ── Quick Actions ──────────────────────────── -->
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px">
      <button onclick="switchTab('consult')" style="background:#e3f2fd;border:1.5px solid #90caf9;border-radius:12px;padding:13px;text-align:center;cursor:pointer;font-family:Cairo,sans-serif">
        <div style="font-size:1.3rem">💬</div>
        <div style="font-weight:700;font-size:.8rem;color:#1565c0;margin-top:3px">استشاراتي</div>
      </button>
      <button onclick="switchTab('profile')" style="background:#f3e5f5;border:1.5px solid #ce93d8;border-radius:12px;padding:13px;text-align:center;cursor:pointer;font-family:Cairo,sans-serif">
        <div style="font-size:1.3rem">⚙️</div>
        <div style="font-weight:700;font-size:.8rem;color:#6a1b9a;margin-top:3px">إعداداتي</div>
      </button>
    </div>

    <!-- ── Pending Bookings ──────────────────────── -->
    <div style="background:#fff;border-radius:12px;padding:16px;margin-bottom:14px;border:1.5px solid var(--border)">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
        <h4 style="margin:0;color:var(--g1);font-weight:800">📅 طلبات تنتظر قرارك</h4>
        ${pending>0?`<span style="background:#e8f5e9;color:#2e7d32;border-radius:8px;padding:3px 10px;font-size:.72rem;font-weight:700">${pending} جديد</span>`:''}
      </div>`;

  const pendingBk = bookings.filter(b=>b.status==='pending');
  if(!pendingBk.length){
    html += '<div style="text-align:center;padding:16px;color:var(--text2);font-size:.88rem">✅ لا طلبات معلقة حالياً</div>';
  }
  pendingBk.forEach(bk=>{
    html += `<div style="border:1.5px solid #c8e6c9;border-radius:10px;padding:12px;margin-bottom:8px;background:#f9fff9">
      <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;flex-wrap:wrap">
        <div style="flex:1">
          <div style="font-weight:700;font-size:.9rem">${h(bk.user_name||'مستخدم')}</div>
          <div style="font-size:.78rem;color:var(--text2);margin-top:2px">📅 ${h(bk.booking_date||'')} ${h(bk.booking_time||'')}</div>
          ${bk.service_title?`<div style="font-size:.72rem;color:#888;margin-top:2px">🛠️ ${h(bk.service_title)}</div>`:''}
          ${bk.notes?`<div style="font-size:.72rem;color:#888;margin-top:2px;background:#fff;padding:4px 8px;border-radius:6px">📝 ${h(bk.notes)}</div>`:''}
        </div>
        <div style="display:flex;gap:6px;flex-shrink:0">
          <button onclick="confirmProviderBooking(${bk.id},'confirm')"
            style="background:#073328;color:#fff;border:none;padding:8px 12px;border-radius:8px;font-size:.78rem;cursor:pointer;font-family:Cairo,sans-serif;font-weight:700">✅ قبول</button>
          <button onclick="confirmProviderBooking(${bk.id},'reject')"
            style="background:#fbe9e7;color:#c62828;border:1.5px solid #ef9a9a;padding:8px 10px;border-radius:8px;font-size:.78rem;cursor:pointer;font-family:Cairo,sans-serif">رفض</button>
        </div>
      </div>
    </div>`;
  });
  html += '</div>';

  // Active bookings
  const activeBk = bookings.filter(b=>['confirmed','in_progress'].includes(b.status));
  if(activeBk.length){
    html += `<div style="background:#fff;border-radius:12px;padding:16px;margin-bottom:14px;border:1.5px solid #bbdefb">
      <h4 style="margin:0 0 12px;color:#1565c0;font-weight:800">🔵 الحجوزات النشطة (${activeBk.length})</h4>`;
    activeBk.forEach(bk=>{
      html += `<div style="border:1px solid #e3f2fd;border-radius:10px;padding:12px;margin-bottom:8px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:6px">
        <div>
          <div style="font-weight:700;font-size:.88rem">${h(bk.user_name||'')}</div>
          <div style="font-size:.76rem;color:var(--text2)">📅 ${h(bk.booking_date||'')} · ${bk.consultation_type==='video'?'🎥 فيديو':'💬 نص'}</div>
          <div style="margin-top:4px">
            <span style="background:${bk.status==='in_progress'?'#e8f5e9':'#fff3e0'};color:${bk.status==='in_progress'?'#2e7d32':'#e65100'};padding:2px 8px;border-radius:6px;font-size:.7rem">
              ${bk.status==='in_progress'?'⚡ جارية':'⏰ مؤكدة'}
            </span>
          </div>
        </div>
        <div style="display:flex;gap:6px">
          ${bk.status==='confirmed'?`<button onclick="updateProviderBooking(${bk.id},'start')"
            style="background:#e65100;color:#fff;border:none;padding:7px 12px;border-radius:8px;font-size:.78rem;cursor:pointer;font-family:Cairo,sans-serif;font-weight:700">▶️ ابدأ</button>`:''}
          ${bk.status==='in_progress'?`<button onclick="updateProviderBooking(${bk.id},'complete')"
            style="background:#2e7d32;color:#fff;border:none;padding:7px 12px;border-radius:8px;font-size:.78rem;cursor:pointer;font-family:Cairo,sans-serif;font-weight:700">✅ أكمل</button>`:''}
        </div>
      </div>`;
    });
    html += '</div>';
  }

  // My Services
  html += `<div style="background:#fff;border-radius:12px;padding:16px;margin-bottom:14px;border:1.5px solid var(--border)">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
      <h4 style="margin:0;color:var(--g1);font-weight:800">🛠️ خدماتي (${services.length})</h4>
      <button onclick="toggleProviderServiceForm()" style="background:#073328;color:#fff;border:none;padding:7px 14px;border-radius:8px;font-size:.78rem;cursor:pointer;font-family:Cairo,sans-serif;font-weight:700">+ إضافة</button>
    </div>

    <!-- Add Service Form -->
    <div id="prov-svc-form" style="display:none;border:1.5px solid #073328;border-radius:10px;padding:14px;margin-bottom:12px;background:#f0faf4">
      <input id="prov-svc-title" placeholder="عنوان الخدمة *" style="width:100%;padding:10px;border:1.5px solid #ddd;border-radius:8px;font-family:Cairo,sans-serif;margin-bottom:8px;box-sizing:border-box">
      <textarea id="prov-svc-desc" placeholder="وصف الخدمة بالتفصيل *" rows="2" style="width:100%;padding:10px;border:1.5px solid #ddd;border-radius:8px;font-family:Cairo,sans-serif;resize:vertical;margin-bottom:8px;box-sizing:border-box"></textarea>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px">
        <select id="prov-svc-ptype" style="padding:10px;border:1.5px solid #ddd;border-radius:8px;font-family:Cairo,sans-serif">
          <option value="fixed">سعر محدد</option>
          <option value="hourly">بالساعة</option>
          <option value="negotiable">قابل للتفاوض</option>
          <option value="free">مجاناً</option>
        </select>
        <input id="prov-svc-price" type="number" placeholder="السعر SDG" style="padding:10px;border:1.5px solid #ddd;border-radius:8px;font-family:Cairo,sans-serif">
      </div>
      <div style="display:flex;gap:8px">
        <button onclick="submitProviderService()" style="flex:1;background:#073328;color:#fff;border:none;padding:10px;border-radius:8px;cursor:pointer;font-family:Cairo,sans-serif;font-weight:700">💾 حفظ الخدمة</button>
        <button onclick="toggleProviderServiceForm()" style="background:transparent;color:#073328;border:1.5px solid #073328;padding:10px 14px;border-radius:8px;cursor:pointer;font-family:Cairo,sans-serif">إلغاء</button>
      </div>
    </div>`;

  if(!services.length){
    html += `<div style="text-align:center;padding:20px;color:var(--text2)">
      <div style="font-size:2rem;margin-bottom:8px">🛠️</div>
      <div style="font-weight:700;margin-bottom:4px">لم تُضف خدمات بعد</div>
      <div style="font-size:.82rem">أضف خدمتك الأولى ليتمكن العملاء من الحجز</div>
    </div>`;
  }
  services.forEach(sv=>{
    html += `<div style="border:1px solid #eee;border-radius:10px;padding:12px;margin-bottom:8px;display:flex;justify-content:space-between;align-items:center;gap:8px">
      <div style="flex:1">
        <div style="font-weight:700;font-size:.88rem">${h(sv.title)}</div>
        <div style="font-size:.74rem;color:var(--text2);margin-top:2px">
          💰 ${sv.pricing_type==='free'?'مجاناً':Number(sv.price_sdg||0).toLocaleString()+' SDG'}
          · 📅 ${sv.bookings_count||0} حجز
        </div>
      </div>
      <span style="background:${sv.is_active?'#e8f5e9':'#fbe9e7'};color:${sv.is_active?'#2e7d32':'#c62828'};padding:3px 8px;border-radius:8px;font-size:.7rem;white-space:nowrap">
        ${sv.is_active?'✅ نشطة':'⏸️ موقوفة'}
      </span>
    </div>`;
  });
  html += '</div>';

  // AI Tools
  if(['teacher','academic'].includes(u.user_type)){
    html += `<div style="background:linear-gradient(135deg,#e3f2fd,#f3e5f5);border-radius:12px;padding:16px;margin-bottom:14px;border:1.5px solid #90caf9">
      <div style="font-weight:800;color:#1565c0;margin-bottom:10px">🤖 أدوات AI للمعلمين</div>
      <button onclick="document.getElementById('lesson-generator-overlay')?.classList.add('show')"
        style="background:#1565c0;color:#fff;border:none;border-radius:8px;padding:10px 18px;font-family:Cairo,sans-serif;font-weight:700;font-size:.85rem;cursor:pointer">
        ✨ إنشاء درس بـ AI
      </button>
    </div>`;
  }

  // Upgrade plan
  if(!u.provider_plan || u.provider_plan==='basic'){
    html += `<div style="background:linear-gradient(135deg,#fff8e1,#fff3e0);border-radius:12px;padding:16px;border:1.5px solid #ffcc80;text-align:center">
      <div style="font-size:1.2rem;margin-bottom:6px">⬆️</div>
      <div style="font-weight:800;color:#e65100;margin-bottom:4px">رقّ لخطة المزود المميزة</div>
      <div style="font-size:.78rem;color:#777;margin-bottom:12px">ظهور أولوي · عمولة أقل · أدوات متقدمة</div>
      <button class="btn btn-gold" onclick="showModal('upgrade')">ارقَ الآن →</button>
    </div>`;
  }

  html += '</div>';
  c.innerHTML = html;
}

function toggleProviderServiceForm(){
  const f = document.getElementById('prov-svc-form');
  if(f) f.style.display = f.style.display==='none'?'block':'none';
}

async function confirmProviderBooking(id, action){
  let reason = '';
  if(action==='reject') reason = prompt('سبب الرفض (اختياري):') || '';
  const r = await fetch('/api/booking/confirm.php',{
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({booking_id:id, action, rejection_reason:reason})
  });
  const d = await r.json();
  toast(d.message || (action==='confirm'?'✅ تم القبول':'❌ تم الرفض'));
  if(d.success) loadProviderDashboard();
}

async function updateProviderBooking(id, action){
  const r = await fetch('/api/booking/status.php',{
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({booking_id:id, action})
  });
  const d = await r.json();
  toast(d.success?(action==='start'?'▶️ الخدمة بدأت':'✅ اكتملت!'):(d.message||'خطأ'));
  if(d.success) loadProviderDashboard();
}

async function submitProviderService(){
  const title = document.getElementById('prov-svc-title')?.value?.trim();
  const desc  = document.getElementById('prov-svc-desc')?.value?.trim();
  const ptype = document.getElementById('prov-svc-ptype')?.value;
  const price = document.getElementById('prov-svc-price')?.value;
  if(!title||title.length<3){toast('أدخل عنوان الخدمة');return;}
  if(!desc||desc.length<10){toast('أدخل وصفاً للخدمة (10 أحرف على الأقل)');return;}
  const r = await fetch('/api/provider/services.php?action=create',{
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({title, description:desc, pricing_type:ptype, price_sdg:Number(price)||0})
  });
  const d = await r.json();
  toast(d.success?'✅ تمت الإضافة بنجاح!':(d.message||'خطأ'));
  if(d.success) loadProviderDashboard();
}
