// ResDri driver app — screens.
// All order data is live from the backend (/orders/pool). There is no seeded
// demo array — an empty pool renders the real "empty" state.

const VERTICAL_LABEL_AR = { food: 'طعام', parcel: 'طرد', grocery: 'بقالة' };

// ────────────────────────────────────────────────────────────
// Home — three states (online | offline | empty). Designed for
// "what should I take now?" — minimal top chrome, sheet defaults
// high enough to show 3+ orders, sort/filter chips, top-pick
// highlight, inline accept.
// ────────────────────────────────────────────────────────────
function HomeScreen({
  online, setOnline, homeState, openOrder, acceptOrder, today,
  tabBarHeight = 72, setHomeState, radiusKm = 1.5, setRadiusKm,
  orders, driverLatLng, driverName, config,
}) {
  // Radius slider bounds — server-driven (admin Settings). No hardcoded range.
  const RADIUS_MIN  = (config && config.radiusMinKm)  || 0.5;
  const RADIUS_MAX  = (config && config.maxRadiusKm)  || 5;
  const RADIUS_STEP = (config && config.radiusStepKm) || 0.5;

  // Live API orders only — no demo fallback. Empty → the "empty" home state.
  const pool = Array.isArray(orders) ? orders : [];
  // Helper: where to place this order's pin on the static map source pixels.
  //   - prefer the live order's projected mapPos (from real lat/lng)
  //   - else the design's hand-placed PIN_COORDS by id
  //   - else fall back to the city centre
  const pinFor = (o) => o.mapPos || PIN_COORDS[o.id] || PIN_COORDS.CENTER;

  // Lower collapsed default so more map is visible behind the sheet
  const [sheet, setSheet] = React.useState(0.50);
  const [sort, setSort]   = React.useState('best'); // best | nearest | highest
  const [filter, setFilter] = React.useState('all'); // all | food | parcel | grocery

  const coversTabBar = sheet > 0.7;
  const isExpanded   = sheet > 0.7;

  const showPool    = homeState === 'online' && online;
  const showEmpty   = homeState === 'empty'  && online;
  const showOffline = !online || homeState === 'offline';

  const mapMode = showOffline || showEmpty ? 'driver-only' : 'pool';
  const mapDim  = showOffline;

  // Sorted/filtered orders — also gate by radius (using toPickup distance)
  const filtered = React.useMemo(() => {
    let list = pool.filter(o => filter === 'all' ? true : o.kind === filter);
    list = list.filter(o => (o.toPickup ?? o.distance) <= radiusKm);
    const score = (o) => (o.payout + (o.bonus || 0)) / Math.max(0.5, o.distance);
    if (sort === 'nearest') list = [...list].sort((a, b) => (a.toPickup ?? a.distance) - (b.toPickup ?? b.distance));
    else if (sort === 'highest') list = [...list].sort((a, b) => (b.payout + b.bonus) - (a.payout + a.bonus));
    else list = [...list].sort((a, b) => score(b) - score(a));
    return list;
  }, [pool, sort, filter, radiusKm]);

  // Out-of-radius orders — shown as edge indicators on the map
  const outOfRadius = React.useMemo(() => {
    const cutoff = filter === 'all' ? pool : pool.filter(o => o.kind === filter);
    return cutoff
      .filter(o => (o.toPickup ?? o.distance) > radiusKm)
      .map(o => ({
        id: o.id,
        kind: o.kind,
        payout: o.payout,
        bonus: o.bonus || 0,
        distanceKm: o.toPickup ?? o.distance,
        pos: pinFor(o),
      }));
  }, [pool, filter, radiusKm]);

  const topPickId = filtered[0]?.id;

  // Visible map area (above the bottom sheet)
  const sheetTopPx = (1 - sheet) * 874;
  const visibleArea = {
    top: 110,
    left: 0,
    right: 402,
    bottom: Math.max(140, sheetTopPx - 8),
  };

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', background: 'var(--bg)' }}>
      {/* MAP — fills behind */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
        <MapView mode={mapMode} dim={mapDim} visibleArea={visibleArea}
          driverLatLng={driverLatLng}
          onPickPin={(id) => openOrder(id)}
          radiusKm={radiusKm}
          orders={filtered.map(o => ({
            id: o.id, kind: o.kind, payout: o.payout, bonus: o.bonus || 0,
            pos: pinFor(o),
          }))}
          outOfRadiusOrders={outOfRadius}
        />
      </div>

      {/* SLIM TOP — avatar + earnings pill + bell, all in one row */}
      <SlimTopBar online={online} today={today} orders={filtered.length} driverName={driverName} />

      {/* RADIUS ADJUSTER — floating, top-right under the bell, only when online */}
      {showPool && (
        <div style={{
          position: 'absolute', top: 110, insetInlineEnd: 12, zIndex: 22,
          background: 'var(--surface)',
          border: '1px solid var(--line)',
          borderRadius: 14,
          boxShadow: '0 4px 14px rgba(15,23,42,0.10)',
          padding: 4,
          display: 'flex', alignItems: 'center', gap: 2,
          fontFamily: 'inherit',
        }}>
          <button className="tap" onClick={() => setRadiusKm && setRadiusKm(Math.max(RADIUS_MIN, +(radiusKm - RADIUS_STEP).toFixed(1)))} style={{
            width: 32, height: 32, borderRadius: 10,
            background: 'transparent', border: 'none',
            color: 'var(--text-2)', fontFamily: 'inherit', fontWeight: 800, fontSize: 18,
            display: 'grid', placeItems: 'center', cursor: 'pointer',
          }}>−</button>
          <div style={{
            padding: '0 4px',
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            lineHeight: 1,
          }}>
            <span className="num" style={{ fontSize: 14, fontWeight: 900, color: 'var(--primary)' }}>
              {radiusKm.toFixed(1).replace(/\.0$/, '')}
            </span>
            <span style={{ fontSize: 9, fontWeight: 700, color: 'var(--text-2)', marginTop: 1, letterSpacing: '0.04em' }}>
              كم
            </span>
          </div>
          <button className="tap" onClick={() => setRadiusKm && setRadiusKm(Math.min(RADIUS_MAX, +(radiusKm + RADIUS_STEP).toFixed(1)))} style={{
            width: 32, height: 32, borderRadius: 10,
            background: 'transparent', border: 'none',
            color: 'var(--text-2)', fontFamily: 'inherit', fontWeight: 800, fontSize: 18,
            display: 'grid', placeItems: 'center', cursor: 'pointer',
          }}>+</button>
        </div>
      )}

      {/* BOTTOM SHEET */}
      <div style={{
        position: 'absolute', left: 0, right: 0,
        bottom: coversTabBar ? 0 : tabBarHeight,
        height: `calc(${Math.round(sheet * 100)}% - ${coversTabBar ? 0 : tabBarHeight}px)`,
        background: 'var(--surface)',
        borderTopLeftRadius: 26, borderTopRightRadius: 26,
        boxShadow: '0 -10px 30px rgba(15,23,42,0.18), 0 -1px 0 var(--line)',
        transition: 'height 0.32s cubic-bezier(.32,.72,.16,1), bottom 0.32s cubic-bezier(.32,.72,.16,1)',
        display: 'flex', flexDirection: 'column',
        zIndex: 18,
      }}>
        {/* Drag handle — clear up/down affordance */}
        <button className="tap" onClick={() => setSheet(isExpanded ? 0.42 : 0.82)}
             style={{
               padding: '10px 16px 6px', display: 'flex', flexDirection: 'column',
               alignItems: 'center', gap: 4, flexShrink: 0,
               background: 'transparent', border: 'none', width: '100%',
               fontFamily: 'inherit', cursor: 'pointer',
             }}>
          {/* The bar */}
          <div style={{
            width: 44, height: 5, borderRadius: 999,
            background: 'var(--line-strong)',
          }} />
          {/* Direction indicator */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 5,
            fontSize: 11, fontWeight: 700, color: 'var(--text-2)',
            letterSpacing: '-0.01em',
          }}>
            <Icon name={isExpanded ? 'chev-down' : 'chev-up'} size={14} color="var(--text-2)" />
            <span>{isExpanded ? 'اسحب لتصغير' : 'اسحب لعرض الكل'}</span>
            <Icon name={isExpanded ? 'chev-down' : 'chev-up'} size={14} color="var(--text-2)" />
          </div>
        </button>

        {/* STICKY ONLINE LEVER */}
        <div style={{ padding: '8px 14px 6px', flexShrink: 0 }}>
          <OnlineLever online={online} onToggle={() => {
            const next = !online;
            setOnline(next);
            if (setHomeState) setHomeState(next ? 'online' : 'offline');
          }} />
        </div>

        {/* Content varies by state */}
        {showOffline && <OfflineHomeContent today={today} />}
        {showEmpty   && <EmptyHomeContent />}
        {showPool    && (
          <PoolHomeContent
            orders={filtered}
            topPickId={topPickId}
            sort={sort} setSort={setSort}
            filter={filter} setFilter={setFilter}
            openOrder={openOrder} acceptOrder={acceptOrder}
            isExpanded={isExpanded}
            onToggleExpand={() => setSheet(isExpanded ? 0.42 : 0.82)}
          />
        )}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// SlimTopBar — compact single-row top chrome
// Layout (RTL): [avatar+greeting] [earnings pill]            [bell]
// ────────────────────────────────────────────────────────────
function SlimTopBar({ online, today, orders, driverName }) {
  const initial = (driverName || 'م').trim().charAt(0) || 'م';
  return (
    <div style={{
      position: 'absolute', top: 0, left: 0, right: 0, zIndex: 22,
      padding: '54px 12px 8px',
      display: 'flex', alignItems: 'center', gap: 8,
      pointerEvents: 'none',
    }}>
      {/* Avatar with online dot */}
      <div className="tap" style={{
        width: 40, height: 40, borderRadius: 999,
        background: 'var(--primary)', color: '#fff',
        display: 'grid', placeItems: 'center',
        fontWeight: 800, fontSize: 16,
        border: '2px solid var(--surface)',
        boxShadow: '0 4px 12px rgba(15,23,42,0.10)',
        position: 'relative',
        pointerEvents: 'auto', flexShrink: 0,
      }}>
        {initial}
        <span style={{
          position: 'absolute', bottom: -2, left: -2,
          width: 12, height: 12, borderRadius: 999,
          background: online ? 'var(--success)' : 'var(--text-3)',
          border: '2px solid var(--surface)',
        }} />
      </div>

      {/* Earnings pill — tappable, expands to Earnings tab */}
      <button className="tap" style={{
        flex: 1, minWidth: 0, height: 40, borderRadius: 999,
        background: 'var(--surface)',
        border: '1px solid var(--line)',
        boxShadow: '0 4px 12px rgba(15,23,42,0.08)',
        padding: '0 14px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontFamily: 'inherit', cursor: 'pointer',
        pointerEvents: 'auto',
      }}>
        <span style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-2)' }}>اليوم</span>
          <BigNumber value={today} size="sm" weight={800} />
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--text-2)', fontSize: 12 }}>
          <span className="num" style={{ fontWeight: 800, color: 'var(--text)' }}>{orders}</span>
          <span>طلب</span>
          <Icon name="chev-left" size={14} color="var(--text-3)" />
        </span>
      </button>

      {/* Bell */}
      <button className="tap" style={{
        width: 40, height: 40, borderRadius: 999,
        background: 'var(--surface)', color: 'var(--text)',
        border: '1px solid var(--line)',
        display: 'grid', placeItems: 'center',
        boxShadow: '0 4px 12px rgba(15,23,42,0.08)',
        pointerEvents: 'auto', position: 'relative', flexShrink: 0,
      }}>
        <Icon name="bell" size={18} color="var(--text)" />
        {online && (
          <span style={{
            position: 'absolute', top: 6, left: 6,
            width: 8, height: 8, borderRadius: 999,
            background: 'var(--danger)',
            border: '2px solid var(--surface)',
          }} />
        )}
      </button>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// PoolHomeContent — list with sort/filter chips + featured top pick
// ────────────────────────────────────────────────────────────
function PoolHomeContent({ orders, topPickId, sort, setSort, filter, setFilter, openOrder, acceptOrder, isExpanded, onToggleExpand }) {
  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' },
  ];

  return (
    <>
      {/* Sort + filter row */}
      <div style={{
        padding: '4px 14px 8px',
        display: 'flex', flexDirection: 'column', gap: 8,
        flexShrink: 0,
      }}>
        {/* Sort segmented */}
        <div style={{
          background: 'var(--surface-2)',
          borderRadius: 12,
          padding: 3,
          display: 'flex',
          flexShrink: 0,
        }}>
          {sortOpts.map(o => (
            <button key={o.id} className="tap" onClick={() => setSort(o.id)} style={{
              flex: 1, height: 32, 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: 12,
              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: 32, padding: '0 12px', 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: 12,
                display: 'inline-flex', alignItems: 'center', gap: 5,
                whiteSpace: 'nowrap', flexShrink: 0,
              }}>
                {o.icon && <Icon name={o.icon} size={13} color={active ? '#fff' : 'var(--text-2)'} />}
                <span>{o.lbl}</span>
              </button>
            );
          })}
          <div style={{ flex: 1 }} />
        </div>
      </div>

      {/* Pool list */}
      <div className="screen-scroll" style={{
        flex: 1, overflowY: 'auto',
        padding: '6px 14px 24px',
        display: 'flex', flexDirection: 'column', gap: 12,
      }}>
        {orders.length === 0 ? (
          <div style={{
            padding: '40px 16px', textAlign: 'center',
            color: 'var(--text-2)',
          }}>
            <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>لا طلبات بهذا التصنيف</div>
            <div style={{ fontSize: 12 }}>جرّب تصنيفاً آخر</div>
          </div>
        ) : orders.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>
    </>
  );
}

function OfflineHomeContent({ today }) {
  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column',
      padding: '14px 18px 24px',
    }}>
      <div style={{
        background: 'var(--surface-2)',
        border: '1px solid var(--line)',
        borderRadius: 16, padding: 14,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: 'var(--bg)',
          border: '1px solid var(--line)',
          display: 'grid', placeItems: 'center',
          flexShrink: 0,
        }}>
          <Icon name="walk" size={22} color="var(--text-2)" />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>
            أنت غير متّصل حالياً
          </div>
          <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2, lineHeight: 1.5 }}>
            لن تتلقى أي طلبات. اضغط الزر أعلاه عندما تكون جاهزاً للعمل.
          </div>
        </div>
      </div>

      {/* Pre-check list */}
      <div style={{
        marginTop: 14,
        background: 'color-mix(in oklch, var(--primary) 6%, var(--surface))',
        border: '1px dashed color-mix(in oklch, var(--primary) 28%, transparent)',
        borderRadius: 16,
        padding: 14,
      }}>
        <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>
          قبل أن تتّصل
        </div>
        <CheckRow ok label="موقعك مفعّل (GPS)" />
        <CheckRow ok label="الإشعارات مسموح بها" />
        <CheckRow ok label="النقد بحوزتك تحت الحد" detail="₪48 / ₪500" />
      </div>
    </div>
  );
}

function CheckRow({ ok, label, detail }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '6px 0',
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 999,
        background: ok ? 'var(--success)' : 'var(--surface-2)',
        color: '#fff',
        display: 'grid', placeItems: 'center',
        flexShrink: 0,
      }}>
        <Icon name="check" size={14} strokeWidth={3} color="#fff" />
      </div>
      <span style={{ flex: 1, fontSize: 14, color: 'var(--text)', fontWeight: 600 }}>{label}</span>
      {detail && <span className="num" style={{ fontSize: 13, color: 'var(--text-2)', fontWeight: 700 }}>{detail}</span>}
    </div>
  );
}

function EmptyHomeContent() {
  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      padding: '18px 22px 36px',
      textAlign: 'center',
    }}>
      {/* Friendly "listening" illustration — concentric radar circles + icon */}
      <div style={{
        position: 'relative', width: 130, height: 130,
        display: 'grid', placeItems: 'center',
        marginBottom: 18,
      }}>
        {[0, 0.6, 1.2].map(d => (
          <div key={d} style={{
            position: 'absolute', inset: 0, borderRadius: '50%',
            border: '2px solid var(--primary)',
            opacity: 0.25,
            animation: `radar-soft 2.4s ease-out ${d}s infinite`,
          }} />
        ))}
        <div style={{
          width: 60, height: 60, borderRadius: 999,
          background: 'color-mix(in oklch, var(--primary) 12%, var(--surface))',
          border: '2px solid color-mix(in oklch, var(--primary) 30%, transparent)',
          color: 'var(--primary)',
          display: 'grid', placeItems: 'center',
        }}>
          <Icon name="volume" size={28} color="var(--primary)" />
        </div>
      </div>
      <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)', marginBottom: 6 }}>
        لا توجد طلبات في الوقت الحالي
      </div>
      <div style={{ fontSize: 13, color: 'var(--text-2)', maxWidth: 280, lineHeight: 1.55 }}>
        سنخبرك فور توفّر طلب في منطقتك. لا تحتاج إلى إبقاء الشاشة مفتوحة.
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Incoming order alert — HERO screen. Calm dispatch-radio chirp.
//   - Two RTL placements via prop `primarySide` ('right' = leading, 'left' = trailing)
//   - 15-second countdown ring
//   - Soft radar pulse animation
// ────────────────────────────────────────────────────────────
function IncomingAlert({ order, onAccept, onSkip, primarySide = 'right' }) {
  const [t, setT] = React.useState(15);
  React.useEffect(() => {
    if (t <= 0) { onSkip(); return; }
    const id = setTimeout(() => setT(t - 1), 1000);
    return () => clearTimeout(id);
  }, [t]);

  const verticalC = { food: '#E11D48', parcel: '#2563EB', grocery: '#16A34A' }[order.kind];
  const ringP = (15 - t) / 15;

  const acceptBtn = (
    <button className="tap" onClick={onAccept} style={{
      flex: 1, height: 76, borderRadius: 22,
      background: 'var(--success)', color: '#fff',
      fontFamily: 'inherit', fontSize: 22, fontWeight: 800,
      border: 'none',
      boxShadow: '0 10px 28px rgba(22,163,74,0.45)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
    }}>
      <Icon name="check" size={28} strokeWidth={3} />
      <span>قبول</span>
    </button>
  );
  const skipBtn = (
    <button className="tap" onClick={onSkip} style={{
      width: 76, height: 76, borderRadius: 22,
      background: 'rgba(255,255,255,0.08)',
      color: '#fff', border: '1.5px solid rgba(255,255,255,0.18)',
      fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
      display: 'grid', placeItems: 'center', gap: 2,
    }}>
      <Icon name="close" size={26} strokeWidth={2.5} />
    </button>
  );

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'radial-gradient(ellipse at top, #102135 0%, #07111E 60%, #050912 100%)',
      color: '#fff', zIndex: 100,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* Subtle vertical-stripe texture for "workhorse" feel */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'repeating-linear-gradient(90deg, rgba(255,255,255,0.012) 0 1px, transparent 1px 22px)',
        pointerEvents: 'none',
      }} />

      {/* Top banner: dispatch label + sound icon */}
      <div style={{
        position: 'relative',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '58px 22px 0',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            width: 8, height: 8, borderRadius: 999, background: '#22D3EE',
            boxShadow: '0 0 0 0 rgba(34,211,238,0.6)',
            animation: 'radar-soft 1.6s ease-out infinite',
            position: 'relative', color: '#22D3EE',
          }} className="pulse-ring" />
          <span style={{
            fontSize: 12, fontWeight: 800, color: '#9CC9D9',
            letterSpacing: '0.16em', textTransform: 'uppercase',
          }}>
            <span dir="rtl">طلب وارد</span> · DISPATCH
          </span>
        </div>
        <Icon name="volume" size={20} color="#9CC9D9" />
      </div>

      {/* Center: vertical chip + huge payout + countdown ring */}
      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        padding: '0 24px', position: 'relative',
      }}>
        {/* Vertical badge + label */}
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 10, marginBottom: 18,
          background: 'rgba(255,255,255,0.06)',
          border: '1px solid rgba(255,255,255,0.10)',
          padding: '6px 14px 6px 8px',
          borderRadius: 999,
          whiteSpace: 'nowrap',
          maxWidth: '90%',
        }}>
          <span style={{
            width: 28, height: 28, borderRadius: 999,
            background: verticalC, display: 'grid', placeItems: 'center',
          }}>
            <Icon name={{ food: 'food', parcel: 'package', grocery: 'cart' }[order.kind]} size={16} color="#fff" />
          </span>
          <span style={{ fontSize: 14, fontWeight: 700, color: '#fff' }}>
            {VERTICAL_LABEL_AR[order.kind]} · {order.business}
          </span>
        </div>

        {/* Payout — HUGE, with countdown ring around it */}
        <div style={{ position: 'relative', display: 'grid', placeItems: 'center' }}>
          {/* Soft radar pulse (only first few seconds) */}
          {t > 11 && (
            <div style={{
              position: 'absolute', width: 260, height: 260, borderRadius: '50%',
              border: '2px solid rgba(34,211,238,0.28)',
              animation: 'radar-soft 2.0s ease-out infinite',
            }} />
          )}
          {/* Countdown ring */}
          <svg width="280" height="280" style={{ position: 'absolute' }}>
            <circle cx="140" cy="140" r="124" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="6" />
            <circle cx="140" cy="140" r="124" fill="none"
              stroke="#22D3EE" strokeWidth="6" strokeLinecap="round"
              strokeDasharray={2 * Math.PI * 124}
              strokeDashoffset={2 * Math.PI * 124 * ringP}
              transform="rotate(-90 140 140)"
              style={{ transition: 'stroke-dashoffset 0.95s linear' }}
            />
          </svg>
          <div style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            position: 'relative',
          }}>
            <span style={{
              fontSize: 11, fontWeight: 800, color: '#9CC9D9',
              letterSpacing: '0.14em', textTransform: 'uppercase',
            }}>أرباحك</span>
            <BigNumber value={order.payout + order.bonus} size="xl" weight={900} color="#fff" />
            {order.bonus > 0 && (
              <span style={{
                fontSize: 14, fontWeight: 800,
                color: '#1A1300',
                background: 'var(--accent)',
                padding: '4px 14px', borderRadius: 999,
                marginTop: 4,
                display: 'inline-flex', gap: 4, alignItems: 'center',
                whiteSpace: 'nowrap',
              }}>
                <span className="num">+₪{order.bonus}</span>
                <span>مكافأة</span>
              </span>
            )}
            <div style={{
              marginTop: 14, color: '#22D3EE', fontSize: 13, fontWeight: 800,
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <Icon name="clock" size={14} />
              <span className="num">{t}</span><span>ثانية</span>
            </div>
          </div>
        </div>

        {/* Route summary */}
        <div style={{
          marginTop: 28, width: '100%', maxWidth: 360,
          background: 'rgba(255,255,255,0.05)',
          border: '1px solid rgba(255,255,255,0.10)',
          borderRadius: 18,
          padding: 14,
          display: 'flex', flexDirection: 'column', gap: 10,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 8, height: 8, borderRadius: 2, background: '#22D3EE' }} />
            <div style={{ flex: 1, fontSize: 14, fontWeight: 700, color: '#fff' }}>{order.pickup}</div>
          </div>
          <div style={{ height: 1, background: 'rgba(255,255,255,0.08)', marginInlineStart: 14 }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 8, height: 8, borderRadius: 999, background: '#F87171' }} />
            <div style={{ flex: 1, fontSize: 14, fontWeight: 700, color: '#fff' }}>{order.dropoff}</div>
          </div>
          <div style={{
            display: 'flex', justifyContent: 'space-between',
            paddingTop: 6, marginTop: 2,
            borderTop: '1px dashed rgba(255,255,255,0.12)',
            fontSize: 12, color: '#9CC9D9',
            gap: 6,
          }}>
            <span><span className="num">{order.distance.toFixed(1)}</span> كم</span>
            <span>~<span className="num">{order.eta}</span> دقيقة</span>
            <span>طلب <span className="num">#{order.shortId}</span></span>
          </div>
        </div>
      </div>

      {/* Bottom: Accept + Skip — primary on configurable side */}
      <div style={{
        padding: '14px 22px 38px',
        display: 'flex', flexDirection: primarySide === 'right' ? 'row-reverse' : 'row',
        gap: 12,
      }}>
        {acceptBtn}
        {skipBtn}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Order Detail (pre-accept) — full route on map + giant Accept
// ────────────────────────────────────────────────────────────
function OrderDetail({ order, onAccept, onBack, onSkip }) {
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: '52%' }}>
        <MapView mode="route" scale={0.62} offsetX={-200} offsetY={-150} />
      </div>

      {/* Back chip */}
      <div className="tap" onClick={onBack} style={{
        position: 'absolute', top: 56, insetInlineStart: 14, zIndex: 30,
        width: 44, height: 44, borderRadius: 999,
        background: 'var(--surface)', color: 'var(--text)',
        display: 'grid', placeItems: 'center',
        boxShadow: '0 4px 14px rgba(0,0,0,0.12)',
        border: '1px solid var(--line)',
      }}>
        <Icon name="chev-right" size={22} />
      </div>

      {/* Distance/eta floating chip */}
      <div style={{
        position: 'absolute', top: 56, insetInlineEnd: 14, zIndex: 30,
        background: 'var(--surface)',
        boxShadow: '0 4px 14px rgba(0,0,0,0.12)',
        border: '1px solid var(--line)',
        borderRadius: 14,
        padding: '8px 12px',
        display: 'flex', flexDirection: 'column', alignItems: 'flex-end',
      }}>
        <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-2)' }}>المسافة الكلية</span>
        <span className="num" style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)' }}>
          {order.distance.toFixed(1)} كم
        </span>
      </div>

      {/* Bottom sheet — details */}
      <div className="screen-scroll" style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: '58%',
        background: 'var(--surface)',
        borderTopLeftRadius: 28, borderTopRightRadius: 28,
        boxShadow: '0 -8px 30px rgba(15,23,42,0.18)',
        overflowY: 'auto',
        zIndex: 20,
        paddingBottom: 120,
      }}>
        {/* Handle */}
        <div style={{
          width: 44, height: 5, borderRadius: 999,
          background: 'var(--line-strong)', margin: '10px auto 8px',
        }} />

        {/* Vertical + business + payout */}
        <div style={{ padding: '8px 18px 14px', display: 'flex', alignItems: 'center', gap: 12 }}>
          <VerticalChip kind={order.kind} size={48} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--text)' }}>{order.business}</div>
            <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>
              {VERTICAL_LABEL_AR[order.kind]} · للزبون {order.customer}
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
            <BigNumber value={order.payout + order.bonus} size="md" weight={900} />
            {order.bonus > 0 && (
              <span className="num" style={{
                fontSize: 11, fontWeight: 800, color: 'var(--accent-700)',
                background: 'color-mix(in oklch, var(--accent) 22%, transparent)',
                padding: '2px 7px', borderRadius: 4, marginTop: 3,
              }}>{'+₪' + order.bonus} مكافأة</span>
            )}
          </div>
        </div>

        {/* Route */}
        <div style={{ padding: '0 18px 14px' }}>
          <div style={{ display: 'flex', alignItems: 'stretch', gap: 12 }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 6 }}>
              <div style={{ width: 12, height: 12, borderRadius: 3, background: 'var(--primary)' }} />
              <div style={{ width: 2, height: 36, background: 'var(--line)' }} />
              <div style={{ width: 12, height: 12, borderRadius: 999, background: 'var(--danger)' }} />
            </div>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>الاستلام</div>
                <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginTop: 2 }}>{order.pickup}</div>
              </div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>التسليم</div>
                <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginTop: 2 }}>{order.dropoff}</div>
              </div>
            </div>
          </div>
        </div>

        {/* Payout breakdown */}
        <div style={{
          margin: '0 16px 14px',
          background: 'var(--surface-2)',
          borderRadius: 16,
          padding: 14,
          border: '1px solid var(--line)',
        }}>
          <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>
            تفصيل الأرباح
          </div>
          <MoneyRow label="عمولة التوصيل" value={order.payout} />
          {order.bonus > 0 && <MoneyRow label="مكافأة الشريك" value={'+' + order.bonus} accent />}
          <div style={{ height: 1, background: 'var(--line)', margin: '8px 0' }} />
          <MoneyRow label="الإجمالي لك" value={order.payout + order.bonus} bold />
          {order.cash > 0 && (
            <>
              <div style={{ height: 8 }} />
              <div style={{
                background: 'color-mix(in oklch, var(--accent) 14%, transparent)',
                border: '1px dashed color-mix(in oklch, var(--accent) 32%, transparent)',
                borderRadius: 10, padding: '8px 10px',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              }}>
                <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--accent-700)' }}>اقبض نقداً من الزبون</span>
                <BigNumber value={order.cash} size="sm" color="var(--accent-700)" />
              </div>
            </>
          )}
        </div>

        {/* Notes */}
        {order.notes && (
          <div style={{ margin: '0 18px 14px' }}>
            <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6 }}>ملاحظة من المرسل</div>
            <div style={{
              background: 'var(--surface-2)',
              borderRadius: 14, padding: 12,
              border: '1px solid var(--line)',
              fontSize: 14, color: 'var(--text)', lineHeight: 1.45,
            }}>"{order.notes}"</div>
          </div>
        )}

        {/* Compatibility */}
        <div style={{ margin: '0 18px 14px', display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon name="check-circle" size={18} color="var(--success)" />
          <span style={{ fontSize: 13, color: 'var(--text-2)' }}>متوافق مع مركبتك (سيارة)</span>
        </div>
      </div>

      {/* Bottom action bar — pinned */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: 'var(--surface)',
        padding: '14px 18px 30px',
        boxShadow: '0 -2px 20px rgba(15,23,42,0.10)',
        zIndex: 30,
        display: 'flex', gap: 10,
      }}>
        <PrimaryButton tone="ghost" size="lg" fullWidth={false} onClick={onSkip}>تخطي</PrimaryButton>
        <div style={{ flex: 1 }}>
          <PrimaryButton tone="success" size="lg" leadingIcon="check" onClick={onAccept}>قبول الطلب</PrimaryButton>
        </div>
      </div>
    </div>
  );
}

function MoneyRow({ label, value, bold, accent }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 0' }}>
      <span style={{ fontSize: 14, color: bold ? 'var(--text)' : 'var(--text-2)', fontWeight: bold ? 700 : 500 }}>{label}</span>
      <span className="num" style={{
        fontSize: bold ? 18 : 14, fontWeight: bold ? 800 : 700,
        color: accent ? 'var(--accent-700)' : 'var(--text)',
      }}>{value} ₪</span>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Active order — heading to pickup
// ────────────────────────────────────────────────────────────
function ToPickup({ order, onArrived, onBack }) {
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0 }}>
        <MapView mode="route" driverPos="route-pickup" scale={0.7} offsetX={-260} offsetY={-180} />
      </div>

      {/* Top card: pickup info */}
      <div style={{
        position: 'absolute', top: 56, left: 12, right: 12, zIndex: 30,
        background: 'var(--surface)',
        borderRadius: 18,
        border: '1px solid var(--line)',
        boxShadow: '0 8px 22px rgba(15,23,42,0.14)',
        padding: 14,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: 'var(--primary)', color: '#fff',
          display: 'grid', placeItems: 'center',
        }}>
          <Icon name="shop" size={22} color="#fff" />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>الاستلام من</div>
          <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--text)' }}>{order.business}</div>
          <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 1 }}>{order.pickup}</div>
        </div>
        <div className="tap" style={{ width: 40, height: 40, borderRadius: 999, background: 'var(--primary-100)', color: 'var(--primary)', display: 'grid', placeItems: 'center' }}>
          <Icon name="phone" size={20} color="var(--primary)" />
        </div>
      </div>

      {/* ETA banner */}
      <div style={{
        position: 'absolute', top: 158, insetInlineEnd: 14, zIndex: 30,
        background: 'var(--primary)', color: '#fff',
        borderRadius: 14, padding: '8px 14px',
        boxShadow: '0 8px 22px color-mix(in oklch, var(--primary) 30%, transparent)',
        whiteSpace: 'nowrap',
      }}>
        <div style={{ fontSize: 10, fontWeight: 800, opacity: 0.85, letterSpacing: '0.1em' }}>الوصول خلال</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span className="num" style={{ fontSize: 22, fontWeight: 900 }}>4</span>
          <span style={{ fontSize: 14, fontWeight: 700 }}>دقائق</span>
        </div>
      </div>

      {/* Bottom action sheet */}
      <ActionSheet>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>الخطوة ١ من ٢</div>
            <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)' }}>توجّه إلى نقطة الاستلام</div>
          </div>
          <span className="num" style={{ fontSize: 14, fontWeight: 800, color: 'var(--text-2)' }}>
            {order.distance.toFixed(1)} كم
          </span>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="tap" style={{
            height: 52, padding: '0 14px', borderRadius: 14,
            background: 'var(--surface-2)', color: 'var(--text)',
            border: '1px solid var(--line)',
            fontFamily: 'inherit', fontWeight: 700, fontSize: 14,
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <Icon name="nav" size={18} color="var(--primary)" />
            فتح في خرائط جوجل
          </button>
          <div style={{ flex: 1 }}>
            <PrimaryButton tone="primary" size="md" leadingIcon="check" onClick={onArrived}>
              وصلت إلى المتجر
            </PrimaryButton>
          </div>
        </div>
      </ActionSheet>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// At pickup — confirm handover, optional photo
// ────────────────────────────────────────────────────────────
function AtPickup({ order, onPicked }) {
  const [photo, setPhoto] = React.useState(false);
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0 }}>
        <MapView mode="route" scale={0.7} offsetX={-280} offsetY={-200} />
      </div>

      <div style={{
        position: 'absolute', top: 56, left: 12, right: 12, zIndex: 30,
        background: 'var(--surface)', borderRadius: 18, border: '1px solid var(--line)',
        boxShadow: '0 8px 22px rgba(15,23,42,0.14)',
        padding: 14, display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <StatusPill tone="success">وصلت إلى الاستلام</StatusPill>
        <div style={{ flex: 1, fontSize: 14, fontWeight: 700, color: 'var(--text)', textAlign: 'end' }}>
          {order.business}
        </div>
      </div>

      <ActionSheet>
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>تأكيد الاستلام</div>
          <div style={{ fontSize: 19, fontWeight: 800, color: 'var(--text)', marginTop: 4 }}>هل استلمت الطلب من المتجر؟</div>
        </div>

        {/* Photo affordance */}
        <div className="tap" onClick={() => setPhoto(!photo)} style={{
          height: 92, borderRadius: 14,
          background: photo ? 'color-mix(in oklch, var(--success) 14%, transparent)' : 'var(--surface-2)',
          border: photo ? '1.5px solid color-mix(in oklch, var(--success) 32%, transparent)' : '1.5px dashed var(--line-strong)',
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '0 16px', marginBottom: 14,
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: 12,
            background: photo ? 'var(--success)' : 'var(--surface)',
            color: photo ? '#fff' : 'var(--text-2)',
            display: 'grid', placeItems: 'center',
            border: photo ? 'none' : '1px solid var(--line)',
          }}>
            <Icon name={photo ? 'check' : 'camera'} size={24} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 800, color: 'var(--text)' }}>
              {photo ? 'تم التقاط صورة الإيصال' : 'صورة الإيصال (اختياري)'}
            </div>
            <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>
              {photo ? 'اضغط لإعادة التقاط' : 'يساعد في حل النزاعات لاحقاً'}
            </div>
          </div>
        </div>

        <PrimaryButton tone="success" size="lg" leadingIcon="check" onClick={onPicked}>
          تأكيد الاستلام والمتابعة
        </PrimaryButton>
      </ActionSheet>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Heading to dropoff
// ────────────────────────────────────────────────────────────
function ToDropoff({ order, onArrived }) {
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0 }}>
        <MapView mode="route" driverPos="route-dropoff" scale={0.7} offsetX={-280} offsetY={-220} />
      </div>

      <div style={{
        position: 'absolute', top: 56, left: 12, right: 12, zIndex: 30,
        background: 'var(--surface)', borderRadius: 18, border: '1px solid var(--line)',
        boxShadow: '0 8px 22px rgba(15,23,42,0.14)',
        padding: 14, display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: 'var(--danger)', color: '#fff',
          display: 'grid', placeItems: 'center',
        }}>
          <Icon name="pin" size={22} color="#fff" />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>الزبون</div>
          <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--text)' }}>{order.customer}</div>
          <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 1 }}>{order.dropoff}</div>
        </div>
        <div className="tap" style={{ width: 40, height: 40, borderRadius: 999, background: 'color-mix(in oklch, var(--whatsapp) 18%, transparent)', color: 'var(--whatsapp)', display: 'grid', placeItems: 'center' }}>
          <Icon name="whatsapp" size={20} color="var(--whatsapp)" />
        </div>
      </div>

      {/* ETA */}
      <div style={{
        position: 'absolute', top: 158, insetInlineEnd: 14, zIndex: 30,
        background: 'var(--danger)', color: '#fff',
        borderRadius: 14, padding: '8px 14px',
        boxShadow: '0 8px 22px rgba(220,38,38,0.30)',
        whiteSpace: 'nowrap',
      }}>
        <div style={{ fontSize: 10, fontWeight: 800, opacity: 0.85, letterSpacing: '0.1em' }}>الوصول خلال</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span className="num" style={{ fontSize: 22, fontWeight: 900 }}>6</span>
          <span style={{ fontSize: 14, fontWeight: 700 }}>دقائق</span>
        </div>
      </div>

      <ActionSheet>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>الخطوة ٢ من ٢</div>
            <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)' }}>توجّه إلى الزبون</div>
          </div>
          <span className="num" style={{ fontSize: 14, fontWeight: 800, color: 'var(--text-2)' }}>
            1.4 كم
          </span>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="tap" style={{
            height: 52, padding: '0 14px', borderRadius: 14,
            background: 'var(--surface-2)', color: 'var(--text)',
            border: '1px solid var(--line)',
            fontFamily: 'inherit', fontWeight: 700, fontSize: 14,
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <Icon name="nav" size={18} color="var(--primary)" />
            فتح في خرائط جوجل
          </button>
          <div style={{ flex: 1 }}>
            <PrimaryButton tone="primary" size="md" leadingIcon="check" onClick={onArrived}>
              وصلت إلى الزبون
            </PrimaryButton>
          </div>
        </div>
      </ActionSheet>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// CASH COLLECTION — hero. Customer is standing right there.
//   - Singular focus: the amount, large and unambiguous
//   - Slide-to-confirm (deliberate, not one-tap)
//   - Minimal competing UI
// ────────────────────────────────────────────────────────────
function CashCollection({ order, onCollected, onBack }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'linear-gradient(180deg, var(--surface) 0%, color-mix(in oklch, var(--accent) 6%, var(--bg)) 100%)',
      overflow: 'hidden', display: 'flex', flexDirection: 'column',
    }}>
      {/* Minimal header — just back + step */}
      <div style={{
        padding: '56px 18px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div className="tap" onClick={onBack} style={{
          width: 40, height: 40, borderRadius: 999,
          background: 'var(--surface)', border: '1px solid var(--line)',
          display: 'grid', placeItems: 'center',
          boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
        }}>
          <Icon name="chev-right" size={20} />
        </div>
        <span style={{
          fontSize: 11, fontWeight: 800, color: 'var(--text-2)',
          letterSpacing: '0.14em', textTransform: 'uppercase',
        }}>تحصيل نقدي</span>
        <div style={{ width: 40 }} />
      </div>

      {/* Customer banner */}
      <div style={{ padding: '24px 22px 0', textAlign: 'center' }}>
        <div style={{ fontSize: 14, color: 'var(--text-2)', marginBottom: 6 }}>اقبض من</div>
        <div style={{ fontSize: 28, fontWeight: 800, color: 'var(--text)' }}>{order.customer}</div>
        <div style={{ fontSize: 13, color: 'var(--text-3)', marginTop: 2 }}>طلب <span className="num">#{order.shortId}</span></div>
      </div>

      {/* The big number — visually dominant, calm */}
      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        padding: '0 22px',
      }}>
        {/* Soft halo behind the number */}
        <div style={{ position: 'relative', display: 'grid', placeItems: 'center' }}>
          <div style={{
            position: 'absolute', width: 320, height: 320, borderRadius: '50%',
            background: 'radial-gradient(circle, color-mix(in oklch, var(--accent) 16%, transparent) 0%, transparent 70%)',
            pointerEvents: 'none',
          }} />
          <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <BigNumber value={order.cash} size="xl" color="var(--accent-700)" weight={900} />
            <span style={{
              fontSize: 13, fontWeight: 700, color: 'var(--text-2)',
              marginTop: 14, letterSpacing: '0.04em',
            }}>المبلغ المطلوب نقداً (شامل الضريبة)</span>
          </div>
        </div>

        {/* Breakdown — quiet, secondary */}
        <div style={{
          marginTop: 36, width: '100%', maxWidth: 360,
          background: 'var(--surface)',
          borderRadius: 16,
          border: '1px solid var(--line)',
          padding: 14,
        }}>
          <MoneyRow label="قيمة الطلب" value={Math.round(order.cash * 0.85)} />
          <MoneyRow label="ضريبة القيمة المضافة ١٨٪" value={order.cash - Math.round(order.cash * 0.85)} />
          <div style={{ height: 1, background: 'var(--line)', margin: '6px 0' }} />
          <MoneyRow label="الإجمالي" value={order.cash} bold />
        </div>
      </div>

      {/* Slide-to-confirm — deliberate */}
      <div style={{ padding: '14px 22px 30px' }}>
        <SlideToConfirm
          label="اسحب لتأكيد استلام النقد"
          color="var(--success)"
          icon="check"
          onConfirm={onCollected}
        />
        <div style={{
          textAlign: 'center', fontSize: 11, color: 'var(--text-3)', marginTop: 10,
          fontWeight: 600,
        }}>
          عدّ المبلغ أمام الزبون قبل التأكيد. لا يمكن التراجع.
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Completed summary
// ────────────────────────────────────────────────────────────
function Completed({ order, onClose, totalToday }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'var(--bg)',
      display: 'flex', flexDirection: 'column',
      padding: '56px 18px 30px',
      overflow: 'auto',
    }}>
      {/* Check mark */}
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', marginTop: 8, marginBottom: 18,
      }}>
        <div style={{
          width: 86, height: 86, borderRadius: 999,
          background: 'var(--success)', color: '#fff',
          display: 'grid', placeItems: 'center',
          boxShadow: '0 10px 32px rgba(22,163,74,0.32)',
        }}>
          <Icon name="check" size={48} strokeWidth={3} color="#fff" />
        </div>
        <div style={{ fontSize: 24, fontWeight: 800, color: 'var(--text)', marginTop: 18, textAlign: 'center', whiteSpace: 'nowrap' }}>
          تم تسليم الطلب
        </div>
        <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 6, textAlign: 'center' }}>
          طلب <span className="num">#{order.shortId}</span> · للزبون {order.customer}
        </div>
      </div>

      {/* Earnings card */}
      <div style={{
        background: 'var(--surface)',
        borderRadius: 22,
        border: '1px solid var(--line)',
        padding: 18,
        boxShadow: '0 6px 22px rgba(15,23,42,0.08)',
      }}>
        <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
          ربحك من هذا الطلب
        </div>
        <div style={{ marginTop: 6, marginBottom: 14 }}>
          <BigNumber value={order.payout + order.bonus} size="lg" weight={900} accent />
        </div>

        <MoneyRow label="عمولة التوصيل" value={order.payout} />
        {order.bonus > 0 && <MoneyRow label="مكافأة الشريك" value={'+' + order.bonus} accent />}
        <div style={{ height: 1, background: 'var(--line)', margin: '10px 0' }} />
        <MoneyRow label="نقد بحوزتك الآن" value={order.cash} bold />
        <MoneyRow label="عمولة مستحقة للمنصة" value={order.cash - (order.payout + order.bonus)} bold />
      </div>

      {/* Quick stats */}
      <div style={{
        display: 'flex', gap: 10, marginTop: 14,
      }}>
        <Stat label="المسافة" value={order.distance.toFixed(1) + ' كم'} />
        <Stat label="المدة" value={'18 د'} />
        <Stat label="أرباح اليوم" value={'₪' + totalToday} />
      </div>

      <div style={{ flex: 1 }} />

      <PrimaryButton tone="primary" size="lg" onClick={onClose}>
        العودة إلى الطلبات
      </PrimaryButton>
    </div>
  );
}

function Stat({ label, value }) {
  return (
    <div style={{
      flex: 1, background: 'var(--surface)', borderRadius: 14,
      border: '1px solid var(--line)',
      padding: '10px 12px',
    }}>
      <div style={{ fontSize: 10, fontWeight: 800, color: 'var(--text-2)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{label}</div>
      <div className="num" style={{ fontSize: 15, fontWeight: 800, color: 'var(--text)', marginTop: 4 }}>{value}</div>
    </div>
  );
}

Object.assign(window, {
  HomeScreen, IncomingAlert, OrderDetail,
  ToPickup, AtPickup, ToDropoff,
  CashCollection, Completed,
});
