// ResDri — Earnings, Wallet, Profile tab screens.
// All idle screens use the same chrome: AppTopBar at top, content scrolling,
// TabBar at bottom. Layouts assume content padding accounts for both.

const TOP_PAD = 108;   // clearance below the app top bar
const BOT_PAD = 92;    // clearance above the tab bar

// ═══════════════════════════════════════════════════════════
// ORDERS — full-screen pool list, no map
// Pure list view of available orders. Same sort/filter as Home sheet.
// ═══════════════════════════════════════════════════════════
function OrdersScreen({ online, today, openOrder, acceptOrder, radiusKm = 2.0, orders, driverName }) {
  const [sort, setSort]     = React.useState('best');
  const [filter, setFilter] = React.useState('all');
  // Live API orders only — no demo fallback.
  const pool = Array.isArray(orders) ? orders : [];

  const sortOpts = [
    { id: 'best',    lbl: 'الأفضل' },
    { id: 'nearest', lbl: 'الأقرب' },
    { id: 'highest', lbl: 'الأعلى ربحاً' },
  ];
  const filterOpts = [
    { id: 'all',     lbl: 'الكل',   icon: null },
    { id: 'food',    lbl: 'طعام',   icon: 'food' },
    { id: 'parcel',  lbl: 'طرود',   icon: 'package' },
    { id: 'grocery', lbl: 'بقالة',  icon: 'cart' },
  ];

  const all = pool.filter(o => filter === 'all' ? true : o.kind === filter);
  const inRadius   = all.filter(o => (o.toPickup ?? o.distance) <= radiusKm);
  const outRadius  = all.filter(o => (o.toPickup ?? o.distance) >  radiusKm);

  const score = (o) => (o.payout + (o.bonus || 0)) / Math.max(0.5, o.distance);
  const sortFn = sort === 'nearest'
    ? ((a, b) => (a.toPickup ?? a.distance) - (b.toPickup ?? b.distance))
    : sort === 'highest'
      ? ((a, b) => (b.payout + b.bonus) - (a.payout + a.bonus))
      : ((a, b) => score(b) - score(a));

  const sortedIn  = [...inRadius].sort(sortFn);
  const sortedOut = [...outRadius].sort(sortFn);
  const topPickId = sortedIn[0]?.id;

  return (
    <div className="screen-scroll" style={{
      position: 'absolute', inset: 0,
      paddingTop: TOP_PAD, paddingBottom: BOT_PAD,
      overflowY: 'auto', background: 'var(--bg)',
    }}>
      <AppTopBar title={driverName || ''} online={online} badge={online ? 1 : 0} />

      {/* Title + radius indicator */}
      <div style={{ padding: '0 18px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <div>
          <div style={{ fontSize: 26, fontWeight: 900, color: 'var(--text)', letterSpacing: '-0.01em' }}>
            الطلبات
          </div>
          <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>
            <span className="num">{inRadius.length}</span> في نطاقك ·
            <span style={{ marginInline: 4 }} />
            <span className="num">{outRadius.length}</span> خارج النطاق
          </div>
        </div>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          background: 'color-mix(in oklch, var(--primary) 12%, var(--surface))',
          border: '1px solid color-mix(in oklch, var(--primary) 28%, transparent)',
          color: 'var(--primary)',
          padding: '6px 10px', borderRadius: 999,
          fontSize: 12, fontWeight: 800,
        }}>
          <Icon name="pin" size={14} color="var(--primary)" />
          <span>نطاق</span>
          <span className="num">{radiusKm.toFixed(1).replace(/\.0$/, '')}</span>
          <span>كم</span>
        </div>
      </div>

      {/* Sort + filter row */}
      <div style={{ padding: '0 16px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {/* Sort segmented */}
        <div style={{
          background: 'var(--surface-2)',
          borderRadius: 12, padding: 3,
          display: 'flex',
        }}>
          {sortOpts.map(o => (
            <button key={o.id} className="tap" onClick={() => setSort(o.id)} style={{
              flex: 1, height: 36, border: 'none',
              background: sort === o.id ? 'var(--surface)' : 'transparent',
              color: sort === o.id ? 'var(--text)' : 'var(--text-2)',
              fontFamily: 'inherit', fontWeight: sort === o.id ? 800 : 600, fontSize: 13,
              borderRadius: 9,
              boxShadow: sort === o.id ? '0 1px 3px rgba(0,0,0,0.06)' : 'none',
            }}>{o.lbl}</button>
          ))}
        </div>

        {/* Filter chips */}
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto' }} className="screen-scroll">
          {filterOpts.map(o => {
            const active = filter === o.id;
            return (
              <button key={o.id} className="tap" onClick={() => setFilter(o.id)} style={{
                height: 34, padding: '0 14px', borderRadius: 999,
                background: active ? 'var(--primary)' : 'var(--surface)',
                color: active ? '#fff' : 'var(--text)',
                border: active ? 'none' : '1px solid var(--line)',
                fontFamily: 'inherit', fontWeight: 700, fontSize: 13,
                display: 'inline-flex', alignItems: 'center', gap: 5,
                whiteSpace: 'nowrap', flexShrink: 0,
              }}>
                {o.icon && <Icon name={o.icon} size={14} color={active ? '#fff' : 'var(--text-2)'} />}
                <span>{o.lbl}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* IN-RADIUS list */}
      <div style={{ padding: '4px 14px 0', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {sortedIn.length === 0 && (
          <div style={{
            padding: '32px 16px', textAlign: 'center',
            background: 'var(--surface)', borderRadius: 16,
            border: '1px dashed var(--line-strong)',
            color: 'var(--text-2)',
          }}>
            <div style={{ fontSize: 15, fontWeight: 800, marginBottom: 4, color: 'var(--text)' }}>
              لا توجد طلبات في نطاقك حالياً
            </div>
            <div style={{ fontSize: 12 }}>وسّع نطاق العمل من الشاشة الرئيسية للوصول إلى المزيد.</div>
          </div>
        )}
        {sortedIn.map(o => (
          <OrderCard key={o.id} order={o}
            featured={o.id === topPickId}
            onClick={() => openOrder(o.id)}
            onAccept={() => acceptOrder ? acceptOrder(o.id) : openOrder(o.id)}
          />
        ))}
      </div>

      {/* OUT-OF-RADIUS section */}
      {sortedOut.length > 0 && (
        <>
          <div style={{
            margin: '20px 18px 8px',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <div style={{ height: 1, flex: 1, background: 'var(--line)' }} />
            <span style={{
              fontSize: 11, fontWeight: 800, color: 'var(--text-2)',
              letterSpacing: '0.08em', textTransform: 'uppercase',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <Icon name="pin" size={12} color="var(--text-2)" />
              خارج نطاقك
            </span>
            <div style={{ height: 1, flex: 1, background: 'var(--line)' }} />
          </div>
          <div style={{ padding: '0 14px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {sortedOut.map(o => (
              <div key={o.id} style={{ position: 'relative', opacity: 0.65 }}>
                <OrderCard order={o}
                  onClick={() => openOrder(o.id)}
                  onAccept={() => acceptOrder ? acceptOrder(o.id) : openOrder(o.id)}
                />
                {/* Distance badge overlay top-left */}
                <span style={{
                  position: 'absolute', top: 10, insetInlineStart: 10, zIndex: 2,
                  background: 'var(--text)', color: 'var(--surface)',
                  fontSize: 10, fontWeight: 800,
                  padding: '3px 7px', borderRadius: 6,
                  display: 'inline-flex', alignItems: 'center', gap: 3,
                  whiteSpace: 'nowrap',
                }}>
                  <span className="num">{(o.toPickup ?? o.distance).toFixed(1)}</span>
                  <span>كم</span>
                </span>
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// EARNINGS — today / week / month + performance tile
// ═══════════════════════════════════════════════════════════
// HH:MM in Latin digits regardless of locale.
function fmtClock(ts) {
  if (!ts) return '';
  const d = new Date(ts);
  if (isNaN(d.getTime())) return '';
  return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
}

const EARN_EMPTY = {
  today: { total: 0, orders: 0 },
  week:  { total: 0, orders: 0 },
  month: { total: 0, orders: 0 },
  days: [],
};

function EarningsScreen({ online, driverName }) {
  const [tab, setTab] = React.useState('week');
  const [earn, setEarn] = React.useState(null);       // null = loading
  const [history, setHistory] = React.useState(null);

  // Pull real earnings (today/week/month + 7-day series) and recent orders.
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [e, h] = await Promise.all([
          window.api.earnings(),
          window.api.history(6).catch(() => []),
        ]);
        if (cancelled) return;
        setEarn(e || EARN_EMPTY);
        setHistory(Array.isArray(h) ? h.filter(o => o && o.status === 'COMPLETED') : []);
      } catch (err) {
        if (!cancelled) { setEarn(EARN_EMPTY); setHistory([]); }
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const loading = earn === null;
  const totals = earn || EARN_EMPTY;
  const sel = totals[tab] || { total: 0, orders: 0 };
  const days = totals.days || [];
  const max = Math.max(1, ...days.map(d => d.total || 0));
  const avg = sel.orders > 0 ? (sel.total / sel.orders) : 0;

  return (
    <div className="screen-scroll" style={{
      position: 'absolute', inset: 0,
      paddingTop: TOP_PAD, paddingBottom: BOT_PAD,
      overflowY: 'auto', background: 'var(--bg)',
    }}>
      <AppTopBar title={driverName || ''} online={online} badge={online ? 1 : 0} />

      {/* Page title */}
      <div style={{ padding: '0 18px 12px' }}>
        <div style={{ fontSize: 28, fontWeight: 900, color: 'var(--text)', letterSpacing: '-0.01em' }}>
          الأرباح
        </div>
      </div>

      {/* Segmented tabs */}
      <div style={{
        margin: '0 16px 16px',
        background: 'var(--surface-2)',
        borderRadius: 14,
        padding: 4,
        display: 'flex', flexDirection: 'row-reverse',
      }}>
        {[
          { id: 'today', lbl: 'اليوم' },
          { id: 'week',  lbl: 'آخر ٧ أيام' },
          { id: 'month', lbl: 'آخر ٣٠ يوم' },
        ].map(t => (
          <button key={t.id} className="tap" onClick={() => setTab(t.id)} style={{
            flex: 1, height: 38, border: 'none',
            background: tab === t.id ? 'var(--surface)' : 'transparent',
            color: tab === t.id ? 'var(--text)' : 'var(--text-2)',
            fontFamily: 'inherit', fontWeight: tab === t.id ? 800 : 600, fontSize: 14,
            borderRadius: 10,
            boxShadow: tab === t.id ? '0 1px 3px rgba(0,0,0,0.06)' : 'none',
          }}>{t.lbl}</button>
        ))}
      </div>

      {/* Total + breakdown card */}
      <div style={{
        margin: '0 16px 14px',
        background: 'var(--surface)',
        border: '1px solid var(--line)',
        borderRadius: 22, padding: 18,
        boxShadow: '0 6px 18px rgba(15,23,42,0.06)',
      }}>
        <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
          إجمالي الأرباح
        </div>
        <div style={{ marginTop: 4, opacity: loading ? 0.4 : 1 }}>
          <BigNumber value={sel.total} size="lg" weight={900} />
        </div>
        <div style={{
          marginTop: 8, display: 'flex', justifyContent: 'space-between',
          fontSize: 12, color: 'var(--text-2)',
        }}>
          <span><span className="num">{sel.orders}</span> طلب</span>
          <span><span className="num">{avg.toFixed(1)}</span> متوسط/طلب</span>
        </div>

        {/* Bar chart — 7-day series */}
        {tab === 'week' && days.length > 0 && (
          <div style={{
            marginTop: 18, paddingTop: 14, borderTop: '1px dashed var(--line)',
          }}>
            <div style={{
              display: 'flex', flexDirection: 'row-reverse',
              alignItems: 'flex-end', justifyContent: 'space-between',
              gap: 6, height: 100,
            }}>
              {days.map((d, i) => (
                <div key={d.date || i} style={{
                  flex: 1, display: 'flex', flexDirection: 'column',
                  alignItems: 'center', gap: 4, height: '100%',
                  justifyContent: 'flex-end',
                }}>
                  <div className="num" style={{
                    fontSize: 10, fontWeight: 800,
                    color: d.today ? 'var(--accent-700)' : 'var(--text-3)',
                  }}>{d.total}</div>
                  <div style={{
                    width: '100%', maxWidth: 22,
                    height: `${Math.max(2, (d.total / max) * 70)}px`,
                    background: d.today ? 'var(--accent)' : 'color-mix(in oklch, var(--primary) 24%, transparent)',
                    borderRadius: 6,
                  }} />
                  <div style={{ fontSize: 11, color: 'var(--text-2)', fontWeight: 700 }}>{d.label}</div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Recent orders — real completed history */}
      <div style={{ padding: '4px 18px 6px' }}>
        <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          آخر الطلبات
        </div>
      </div>
      {history && history.length === 0 && (
        <div style={{
          margin: '0 16px', padding: '18px 14px', textAlign: 'center',
          color: 'var(--text-3)', fontSize: 13, fontWeight: 600,
        }}>
          لا توجد طلبات مكتملة بعد
        </div>
      )}
      {(history || []).map(o => (
        <HistoryRow key={o.id}
          business={o.business}
          customer={o.customer}
          amt={(Number(o.payout) || 0) + (Number(o.bonus) || 0)}
          time={fmtClock(o._raw && o._raw.completedAt) || fmtClock(o.createdAt)}
          kind={o.kind}
        />
      ))}
    </div>
  );
}

function KPI({ label, value, suffix, tone }) {
  const colors = {
    accent:  'var(--accent-700)',
    primary: 'var(--primary)',
    success: 'var(--success)',
    danger:  'var(--danger)',
  };
  const c = colors[tone] || 'var(--text)';
  return (
    <div style={{
      background: 'var(--surface-2)',
      border: '1px solid var(--line)',
      borderRadius: 14, padding: 12,
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-2)' }}>{label}</div>
      <div style={{ marginTop: 4, display: 'flex', alignItems: 'baseline', gap: 3 }}>
        <span className="num" style={{ fontSize: 24, fontWeight: 900, color: c, letterSpacing: '-0.02em' }}>{value}</span>
        <span style={{ fontSize: 14, fontWeight: 700, color: c, opacity: 0.85 }}>{suffix}</span>
      </div>
    </div>
  );
}

function HistoryRow({ business, customer, amt, time, kind }) {
  return (
    <div style={{
      margin: '0 16px 8px',
      background: 'var(--surface)',
      border: '1px solid var(--line)',
      borderRadius: 14,
      padding: '10px 12px',
      display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <VerticalChip kind={kind} size={32} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>{business}</div>
        <div style={{ fontSize: 11, color: 'var(--text-2)', marginTop: 1 }}>
          للزبون {customer} · <span className="num">{time}</span>
        </div>
      </div>
      <BigNumber value={amt} size="sm" weight={800} />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// WALLET — commission owed vs cash held + settle button
// ═══════════════════════════════════════════════════════════
function WalletScreen({ online, driver, driverName }) {
  // Real driver wallet from /drivers/me. Cash cap from server config.
  const cash = Number(driver?.cashHeld) || 0;             // cash currently in driver's hand
  const commission = Number(driver?.commissionOwed) || 0; // commission owed to platform
  const cap = (window.RESDRI_CONFIG && window.RESDRI_CONFIG.cashCapIls) || 500;
  const pct = Math.min(1, cap > 0 ? commission / cap : 0);
  const nearCap = pct > 0.7;

  return (
    <div className="screen-scroll" style={{
      position: 'absolute', inset: 0,
      paddingTop: TOP_PAD, paddingBottom: BOT_PAD,
      overflowY: 'auto', background: 'var(--bg)',
    }}>
      <AppTopBar title={driverName || ''} online={online} badge={online ? 1 : 0} />

      <div style={{ padding: '0 18px 12px' }}>
        <div style={{ fontSize: 28, fontWeight: 900, color: 'var(--text)' }}>المحفظة</div>
      </div>

      {/* Big split card */}
      <div style={{
        margin: '0 16px 14px',
        background: 'var(--surface)',
        border: '1px solid var(--line)',
        borderRadius: 22,
        overflow: 'hidden',
      }}>
        <div style={{
          padding: 18,
          background: nearCap
            ? 'color-mix(in oklch, var(--accent) 12%, transparent)'
            : 'transparent',
        }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
            <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
              عمولة مستحقة للمنصة
            </span>
            <span className="num" style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 700 }}>
              من حد ₪{cap}
            </span>
          </div>
          <div style={{ marginTop: 6, display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
            <BigNumber value={commission} size="lg" weight={900} accent={nearCap} />
          </div>
          {/* Progress bar */}
          <div style={{
            marginTop: 12, height: 8, borderRadius: 999,
            background: 'var(--surface-2)', overflow: 'hidden',
          }}>
            <div style={{
              height: '100%', width: `${pct * 100}%`,
              background: nearCap ? 'var(--accent)' : 'var(--primary)',
              borderRadius: 999,
              transition: 'width 0.3s',
            }} />
          </div>
          {nearCap && (
            <div style={{
              marginTop: 10, fontSize: 12, fontWeight: 700, color: 'var(--accent-700)',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <Icon name="bell" size={14} color="var(--accent-700)" />
              <span>اقتربت من الحد. سدّد قريباً للاستمرار في تلقي الطلبات.</span>
            </div>
          )}
        </div>

        <div style={{ height: 1, background: 'var(--line)' }} />

        {/* Cash held */}
        <div style={{ padding: 18 }}>
          <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
            نقد بحوزتك
          </div>
          <div style={{ marginTop: 6, display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
            <BigNumber value={cash} size="md" weight={800} />
            <span style={{ fontSize: 12, color: 'var(--text-2)' }}>
              منه <span className="num">₪{commission}</span> للمنصة
            </span>
          </div>
        </div>
      </div>

      {/* Settle now CTA */}
      <div style={{ padding: '0 16px 14px' }}>
        <PrimaryButton tone="primary" size="lg" leadingIcon="wallet">
          تسوية الآن (₪<span className="num">{commission}</span>)
        </PrimaryButton>
      </div>

      {/* Settlement points */}
      <div style={{
        margin: '0 16px 14px',
        background: 'var(--surface)',
        border: '1px solid var(--line)',
        borderRadius: 18, padding: 14,
      }}>
        <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--text)', marginBottom: 10 }}>
          نقاط التسوية القريبة
        </div>
        {[
          { name: 'مكتب ريسدري — البلدة القديمة', dist: 1.2, open: true },
          { name: 'دكان أبو وليد', dist: 2.4, open: true },
          { name: 'محطة وقود الزيتون', dist: 3.1, open: false },
        ].map((p, i, arr) => (
          <div key={p.name} style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 0',
            borderBottom: i < arr.length - 1 ? '1px solid var(--line)' : 'none',
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: p.open ? 'color-mix(in oklch, var(--success) 14%, transparent)' : 'var(--surface-2)',
              color: p.open ? 'var(--success)' : 'var(--text-3)',
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              <Icon name="pin" size={18} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text)' }}>{p.name}</div>
              <div style={{ fontSize: 11, color: 'var(--text-2)', marginTop: 1 }}>
                <span className="num">{p.dist.toFixed(1)}</span> كم · {p.open ? 'مفتوح الآن' : 'مغلق'}
              </div>
            </div>
            <Icon name="chev-left" size={18} color="var(--text-3)" />
          </div>
        ))}
      </div>

      {/* History */}
      <div style={{ padding: '4px 18px 6px' }}>
        <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          آخر التسويات
        </div>
      </div>
      {[
        { d: 'الأمس 16:42', amt: 320 },
        { d: 'الإثنين 18:10', amt: 285 },
        { d: 'الأحد 19:05', amt: 410 },
      ].map((s, i) => (
        <div key={i} style={{
          margin: '0 16px 8px',
          background: 'var(--surface)',
          border: '1px solid var(--line)',
          borderRadius: 14,
          padding: '10px 14px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>تم تسوية النقد</div>
            <div className="num" style={{ fontSize: 11, color: 'var(--text-2)', marginTop: 1 }}>{s.d}</div>
          </div>
          <BigNumber value={s.amt} size="sm" weight={800} />
        </div>
      ))}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// PROFILE — avatar + rows
// ═══════════════════════════════════════════════════════════
// Vehicle kind → (Arabic label, VehicleIcon kind)
const VEHICLE_LABEL = { CAR: 'سيارة', MOTORBIKE: 'دراجة نارية', BICYCLE: 'دراجة هوائية' };
const VEHICLE_ICON  = { CAR: 'car', MOTORBIKE: 'bike', BICYCLE: 'bike' };
// Account status → Arabic label
const STATUS_LABEL = {
  APPROVED: 'حساب معتمد', AWAITING_REVIEW: 'قيد المراجعة',
  PENDING_KYC: 'بانتظار المستندات', SUSPENDED: 'موقوف', REJECTED: 'مرفوض',
};

function ProfileScreen({ online, driver, driverName, onLogout }) {
  // Everything here is the real logged-in driver from /drivers/me.
  const name   = driver?.fullName || driverName || '—';
  const phone  = driver?.phone || '';
  const initial = (name && name.trim()[0]) || '؟';
  const vKind  = driver?.vehicleKind || null;
  const vLabel = vKind ? (VEHICLE_LABEL[vKind] || 'مركبة') : null;
  const vIcon  = vKind ? (VEHICLE_ICON[vKind] || 'car') : 'car';
  const plate  = driver?.vehiclePlate || '';
  const color  = driver?.vehicleColor || '';
  const docs   = Array.isArray(driver?.documents) ? driver.documents.length : 0;
  const statusLabel = STATUS_LABEL[driver?.status] || '';

  return (
    <div className="screen-scroll" style={{
      position: 'absolute', inset: 0,
      paddingTop: TOP_PAD, paddingBottom: BOT_PAD,
      overflowY: 'auto', background: 'var(--bg)',
    }}>
      <AppTopBar title=" " online={online} badge={online ? 1 : 0} />

      {/* Big profile card */}
      <div style={{ padding: '0 16px 14px' }}>
        <div style={{
          background: 'var(--surface)', borderRadius: 22, padding: 18,
          border: '1px solid var(--line)',
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{
            width: 64, height: 64, borderRadius: 999,
            background: 'var(--primary)', color: '#fff',
            display: 'grid', placeItems: 'center',
            fontWeight: 800, fontSize: 24,
          }}>{initial}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--text)' }}>{name}</div>
            {phone && <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>
              <span className="num" dir="ltr">{phone}</span>
            </div>}
            {statusLabel && (
              <div style={{ marginTop: 6 }}>
                <span style={{
                  fontSize: 11, fontWeight: 800,
                  color: driver?.status === 'APPROVED' ? 'var(--success)' : 'var(--text-3)',
                }}>{statusLabel}</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Vehicle card — only when a vehicle is on file */}
      {vKind && (
      <div style={{ padding: '0 16px 14px' }}>
        <div style={{
          background: 'var(--surface)', borderRadius: 18,
          border: '1px solid var(--line)',
          padding: 14,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 52, height: 52, borderRadius: 14,
            background: 'color-mix(in oklch, var(--primary) 12%, var(--surface-2))',
            color: 'var(--primary)',
            display: 'grid', placeItems: 'center',
          }}>
            <VehicleIcon kind={vIcon} size={28} color="var(--primary)" />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--text)' }}>{vLabel}</div>
            {(plate || color) && (
              <div className="num" style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>
                {[plate && `لوحة ${plate}`, color].filter(Boolean).join(' · ')}
              </div>
            )}
          </div>
        </div>
      </div>
      )}

      {/* Menu rows */}
      <Section>
        <Row name="package" label="مستنداتي" detail={docs ? `${docs} وثائق` : 'لا توجد وثائق'} />
        <Row name="bell"    label="إعدادات الإشعارات" />
      </Section>

      <Section>
        <Row name="whatsapp" label="الدعم عبر واتساب" tint="success" />
        <Row name="message"  label="الأسئلة الشائعة" />
        <Row name="gear"     label="عن التطبيق" detail="نسخة 1.2.0" />
      </Section>

      <div style={{ padding: '8px 16px 16px' }}>
        <button className="tap" onClick={() => onLogout && onLogout()} style={{
          width: '100%', height: 50, borderRadius: 14,
          background: 'transparent', color: 'var(--danger)',
          border: '1.5px solid color-mix(in oklch, var(--danger) 28%, transparent)',
          fontFamily: 'inherit', fontWeight: 700, fontSize: 15,
          cursor: 'pointer',
        }}>تسجيل الخروج</button>
      </div>
    </div>
  );
}

function Section({ children }) {
  return (
    <div style={{
      margin: '0 16px 12px',
      background: 'var(--surface)',
      borderRadius: 18,
      border: '1px solid var(--line)',
      overflow: 'hidden',
    }}>{children}</div>
  );
}

function Row({ name, label, detail, warning, tint }) {
  const tintMap = {
    success: { bg: 'color-mix(in oklch, var(--success) 12%, transparent)', fg: 'var(--success)' },
    danger:  { bg: 'color-mix(in oklch, var(--danger) 12%, transparent)', fg: 'var(--danger)' },
  };
  const t = tint ? tintMap[tint] : null;
  return (
    <div className="tap" style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 14px',
      borderBottom: '1px solid var(--line)',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10,
        background: t?.bg || 'var(--surface-2)',
        color: t?.fg || 'var(--text-2)',
        display: 'grid', placeItems: 'center', flexShrink: 0,
      }}>
        <Icon name={name} size={20} color={t?.fg || 'var(--text-2)'} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)' }}>{label}</div>
        {detail && <div style={{ fontSize: 12, color: warning ? 'var(--accent-700)' : 'var(--text-2)', marginTop: 2 }}>{detail}</div>}
      </div>
      <Icon name="chev-left" size={18} color="var(--text-3)" />
    </div>
  );
}

Object.assign(window, {
  OrdersScreen, EarningsScreen, WalletScreen, ProfileScreen,
});
