<!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="#16305C">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="<?= e($companyName) ?>">
<link rel="manifest" href="<?= Router::url('shop/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">
<style>
:root {
    --navy: #16305C; --navy-2: #0E1F42; --gold: #C1872E; --teal: #1D7A8C;
    --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;
    padding-bottom: env(safe-area-inset-bottom);
}
.app { max-width: 480px; margin: 0 auto; min-height: 100vh; background: var(--bg); position: relative; padding-bottom: 150px; }

/* ---- Splash / Loading screen ---- */
#rmsSplashScreen {
    position: fixed; inset: 0; z-index: 1000;
    background: linear-gradient(150deg, var(--navy) 0%, var(--navy-2) 100%);
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    color: #fff; transition: opacity 0.4s ease, visibility 0.4s ease;
}
#rmsSplashScreen.hide { opacity: 0; visibility: hidden; pointer-events: none; }
.splash-icon {
    width: 74px; height: 74px; border-radius: 20px; background: rgba(255,255,255,0.12);
    display: flex; align-items: center; justify-content: center; font-size: 32px; margin-bottom: 16px;
    animation: rmsSplashPulse 1.8s ease-in-out infinite; overflow: hidden;
}
.splash-icon img { width: 100%; height: 100%; object-fit: cover; }
@keyframes rmsSplashPulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.06); } }
.splash-title { font-family: 'Fraunces', serif; font-size: 22px; font-weight: 700; }
.splash-sub { font-size: 12px; color: rgba(255,255,255,0.7); margin-top: 3px; margin-bottom: 28px; letter-spacing: 0.04em; text-transform: uppercase; }
.splash-spinner {
    width: 30px; height: 30px; border-radius: 50%; border: 3px solid rgba(255,255,255,0.25); border-top-color: var(--gold);
    animation: rmsSplashSpin 0.8s linear infinite;
}
@keyframes rmsSplashSpin { to { transform: rotate(360deg); } }
.splash-footer {
    position: absolute; bottom: 26px; left: 0; right: 0; text-align: center;
    font-size: 10.5px; color: rgba(255,255,255,0.45); letter-spacing: 0.03em;
}

/* ---- Bottom Navigation Bar ---- */
.bottom-nav {
    position: fixed; left: 50%; bottom: 0; transform: translateX(-50%); width: 100%; max-width: 480px;
    background: var(--surface); 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;
}
.bottom-nav button i { font-size: 17px; }
.bottom-nav button.active { color: var(--navy); }
.bottom-nav button.active i { color: var(--teal); }

/* ---- Header ---- */
.app-header {
    position: sticky; top: 0; z-index: 30; background: linear-gradient(120deg, var(--navy), var(--navy-2));
    color: #fff; padding: 16px 18px; display: flex; align-items: center; justify-content: space-between;
    padding-top: calc(16px + env(safe-area-inset-top));
}
.app-header .brand { display: flex; align-items: center; gap: 10px; }
.app-header .brand-logo {
    width: 38px; height: 38px; border-radius: 10px; background: rgba(255,255,255,0.15);
    display: flex; align-items: center; justify-content: center; font-size: 17px; flex-shrink: 0; overflow: hidden;
}
.app-header .brand-logo img { width: 100%; height: 100%; object-fit: cover; }
.app-header h1 { font-family: 'Fraunces', serif; font-size: 16px; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 220px; }
.app-header .sub { font-size: 10.5px; color: rgba(255,255,255,0.7); display: flex; align-items: center; gap: 5px; }
.live-dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: #4B6B3A; animation: rmsLiveDotPulse 1.6s infinite; }
@keyframes rmsLiveDotPulse { 0% { box-shadow: 0 0 0 0 rgba(75,107,58,0.6); } 70% { box-shadow: 0 0 0 5px rgba(75,107,58,0); } 100% { box-shadow: 0 0 0 0 rgba(75,107,58,0); } }
.cart-btn { position: relative; width: 40px; height: 40px; border-radius: 10px; background: rgba(255,255,255,0.15); border: none; color: #fff; font-size: 16px; }
.cart-btn .badge {
    position: absolute; top: -4px; right: -4px; background: var(--gold); color: #fff; font-size: 10px; font-weight: 800;
    width: 18px; height: 18px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
}

/* ---- Install banner ---- */
.install-banner {
    display: none; align-items: center; gap: 10px; background: #FDF3E4; border-bottom: 1px solid #EAD3A0;
    padding: 10px 16px; font-size: 12px; color: #4B3A1E;
}
.install-banner.show { display: flex; }
.install-banner button { margin-left: auto; background: var(--gold); color: #fff; border: none; padding: 7px 14px; border-radius: 7px; font-weight: 700; font-size: 12px; }
.install-banner .ib-close { background: transparent; color: #4B3A1E; padding: 4px; font-size: 14px; }

.closed-banner {
    display: flex; align-items: center; gap: 8px; background: #FBEBEB; color: #8A2A2A;
    padding: 11px 16px; font-size: 12.5px; font-weight: 700; border-bottom: 1px solid #F2D2D2;
}

.rms-toast {
    position: fixed; top: 16px; left: 50%; transform: translateX(-50%) translateY(-20px);
    background: #1E2430; color: #fff; padding: 12px 20px; border-radius: 10px; font-size: 12.5px; font-weight: 600;
    z-index: 2000; opacity: 0; visibility: hidden; transition: opacity 0.25s ease, transform 0.25s ease;
    box-shadow: 0 6px 20px rgba(0,0,0,0.25); max-width: 90%; text-align: center;
}
.rms-toast.show { opacity: 1; visibility: visible; transform: translateX(-50%) translateY(0); }
.rms-toast.error { background: #B23A3A; }

/* ---- Category tabs ---- */
.cat-tabs { display: flex; gap: 8px; padding: 14px 16px 8px; overflow-x: auto; }
.cat-tab { padding: 8px 16px; border-radius: 100px; background: var(--surface); border: 1px solid var(--border); font-size: 12.5px; font-weight: 700; color: var(--muted); white-space: nowrap; }
.cat-tab.active { background: var(--navy); color: #fff; border-color: var(--navy); }

/* ---- Menu grid ---- */
.menu-section { padding: 4px 16px 10px; }
.menu-section h2 { font-size: 14px; margin: 14px 0 10px; }
.item-card {
    display: flex; gap: 12px; background: var(--surface); border-radius: 12px; padding: 12px; margin-bottom: 10px;
    box-shadow: 0 1px 4px rgba(20,25,40,0.05); border: 1px solid var(--border);
}
.item-card .item-img {
    width: 66px; height: 66px; border-radius: 10px; background: #EEF0F5; flex-shrink: 0; background-size: cover; background-position: center;
    display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: 20px;
}
.item-card .item-body { flex: 1; min-width: 0; }
.item-card .item-name { font-size: 13.5px; font-weight: 700; }
.item-card .item-desc { font-size: 11px; color: var(--muted); margin-top: 2px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.item-card .item-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 8px; }
.item-card .item-price { font-size: 13.5px; font-weight: 800; color: var(--navy); }
.add-btn { background: var(--teal); color: #fff; border: none; width: 30px; height: 30px; border-radius: 8px; font-size: 14px; }
.view-menu-btn { background: var(--teal); color: #fff; border: none; padding: 6px 12px; border-radius: 7px; font-size: 10.5px; font-weight: 700; white-space: nowrap; }
.orders-today-badge { font-size: 10px; color: var(--gold); font-weight: 700; display: flex; align-items: center; gap: 4px; margin-top: 3px; }

/* ---- Profile hero (My Account) ---- */
.profile-hero {
    background: linear-gradient(120deg, var(--navy), var(--navy-2)); border-radius: 14px;
    padding: 22px 16px 38px; text-align: center; margin-bottom: 0; color: #fff; position: relative;
}
.profile-avatar-ring { width: 76px; height: 76px; 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); color: #fff;
    display: flex; align-items: center; justify-content: center; font-size: 26px; font-weight: 800; overflow: hidden;
}
.profile-name { font-family: 'Fraunces', serif; font-size: 17px; font-weight: 700; }
.profile-phone { font-size: 12px; color: rgba(255,255,255,0.75); margin-top: 2px; }

.profile-details-card { background: var(--surface, #fff); border-radius: 12px; padding: 4px 14px; margin-bottom: 16px; box-shadow: 0 1px 4px rgba(20,25,40,0.05); }
.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: 18px; color: var(--teal); text-align: center; font-size: 13px; }
.pd-row .pd-label { font-size: 10px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; font-weight: 700; }
.pd-row .pd-value { font-size: 12.5px; font-weight: 600; color: var(--text); }
.pd-row .pd-value.muted { color: var(--muted); font-weight: 500; font-style: italic; }

.profile-action-tabs { display: flex; background: var(--bg); border-radius: 12px; padding: 4px; margin-bottom: 16px; gap: 4px; }
.profile-action-tabs button {
    flex: 1; display: flex; flex-direction: column; align-items: center; gap: 5px; padding: 12px 4px;
    background: transparent; border: none; border-radius: 9px; color: var(--muted); font-family: inherit;
    transition: background 0.15s ease, color 0.15s ease;
}
.profile-action-tabs button i { font-size: 15px; }
.profile-action-tabs button span { font-size: 10px; font-weight: 700; }
.profile-action-tabs button:active { background: var(--surface, #fff); color: var(--navy); }
.profile-action-tabs button:hover { background: var(--surface, #fff); color: var(--teal); box-shadow: 0 1px 4px rgba(20,25,40,0.06); }
.qty-stepper { display: flex; align-items: center; gap: 8px; background: var(--teal); border-radius: 8px; padding: 3px 6px; }
.qty-stepper button { background: transparent; border: none; color: #fff; width: 22px; height: 22px; font-size: 13px; }
.qty-stepper .qty-val { color: #fff; font-weight: 700; font-size: 12.5px; min-width: 14px; text-align: center; }

/* ---- Floating cart bar ---- */
.floating-cart {
    display: none; position: fixed; bottom: 78px; left: 50%; transform: translateX(-50%); width: calc(100% - 32px); max-width: 448px;
    background: var(--navy); color: #fff; border-radius: 12px; padding: 14px 18px; align-items: center; justify-content: space-between;
    box-shadow: 0 8px 24px rgba(22,48,92,0.35); z-index: 25; border: none; font-family: inherit;
}
.floating-cart.show { display: flex; }
.floating-cart .fc-count { background: var(--gold); font-size: 11px; font-weight: 800; padding: 3px 8px; border-radius: 100px; margin-right: 8px; }
.floating-cart .fc-total { font-weight: 800; font-size: 14px; }
.floating-cart .fc-label { font-size: 13px; font-weight: 700; display: flex; align-items: center; }

/* ---- Bottom sheet (Cart / Checkout / Success) ---- */
.sheet-overlay { display: none; position: fixed; inset: 0; background: rgba(10,14,25,0.5); z-index: 40; }
.sheet-overlay.open { display: block; }
.sheet {
    position: fixed; left: 50%; bottom: 0; transform: translateX(-50%); width: 100%; max-width: 480px;
    background: var(--surface); border-radius: 18px 18px 0 0; max-height: 88vh; overflow-y: auto;
    padding: 18px 18px calc(18px + env(safe-area-inset-bottom));
}
.sheet-handle { width: 40px; height: 4px; background: var(--border); border-radius: 4px; margin: 0 auto 14px; }
.sheet-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
.sheet-head h3 { font-size: 16px; margin: 0; }
.sheet-close { background: var(--bg); border: none; width: 30px; height: 30px; border-radius: 8px; color: var(--muted); }

.cart-row { display: flex; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid var(--border); }
.cart-row .cr-name { flex: 1; font-size: 12.5px; font-weight: 600; }
.cart-row .cr-price { font-size: 11px; color: var(--muted); }
.cart-summary-row { display: flex; justify-content: space-between; font-size: 12.5px; padding: 5px 0; color: var(--muted); }
.cart-summary-row.total { font-size: 15px; font-weight: 800; color: var(--text); border-top: 1px solid var(--border); margin-top: 6px; padding-top: 10px; }

.form-group { margin-bottom: 12px; }
.form-group label { display: block; font-size: 11.5px; font-weight: 700; color: var(--muted); margin-bottom: 5px; text-transform: uppercase; letter-spacing: 0.03em; }
.form-control { width: 100%; padding: 11px 13px; border: 1px solid var(--border); border-radius: 9px; font-size: 13.5px; font-family: inherit; background: var(--bg); }
.order-type-toggle { display: flex; gap: 8px; margin-bottom: 14px; }
.order-type-toggle button { flex: 1; padding: 11px; border-radius: 9px; border: 1.5px solid var(--border); background: var(--surface); font-weight: 700; font-size: 13px; color: var(--muted); }
.order-type-toggle button.active { border-color: var(--navy); background: var(--navy); color: #fff; }

.big-btn { width: 100%; padding: 14px; border-radius: 10px; border: none; font-weight: 800; font-size: 14px; background: var(--teal); color: #fff; }
.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; }

/* ---- In-app order tracking view ---- */
.trk-status-badge { display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border-radius: 100px; font-size: 12.5px; font-weight: 700; margin-bottom: 14px; }
.trk-pending { background: #EEF0F5; color: #7A8194; }
.trk-confirmed { background: #EAF1FB; color: #2E5FB0; }
.trk-preparing, .trk-ready { background: #FDF3E4; color: #8A611F; }
.trk-out_for_delivery { background: #EAF1FB; color: #2E5FB0; }
.trk-completed { background: #EEF3EA; color: #3D5830; }
.trk-cancelled { background: #FBEBEB; color: #8A2A2A; }
.trk-progress-track { width: 100%; height: 7px; background: var(--bg); border-radius: 100px; overflow: hidden; margin-top: 6px; }
.trk-progress-fill { height: 100%; background: linear-gradient(90deg, #4B6B3A, var(--teal)); border-radius: 100px; transition: width 0.4s ease; }
.trk-progress-pct { font-size: 11px; color: var(--muted); margin-top: 5px; text-align: right; }
.trk-stepper { display: flex; align-items: flex-start; margin: 18px 0 4px; overflow-x: auto; padding-bottom: 4px; }
.trk-step { display: flex; flex-direction: column; align-items: center; flex: 1; min-width: 64px; position: relative; gap: 6px; }
.trk-step:not(:last-child)::after { content: ''; position: absolute; top: 15px; left: 50%; width: 100%; height: 2px; background: var(--border); z-index: 0; }
.trk-step.done:not(:last-child)::after { background: #4B6B3A; }
.trk-node { width: 30px; height: 30px; border-radius: 50%; background: var(--bg); color: var(--muted); display: flex; align-items: center; justify-content: center; font-size: 12px; position: relative; z-index: 1; }
.trk-step.done .trk-node { background: #4B6B3A; color: #fff; }
.trk-step.current .trk-node { background: var(--teal); color: #fff; box-shadow: 0 0 0 4px rgba(29,122,140,0.15); }
.trk-label { font-size: 9.5px; font-weight: 700; text-align: center; color: var(--muted); }
.trk-step.done .trk-label, .trk-step.current .trk-label { color: var(--text); }
.trk-time { font-size: 8.5px; color: var(--muted); text-align: center; }
.trk-live-note { display: flex; align-items: center; gap: 6px; font-size: 10.5px; color: var(--muted); margin-bottom: 4px; }

/* ---- Item detail popup ---- */
.item-detail-img { width: 100%; height: 220px; border-radius: 12px; background: #EEF0F5; background-size: cover; background-position: center; display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: 40px; margin-bottom: 16px; }
.item-detail-name { font-size: 19px; font-weight: 800; margin-bottom: 4px; }
.item-detail-price { font-size: 16px; font-weight: 800; color: var(--navy); margin-bottom: 12px; }
.item-detail-desc { font-size: 13px; color: var(--text); line-height: 1.6; margin-bottom: 18px; }
.item-detail-qty-row { display: flex; align-items: center; justify-content: space-between; background: var(--bg); border-radius: 10px; padding: 10px 14px; margin-bottom: 14px; }
.item-detail-qty-row .qty-stepper { background: var(--teal); }

/* ---- Promotions slideshow (Home tab) ---- */
.promo-slideshow { position: relative; border-radius: 14px; overflow: hidden; }
.promo-track { display: flex; transition: transform 0.45s ease; }
.promo-slide {
    flex: 0 0 100%; min-height: 150px; background: linear-gradient(120deg, var(--navy), var(--navy-2));
    background-size: cover; background-position: center; color: #fff; padding: 22px 18px;
    display: flex; flex-direction: column; justify-content: center; position: relative;
}
.promo-slide::before { content: ''; position: absolute; inset: 0; background: linear-gradient(0deg, rgba(14,31,66,0.75), rgba(14,31,66,0.35)); }
.promo-slide.no-image::before { display: none; }
.promo-slide.promo-image-only::before { display: none; }
.promo-slide > * { position: relative; z-index: 1; }
.promo-eyebrow { font-family: 'Fraunces', serif; font-size: 20px; font-weight: 700; margin-bottom: 4px; }
.promo-subtitle { font-size: 12.5px; color: rgba(255,255,255,0.85); margin-bottom: 16px; }
.promo-btn { background: var(--gold); width: auto; padding: 10px 20px; align-self: flex-start; }
.promo-dots { position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%); display: flex; gap: 6px; z-index: 2; }
.promo-dot { width: 6px; height: 6px; border-radius: 50%; background: rgba(255,255,255,0.4); transition: all 0.25s ease; cursor: pointer; }
.promo-dot.active { background: #fff; width: 18px; border-radius: 4px; }

.success-view { text-align: center; padding: 20px 10px; }
.success-view .icon { font-size: 46px; color: var(--success); margin-bottom: 12px; }
.success-view h3 { font-size: 18px; margin-bottom: 6px; }
.success-view p { font-size: 13px; color: var(--muted); margin-bottom: 20px; }

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

<div id="rmsSplashScreen">
    <div class="splash-icon">
        <?php if ($logoUrl): ?>
        <img src="<?= e($logoUrl) ?>" alt="<?= e($companyName) ?>">
        <?php else: ?>
        <i class="fa-solid fa-bowl-rice"></i>
        <?php endif; ?>
    </div>
    <div class="splash-title"><?= e($companyName) ?></div>
    <div class="splash-sub">Order Online</div>
    <div class="splash-spinner"></div>
    <div class="splash-footer">Powered by MJ Systems 1.2V</div>
</div>

<div class="app">
    <div class="app-header">
        <div class="brand">
            <div class="brand-logo">
                <?php if ($logoUrl): ?>
                <img src="<?= e($logoUrl) ?>" alt="<?= e($companyName) ?>">
                <?php else: ?>
                <i class="fa-solid fa-bowl-rice"></i>
                <?php endif; ?>
            </div>
            <div>
                <h1 id="rmsGreetingName">Hi there!</h1>
                <div class="sub"><span class="live-dot"></span> <span id="rmsGreetingText">Welcome</span> · <span id="rmsOnlineStatus">Online</span></div>
            </div>
        </div>
        <div style="display:flex;gap:8px;">
            <button class="cart-btn" onclick="rmsOpenSheet('cart')">
                <i class="fa-solid fa-basket-shopping"></i>
                <span class="badge" id="rmsCartBadge" style="display:none;">0</span>
            </button>
        </div>
    </div>

    <div class="install-banner" id="rmsInstallBanner">
        <i class="fa-solid fa-mobile-screen-button"></i>
        <span>Install this app for faster ordering</span>
        <button onclick="rmsInstallApp()">Install</button>
        <button class="ib-close" onclick="document.getElementById('rmsInstallBanner').classList.remove('show'); localStorage.setItem('currypot_install_dismissed', '1');"><i class="fa-solid fa-xmark"></i></button>
    </div>

    <div class="closed-banner" id="rmsClosedBanner" style="display:none;">
        <i class="fa-solid fa-circle-xmark"></i>
        <span id="rmsClosedBannerText">We're currently closed.</span>
    </div>

    <!-- HOME TAB -->
    <div id="rmsTabHome">
        <div class="menu-section">
            <div class="promo-slideshow" id="rmsPromoSlideshow" style="margin-top:10px;">
                <div class="promo-track" id="rmsPromoTrack"></div>
                <div class="promo-dots" id="rmsPromoDots"></div>
            </div>

            <h2 style="margin-top:20px;">Categories</h2>
            <div id="rmsHomeCategories" style="display:flex;flex-wrap:wrap;gap:8px;"></div>

            <h2 style="margin-top:20px;">Today's Menu</h2>
            <div id="rmsHomeTodaysMenu">
                <div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>
            </div>
        </div>
    </div>

    <!-- MENU TAB -->
    <div id="rmsTabMenu" style="display:none;">
        <div class="cat-tabs" id="rmsCatTabs"></div>
        <div class="menu-section" id="rmsMenuSection">
            <div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading menu...</div>
        </div>
    </div>

    <!-- ORDERS TAB -->
    <div id="rmsTabOrders" style="display:none;">
        <div class="menu-section">
            <h2 style="margin-top:14px;">My Orders</h2>
            <div id="rmsOrdersTabContent"></div>
        </div>
    </div>
</div>

<button class="floating-cart" id="rmsFloatingCart" onclick="rmsOpenSheet('cart')">
    <span class="fc-label"><span class="fc-count" id="rmsFcCount">0</span> View Cart</span>
    <span class="fc-total" id="rmsFcTotal">Rs. 0</span>
</button>

<div class="bottom-nav">
    <button id="rmsNavHome" class="active" onclick="rmsSwitchTab('home')"><i class="fa-solid fa-house"></i> Home</button>
    <button id="rmsNavMenu" onclick="rmsSwitchTab('menu')"><i class="fa-solid fa-utensils"></i> Menu</button>
    <button id="rmsNavOrders" onclick="rmsSwitchTab('orders')"><i class="fa-solid fa-receipt"></i> Orders</button>
    <button id="rmsNavAccount" onclick="rmsOpenAccountSheet()"><i class="fa-solid fa-user"></i> Account</button>
</div>

<!-- Cart / Checkout / Success bottom sheet -->
<div class="sheet-overlay" id="rmsSheetOverlay" onclick="if(event.target===this) rmsCloseSheet()">
    <div class="sheet" onclick="event.stopPropagation()">
        <div class="sheet-handle"></div>

        <!-- CART VIEW -->
        <div id="rmsCartView">
            <div class="sheet-head"><h3>Your Cart</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div id="rmsCartRows"></div>
            <div id="rmsCartEmpty" class="empty-state" style="display:none;"><i class="fa-solid fa-basket-shopping" style="font-size:26px;display:block;margin-bottom:8px;"></i>Your cart is empty.</div>
            <div id="rmsCartSummary" style="margin-top:10px;"></div>
            <button class="big-btn" style="margin-top:14px;" id="rmsGoCheckoutBtn" onclick="rmsOpenSheet('checkout')" disabled>Proceed to Checkout</button>
        </div>

        <!-- CHECKOUT VIEW -->
        <div id="rmsCheckoutView" style="display:none;">
            <div class="sheet-head"><h3>Checkout</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div class="error-banner" id="rmsCheckoutError"></div>

            <div id="rmsCheckoutLoggedInBanner" style="display:none;background:var(--bg);border-radius:9px;padding:10px 12px;font-size:12px;margin-bottom:12px;">
                <i class="fa-solid fa-circle-check" style="color:var(--success);"></i> Ordering as <strong id="rmsCheckoutLoggedInName"></strong>
            </div>
            <div id="rmsGuestLoginPrompt" style="display:none;">
                <div class="empty-state" style="padding:20px 10px;background:var(--bg);border-radius:10px;margin-bottom:16px;">
                    <i class="fa-solid fa-lock" style="font-size:26px;display:block;margin-bottom:10px;"></i>
                    Please log in or create an account to place your order.
                    <div style="display:flex;gap:8px;margin-top:14px;">
                        <button class="big-btn" onclick="rmsShowAuthView('rmsLoginView')">Log In</button>
                        <button class="big-btn" style="background:var(--surface,#fff);color:var(--text);border:1.5px solid var(--border);" onclick="rmsShowAuthView('rmsRegisterView')">Create Account</button>
                    </div>
                </div>
            </div>
            <div id="rmsCheckoutFields">

            <div class="form-group">
                <label>Delivery Area</label>
                <select id="rmsZoneSelect" class="form-control" onchange="rmsRenderCartSummary()"><option value="">Loading areas...</option></select>
            </div>
            <div class="form-group"><label>Delivery Address</label><textarea id="rmsAddress" class="form-control" rows="2" placeholder="House no, street, landmark"></textarea></div>

            <label style="display:block; font-size: 11.5px; font-weight: 700; color: var(--muted); margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.03em;">Payment Method</label>
            <div class="order-type-toggle" style="margin-bottom:10px;">
                <button type="button" id="rmsPayCard" onclick="rmsSetPaymentMethod('CARD')"><i class="fa-solid fa-credit-card"></i> Card</button>
                <button type="button" id="rmsPayBank" onclick="rmsSetPaymentMethod('BANK_TRANSFER')"><i class="fa-solid fa-building-columns"></i> Bank</button>
                <button type="button" id="rmsPayCod" onclick="rmsSetPaymentMethod('COD')"><i class="fa-solid fa-money-bill-wave"></i> COD</button>
            </div>

            <div id="rmsPaymentInfoBox" style="background:var(--bg);border-radius:9px;padding:12px 14px;font-size:12px;color:var(--muted);margin-bottom:14px;"></div>

            <div id="rmsBankProofFields" style="display:none;">
                <div class="form-group">
                    <label>Transfer Reference Number</label>
                    <input type="text" id="rmsPaymentReference" class="form-control" placeholder="e.g. Bank slip / transaction reference">
                </div>
                <div class="form-group">
                    <label>Deposit Slip Photo</label>
                    <div id="rmsSlipPreviewWrap" style="display:none;margin-bottom:8px;">
                        <img id="rmsSlipPreview" style="width:100%;max-height:180px;object-fit:contain;border-radius:8px;border:1px solid var(--border);background:#fff;">
                    </div>
                    <label for="rmsSlipInput" style="display:flex;align-items:center;justify-content:center;gap:8px;padding:14px;border:1.5px dashed var(--border);border-radius:9px;color:var(--muted);font-weight:700;font-size:12.5px;cursor:pointer;">
                        <i class="fa-solid fa-camera"></i> <span id="rmsSlipLabel">Take Photo / Upload Slip</span>
                    </label>
                    <input type="file" id="rmsSlipInput" accept="image/*" capture="environment" style="display:none;" onchange="rmsHandleSlipUpload(event)">
                </div>
            </div>

            <div class="form-group"><label>Notes (optional)</label><input type="text" id="rmsOrderNotes" class="form-control" placeholder="e.g. Less spicy, no onions"></div>

            <div id="rmsCheckoutSummary" style="margin-top:8px;"></div>
            <button class="big-btn" style="margin-top:14px;" id="rmsPlaceOrderBtn" onclick="rmsPlaceOrder()">Place Order</button>
            </div>
        </div>

        <!-- SUCCESS VIEW -->
        <div id="rmsSuccessView" style="display:none;">
            <div class="success-view">
                <i class="fa-solid fa-circle-check icon"></i>
                <h3>Order Placed!</h3>
                <p>Order <strong id="rmsSuccessOrderNum"></strong> has been sent to the kitchen.</p>
                <button class="big-btn" id="rmsSuccessTrackBtn" onclick="rmsOpenTrack(document.getElementById('rmsSuccessOrderNum').textContent)">Track My Order</button>
                <button class="big-btn" style="background:var(--bg);color:var(--text);margin-top:10px;" onclick="rmsCloseSheet()">Continue Browsing</button>
            </div>
        </div>

        <!-- IN-APP ORDER TRACKING VIEW -->
        <div id="rmsTrackView" style="display:none;">
            <div class="sheet-head"><h3>Track Order</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div id="rmsTrackContent"><div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div></div>
        </div>

        <!-- ITEM DETAIL POPUP -->
        <div id="rmsItemDetailView" style="display:none;">
            <div class="sheet-head"><h3>Item Details</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div id="rmsItemDetailContent"></div>
        </div>

        <!-- PAYMENT HISTORY VIEW -->
        <div id="rmsPaymentHistoryView" style="display:none;">
            <div class="sheet-head"><h3>Payment History</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div id="rmsPaymentHistoryContent"><div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div></div>
        </div>

        <!-- ACCOUNT VIEW (logged in: profile + my orders / logged out: prompt) -->
        <div id="rmsAccountView" style="display:none;">
            <div class="sheet-head"><h3>My Account</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div id="rmsAccountLoggedOut" style="display:none;">
                <div class="empty-state" style="padding:20px 10px;">
                    <i class="fa-solid fa-user-circle" style="font-size:32px;display:block;margin-bottom:10px;"></i>
                    Log in to track your orders faster and skip re-typing your details every time.
                </div>
                <button class="big-btn" onclick="rmsShowAuthView('rmsLoginView')">Log In</button>
                <button class="big-btn" style="background:var(--bg);color:var(--text);margin-top:10px;" onclick="rmsShowAuthView('rmsRegisterView')">Create an Account</button>
            </div>
            <div id="rmsAccountLoggedIn" style="display:none;">
                <div class="profile-hero">
                    <div class="profile-avatar-ring">
                        <div class="profile-avatar" id="rmsAccountAvatar"></div>
                    </div>
                    <div class="profile-name" id="rmsAccountName"></div>
                    <div class="profile-phone" id="rmsAccountPhone"></div>
                </div>

                <div style="display:flex;gap:8px;margin:14px 0;">
                    <div style="flex:1;background:var(--bg);border-radius:10px;padding:12px 10px;text-align:center;">
                        <div style="font-size:16px;font-weight:800;color:var(--navy);" id="rmsStatOrderCount">0</div>
                        <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;">Orders</div>
                    </div>
                    <div style="flex:1;background:var(--bg);border-radius:10px;padding:12px 10px;text-align:center;">
                        <div style="font-size:16px;font-weight:800;color:var(--navy);" id="rmsStatTotalSpent">Rs. 0</div>
                        <div style="font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;">Total Spent</div>
                    </div>
                </div>

                <div class="profile-details-card" id="rmsProfileDetailsCard"></div>

                <div class="profile-action-tabs">
                    <button onclick="rmsOpenEditProfile()"><i class="fa-solid fa-user-pen"></i><span>Edit Profile</span></button>
                    <button onclick="rmsShowAuthView('rmsChangePasswordView')"><i class="fa-solid fa-key"></i><span>Password</span></button>
                    <button onclick="rmsOpenPaymentHistory()"><i class="fa-solid fa-receipt"></i><span>Payments</span></button>
                </div>

                <button class="big-btn" style="background:var(--bg);color:var(--danger);" onclick="rmsLogout()"><i class="fa-solid fa-right-from-bracket"></i> Log Out</button>
            </div>
        </div>

        <!-- LOGIN VIEW -->
        <div id="rmsLoginView" style="display:none;">
            <div class="sheet-head"><h3>Log In</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div class="error-banner" id="rmsLoginError"></div>
            <form onsubmit="rmsDoLogin(); return false;">
            <div class="form-group"><label>Phone Number</label><input type="tel" id="rmsLoginPhone" class="form-control" placeholder="07XXXXXXXX" autocomplete="username"></div>
            <div class="form-group"><label>Password</label><input type="password" id="rmsLoginPassword" class="form-control" placeholder="Your password" autocomplete="current-password"></div>
            <button type="submit" class="big-btn" id="rmsLoginBtn">Log In</button>
            </form>
            <div style="text-align:center;margin-top:14px;font-size:12.5px;">
                <a href="javascript:void(0)" onclick="rmsShowAuthView('rmsForgotView')" style="color:var(--teal);">Forgot password?</a>
                &nbsp;·&nbsp;
                <a href="javascript:void(0)" onclick="rmsShowAuthView('rmsRegisterView')" style="color:var(--teal);">Create an account</a>
            </div>
        </div>

        <!-- REGISTER VIEW -->
        <div id="rmsRegisterView" style="display:none;">
            <div class="sheet-head"><h3>Create Account</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div class="error-banner" id="rmsRegisterError"></div>
            <form onsubmit="rmsDoRegister(); return false;">
            <div class="form-group"><label>Full Name</label><input type="text" id="rmsRegName" class="form-control" placeholder="Your name" autocomplete="name"></div>
            <div class="form-group"><label>Phone Number</label><input type="tel" id="rmsRegPhone" class="form-control" placeholder="07XXXXXXXX" autocomplete="username"></div>
            <div class="form-group"><label>Email (optional)</label><input type="email" id="rmsRegEmail" class="form-control" placeholder="you@example.com" autocomplete="email"></div>
            <div class="form-group"><label>Password</label><input type="password" id="rmsRegPassword" class="form-control" placeholder="At least 6 characters" autocomplete="new-password"></div>
            <button type="submit" class="big-btn" id="rmsRegisterBtn">Create Account</button>
            </form>
            <div style="text-align:center;margin-top:14px;font-size:12.5px;">
                Already have an account? <a href="javascript:void(0)" onclick="rmsShowAuthView('rmsLoginView')" style="color:var(--teal);">Log in</a>
            </div>
        </div>

        <!-- FORGOT PASSWORD VIEW -->
        <div id="rmsForgotView" style="display:none;">
            <div class="sheet-head"><h3>Reset Password</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div class="error-banner" id="rmsForgotError"></div>
            <div id="rmsForgotStep1">
                <div style="font-size:12.5px;color:var(--muted);margin-bottom:12px;">Enter your phone number and we'll generate a reset code.</div>
                <form onsubmit="rmsDoForgotPassword(); return false;">
                <div class="form-group"><label>Phone Number</label><input type="tel" id="rmsForgotPhone" class="form-control" placeholder="07XXXXXXXX" autocomplete="username"></div>
                <button type="submit" class="big-btn" id="rmsForgotBtn">Send Reset Code</button>
                </form>
            </div>
            <div id="rmsForgotStep2" style="display:none;">
                <div class="error-banner show" style="background:#EAF1FB;color:#2E5FB0;" id="rmsForgotDebugNote"></div>
                <form onsubmit="rmsDoResetPassword(); return false;">
                <div class="form-group"><label>Reset Code</label><input type="text" id="rmsResetToken" class="form-control" placeholder="Paste the code"></div>
                <div class="form-group"><label>New Password</label><input type="password" id="rmsResetPassword" class="form-control" placeholder="At least 6 characters" autocomplete="new-password"></div>
                <button type="submit" class="big-btn" id="rmsResetBtn">Reset Password</button>
                </form>
            </div>
            <div style="text-align:center;margin-top:14px;font-size:12.5px;">
                <a href="javascript:void(0)" onclick="rmsShowAuthView('rmsLoginView')" style="color:var(--teal);">Back to Log In</a>
            </div>
        </div>

        <!-- EDIT PROFILE VIEW -->
        <div id="rmsEditProfileView" style="display:none;">
            <div class="sheet-head"><h3>Edit Profile</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div class="error-banner" id="rmsEditProfileError"></div>

            <div style="display:flex;flex-direction:column;align-items:center;margin-bottom:16px;">
                <div style="position:relative;width:80px;height:80px;">
                    <div id="rmsProfilePicPreviewWrap" style="width:80px;height:80px;border-radius:50%;overflow:hidden;background:var(--navy);display:flex;align-items:center;justify-content:center;">
                        <span id="rmsProfilePicInitial" style="color:#fff;font-size:26px;font-weight:800;"></span>
                        <img id="rmsProfilePicImg" style="display:none;width:100%;height:100%;object-fit:cover;">
                    </div>
                    <label for="rmsProfilePicInput" style="position:absolute;bottom:-2px;right:-2px;width:28px;height:28px;border-radius:50%;background:var(--teal);color:#fff;display:flex;align-items:center;justify-content:center;font-size:12px;cursor:pointer;border:2px solid #fff;">
                        <i class="fa-solid fa-camera"></i>
                    </label>
                    <input type="file" id="rmsProfilePicInput" accept="image/*" style="display:none;" onchange="rmsHandleProfilePicUpload(event)">
                </div>
                <div style="font-size:11px;color:var(--muted);margin-top:8px;">Tap the camera to update your photo</div>
            </div>

            <div class="form-group"><label>Full Name</label><input type="text" id="rmsEditProfileName" class="form-control"></div>
            <div class="form-group"><label>Date of Birth</label><input type="date" id="rmsEditProfileDob" class="form-control"></div>
            <div class="form-group"><label>Email</label><input type="email" id="rmsEditProfileEmail" class="form-control" placeholder="you@example.com"></div>
            <div class="form-group"><label>Default Delivery Address</label><textarea id="rmsEditProfileAddress" class="form-control" rows="2" placeholder="Saved for faster checkout"></textarea></div>
            <div style="font-size:11.5px;color:var(--muted);margin-bottom:14px;"><i class="fa-solid fa-lock"></i> Phone number can't be changed since it's your login ID. Contact us if it needs updating.</div>
            <button class="big-btn" id="rmsSaveProfileBtn" onclick="rmsDoUpdateProfile()">Save Changes</button>
        </div>

        <!-- CHANGE PASSWORD VIEW -->
        <div id="rmsChangePasswordView" style="display:none;">
            <div class="sheet-head"><h3>Change Password</h3><button class="sheet-close" onclick="rmsCloseSheet()"><i class="fa-solid fa-xmark"></i></button></div>
            <div class="error-banner" id="rmsChangePasswordError"></div>
            <form onsubmit="rmsDoChangePassword(); return false;">
            <div class="form-group"><label>Current Password</label><input type="password" id="rmsCurrentPassword" class="form-control" autocomplete="current-password"></div>
            <div class="form-group"><label>New Password</label><input type="password" id="rmsNewPassword" class="form-control" placeholder="At least 6 characters" autocomplete="new-password"></div>
            <div class="form-group"><label>Confirm New Password</label><input type="password" id="rmsConfirmNewPassword" class="form-control" autocomplete="new-password"></div>
            <button type="submit" class="big-btn" id="rmsSavePasswordBtn">Update Password</button>
            </form>
        </div>
    </div>
</div>

<script src="https://www.payhere.lk/lib/payhere.js"></script>
<script>
const API_BASE = "<?= BASE_URL ?>/api";
let rmsMenu = [];
let rmsZones = [];
let rmsCart = JSON.parse(localStorage.getItem('currypot_cart') || '[]');
let rmsOrderType = 'ONLINE_DELIVERY';
let rmsCurrentCustomer = null;

// ---- Check login state on load ----
let rmsCurrentStats = { order_count: 0, total_spent: 0 };

function rmsCheckAuthState() {
    fetch(API_BASE + '/auth/me').then(r => r.json()).then(data => {
        rmsCurrentCustomer = (data.success && data.loggedIn) ? data.customer : null;
        rmsCurrentStats = (data.success && data.loggedIn && data.stats) ? data.stats : { order_count: 0, total_spent: 0 };
        rmsUpdateAuthUI();
    }).catch(() => {});
}
function rmsUpdateAuthUI() {
    rmsUpdateGreeting();
}

function rmsGreetingPhrase() {
    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 rmsUpdateGreeting() {
    const nameEl = document.getElementById('rmsGreetingName');
    const textEl = document.getElementById('rmsGreetingText');
    if (nameEl) nameEl.textContent = rmsCurrentCustomer ? `Hi, ${rmsCurrentCustomer.name}!` : 'Hi there!';
    if (textEl) textEl.textContent = rmsGreetingPhrase();
}
rmsUpdateGreeting();
setInterval(rmsUpdateGreeting, 60000); // keep the greeting accurate as time passes while the app stays open

let rmsDeviceOnline = navigator.onLine;
let rmsStoreOpen = true; // updated by rmsCheckStoreStatus() below
let rmsLastKnownOpenState = null; // tracks transitions so the popup only fires once per change

function rmsRenderOnlineIndicator() {
    const el = document.getElementById('rmsOnlineStatus');
    const dot = document.querySelector('.app-header .live-dot');
    if (!el) return;

    if (!rmsDeviceOnline) {
        el.textContent = 'No Internet'; el.style.color = '#E8A0A0';
        if (dot) dot.style.background = '#B23A3A';
    } else if (!rmsStoreOpen) {
        el.textContent = 'Offline'; el.style.color = '#E8A0A0';
        if (dot) dot.style.background = '#B23A3A';
    } else {
        el.textContent = 'Online'; el.style.color = '';
        if (dot) dot.style.background = '#4B6B3A';
    }
}
window.addEventListener('online', () => { rmsDeviceOnline = true; rmsRenderOnlineIndicator(); });
window.addEventListener('offline', () => { rmsDeviceOnline = false; rmsRenderOnlineIndicator(); });
rmsRenderOnlineIndicator();

// ---- Toast popup (small, auto-dismissing message) ----
function rmsShowToast(message, isError) {
    let toast = document.getElementById('rmsToast');
    if (!toast) {
        toast = document.createElement('div');
        toast.id = 'rmsToast';
        toast.className = 'rms-toast';
        document.body.appendChild(toast);
    }
    toast.textContent = message;
    toast.className = 'rms-toast show' + (isError ? ' error' : '');
    clearTimeout(rmsShowToast._timer);
    rmsShowToast._timer = setTimeout(() => { toast.classList.remove('show'); }, 4000);
}

// ---- Store open/closed status (order hours) ----
function rmsCheckStoreStatus() {
    fetch(API_BASE + '/store-status').then(r => r.json()).then(data => {
        if (!data.success) return;
        rmsStoreOpen = data.is_open;
        rmsRenderOnlineIndicator();

        const banner = document.getElementById('rmsClosedBanner');
        if (!data.is_open) {
            document.getElementById('rmsClosedBannerText').textContent = data.message;
            banner.style.display = 'flex';
        } else {
            banner.style.display = 'none';
        }

        // Pop up a small toast only when the state actually changes (not on every 60s poll)
        if (rmsLastKnownOpenState !== null && rmsLastKnownOpenState !== data.is_open) {
            rmsShowToast(data.is_open ? "We're back online — you can order now!" : (data.message || "We're currently closed."), !data.is_open);
        } else if (rmsLastKnownOpenState === null && !data.is_open) {
            // First check on page load — still worth telling them if already closed
            rmsShowToast(data.message || "We're currently closed.", true);
        }
        rmsLastKnownOpenState = data.is_open;
    }).catch(() => {});
}
rmsCheckStoreStatus();
setInterval(rmsCheckStoreStatus, 60000);

rmsCheckAuthState();
setInterval(rmsCheckAuthState, 90000); // heartbeat — keeps "last active" fresh for the Online Now count on the admin Dashboard

// ---- Bottom nav tab switching ----
let rmsOrdersPollTimer = null;

function rmsSwitchTab(tab) {
    ['Home', 'Menu', 'Orders'].forEach(t => {
        document.getElementById('rmsTab' + t).style.display = (t.toLowerCase() === tab) ? 'block' : 'none';
    });
    ['rmsNavHome', 'rmsNavMenu', 'rmsNavOrders'].forEach(id => document.getElementById(id).classList.remove('active'));
    document.getElementById('rmsNav' + tab.charAt(0).toUpperCase() + tab.slice(1)).classList.add('active');
    window.scrollTo({ top: 0, behavior: 'smooth' });

    clearInterval(rmsOrdersPollTimer);
    if (tab === 'orders') {
        rmsLoadOrdersTab();
        // Live refresh order statuses every 12s while this tab is open — stops automatically when leaving
        rmsOrdersPollTimer = setInterval(() => { if (rmsCurrentCustomer) rmsLoadOrdersTab(true); }, 12000);
    }
}

function rmsLoadOrdersTab(isBackgroundRefresh) {
    const el = document.getElementById('rmsOrdersTabContent');
    if (!rmsCurrentCustomer) {
        el.innerHTML = `<div class="empty-state" style="padding:24px 10px;">
            <i class="fa-solid fa-lock" style="font-size:26px;display:block;margin-bottom:10px;"></i>
            Log in to see your order history.
            <div style="margin-top:14px;"><button class="big-btn" style="width:auto;padding:10px 24px;" onclick="rmsShowAuthView('rmsLoginView'); document.getElementById('rmsSheetOverlay').classList.add('open');">Log In</button></div>
        </div>`;
        return;
    }
    if (!isBackgroundRefresh) {
        el.innerHTML = '<div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>';
    }
    fetch(API_BASE + '/orders/mine').then(r => r.json()).then(data => {
        if (!data.success || data.orders.length === 0) {
            el.innerHTML = '<div class="empty-state" style="padding:16px 0;">No orders yet — your order history will show up here.</div>';
            return;
        }
        el.innerHTML = data.orders.map(o => {
            const isFinished = o.status === 'COMPLETED' || o.status === 'CANCELLED';
            const btnLabel = isFinished ? 'View My Order' : 'Track My Order';
            return `
            <div class="item-card" style="display:block;">
                <div style="display:flex;justify-content:space-between;align-items:center;">
                    <strong style="font-size:13px;">${o.order_number}</strong>
                    <span style="font-size:11px;color:var(--teal);font-weight:700;">${o.status_label}</span>
                </div>
                <div style="font-size:11.5px;color:var(--muted);margin-top:4px;">${o.item_count} items · Rs. ${o.total_amount.toFixed(2)} · ${o.created_at}</div>
                <div style="margin-top:10px;">
                    <a href="javascript:void(0)" onclick="rmsOpenTrack('${o.order_number}')" style="display:block;text-align:center;padding:8px;border-radius:7px;background:var(--bg);color:var(--navy);font-size:11.5px;font-weight:700;text-decoration:none;">${btnLabel}</a>
                </div>
            </div>
        `;
        }).join('');
    }).catch(() => {
        if (!isBackgroundRefresh) el.innerHTML = '<div class="empty-state" style="padding:16px 0;">Could not load orders.</div>';
    });
}

let rmsAccountPollTimer = null;

function rmsOpenAccountSheet() {
    clearInterval(rmsAccountPollTimer);
    if (rmsCurrentCustomer) {
        document.getElementById('rmsAccountLoggedIn').style.display = 'block';
        document.getElementById('rmsAccountLoggedOut').style.display = 'none';
        document.getElementById('rmsAccountName').textContent = rmsCurrentCustomer.name;
        document.getElementById('rmsAccountPhone').textContent = rmsCurrentCustomer.phone;
        document.getElementById('rmsAccountAvatar').textContent = '';
        rmsUpdateAccountAvatar();
        document.getElementById('rmsStatOrderCount').textContent = rmsCurrentStats.order_count;
        document.getElementById('rmsStatTotalSpent').textContent = 'Rs. ' + rmsCurrentStats.total_spent.toFixed(2);
        rmsRenderProfileDetailsCard();
    } else {
        document.getElementById('rmsAccountLoggedIn').style.display = 'none';
        document.getElementById('rmsAccountLoggedOut').style.display = 'block';
    }
    rmsShowView('rmsAccountView');
    document.getElementById('rmsSheetOverlay').classList.add('open');
}



async function rmsReorder(orderId) {
    try {
        const res = await fetch(API_BASE + '/orders/reorder', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ order_id: orderId }),
        });
        const data = await res.json();
        if (!data.success || data.items.length === 0) { alert('Sorry, those items are no longer available.'); return; }
        data.items.forEach(it => {
            const existing = rmsCart.find(l => l.menu_item_id === it.menu_item_id && l.variant_id === it.variant_id);
            if (existing) existing.quantity += it.quantity;
            else rmsCart.push({ menu_item_id: it.menu_item_id, variant_id: it.variant_id, name: it.name, unit_price: 0, quantity: it.quantity });
        });
        rmsSaveCart();
        rmsUpdateCartUI();
        rmsOpenSheet('cart');
    } catch (e) { alert('Something went wrong reordering.'); }
}

async function rmsDoLogin() {
    const errEl = document.getElementById('rmsLoginError');
    errEl.classList.remove('show');
    const phone = document.getElementById('rmsLoginPhone').value.trim();
    const password = document.getElementById('rmsLoginPassword').value;
    if (!phone || !password) { errEl.textContent = 'Enter your phone and password.'; errEl.classList.add('show'); return; }

    const btn = document.getElementById('rmsLoginBtn'); btn.disabled = true; btn.textContent = 'Logging in...';
    try {
        const res = await fetch(API_BASE + '/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ phone, 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; }
        rmsCurrentCustomer = data.customer;
        rmsUpdateAuthUI();
        rmsOpenAccountSheet();
    } catch (e) { errEl.textContent = 'Network error. Please try again.'; errEl.classList.add('show'); }
    btn.disabled = false; btn.textContent = 'Log In';
}

async function rmsDoRegister() {
    const errEl = document.getElementById('rmsRegisterError');
    errEl.classList.remove('show');
    const name = document.getElementById('rmsRegName').value.trim();
    const phone = document.getElementById('rmsRegPhone').value.trim();
    const email = document.getElementById('rmsRegEmail').value.trim();
    const password = document.getElementById('rmsRegPassword').value;
    if (!name || !phone || !password) { errEl.textContent = 'Please fill in name, phone, and password.'; errEl.classList.add('show'); return; }

    const btn = document.getElementById('rmsRegisterBtn'); btn.disabled = true; btn.textContent = 'Creating account...';
    try {
        const res = await fetch(API_BASE + '/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, phone, email, password }) });
        const data = await res.json();
        if (!data.success) { errEl.textContent = data.message; errEl.classList.add('show'); btn.disabled = false; btn.textContent = 'Create Account'; return; }
        rmsCurrentCustomer = data.customer;
        rmsUpdateAuthUI();
        rmsOpenAccountSheet();
    } catch (e) { errEl.textContent = 'Network error. Please try again.'; errEl.classList.add('show'); }
    btn.disabled = false; btn.textContent = 'Create Account';
}

async function rmsDoForgotPassword() {
    const errEl = document.getElementById('rmsForgotError');
    errEl.classList.remove('show');
    const phone = document.getElementById('rmsForgotPhone').value.trim();
    if (!phone) { errEl.textContent = 'Enter your phone number.'; errEl.classList.add('show'); return; }

    const btn = document.getElementById('rmsForgotBtn'); btn.disabled = true; btn.textContent = 'Sending...';
    try {
        const res = await fetch(API_BASE + '/auth/forgot-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ phone }) });
        const data = await res.json();
        document.getElementById('rmsForgotStep1').style.display = 'none';
        document.getElementById('rmsForgotStep2').style.display = 'block';
        document.getElementById('rmsForgotDebugNote').textContent = data.debug_token
            ? 'SMS isn\'t connected yet — for now, your reset code is: ' + data.debug_token
            : data.message;
        if (data.debug_token) document.getElementById('rmsResetToken').value = data.debug_token;
    } catch (e) { errEl.textContent = 'Network error. Please try again.'; errEl.classList.add('show'); }
    btn.disabled = false; btn.textContent = 'Send Reset Code';
}

async function rmsDoResetPassword() {
    const errEl = document.getElementById('rmsForgotError');
    errEl.classList.remove('show');
    const token = document.getElementById('rmsResetToken').value.trim();
    const password = document.getElementById('rmsResetPassword').value;
    if (!token || !password) { errEl.textContent = 'Enter the reset code and a new password.'; errEl.classList.add('show'); return; }

    const btn = document.getElementById('rmsResetBtn'); btn.disabled = true; btn.textContent = 'Resetting...';
    try {
        const res = await fetch(API_BASE + '/auth/reset-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token, password }) });
        const data = await res.json();
        if (!data.success) { errEl.textContent = data.message; errEl.classList.add('show'); btn.disabled = false; btn.textContent = 'Reset Password'; return; }
        document.getElementById('rmsForgotStep1').style.display = 'block';
        document.getElementById('rmsForgotStep2').style.display = 'none';
        rmsShowAuthView('rmsLoginView');
    } catch (e) { errEl.textContent = 'Network error. Please try again.'; errEl.classList.add('show'); }
    btn.disabled = false; btn.textContent = 'Reset Password';
}

function rmsLogout() {
    fetch(API_BASE + '/auth/logout', { method: 'POST' }).then(() => {
        rmsCurrentCustomer = null;
        rmsUpdateAuthUI();
        rmsCloseSheet();
        if (document.getElementById('rmsTabOrders').style.display !== 'none') rmsLoadOrdersTab();
    });
}

function rmsOpenPaymentHistory() {
    document.getElementById('rmsPaymentHistoryContent').innerHTML = '<div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>';
    rmsShowView('rmsPaymentHistoryView');
    document.getElementById('rmsSheetOverlay').classList.add('open');

    fetch(API_BASE + '/account/payments').then(r => r.json()).then(data => {
        const el = document.getElementById('rmsPaymentHistoryContent');
        if (!data.success) {
            el.innerHTML = '<div class="empty-state">Could not load payment history.</div>';
            return;
        }
        if (data.payments.length === 0) {
            el.innerHTML = '<div class="empty-state" style="padding:20px 0;"><i class="fa-solid fa-receipt" style="font-size:26px;display:block;margin-bottom:8px;"></i>No payments yet.</div>';
            return;
        }

        const statusBadge = { PAID: '<span style="color:#3D5830;font-weight:700;">Paid</span>', PENDING: '<span style="color:#8A611F;font-weight:700;">Pending</span>', REFUNDED: '<span style="color:#8A2A2A;font-weight:700;">Refunded</span>' };

        el.innerHTML = `
            <div style="background:var(--bg);border-radius:10px;padding:12px 14px;margin-bottom:14px;display:flex;justify-content:space-between;align-items:center;">
                <span style="font-size:12px;color:var(--muted);font-weight:700;">Total Paid</span>
                <span style="font-size:16px;font-weight:800;color:var(--navy);">Rs. ${data.total_paid.toFixed(2)}</span>
            </div>
            ${data.payments.map(p => `
                <div class="cart-row" style="align-items:flex-start;">
                    <div style="flex:1;">
                        <div class="cr-name">${p.order_number} <span style="color:var(--muted);font-weight:400;">· ${p.method}</span></div>
                        <div class="cr-price">${p.paid_at}${p.fee_amount > 0 ? ' · Fee Rs. ' + p.fee_amount.toFixed(2) : ''}</div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-weight:700;font-size:13px;">Rs. ${p.amount.toFixed(2)}</div>
                        <div style="font-size:11px;">${statusBadge[p.status] || p.status}</div>
                    </div>
                </div>
            `).join('')}
        `;
    }).catch(() => {
        document.getElementById('rmsPaymentHistoryContent').innerHTML = '<div class="empty-state">Network error loading payment history.</div>';
    });
}

function rmsOpenEditProfile() {
    document.getElementById('rmsEditProfileName').value = rmsCurrentCustomer.name || '';
    document.getElementById('rmsEditProfileEmail').value = rmsCurrentCustomer.email || '';
    document.getElementById('rmsEditProfileAddress').value = rmsCurrentCustomer.address || '';
    document.getElementById('rmsEditProfileDob').value = rmsCurrentCustomer.date_of_birth || '';
    rmsRenderProfilePicPreview();
    rmsShowAuthView('rmsEditProfileView');
}

function rmsRenderProfilePicPreview() {
    const img = document.getElementById('rmsProfilePicImg');
    const initial = document.getElementById('rmsProfilePicInitial');
    if (rmsCurrentCustomer && rmsCurrentCustomer.profile_pic_url) {
        img.src = rmsCurrentCustomer.profile_pic_url;
        img.style.display = 'block';
        initial.style.display = 'none';
    } else {
        img.style.display = 'none';
        initial.style.display = 'block';
        initial.textContent = rmsCurrentCustomer ? rmsCurrentCustomer.name.substring(0, 1).toUpperCase() : '?';
    }
}

async function rmsHandleProfilePicUpload(event) {
    const file = event.target.files[0];
    if (!file) return;
    if (file.size > 4 * 1024 * 1024) { alert('Please choose an image under 4MB.'); event.target.value = ''; return; }

    const reader = new FileReader();
    reader.onload = async function (e) {
        try {
            const res = await fetch(API_BASE + '/auth/upload-profile-pic', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ image_base64: e.target.result }),
            });
            const data = await res.json();
            if (!data.success) { alert(data.message || 'Could not upload photo.'); return; }
            rmsCurrentCustomer = data.customer;
            rmsRenderProfilePicPreview();
            rmsUpdateAccountAvatar();
        } catch (err) { alert('Network error uploading photo.'); }
    };
    reader.readAsDataURL(file);
}

function rmsUpdateAccountAvatar() {
    const wrap = document.getElementById('rmsAccountAvatar');
    if (!wrap) return;
    if (rmsCurrentCustomer && rmsCurrentCustomer.profile_pic_url) {
        wrap.innerHTML = `<img src="${rmsCurrentCustomer.profile_pic_url}" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">`;
    } else {
        wrap.textContent = rmsCurrentCustomer ? rmsCurrentCustomer.name.substring(0, 1).toUpperCase() : '';
    }
}

function rmsFormatDob(dobStr) {
    if (!dobStr) return null;
    const d = new Date(dobStr + 'T00:00:00');
    if (isNaN(d.getTime())) return null;
    return d.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
}

function rmsRenderProfileDetailsCard() {
    const el = document.getElementById('rmsProfileDetailsCard');
    if (!el || !rmsCurrentCustomer) return;
    const c = rmsCurrentCustomer;
    const dobFormatted = rmsFormatDob(c.date_of_birth);

    el.innerHTML = `
        <div class="pd-row">
            <i class="fa-solid fa-phone"></i>
            <div><div class="pd-label">Phone</div><div class="pd-value">${c.phone}</div></div>
        </div>
        <div class="pd-row">
            <i class="fa-solid fa-envelope"></i>
            <div><div class="pd-label">Email</div><div class="pd-value ${c.email ? '' : 'muted'}">${c.email || 'Not added yet'}</div></div>
        </div>
        <div class="pd-row">
            <i class="fa-solid fa-cake-candles"></i>
            <div><div class="pd-label">Date of Birth</div><div class="pd-value ${dobFormatted ? '' : 'muted'}">${dobFormatted || 'Not added yet'}</div></div>
        </div>
        <div class="pd-row">
            <i class="fa-solid fa-location-dot"></i>
            <div><div class="pd-label">Default Delivery Address</div><div class="pd-value ${c.address ? '' : 'muted'}">${c.address || 'Not added yet'}</div></div>
        </div>
    `;
}

async function rmsDoUpdateProfile() {
    const errEl = document.getElementById('rmsEditProfileError');
    errEl.classList.remove('show');
    const name = document.getElementById('rmsEditProfileName').value.trim();
    const email = document.getElementById('rmsEditProfileEmail').value.trim();
    const address = document.getElementById('rmsEditProfileAddress').value.trim();
    const dob = document.getElementById('rmsEditProfileDob').value;
    if (!name) { errEl.textContent = 'Name cannot be empty.'; errEl.classList.add('show'); return; }

    const btn = document.getElementById('rmsSaveProfileBtn'); btn.disabled = true; btn.textContent = 'Saving...';
    try {
        const res = await fetch(API_BASE + '/auth/update-profile', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, email, address, date_of_birth: dob }) });
        const data = await res.json();
        if (!data.success) { errEl.textContent = data.message; errEl.classList.add('show'); btn.disabled = false; btn.textContent = 'Save Changes'; return; }
        rmsCurrentCustomer = data.customer;
        rmsOpenAccountSheet();
    } catch (e) { errEl.textContent = 'Network error. Please try again.'; errEl.classList.add('show'); }
    btn.disabled = false; btn.textContent = 'Save Changes';
}

async function rmsDoChangePassword() {
    const errEl = document.getElementById('rmsChangePasswordError');
    errEl.classList.remove('show');
    const current = document.getElementById('rmsCurrentPassword').value;
    const newPass = document.getElementById('rmsNewPassword').value;
    const confirm = document.getElementById('rmsConfirmNewPassword').value;

    if (!current || !newPass) { errEl.textContent = 'Please fill in all fields.'; errEl.classList.add('show'); return; }
    if (newPass !== confirm) { errEl.textContent = 'New passwords do not match.'; errEl.classList.add('show'); return; }

    const btn = document.getElementById('rmsSavePasswordBtn'); btn.disabled = true; btn.textContent = 'Updating...';
    try {
        const res = await fetch(API_BASE + '/auth/change-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ current_password: current, new_password: newPass }) });
        const data = await res.json();
        if (!data.success) { errEl.textContent = data.message; errEl.classList.add('show'); btn.disabled = false; btn.textContent = 'Update Password'; return; }
        document.getElementById('rmsCurrentPassword').value = '';
        document.getElementById('rmsNewPassword').value = '';
        document.getElementById('rmsConfirmNewPassword').value = '';
        alert('Password updated successfully.');
        rmsOpenAccountSheet();
    } catch (e) { errEl.textContent = 'Network error. Please try again.'; errEl.classList.add('show'); }
    btn.disabled = false; btn.textContent = 'Update Password';
}

function rmsSaveCart() { localStorage.setItem('currypot_cart', JSON.stringify(rmsCart)); }

// ---- Load menu (initial load + periodic live refresh) ----
let rmsMenuLoadedOnce = false;
const rmsSplashStartTime = Date.now();

function rmsHideSplash() {
    const elapsed = Date.now() - rmsSplashStartTime;
    const minDisplayMs = 900; // avoid a jarring flash on fast connections
    const wait = Math.max(0, minDisplayMs - elapsed);
    setTimeout(() => {
        document.getElementById('rmsSplashScreen')?.classList.add('hide');
    }, wait);
}

function rmsFetchMenu(isBackgroundRefresh) {
    fetch(API_BASE + '/menu').then(r => r.json()).then(data => {
        if (!data.success) { if (!isBackgroundRefresh) rmsHideSplash(); return; }

        // Capture which category tab is active BEFORE we wipe and rebuild the tab bar
        const activeTabIndex = [...document.querySelectorAll('#rmsCatTabs .cat-tab')].findIndex(t => t.classList.contains('active'));
        const preserveIndex = activeTabIndex >= 0 ? activeTabIndex : 0;

        rmsMenu = data.categories;
        rmsRenderTabs(preserveIndex);
        rmsRenderMenu(preserveIndex);
        rmsRenderHomeTodaysMenu();
        rmsUpdateCartUI();
        rmsMenuLoadedOnce = true;
        if (!isBackgroundRefresh) rmsHideSplash();
    }).catch(() => {
        if (!isBackgroundRefresh && !rmsMenuLoadedOnce) {
            document.getElementById('rmsMenuSection').innerHTML = '<div class="empty-state"><i class="fa-solid fa-triangle-exclamation" style="font-size:24px;display:block;margin-bottom:8px;"></i>Could not load the menu. Please check your connection.</div>';
        }
        if (!isBackgroundRefresh) rmsHideSplash();
        // Silent fail on background refreshes — keep showing the last known-good menu
    });
}

rmsFetchMenu(false);
setInterval(() => rmsFetchMenu(true), 30000); // live menu/price/availability sync every 30s
setTimeout(rmsHideSplash, 8000); // safety net — never leave the user stuck on the splash screen

fetch(API_BASE + '/zones').then(r => r.json()).then(data => {
    if (!data.success) return;
    rmsZones = data.zones;
    const sel = document.getElementById('rmsZoneSelect');
    sel.innerHTML = '<option value="">— Select your area —</option>' + rmsZones.map(z =>
        `<option value="${z.id}" data-fee="${z.delivery_fee}" data-free="${z.is_free_delivery}">${z.name}${z.is_free_delivery ? ' (Free Delivery)' : ' (Rs.' + z.delivery_fee + ')'}</option>`
    ).join('');
}).catch(() => {});

// ---- Promotions slideshow (Home tab) ----
let rmsPromoIndex = 0;
let rmsPromoAutoTimer = null;
const rmsDefaultPromoSlide = {
    eyebrow: "Welcome to <?= e($companyName) ?>",
    subtitle: <?= json_encode(setting('tagline') ?: "Hurry up! Order now for today's lunch.") ?>,
    button_text: 'Browse Menu', image_url: null,
};

fetch(API_BASE + '/promotions').then(r => r.json()).then(data => {
    const adminSlides = (data.success && data.promotions) ? data.promotions : [];
    rmsRenderPromoSlides([rmsDefaultPromoSlide, ...adminSlides]);
}).catch(() => {
    rmsRenderPromoSlides([rmsDefaultPromoSlide]);
});

function rmsRenderPromoSlides(slides) {
    const track = document.getElementById('rmsPromoTrack');
    const dots = document.getElementById('rmsPromoDots');

    track.innerHTML = slides.map(s => {
        const bg = s.image_url ? `style="background-image:url('${s.image_url}')"` : '';
        if (s.image_url) {
            // Custom promo images already have their own text/design baked in — don't overlay
            // more text on top (that's what was clashing). Just make the whole banner tappable.
            return `<div class="promo-slide promo-image-only" style="background-image:url('${s.image_url}');cursor:pointer;" onclick="rmsSwitchTab('menu')"></div>`;
        }
        return `<div class="promo-slide ${s.image_url ? '' : 'no-image'}">
            <div class="promo-eyebrow">${s.eyebrow || ''}</div>
            ${s.subtitle ? `<div class="promo-subtitle">${s.subtitle}</div>` : ''}
            <button class="big-btn promo-btn" onclick="rmsSwitchTab('menu')"><i class="fa-solid fa-utensils"></i> ${s.button_text || 'Browse Menu'}</button>
        </div>`;
    }).join('');

    dots.innerHTML = slides.length > 1 ? slides.map((_, i) => `<span class="promo-dot ${i === 0 ? 'active' : ''}" onclick="rmsGoToPromoSlide(${i})"></span>`).join('') : '';
    dots.style.display = slides.length > 1 ? 'flex' : 'none';

    rmsPromoIndex = 0;
    clearInterval(rmsPromoAutoTimer);
    if (slides.length > 1) {
        rmsPromoAutoTimer = setInterval(() => rmsGoToPromoSlide((rmsPromoIndex + 1) % slides.length), 5000);
    }
}

function rmsGoToPromoSlide(index) {
    rmsPromoIndex = index;
    document.getElementById('rmsPromoTrack').style.transform = `translateX(-${index * 100}%)`;
    document.querySelectorAll('.promo-dot').forEach((d, i) => d.classList.toggle('active', i === index));
}

function rmsRenderTabs(activeIndex) {
    activeIndex = activeIndex || 0;
    const tabs = document.getElementById('rmsCatTabs');
    tabs.innerHTML = rmsMenu.map((cat, i) =>
        `<button class="cat-tab ${i === activeIndex ? 'active' : ''}" onclick="rmsRenderMenu(${i}, this)">${cat.category_name}</button>`
    ).join('');

    const homeCats = document.getElementById('rmsHomeCategories');
    if (homeCats) {
        homeCats.innerHTML = rmsMenu.map((cat, i) =>
            `<button class="cat-tab" onclick="rmsSwitchTab('menu'); setTimeout(() => { document.querySelectorAll('#rmsCatTabs .cat-tab')[${i}]?.click(); }, 50);">${cat.category_name}</button>`
        ).join('');
    }
}

function rmsBuildItemCard(item) {
    const cartQty = rmsGetCartQtyForItem(item.id, null);
    const img = item.image_url ? `style="background-image:url('${item.image_url}')"` : '';
    const imgContent = item.image_url ? '' : '<i class="fa-solid fa-utensils"></i>';
    let footer;
    if (item.variants && item.variants.length > 0) {
        footer = `<button class="add-btn" style="width:auto;padding:0 12px;font-size:11.5px;font-weight:700;" onclick='event.stopPropagation(); rmsOpenVariantPicker(${JSON.stringify(item)})'>Choose <i class="fa-solid fa-chevron-right" style="font-size:9px;"></i></button>`;
    } else if (cartQty > 0) {
        footer = `<div class="qty-stepper" onclick="event.stopPropagation()"><button onclick="rmsChangeQty(${item.id}, null, -1, '${item.name.replace(/'/g,"\\'")}', ${item.base_price})">−</button><span class="qty-val">${cartQty}</span><button onclick="rmsChangeQty(${item.id}, null, 1, '${item.name.replace(/'/g,"\\'")}', ${item.base_price})">+</button></div>`;
    } else {
        footer = `<button class="add-btn" onclick="event.stopPropagation(); rmsChangeQty(${item.id}, null, 1, '${item.name.replace(/'/g,"\\'")}', ${item.base_price})"><i class="fa-solid fa-plus"></i></button>`;
    }
    return `<div class="item-card" onclick='rmsOpenItemDetail(${JSON.stringify(item)})' style="cursor:pointer;">
        <div class="item-img" ${img}>${imgContent}</div>
        <div class="item-body">
            <div class="item-name">${item.name}</div>
            <div class="item-desc">${item.description || ''}</div>
            <div class="item-footer"><span class="item-price">Rs. ${item.base_price.toFixed(2)}</span>${footer}</div>
        </div>
    </div>`;
}

function rmsBuildTodaysMenuCard(item) {
    const img = item.image_url ? `style="background-image:url('${item.image_url}')"` : '';
    const imgContent = item.image_url ? '' : '<i class="fa-solid fa-utensils"></i>';
    const orderedToday = item.orders_today || 0;
    const cartQty = rmsGetCartQtyForItem(item.id, null);

    let footer;
    if (item.variants && item.variants.length > 0) {
        footer = `<button class="add-btn" style="width:auto;padding:0 12px;font-size:11.5px;font-weight:700;" onclick='event.stopPropagation(); rmsOpenVariantPicker(${JSON.stringify(item)})'>Choose <i class="fa-solid fa-chevron-right" style="font-size:9px;"></i></button>`;
    } else if (cartQty > 0) {
        footer = `<div class="qty-stepper" onclick="event.stopPropagation()"><button onclick="rmsChangeQty(${item.id}, null, -1, '${item.name.replace(/'/g,"\\'")}', ${item.base_price})">−</button><span class="qty-val">${cartQty}</span><button onclick="rmsChangeQty(${item.id}, null, 1, '${item.name.replace(/'/g,"\\'")}', ${item.base_price})">+</button></div>`;
    } else {
        footer = `<button class="add-btn" onclick="event.stopPropagation(); rmsChangeQty(${item.id}, null, 1, '${item.name.replace(/'/g,"\\'")}', ${item.base_price})"><i class="fa-solid fa-plus"></i></button>`;
    }

    return `<div class="item-card" onclick='rmsOpenItemDetail(${JSON.stringify(item)})' style="cursor:pointer;">
        <div class="item-img" ${img}>${imgContent}</div>
        <div class="item-body">
            <div class="item-name">${item.name}</div>
            <div class="item-desc">${item.description || ''}</div>
            ${orderedToday > 0 ? `<div class="orders-today-badge"><i class="fa-solid fa-fire"></i> ${orderedToday} ordered today</div>` : ''}
            <div class="item-footer"><span class="item-price">Rs. ${item.base_price.toFixed(2)}</span>${footer}</div>
        </div>
    </div>`;
}

function rmsOpenItemDetail(item) {
    const img = item.image_url ? `style="background-image:url('${item.image_url}')"` : '';
    const imgContent = item.image_url ? '' : '<i class="fa-solid fa-utensils"></i>';
    const cartQty = rmsGetCartQtyForItem(item.id, null);

    let actionHtml;
    if (item.variants && item.variants.length > 0) {
        actionHtml = `
            <div style="font-size:11.5px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:0.04em;margin-bottom:8px;">Choose an Option</div>
            ${item.variants.map(v => `
                <div class="cart-row" style="cursor:pointer;" onclick='rmsChangeQty(${item.id}, ${v.id}, 1, ${JSON.stringify(item.name + " (" + v.name + ")")}, ${v.final_price}); rmsCloseSheet();'>
                    <span class="cr-name">${v.name}</span><strong>Rs. ${v.final_price.toFixed(2)}</strong>
                </div>
            `).join('')}
        `;
    } else {
        actionHtml = `
            <div class="item-detail-qty-row">
                <span style="font-size:12.5px;font-weight:700;">Quantity</span>
                <div class="qty-stepper" id="rmsDetailQtyStepper">
                    <button onclick='rmsChangeQty(${item.id}, null, -1, ${JSON.stringify(item.name)}, ${item.base_price}); rmsRefreshItemDetailQty(${item.id})'>−</button>
                    <span class="qty-val" id="rmsDetailQtyVal">${cartQty}</span>
                    <button onclick='rmsChangeQty(${item.id}, null, 1, ${JSON.stringify(item.name)}, ${item.base_price}); rmsRefreshItemDetailQty(${item.id})'>+</button>
                </div>
            </div>
            <button class="big-btn" onclick='rmsChangeQty(${item.id}, null, 1, ${JSON.stringify(item.name)}, ${item.base_price}); rmsRefreshItemDetailQty(${item.id})'><i class="fa-solid fa-basket-shopping"></i> Add to Cart</button>
        `;
    }

    document.getElementById('rmsItemDetailContent').innerHTML = `
        <div class="item-detail-img" ${img}>${imgContent}</div>
        <div class="item-detail-name">${item.name}</div>
        <div class="item-detail-price">Rs. ${item.base_price.toFixed(2)}</div>
        <div class="item-detail-desc">${item.description || 'No description available.'}</div>
        ${actionHtml}
    `;
    rmsShowView('rmsItemDetailView');
    document.getElementById('rmsSheetOverlay').classList.add('open');
}

function rmsRefreshItemDetailQty(itemId) {
    const valEl = document.getElementById('rmsDetailQtyVal');
    if (valEl) valEl.textContent = rmsGetCartQtyForItem(itemId, null);
}

function rmsRenderMenu(index, btn) {
    if (btn) {
        document.querySelectorAll('.cat-tab').forEach(t => t.classList.remove('active'));
        btn.classList.add('active');
    }
    const cat = rmsMenu[index];
    const section = document.getElementById('rmsMenuSection');
    if (!cat) { section.innerHTML = '<div class="empty-state">No menu items available right now.</div>'; return; }

    section.innerHTML = `<h2>${cat.category_name}</h2>` + cat.items.map(rmsBuildItemCard).join('');
}

function rmsRenderHomeTodaysMenu() {
    const el = document.getElementById('rmsHomeTodaysMenu');
    if (!el) return;
    const allItems = rmsMenu.flatMap(cat => cat.items);
    if (allItems.length === 0) { el.innerHTML = '<div class="empty-state">No items available right now.</div>'; return; }
    el.innerHTML = allItems.map(rmsBuildTodaysMenuCard).join('');
}

function rmsGetCartQtyForItem(menuItemId, variantId) {
    const line = rmsCart.find(l => l.menu_item_id === menuItemId && l.variant_id === variantId);
    return line ? line.quantity : 0;
}

function rmsChangeQty(menuItemId, variantId, delta, name, unitPrice) {
    let line = rmsCart.find(l => l.menu_item_id === menuItemId && l.variant_id === variantId);
    if (!line) {
        if (delta > 0) rmsCart.push({ menu_item_id: menuItemId, variant_id: variantId, name: name, unit_price: unitPrice, quantity: 1 });
    } else {
        line.quantity += delta;
        if (line.quantity <= 0) rmsCart = rmsCart.filter(l => l !== line);
    }
    rmsSaveCart();
    rmsUpdateCartUI();
    const activeTabIndex = [...document.querySelectorAll('.cat-tab')].findIndex(t => t.classList.contains('active'));
    rmsRenderMenu(activeTabIndex >= 0 ? activeTabIndex : 0);
    rmsRenderHomeTodaysMenu();
}

function rmsOpenVariantPicker(item) {
    const options = item.variants.map(v => `<div class="cart-row" style="cursor:pointer;" onclick="rmsChangeQty(${item.id}, ${v.id}, 1, '${item.name.replace(/'/g,"\\'")} (${v.name.replace(/'/g,"\\'")})', ${v.final_price}); rmsCloseSheet();">
        <span class="cr-name">${v.name}</span><strong>Rs. ${v.final_price.toFixed(2)}</strong>
    </div>`).join('');
    document.getElementById('rmsCartRows').innerHTML = `<div style="font-weight:700;margin-bottom:8px;">${item.name} — choose an option:</div>` + options;
    document.getElementById('rmsCartEmpty').style.display = 'none';
    document.getElementById('rmsCartSummary').innerHTML = '';
    document.getElementById('rmsGoCheckoutBtn').style.display = 'none';
    rmsShowView('rmsCartView');
    document.getElementById('rmsSheetOverlay').classList.add('open');
}

function rmsCartTotals() {
    let subtotal = 0, count = 0;
    rmsCart.forEach(l => { subtotal += l.unit_price * l.quantity; count += l.quantity; });
    let deliveryFee = 0;
    if (rmsOrderType === 'ONLINE_DELIVERY') {
        const sel = document.getElementById('rmsZoneSelect');
        const opt = sel && sel.selectedOptions[0];
        if (opt && opt.value) deliveryFee = opt.dataset.free === '1' ? 0 : parseFloat(opt.dataset.fee || 0);
    }
    return { subtotal, count, deliveryFee, total: subtotal + deliveryFee };
}

function rmsUpdateCartUI() {
    const { subtotal, count, total } = rmsCartTotals();
    const badge = document.getElementById('rmsCartBadge');
    badge.style.display = count > 0 ? 'flex' : 'none';
    badge.textContent = count;

    const fc = document.getElementById('rmsFloatingCart');
    fc.classList.toggle('show', count > 0);
    document.getElementById('rmsFcCount').textContent = count;
    document.getElementById('rmsFcTotal').textContent = 'Rs. ' + subtotal.toFixed(2);

    rmsRenderCartRows();
}

function rmsRenderCartRows() {
    const rows = document.getElementById('rmsCartRows');
    const empty = document.getElementById('rmsCartEmpty');
    const goBtn = document.getElementById('rmsGoCheckoutBtn');

    if (rmsCart.length === 0) {
        rows.innerHTML = '';
        empty.style.display = 'block';
        goBtn.disabled = true;
        goBtn.style.display = 'block';
        document.getElementById('rmsCartSummary').innerHTML = '';
        return;
    }
    empty.style.display = 'none';
    goBtn.disabled = false;
    goBtn.style.display = 'block';

    rows.innerHTML = rmsCart.map((l, i) => `
        <div class="cart-row">
            <div style="flex:1;">
                <div class="cr-name">${l.name}</div>
                <div class="cr-price">Rs. ${l.unit_price.toFixed(2)} each</div>
            </div>
            <div class="qty-stepper" style="background:var(--navy);">
                <button onclick="rmsAdjustCartLine(${i}, -1)">−</button>
                <span class="qty-val">${l.quantity}</span>
                <button onclick="rmsAdjustCartLine(${i}, 1)">+</button>
            </div>
        </div>
    `).join('');
    rmsRenderCartSummary();
}

function rmsAdjustCartLine(index, delta) {
    rmsCart[index].quantity += delta;
    if (rmsCart[index].quantity <= 0) rmsCart.splice(index, 1);
    rmsSaveCart();
    rmsUpdateCartUI();
}

function rmsRenderCartSummary() {
    const { subtotal, deliveryFee, total } = rmsCartTotals();
    const html = `
        <div class="cart-summary-row"><span>Subtotal</span><span>Rs. ${subtotal.toFixed(2)}</span></div>
        ${rmsOrderType === 'ONLINE_DELIVERY' ? `<div class="cart-summary-row"><span>Delivery Fee</span><span>${deliveryFee === 0 ? 'FREE' : 'Rs. ' + deliveryFee.toFixed(2)}</span></div>` : ''}
        <div class="cart-summary-row total"><span>Total</span><span>Rs. ${total.toFixed(2)}</span></div>
    `;
    const summaryEl = document.getElementById('rmsCartSummary');
    if (summaryEl) summaryEl.innerHTML = html;
    const checkoutSummaryEl = document.getElementById('rmsCheckoutSummary');
    if (checkoutSummaryEl) checkoutSummaryEl.innerHTML = html;
}

let rmsPaymentMethod = 'CARD';

const rmsPaymentInfo = {
    CARD: '<i class="fa-solid fa-lock"></i> Pay securely by card now — you\'ll be taken to PayHere\'s secure payment page. We never see or store your card details.',
    BANK_TRANSFER: () => `<i class="fa-solid fa-circle-info"></i> Transfer the total to:<br>
        <strong>${rmsBankDetails.account_name || 'CurryPot.lk'}</strong><br>
        ${rmsBankDetails.bank_name || 'Bank details not yet configured'} — Acc No: ${rmsBankDetails.account_number || '—'}<br>
        Please mention your name as the reference. Bring proof of transfer (or show it to the rider) on delivery.`,
    COD: '<i class="fa-solid fa-circle-info"></i> Pay with cash when your order arrives at your door.',
};
let rmsBankDetails = { account_name: '', bank_name: '', account_number: '' };
fetch(API_BASE + '/bank-details').then(r => r.json()).then(data => { if (data.success) rmsBankDetails = data.bank; rmsSetPaymentMethod(rmsPaymentMethod); }).catch(() => {});
rmsSetPaymentMethod('CARD');

let rmsSlipBase64 = null;

function rmsSetPaymentMethod(method) {
    rmsPaymentMethod = method;
    document.getElementById('rmsPayCard').classList.toggle('active', method === 'CARD');
    document.getElementById('rmsPayBank').classList.toggle('active', method === 'BANK_TRANSFER');
    document.getElementById('rmsPayCod').classList.toggle('active', method === 'COD');
    const info = rmsPaymentInfo[method];
    document.getElementById('rmsPaymentInfoBox').innerHTML = typeof info === 'function' ? info() : info;
    document.getElementById('rmsBankProofFields').style.display = method === 'BANK_TRANSFER' ? 'block' : 'none';
}

function rmsHandleSlipUpload(event) {
    const file = event.target.files[0];
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) { alert('Please choose an image under 5MB.'); event.target.value = ''; return; }

    const reader = new FileReader();
    reader.onload = function (e) {
        rmsSlipBase64 = e.target.result;
        document.getElementById('rmsSlipPreview').src = rmsSlipBase64;
        document.getElementById('rmsSlipPreviewWrap').style.display = 'block';
        document.getElementById('rmsSlipLabel').textContent = 'Retake / Change Photo';
    };
    reader.readAsDataURL(file);
}

function rmsShowView(viewId) {
    ['rmsCartView', 'rmsCheckoutView', 'rmsSuccessView', 'rmsAccountView', 'rmsLoginView', 'rmsRegisterView', 'rmsForgotView', 'rmsEditProfileView', 'rmsChangePasswordView', 'rmsTrackView', 'rmsItemDetailView', 'rmsPaymentHistoryView'].forEach(id => {
        document.getElementById(id).style.display = id === viewId ? 'block' : 'none';
    });
}
function rmsShowAuthView(viewId) {
    rmsShowView(viewId);
    document.getElementById('rmsSheetOverlay').classList.add('open');
}

function rmsOpenSheet(view) {
    if (view === 'cart') rmsRenderCartRows();
    if (view === 'checkout') {
        rmsRenderCartSummary();
        const loggedInBanner = document.getElementById('rmsCheckoutLoggedInBanner');
        const loginPrompt = document.getElementById('rmsGuestLoginPrompt');
        const checkoutFields = document.getElementById('rmsCheckoutFields');
        if (rmsCurrentCustomer) {
            loggedInBanner.style.display = 'block';
            loginPrompt.style.display = 'none';
            checkoutFields.style.display = 'block';
            document.getElementById('rmsCheckoutLoggedInName').textContent = rmsCurrentCustomer.name;
            const addressField = document.getElementById('rmsAddress');
            if (rmsCurrentCustomer.address && !addressField.value) addressField.value = rmsCurrentCustomer.address;
        } else {
            loggedInBanner.style.display = 'none';
            loginPrompt.style.display = 'block';
            checkoutFields.style.display = 'none';
        }
    }
    rmsShowView(view === 'cart' ? 'rmsCartView' : 'rmsCheckoutView');
    document.getElementById('rmsSheetOverlay').classList.add('open');
}
function rmsCloseSheet() {
    document.getElementById('rmsSheetOverlay').classList.remove('open');
    clearInterval(rmsAccountPollTimer);
    clearInterval(rmsTrackPollTimer);
}

// ---- In-app order tracking (stays inside the PWA, never navigates away) ----
let rmsTrackPollTimer = null;
let rmsTrackingOrderNumber = null;

const rmsStatusIconMap = { PENDING: 'fa-receipt', CONFIRMED: 'fa-circle-check', PREPARING: 'fa-fire-burner', READY: 'fa-bell-concierge', OUT_FOR_DELIVERY: 'fa-motorcycle', COMPLETED: 'fa-flag-checkered', CANCELLED: 'fa-ban' };

function rmsOpenTrack(orderNumber) {
    rmsTrackingOrderNumber = orderNumber;
    clearInterval(rmsTrackPollTimer);
    document.getElementById('rmsTrackContent').innerHTML = '<div class="loading-state"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>';
    rmsShowView('rmsTrackView');
    document.getElementById('rmsSheetOverlay').classList.add('open');
    rmsFetchTrack();
}

async function rmsFetchTrack() {
    try {
        const res = await fetch(API_BASE + '/orders/track?order=' + encodeURIComponent(rmsTrackingOrderNumber));
        const data = await res.json();
        if (!data.success) {
            document.getElementById('rmsTrackContent').innerHTML = '<div class="empty-state">Could not find that order.</div>';
            return;
        }
        rmsRenderTrack(data);

        const isTerminal = data.status === 'COMPLETED' || data.status === 'CANCELLED';
        if (!isTerminal && !rmsTrackPollTimer) {
            rmsTrackPollTimer = setInterval(rmsFetchTrack, 8000);
        } else if (isTerminal) {
            clearInterval(rmsTrackPollTimer);
            rmsTrackPollTimer = null;
        }
    } catch (e) {
        // Silent fail on background polls; only show an error if nothing has rendered yet
        if (!document.getElementById('rmsTrackContent').querySelector('.trk-status-badge')) {
            document.getElementById('rmsTrackContent').innerHTML = '<div class="empty-state">Network error loading order.</div>';
        }
    }
}

function rmsRenderTrack(data) {
    const pct = data.current_index !== null && data.current_index !== -1 ? Math.round(((data.current_index + 1) / data.flow.length) * 100) : 0;
    const isTerminal = data.status === 'COMPLETED' || data.status === 'CANCELLED';

    let stepperHtml = '';
    if (data.status !== 'CANCELLED') {
        stepperHtml = `
        <div class="trk-progress-track"><div class="trk-progress-fill" style="width:${pct}%;"></div></div>
        <div class="trk-progress-pct">${pct}% complete</div>
        <div class="trk-stepper">
            ${data.flow.map((step, i) => {
                const isDone = data.current_index !== null && i < data.current_index;
                const isCurrent = i === data.current_index;
                const cls = isDone ? 'done' : (isCurrent ? 'current' : '');
                const time = data.history[step.key] || '';
                return `<div class="trk-step ${cls}">
                    <div class="trk-node"><i class="fa-solid ${rmsStatusIconMap[step.key] || 'fa-circle'}"></i></div>
                    <div class="trk-label">${step.label}</div>
                    <div class="trk-time">${time}</div>
                </div>`;
            }).join('')}
        </div>`;
    }

    let itemsHtml = data.items.map(it => `
        <div class="il-row"><span><span class="il-qty">×${it.quantity}</span>${it.name}</span><strong>Rs. ${it.line_total.toFixed(2)}</strong></div>
    `).join('');

    document.getElementById('rmsTrackContent').innerHTML = `
        ${data.status === 'COMPLETED' ? `<div class="celebrate-note" style="background:linear-gradient(120deg,#4B6B3A,#2E4322);color:#fff;border-radius:10px;padding:14px;text-align:center;font-weight:700;font-size:13px;margin-bottom:14px;">🎉 Delivered! Enjoy your meal.</div>` : ''}
        <div style="font-weight:800;font-size:15px;margin-bottom:6px;">${data.order_number}</div>
        <span class="trk-status-badge trk-${data.status.toLowerCase()}">
            ${!isTerminal ? '<span class="live-dot" style="background:#4B6B3A;"></span>' : ''}
            <i class="fa-solid ${rmsStatusIconMap[data.status] || 'fa-circle'}"></i> ${data.status_label}
        </span>
        ${!isTerminal ? `<div class="trk-live-note"><span class="live-dot" style="background:#4B6B3A;"></span> Live tracking — auto-updating</div>` : ''}
        ${stepperHtml}

        <div class="section-title" style="font-size:11px;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);font-weight:700;margin:18px 0 8px;">Items Ordered</div>
        <div class="items-list">${itemsHtml}</div>

        <div class="price-breakdown" style="text-align:left;margin-top:8px;padding-top:8px;border-top:1px solid var(--border);">
            <div class="pb-row" style="display:flex;justify-content:space-between;font-size:12px;color:var(--muted);padding:3px 0;"><span>Subtotal</span><span>Rs. ${data.subtotal.toFixed(2)}</span></div>
            <div class="pb-row" style="display:flex;justify-content:space-between;font-size:12px;color:var(--muted);padding:3px 0;"><span>Delivery Fee</span><span>${data.delivery_fee === 0 ? 'FREE' : 'Rs. ' + data.delivery_fee.toFixed(2)}</span></div>
            <div class="pb-row pb-total" style="display:flex;justify-content:space-between;font-size:14px;font-weight:700;color:var(--text);border-top:1px dashed var(--border);margin-top:4px;padding-top:6px;"><span>Total</span><span>Rs. ${data.total_amount.toFixed(2)}</span></div>
            ${data.balance_due > 0 ? `<div class="pb-row" style="display:flex;justify-content:space-between;font-size:12px;color:var(--danger);font-weight:700;padding:3px 0;"><span>Balance Due</span><span>Rs. ${data.balance_due.toFixed(2)}</span></div>` : ''}
        </div>

        <div class="section-title" style="font-size:11px;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);font-weight:700;margin:18px 0 8px;">Order Details</div>
        <div class="cart-summary-row"><span>Order Type</span><span>${data.order_type}</span></div>
        ${data.zone_name ? `<div class="cart-summary-row"><span>Delivery Area</span><span>${data.zone_name}</span></div>` : ''}
        ${data.rider_name ? `<div class="cart-summary-row"><span>Rider</span><span><i class="fa-solid fa-motorcycle"></i> ${data.rider_name}</span></div>` : ''}
        <div class="cart-summary-row"><span>Placed</span><span>${data.created_at}</span></div>
    `;
}

async function rmsPlaceOrder() {
    const errEl = document.getElementById('rmsCheckoutError');
    errEl.classList.remove('show');

    if (!rmsCurrentCustomer) {
        errEl.textContent = 'Please log in or create an account to place your order.';
        errEl.classList.add('show');
        return;
    }

    const name = rmsCurrentCustomer.name;
    const phone = rmsCurrentCustomer.phone;
    const address = document.getElementById('rmsAddress').value.trim();
    const zoneId = document.getElementById('rmsZoneSelect').value;
    const notes = document.getElementById('rmsOrderNotes').value.trim();
    const paymentReference = document.getElementById('rmsPaymentReference').value.trim();

    if (rmsOrderType === 'ONLINE_DELIVERY' && (!zoneId || !address)) { errEl.textContent = 'Please select your delivery area and enter your address.'; errEl.classList.add('show'); return; }
    if (rmsCart.length === 0) { errEl.textContent = 'Your cart is empty.'; errEl.classList.add('show'); return; }
    if (rmsPaymentMethod === 'BANK_TRANSFER' && !paymentReference) { errEl.textContent = 'Please enter your transfer reference number.'; errEl.classList.add('show'); return; }
    if (rmsPaymentMethod === 'BANK_TRANSFER' && !rmsSlipBase64) { errEl.textContent = 'Please take a photo of your deposit slip.'; errEl.classList.add('show'); return; }

    const btn = document.getElementById('rmsPlaceOrderBtn');
    btn.disabled = true; btn.textContent = 'Placing order...';

    try {
        const res = await fetch(API_BASE + '/orders', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                customer_name: name,
                customer_phone: phone,
                order_type: rmsOrderType,
                delivery_zone_id: zoneId || null,
                delivery_address: address,
                notes: notes,
                payment_method: rmsPaymentMethod,
                payment_reference: rmsPaymentMethod === 'BANK_TRANSFER' ? paymentReference : null,
                deposit_slip_base64: rmsPaymentMethod === 'BANK_TRANSFER' ? rmsSlipBase64 : null,
                items: rmsCart.map(l => ({ menu_item_id: l.menu_item_id, variant_id: l.variant_id, quantity: l.quantity })),
            }),
        });
        const data = await res.json();
        if (!data.success) {
            errEl.textContent = data.message || 'Something went wrong. Please try again.';
            errEl.classList.add('show');
            btn.disabled = false; btn.textContent = 'Place Order';
            return;
        }
        rmsCart = [];
        rmsSaveCart();
        rmsUpdateCartUI();
        rmsSlipBase64 = null;
        document.getElementById('rmsSlipPreviewWrap').style.display = 'none';
        document.getElementById('rmsSlipLabel').textContent = 'Take Photo / Upload Slip';
        document.getElementById('rmsPaymentReference').value = '';
        document.getElementById('rmsSuccessOrderNum').textContent = data.order_number;
        btn.disabled = false; btn.textContent = 'Place Order';
        const activeTabIndex = [...document.querySelectorAll('.cat-tab')].findIndex(t => t.classList.contains('active'));
        rmsRenderMenu(activeTabIndex >= 0 ? activeTabIndex : 0);
        rmsRenderHomeTodaysMenu();

        if (rmsPaymentMethod === 'CARD') {
            rmsStartPayHereCheckout(data.order_id, data.order_number, data.track_url);
        } else {
            rmsShowView('rmsSuccessView');
        }
    } catch (e) {
        errEl.textContent = 'Network error — please check your connection and try again.';
        errEl.classList.add('show');
        btn.disabled = false; btn.textContent = 'Place Order';
    }
}

async function rmsStartPayHereCheckout(orderId, orderNumber, trackUrl) {
    try {
        const res = await fetch(API_BASE + '/payhere/initiate', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ order_id: orderId }),
        });
        const data = await res.json();
        if (!data.success) {
            alert((data.message || 'Card payment isn\'t available right now.') + '\n\nYour order has been placed — you can pay another way and it will be updated once confirmed.');
            rmsShowView('rmsSuccessView');
            return;
        }

        payhere.onCompleted = function () {
            rmsShowView('rmsSuccessView');
        };
        payhere.onDismissed = function () {
            document.getElementById('rmsSuccessOrderNum').textContent = orderNumber;
            alert('Payment was not completed. Your order is still placed — you can retry payment or choose Cash on Delivery when the rider arrives.');
            rmsShowView('rmsSuccessView');
        };
        payhere.onError = function (error) {
            alert('Payment error: ' + error + '\n\nYour order is still placed — you can retry payment or pay another way.');
            rmsShowView('rmsSuccessView');
        };

        payhere.startPayment(data.payment);
    } catch (e) {
        alert('Could not start the payment. Your order has been placed — you can pay another way.');
        rmsShowView('rmsSuccessView');
    }
}

// ---- PWA install prompt ----
let rmsDeferredInstallPrompt = null;
const rmsIsStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true;
const rmsIsIOS = /iphone|ipad|ipod/i.test(navigator.userAgent);
const rmsInstallDismissed = localStorage.getItem('currypot_install_dismissed');

window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    rmsDeferredInstallPrompt = e;
    if (!rmsInstallDismissed && !rmsIsStandalone) {
        rmsShowInstallBanner('Install this app for faster ordering', 'Install', rmsInstallApp);
    }
});

function rmsInstallApp() {
    if (!rmsDeferredInstallPrompt) return;
    rmsDeferredInstallPrompt.prompt();
    rmsDeferredInstallPrompt.userChoice.then(() => {
        document.getElementById('rmsInstallBanner').classList.remove('show');
        rmsDeferredInstallPrompt = null;
    });
}

function rmsShowInstallBanner(text, btnLabel, onClick) {
    const banner = document.getElementById('rmsInstallBanner');
    banner.querySelector('span').textContent = text;
    const btn = banner.querySelector('button:not(.ib-close)');
    btn.textContent = btnLabel;
    btn.onclick = onClick;
    banner.classList.add('show');
}

if (!rmsIsStandalone && !rmsInstallDismissed) {
    if (rmsIsIOS) {
        // iOS Safari never fires beforeinstallprompt — there's no JS install API, so show manual steps instead
        setTimeout(() => {
            rmsShowInstallBanner('Tap Share, then "Add to Home Screen" to install', 'Got it', () => {
                document.getElementById('rmsInstallBanner').classList.remove('show');
                localStorage.setItem('currypot_install_dismissed', '1');
            });
        }, 1500);
    } else {
        // Android/desktop: if beforeinstallprompt hasn't fired within a few seconds, the browser isn't
        // offering it right now (often because the site isn't served over HTTPS yet) — explain instead of staying silent
        setTimeout(() => {
            if (!rmsDeferredInstallPrompt) {
                rmsShowInstallBanner("Open this site over HTTPS to install it as an app", 'OK', () => {
                    document.getElementById('rmsInstallBanner').classList.remove('show');
                    localStorage.setItem('currypot_install_dismissed', '1');
                });
            }
        }, 3000);
    }
}

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