<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<title><?= e($pageTitle) ?></title>
<meta name="theme-color" content="#1D7A8C">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Rider App">
<link rel="manifest" href="<?= Router::url('rider-app/manifest') ?>">
<link rel="apple-touch-icon" href="<?= BASE_URL ?>/assets/icons/icon-192.png">
<link rel="icon" href="<?= BASE_URL ?>/assets/icons/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@600;700&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
<style>
:root {
    --navy: #16305C; --navy-2: #0E1F42; --gold: #C1872E; --teal: #1D7A8C; --teal-2: #124D58;
    --bg: #F4F6FB; --surface: #fff; --border: #E7E9F0; --text: #1E2430; --muted: #7A8194;
    --success: #4B6B3A; --danger: #B23A3A;
}
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
body {
    margin: 0; font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
    background: var(--bg); color: var(--text); -webkit-font-smoothing: antialiased;
}
.app { max-width: 480px; margin: 0 auto; min-height: 100vh; background: var(--bg); padding-bottom: 90px; }

/* ---- Splash ---- */
#riderSplash {
    position: fixed; inset: 0; z-index: 1000; background: linear-gradient(150deg, var(--teal), var(--teal-2));
    display: flex; flex-direction: column; align-items: center; justify-content: center; color: #fff;
    transition: opacity 0.4s ease, visibility 0.4s ease;
}
#riderSplash.hide { opacity: 0; visibility: hidden; pointer-events: none; }
.splash-icon { width: 70px; height: 70px; border-radius: 18px; background: rgba(255,255,255,0.14); display: flex; align-items: center; justify-content: center; font-size: 28px; margin-bottom: 14px; overflow: hidden; animation: riderPulse 1.8s ease-in-out infinite; }
.splash-icon img { width: 100%; height: 100%; object-fit: cover; }
@keyframes riderPulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.06); } }
.splash-title { font-family: 'Fraunces', serif; font-size: 20px; font-weight: 700; }
.splash-sub { font-size: 11.5px; color: rgba(255,255,255,0.75); margin-top: 3px; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 26px; }
.splash-spinner { width: 28px; height: 28px; border-radius: 50%; border: 3px solid rgba(255,255,255,0.25); border-top-color: var(--gold); animation: riderSpin 0.8s linear infinite; }
@keyframes riderSpin { to { transform: rotate(360deg); } }
.splash-footer { position: absolute; bottom: 24px; font-size: 10px; color: rgba(255,255,255,0.4); }

/* ---- Login ---- */
.login-screen { min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 30px 24px; background: linear-gradient(150deg, var(--teal), var(--teal-2)); color: #fff; }
.login-screen .icon { width: 64px; height: 64px; border-radius: 16px; background: rgba(255,255,255,0.15); display: flex; align-items: center; justify-content: center; font-size: 26px; margin-bottom: 14px; overflow: hidden; }
.login-screen .icon img { width: 100%; height: 100%; object-fit: cover; }
.login-screen h1 { font-family: 'Fraunces', serif; font-size: 20px; margin: 0 0 4px; }
.login-screen .sub { font-size: 12px; color: rgba(255,255,255,0.75); margin-bottom: 26px; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 700; }
.login-card { width: 100%; background: #fff; border-radius: 16px; padding: 24px; color: var(--text); box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
.form-group { margin-bottom: 14px; }
.form-group label { display: block; font-size: 11px; font-weight: 700; color: var(--muted); margin-bottom: 5px; text-transform: uppercase; letter-spacing: 0.04em; }
.form-control { width: 100%; padding: 12px 13px; border: 1px solid var(--border); border-radius: 9px; font-size: 14px; font-family: inherit; background: var(--bg); }
.big-btn { width: 100%; padding: 13px; border-radius: 10px; border: none; font-weight: 800; font-size: 14px; background: var(--teal); color: #fff; font-family: inherit; }
.big-btn:disabled { opacity: 0.5; }
.error-banner { background: #FBEBEB; color: #8A2A2A; padding: 10px 12px; border-radius: 8px; font-size: 12px; margin-bottom: 12px; display: none; }
.error-banner.show { display: block; }

/* ---- App header ---- */
.app-header { background: linear-gradient(120deg, var(--teal), var(--teal-2)); color: #fff; padding: 18px; padding-top: calc(18px + env(safe-area-inset-top)); position: sticky; top: 0; z-index: 20; }
.app-header .top-row { display: flex; align-items: center; justify-content: space-between; }
.app-header .rider-avatar { width: 42px; height: 42px; border-radius: 50%; background: rgba(255,255,255,0.18); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 16px; overflow: hidden; }
.app-header .rider-avatar img { width: 100%; height: 100%; object-fit: cover; }
.app-header h1 { font-size: 16px; margin: 0; font-family: 'Fraunces', serif; }
.app-header .sub { font-size: 10.5px; color: rgba(255,255,255,0.8); display: flex; align-items: center; gap: 5px; margin-top: 2px; }
.live-dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: #8FE0A0; animation: riderDotPulse 1.6s infinite; }
@keyframes riderDotPulse { 0% { box-shadow: 0 0 0 0 rgba(143,224,160,0.6); } 70% { box-shadow: 0 0 0 5px rgba(143,224,160,0); } 100% { box-shadow: 0 0 0 0 rgba(143,224,160,0); } }
.header-icon-btn { width: 38px; height: 38px; border-radius: 10px; background: rgba(255,255,255,0.15); border: none; color: #fff; font-size: 15px; }

/* ---- Stats ---- */
.stats-row { display: flex; gap: 8px; padding: 14px 16px 4px; }
.stat-box { flex: 1; background: #fff; border-radius: 12px; padding: 13px 8px; text-align: center; box-shadow: 0 1px 4px rgba(20,25,40,0.05); }
.stat-box .val { font-size: 18px; font-weight: 800; color: var(--navy); }
.stat-box .lbl { font-size: 9px; color: var(--muted); font-weight: 700; text-transform: uppercase; margin-top: 3px; letter-spacing: 0.02em; }

/* ---- Scan CTA ---- */
.scan-cta { margin: 14px 16px; padding: 15px; border-radius: 14px; background: linear-gradient(120deg, var(--gold), #8A611F); color: #fff; display: flex; align-items: center; gap: 12px; border: none; width: calc(100% - 32px); }
.scan-cta .icon-circle { width: 40px; height: 40px; border-radius: 50%; background: rgba(255,255,255,0.2); display: flex; align-items: center; justify-content: center; font-size: 17px; flex-shrink: 0; }
.scan-cta .text { text-align: left; }
.scan-cta .text .t1 { font-weight: 800; font-size: 13.5px; }
.scan-cta .text .t2 { font-size: 10.5px; color: rgba(255,255,255,0.85); }
.scan-cta i.fa-chevron-right { margin-left: auto; opacity: 0.8; }

/* ---- Section title ---- */
.section-title { font-size: 11px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; padding: 4px 16px 8px; }

/* ---- Delivery cards ---- */
.delivery-list { padding: 0 16px; }
.delivery-card { background: #fff; border-radius: 14px; padding: 15px; margin-bottom: 12px; box-shadow: 0 1px 6px rgba(20,25,40,0.06); }
.dc-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; }
.dc-order-num { font-size: 14.5px; font-weight: 800; }
.dc-status { font-size: 10px; font-weight: 800; padding: 4px 11px; border-radius: 100px; text-transform: uppercase; letter-spacing: 0.03em; }
.dc-status.assigned { background: #EAF1FB; color: #2E5FB0; }
.dc-status.picked_up { background: #FDF3E4; color: #8A611F; }
.dc-status.delivered { background: #EEF3EA; color: #3D5830; }
.dc-status.failed { background: #FBEBEB; color: #8A2A2A; }
.dc-info { display: flex; flex-direction: column; gap: 7px; margin-bottom: 10px; }
.dc-row { display: flex; align-items: flex-start; gap: 9px; font-size: 12.5px; color: var(--text); }
.dc-row i { color: var(--muted); width: 14px; margin-top: 2px; font-size: 12px; }
.dc-row .balance-due { color: var(--danger); font-weight: 700; }
.dc-row .balance-paid { color: var(--success); font-weight: 700; }
.dc-quick-actions { display: flex; gap: 8px; margin-bottom: 10px; }
.dc-quick-actions a { flex: 1; display: flex; align-items: center; justify-content: center; gap: 6px; padding: 9px; border-radius: 8px; background: var(--bg); color: var(--navy); font-size: 11.5px; font-weight: 700; text-decoration: none; }
.dc-meta { font-size: 10.5px; color: var(--muted); padding-top: 9px; border-top: 1px dashed var(--border); margin-bottom: 10px; }
.dc-actions { display: flex; gap: 8px; }
.dc-actions button { flex: 1; padding: 12px; border-radius: 10px; border: none; font-weight: 800; font-size: 12.5px; font-family: inherit; }
.btn-pickup { background: var(--teal); color: #fff; }
.btn-delivered { background: var(--success); color: #fff; }
.btn-failed { background: #fff; color: var(--danger); border: 1.5px solid #F2D2D2 !important; }

/* ---- Profile tab ---- */
.profile-hero { background: linear-gradient(120deg, var(--teal), var(--teal-2)); border-radius: 16px; padding: 24px 16px; text-align: center; color: #fff; margin: 14px 16px; }
.profile-avatar-ring { width: 74px; height: 74px; border-radius: 50%; background: rgba(255,255,255,0.15); padding: 4px; margin: 0 auto 10px; }
.profile-avatar { width: 100%; height: 100%; border-radius: 50%; background: var(--gold); display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: 800; overflow: hidden; }
.profile-avatar img { width: 100%; height: 100%; object-fit: cover; }
.profile-name { font-family: 'Fraunces', serif; font-size: 17px; font-weight: 700; }
.profile-sub { font-size: 11.5px; color: rgba(255,255,255,0.75); margin-top: 2px; }
.profile-details-card { background: #fff; border-radius: 12px; margin: 0 16px 14px; box-shadow: 0 1px 4px rgba(20,25,40,0.05); padding: 4px 14px; }
.pd-row { display: flex; align-items: center; gap: 10px; padding: 11px 0; border-bottom: 1px solid var(--border); font-size: 12.5px; }
.pd-row:last-child { border-bottom: none; }
.pd-row i { width: 16px; color: var(--teal); text-align: center; }
.pd-row .pd-label { font-size: 9.5px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.03em; font-weight: 700; }
.pd-row .pd-value { font-size: 12.5px; font-weight: 600; }
.logout-card-btn { margin: 0 16px; width: calc(100% - 32px); background: #fff; color: var(--danger); border: 1.5px solid #F2D2D2; padding: 13px; border-radius: 12px; font-weight: 800; font-size: 13px; }

/* ---- Bottom nav ---- */
.bottom-nav { position: fixed; left: 50%; bottom: 0; transform: translateX(-50%); width: 100%; max-width: 480px; background: #fff; border-top: 1px solid var(--border); display: flex; z-index: 20; padding-bottom: env(safe-area-inset-bottom); box-shadow: 0 -2px 12px rgba(20,25,40,0.06); }
.bottom-nav button { flex: 1; background: none; border: none; padding: 10px 4px 8px; display: flex; flex-direction: column; align-items: center; gap: 3px; color: var(--muted); font-size: 10px; font-weight: 700; font-family: inherit; position: relative; }
.bottom-nav button i { font-size: 17px; }
.bottom-nav button.active { color: var(--navy); }
.bottom-nav button.active i { color: var(--teal); }
.bottom-nav .nav-badge { position: absolute; top: 2px; right: 22%; background: var(--gold); color: #fff; font-size: 9px; font-weight: 800; width: 15px; height: 15px; border-radius: 50%; display: flex; align-items: center; justify-content: center; }

.empty-state { text-align: center; padding: 40px 20px; color: var(--muted); font-size: 13px; }
.loading-state { text-align: center; padding: 40px 20px; color: var(--muted); font-size: 13px; }
.loading-state i { font-size: 24px; margin-bottom: 10px; display: block; }

.modal-overlay { display: none; position: fixed; inset: 0; background: rgba(10,14,25,0.5); z-index: 100; align-items: flex-end; justify-content: center; }
.modal-overlay.open { display: flex; }
.modal-sheet { background: #fff; border-radius: 16px 16px 0 0; padding: 20px; width: 100%; max-width: 480px; padding-bottom: calc(20px + env(safe-area-inset-bottom)); }
</style>
</head>
<body>

<!-- SPLASH -->
<div id="riderSplash">
    <div class="splash-icon">
        <?php if ($logoUrl): ?><img src="<?= e($logoUrl) ?>"><?php else: ?><i class="fa-solid fa-motorcycle"></i><?php endif; ?>
    </div>
    <div class="splash-title"><?= e($companyName) ?></div>
    <div class="splash-sub">Rider App</div>
    <div class="splash-spinner"></div>
    <div class="splash-footer">Powered by MJ Systems 1.2V</div>
</div>

<!-- LOGIN SCREEN -->
<div class="login-screen" id="riderLoginScreen" style="display:none;">
    <div class="icon"><?php if ($logoUrl): ?><img src="<?= e($logoUrl) ?>"><?php else: ?><i class="fa-solid fa-motorcycle"></i><?php endif; ?></div>
    <h1><?= e($companyName) ?></h1>
    <div class="sub">Rider App</div>
    <div class="login-card">
        <div class="error-banner" id="riderLoginError"></div>
        <form onsubmit="riderDoLogin(); return false;">
            <div class="form-group"><label>Username</label><input type="text" id="riderUsername" class="form-control" placeholder="Your username" autocomplete="username"></div>
            <div class="form-group"><label>Password</label><input type="password" id="riderPassword" class="form-control" placeholder="Your password" autocomplete="current-password"></div>
            <button type="submit" class="big-btn" id="riderLoginBtn">Log In</button>
        </form>
    </div>
</div>

<!-- MAIN APP -->
<div class="app" id="riderMainApp" style="display:none;">
    <div class="app-header">
        <div class="top-row">
            <div style="display:flex;align-items:center;gap:12px;">
                <div class="rider-avatar" id="riderAvatar"></div>
                <div>
                    <h1 id="riderGreetingName">Hi there!</h1>
                    <div class="sub"><span class="live-dot"></span> <span id="riderGreetingText">Good day</span></div>
                </div>
            </div>
        </div>
    </div>

    <!-- ACTIVE TAB -->
    <div id="riderTabActive">
        <div class="stats-row">
            <div class="stat-box"><div class="val" id="riderStatActive">0</div><div class="lbl">Active</div></div>
            <div class="stat-box"><div class="val" id="riderStatToday">0</div><div class="lbl">Today</div></div>
            <div class="stat-box"><div class="val" id="riderStatTotal">0</div><div class="lbl">Total</div></div>
        </div>

        <button class="scan-cta" onclick="riderOpenClaimScanner()">
            <div class="icon-circle"><i class="fa-solid fa-qrcode"></i></div>
            <div class="text"><div class="t1">Scan to Confirm Pickup</div><div class="t2">For orders already assigned to you</div></div>
            <i class="fa-solid fa-chevron-right"></i>
        </button>

        <div class="section-title">My Active Deliveries</div>
        <div class="delivery-list" id="riderActiveList">
            <div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>
        </div>
    </div>

    <!-- HISTORY TAB -->
    <div id="riderTabHistory" style="display:none;">
        <div class="section-title" style="padding-top:16px;">Delivery History</div>
        <div class="delivery-list" id="riderHistoryList">
            <div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>
        </div>
    </div>

    <!-- PROFILE TAB -->
    <div id="riderTabProfile" style="display:none;">
        <div class="profile-hero">
            <div class="profile-avatar-ring"><div class="profile-avatar" id="riderProfileAvatar"></div></div>
            <div class="profile-name" id="riderProfileName"></div>
            <div class="profile-sub" id="riderProfilePhone"></div>
        </div>
        <div class="profile-details-card" id="riderProfileDetails"></div>
        <button class="logout-card-btn" onclick="riderLogout()"><i class="fa-solid fa-right-from-bracket"></i> Log Out</button>
    </div>
</div>

<div class="bottom-nav" id="riderBottomNav" style="display:none;">
    <button id="riderNavActiveBtn" class="active" onclick="riderSwitchTab('active')">
        <i class="fa-solid fa-motorcycle"></i> Active
        <span class="nav-badge" id="riderActiveBadge" style="display:none;">0</span>
    </button>
    <button id="riderNavHistoryBtn" onclick="riderSwitchTab('history')"><i class="fa-solid fa-clock-rotate-left"></i> History</button>
    <button id="riderNavProfileBtn" onclick="riderSwitchTab('profile')"><i class="fa-solid fa-user"></i> Profile</button>
</div>

<!-- QR Scanner modal -->
<div class="modal-overlay" id="riderScannerModal">
    <div class="modal-sheet" style="max-width:480px;">
        <h3 style="margin-top:0;" id="riderScannerTitle">Scan Order QR Code</h3>
        <div style="font-size:12px;color:var(--muted);margin-bottom:12px;">Point your camera at the QR code on the printed order label.</div>
        <div id="riderQrReader" style="width:100%;border-radius:10px;overflow:hidden;"></div>
        <div id="riderScanMismatch" style="display:none;background:#FBEBEB;color:#8A2A2A;padding:10px 12px;border-radius:8px;font-size:12px;font-weight:700;margin-top:12px;text-align:center;">
            <i class="fa-solid fa-triangle-exclamation"></i> That QR doesn't match this order — try scanning again.
        </div>
        <button class="big-btn" style="background:var(--bg);color:var(--text);margin-top:14px;" onclick="riderCloseScanner()">Cancel</button>
    </div>
</div>

<!-- COD Cash Collection modal -->
<div class="modal-overlay" id="riderCodModal">
    <div class="modal-sheet" style="text-align:center;">
        <div style="width:56px;height:56px;border-radius:50%;background:#FDF3E4;display:flex;align-items:center;justify-content:center;font-size:24px;margin:0 auto 14px;color:var(--gold);"><i class="fa-solid fa-money-bill-wave"></i></div>
        <h3 style="margin:0 0 6px;">Collect Cash Payment</h3>
        <div style="font-size:13px;color:var(--muted);margin-bottom:6px;">This order has a balance due:</div>
        <div style="font-size:22px;font-weight:800;color:var(--navy);margin-bottom:20px;" id="riderCodAmount">Rs. 0.00</div>
        <input type="hidden" id="riderCodDeliveryId">
        <div style="display:flex;flex-direction:column;gap:8px;">
            <button class="big-btn" style="background:var(--success);" onclick="riderConfirmCodCollected(true)"><i class="fa-solid fa-check"></i> Cash Collected — Mark Delivered</button>
            <button class="big-btn" style="background:var(--bg);color:var(--text);" onclick="riderConfirmCodCollected(false)">Not Collected — Still Mark Delivered</button>
        </div>
    </div>
</div>

<!-- Mark Failed modal -->
<div class="modal-overlay" id="riderFailedModal">
    <div class="modal-sheet">
        <h3 style="margin-top:0;">Mark Delivery Failed</h3>
        <div class="form-group"><label>Reason</label><textarea id="riderFailedNotes" class="form-control" rows="3" placeholder="e.g. Customer not reachable, wrong address"></textarea></div>
        <div style="display:flex;gap:8px;">
            <button class="big-btn" style="background:var(--bg);color:var(--text);" onclick="document.getElementById('riderFailedModal').classList.remove('open')">Cancel</button>
            <button class="big-btn" style="background:var(--danger);" onclick="riderConfirmFailed()">Confirm Failed</button>
        </div>
    </div>
</div>

<script>
const API_BASE = "<?= BASE_URL ?>/api/rider";
let riderCurrentTab = 'active';
let riderFailedDeliveryId = null;
let riderScanner = null;
let riderScanContext = null;
let riderCurrentRider = null;
const riderSplashStart = Date.now();

function riderHideSplash() {
    const wait = Math.max(0, 800 - (Date.now() - riderSplashStart));
    setTimeout(() => document.getElementById('riderSplash').classList.add('hide'), wait);
}

function riderGreetingPhrase() {
    const hour = new Date().getHours();
    if (hour < 5) return 'Good Night';
    if (hour < 12) return 'Good Morning';
    if (hour < 17) return 'Good Afternoon';
    if (hour < 21) return 'Good Evening';
    return 'Good Night';
}

function riderCheckAuth() {
    fetch(API_BASE + '/me').then(r => r.json()).then(data => {
        riderHideSplash();
        if (data.success && data.loggedIn) {
            riderShowApp(data.rider);
        } else {
            document.getElementById('riderLoginScreen').style.display = 'flex';
            document.getElementById('riderMainApp').style.display = 'none';
            document.getElementById('riderBottomNav').style.display = 'none';
        }
    }).catch(() => { riderHideSplash(); document.getElementById('riderLoginScreen').style.display = 'flex'; });
}
riderCheckAuth();
setTimeout(riderHideSplash, 4000); // safety net

function riderShowApp(rider) {
    riderCurrentRider = rider;
    document.getElementById('riderLoginScreen').style.display = 'none';
    document.getElementById('riderMainApp').style.display = 'block';
    document.getElementById('riderBottomNav').style.display = 'flex';
    document.getElementById('riderGreetingName').textContent = 'Hi, ' + rider.name.split(' ')[0] + '!';
    document.getElementById('riderGreetingText').textContent = riderGreetingPhrase();

    const avatarHtml = rider.photo_url ? `<img src="${rider.photo_url}">` : rider.name.substring(0, 1).toUpperCase();
    document.getElementById('riderAvatar').innerHTML = avatarHtml;
    document.getElementById('riderProfileAvatar').innerHTML = avatarHtml;
    document.getElementById('riderProfileName').textContent = rider.name;
    document.getElementById('riderProfilePhone').textContent = rider.phone || '';

    document.getElementById('riderProfileDetails').innerHTML = `
        <div class="pd-row"><i class="fa-solid fa-phone"></i><div><div class="pd-label">Phone</div><div class="pd-value">${rider.phone || '—'}</div></div></div>
        <div class="pd-row"><i class="fa-solid fa-motorcycle"></i><div><div class="pd-label">Vehicle Type</div><div class="pd-value">${rider.vehicle_type || '—'}</div></div></div>
        <div class="pd-row"><i class="fa-solid fa-hashtag"></i><div><div class="pd-label">Vehicle Number</div><div class="pd-value">${rider.vehicle_number || '—'}</div></div></div>
    `;

    riderLoadStats();
    riderLoadDeliveries();
}

async function riderDoLogin() {
    const errEl = document.getElementById('riderLoginError');
    errEl.classList.remove('show');
    const username = document.getElementById('riderUsername').value.trim();
    const password = document.getElementById('riderPassword').value;
    if (!username || !password) { errEl.textContent = 'Please enter your username and password.'; errEl.classList.add('show'); return; }

    const btn = document.getElementById('riderLoginBtn'); btn.disabled = true; btn.textContent = 'Logging in...';
    try {
        const res = await fetch(API_BASE + '/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) });
        const data = await res.json();
        if (!data.success) { errEl.textContent = data.message; errEl.classList.add('show'); btn.disabled = false; btn.textContent = 'Log In'; return; }
        riderShowApp(data.rider);
    } catch (e) { errEl.textContent = 'Network error. Please try again.'; errEl.classList.add('show'); }
    btn.disabled = false; btn.textContent = 'Log In';
}

function riderLogout() {
    fetch(API_BASE + '/logout', { method: 'POST' }).then(() => {
        document.getElementById('riderLoginScreen').style.display = 'flex';
        document.getElementById('riderMainApp').style.display = 'none';
        document.getElementById('riderBottomNav').style.display = 'none';
    });
}

function riderLoadStats() {
    fetch(API_BASE + '/stats').then(r => r.json()).then(data => {
        if (!data.success) return;
        document.getElementById('riderStatActive').textContent = data.stats.active_count;
        document.getElementById('riderStatToday').textContent = data.stats.delivered_today;
        document.getElementById('riderStatTotal').textContent = data.stats.delivered_total;
        const badge = document.getElementById('riderActiveBadge');
        if (data.stats.active_count > 0) { badge.style.display = 'flex'; badge.textContent = data.stats.active_count; }
        else { badge.style.display = 'none'; }
    }).catch(() => {});
}

function riderSwitchTab(tab) {
    riderCurrentTab = tab;
    ['riderTabActive', 'riderTabHistory', 'riderTabProfile'].forEach(id => {
        document.getElementById(id).style.display = id === 'riderTab' + tab.charAt(0).toUpperCase() + tab.slice(1) ? 'block' : 'none';
    });
    ['riderNavActiveBtn', 'riderNavHistoryBtn', 'riderNavProfileBtn'].forEach(id => document.getElementById(id).classList.remove('active'));
    document.getElementById('riderNav' + tab.charAt(0).toUpperCase() + tab.slice(1) + 'Btn').classList.add('active');

    if (tab === 'active') riderLoadDeliveries('active');
    if (tab === 'history') riderLoadDeliveries('history');
}

function riderLoadDeliveries(which) {
    which = which || 'active';
    const listId = which === 'active' ? 'riderActiveList' : 'riderHistoryList';
    const el = document.getElementById(listId);
    el.innerHTML = '<div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>';
    const endpoint = which === 'active' ? '/deliveries' : '/deliveries/history';

    fetch(API_BASE + endpoint).then(r => r.json()).then(data => {
        if (!data.success) { el.innerHTML = '<div class="empty-state">Could not load deliveries.</div>'; return; }
        if (data.deliveries.length === 0) {
            el.innerHTML = `<div class="empty-state"><i class="fa-solid fa-motorcycle" style="font-size:26px;display:block;margin-bottom:8px;"></i>${which === 'active' ? 'No active deliveries right now.' : 'No delivery history yet.'}</div>`;
            return;
        }
        el.innerHTML = data.deliveries.map(riderBuildCard).join('');
    }).catch(() => { el.innerHTML = '<div class="empty-state">Network error loading deliveries.</div>'; });
}

function riderBuildCard(d) {
    let actions = '';
    if (d.status === 'ASSIGNED') {
        actions = `<div class="dc-actions">
            <button class="btn-pickup" onclick="riderOpenScanner(${d.id}, '${d.order_number}', 'picked-up')"><i class="fa-solid fa-qrcode"></i> Scan to Pick Up</button>
            <button class="btn-failed" onclick="riderOpenFailedModal(${d.id})"><i class="fa-solid fa-xmark"></i></button>
        </div>`;
    } else if (d.status === 'PICKED_UP') {
        actions = `<div class="dc-actions">
            <button class="btn-delivered" onclick="riderOpenScanner(${d.id}, '${d.order_number}', 'delivered', ${d.balance_due})"><i class="fa-solid fa-qrcode"></i> Scan to Deliver</button>
            <button class="btn-failed" onclick="riderOpenFailedModal(${d.id})"><i class="fa-solid fa-xmark"></i></button>
        </div>`;
    }

    const mapsUrl = d.delivery_address ? `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(d.delivery_address)}` : null;

    return `<div class="delivery-card">
        <div class="dc-top">
            <div class="dc-order-num">${d.order_number}</div>
            <div class="dc-status ${d.status.toLowerCase()}">${d.status.replace('_', ' ')}</div>
        </div>
        <div class="dc-info">
            <div class="dc-row"><i class="fa-solid fa-user"></i> ${d.customer_name}</div>
            <div class="dc-row"><i class="fa-solid fa-location-dot"></i> ${d.delivery_address || 'No address on file'}${d.zone_name ? ' — ' + d.zone_name : ''}</div>
            <div class="dc-row"><i class="fa-solid fa-bag-shopping"></i> ${d.item_count} items · Rs. ${d.total_amount.toFixed(2)} ${d.balance_due > 0 ? `<span class="balance-due">(Rs. ${d.balance_due.toFixed(2)} due)</span>` : `<span class="balance-paid">(Paid)</span>`}</div>
        </div>
        <div class="dc-quick-actions">
            ${d.customer_phone ? `<a href="tel:${d.customer_phone}"><i class="fa-solid fa-phone"></i> Call</a>` : ''}
            ${mapsUrl ? `<a href="${mapsUrl}" target="_blank"><i class="fa-solid fa-diamond-turn-right"></i> Navigate</a>` : ''}
        </div>
        <div class="dc-meta">
            ${d.assigned_at ? 'Assigned: ' + d.assigned_at : ''}
            ${d.picked_up_at ? ' · Picked up: ' + d.picked_up_at : ''}
            ${d.delivered_at ? ' · Delivered: ' + d.delivered_at : ''}
            ${d.notes ? '<br>Note: ' + d.notes : ''}
        </div>
        ${actions}
    </div>`;
}

function riderStartScanner() {
    if (typeof Html5Qrcode === 'undefined') {
        alert('The QR scanner library failed to load. Please check your internet connection and reload the app.');
        riderCloseScanner();
        return;
    }
    try {
        riderScanner = new Html5Qrcode("riderQrReader");
        const onSuccess = riderHandleScanResult;
        const onFailure = () => {};
        const config = { fps: 10, qrbox: 220 };

        riderScanner.start({ facingMode: "environment" }, config, onSuccess, onFailure).catch(() => {
            riderScanner.start({ facingMode: "user" }, config, onSuccess, onFailure).catch((anyErr) => {
                alert('Could not access the camera: ' + anyErr + '\n\nMake sure a camera is connected and permission is allowed for this site.');
                riderCloseScanner();
            });
        });
    } catch (err) {
        alert('Could not start the scanner: ' + err);
        riderCloseScanner();
    }
}

function riderOpenScanner(deliveryId, orderNumber, action, balanceDue) {
    riderScanContext = { deliveryId, orderNumber, action, balanceDue: balanceDue || 0 };
    document.getElementById('riderScannerTitle').textContent = action === 'picked-up' ? 'Scan to Confirm Pickup' : 'Scan to Confirm Delivery';
    document.getElementById('riderScanMismatch').style.display = 'none';
    document.getElementById('riderScannerModal').classList.add('open');
    riderStartScanner();
}

function riderOpenClaimScanner() {
    riderScanContext = { deliveryId: null, orderNumber: null, action: 'claim' };
    document.getElementById('riderScannerTitle').textContent = 'Scan Order Label to Claim';
    document.getElementById('riderScanMismatch').style.display = 'none';
    document.getElementById('riderScannerModal').classList.add('open');
    riderStartScanner();
}

function riderHandleScanResult(decodedText) {
    let scannedOrderNumber = decodedText;
    try {
        const url = new URL(decodedText);
        scannedOrderNumber = url.searchParams.get('order') || decodedText;
    } catch (e) {}

    const ctx = riderScanContext;

    if (ctx.action === 'claim') {
        riderCloseScanner();
        riderCompleteClaim(scannedOrderNumber);
        return;
    }

    if (scannedOrderNumber !== ctx.orderNumber) {
        document.getElementById('riderScanMismatch').style.display = 'block';
        if (navigator.vibrate) navigator.vibrate(200);
        return;
    }

    riderCloseScanner();
    if (ctx.action === 'picked-up') riderCompletePickedUp(ctx.deliveryId);
    else riderHandleDeliveryScan(ctx.deliveryId, ctx.balanceDue);
}

function riderHandleDeliveryScan(deliveryId, balanceDue) {
    if (balanceDue > 0) {
        document.getElementById('riderCodAmount').textContent = 'Rs. ' + balanceDue.toFixed(2);
        document.getElementById('riderCodDeliveryId').value = deliveryId;
        document.getElementById('riderCodModal').classList.add('open');
    } else {
        riderCompleteDelivered(deliveryId, false);
    }
}

async function riderConfirmCodCollected(collected) {
    const deliveryId = parseInt(document.getElementById('riderCodDeliveryId').value);
    document.getElementById('riderCodModal').classList.remove('open');
    riderCompleteDelivered(deliveryId, collected);
}

async function riderCompleteClaim(orderNumber) {
    try {
        const res = await fetch(API_BASE + '/deliveries/claim', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ order_number: orderNumber }) });
        const data = await res.json();
        if (!data.success) { alert(data.message || 'Could not claim this order.'); return; }
        if (navigator.vibrate) navigator.vibrate(100);
        alert('✅ ' + data.message);
        riderLoadStats();
        riderLoadDeliveries('active');
    } catch (e) { alert('Network error — please try again.'); }
}

function riderCloseScanner() {
    if (riderScanner) {
        riderScanner.stop().then(() => riderScanner.clear()).catch(() => {});
        riderScanner = null;
    }
    document.getElementById('riderScannerModal').classList.remove('open');
}

async function riderCompletePickedUp(deliveryId) {
    await fetch(API_BASE + '/deliveries/picked-up', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ delivery_id: deliveryId }) });
    riderLoadStats();
    riderLoadDeliveries('active');
}

async function riderCompleteDelivered(deliveryId, collectCash) {
    await fetch(API_BASE + '/deliveries/delivered', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ delivery_id: deliveryId, collect_cash: !!collectCash }) });
    riderLoadStats();
    riderLoadDeliveries('active');
}

function riderOpenFailedModal(deliveryId) {
    riderFailedDeliveryId = deliveryId;
    document.getElementById('riderFailedNotes').value = '';
    document.getElementById('riderFailedModal').classList.add('open');
}

async function riderConfirmFailed() {
    const notes = document.getElementById('riderFailedNotes').value.trim();
    await fetch(API_BASE + '/deliveries/failed', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ delivery_id: riderFailedDeliveryId, notes }) });
    document.getElementById('riderFailedModal').classList.remove('open');
    riderLoadStats();
    riderLoadDeliveries('active');
}

setInterval(() => { if (riderCurrentRider) { riderLoadStats(); if (document.getElementById('riderScannerModal').classList.contains('open') === false) riderLoadDeliveries(riderCurrentTab); } }, 20000);

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('<?= BASE_URL ?>/service-worker.js').catch(() => {});
}
</script>
</body>
</html>
