#!/usr/bin/env python3
"""
BNKFX Banking Platform - Localhost High-Performance Preview Server
Serves the complete frontend, mobile-first customer banking app, and admin portal.
"""

import http.server
import socketserver
import os
import re
import json
import urllib.parse
import hashlib
import time
import random
import email.parser
import email.policy
import base64
import html
import secrets
import mail_service
import platform_settings_service
html_lib = html

def parse_request_body(post_data, content_type_header):
    data = {}
    if not post_data:
        return data
    content_type_header = content_type_header or ""
    if "multipart/form-data" in content_type_header:
        try:
            msg_bytes = f"Content-Type: {content_type_header}\r\n\r\n".encode("latin1") + post_data
            msg = email.parser.BytesParser(policy=email.policy.default).parsebytes(msg_bytes)
            for part in msg.iter_parts():
                name = part.get_param("name", header="content-disposition")
                if not name:
                    continue
                filename = part.get_filename()
                if filename:
                    payload = part.get_payload(decode=True) or b""
                    if len(payload) > 0:
                        ct = part.get_content_type() or "application/octet-stream"
                        data[name] = payload
                        data[f"{name}_filename"] = filename
                        data[f"{name}_content_type"] = ct
                        b64 = base64.b64encode(payload).decode("ascii")
                        if name == "icon_file":
                            data["icon_data"] = f"data:{ct};base64,{b64}"
                            data["icon_mime"] = ct
                        elif name == "qr_file":
                            data["qr_data"] = f"data:{ct};base64,{b64}"
                else:
                    try:
                        val = part.get_content()
                    except Exception:
                        val = (part.get_payload(decode=True) or b"").decode("utf-8", errors="replace")
                    if isinstance(val, str):
                        val = val.strip()
                    data[name] = val
            return data
        except Exception:
            pass
    if "application/json" in content_type_header:
        try:
            return json.loads(post_data.decode("utf-8"))
        except Exception:
            pass
    try:
        return dict(urllib.parse.parse_qsl(post_data.decode("utf-8", errors="replace")))
    except Exception:
        return {}

PORT = 8000
WORKSPACE = "/Users/elochukwu/Desktop/Bnkfx"
PUBLIC_DIR = os.path.join(WORKSPACE, "public")
APP_DIR = os.path.join(WORKSPACE, "app")
VIEWS_DIR = os.path.join(APP_DIR, "Views")

# Live Demo State for Full Localhost Interactivity
STATE = {
    "user": {
        "id": 2,
        "first_name": "Elochukwu",
        "last_name": "Elom",
        "email": "elochukwu@bnkfx.com",
        "role": "customer",
        "country": "United States",
        "phone": "+1 (555) 234-5678",
        "address": "742 Evergreen Terrace, Springfield, IL",
        "status": "active",
        "email_verified_at": "2026-10-27 12:00:00",
        "kyc_status": "approved",
        "kyc_document_type": "Passport",
        "kyc_submitted_at": "2026-10-27 11:00:00",
        "kyc_reviewed_at": "2026-10-27 12:30:00",
        "kyc_rejection_reason": None,
        "suspended_reason": None,
        "suspended_at": None,
        "created_at": "2026-10-20 09:30:00"
    },
    "admin": {
        "id": 1,
        "first_name": "Super",
        "last_name": "Admin",
        "email": "admin@bnkfx.com",
        "role": "super_admin",
        "status": "active"
    },
    "impersonation": None,
    "users": [
        {
            "id": 2,
            "first_name": "Elochukwu",
            "last_name": "Elom",
            "email": "elochukwu@bnkfx.com",
            "role": "customer",
            "country": "United States",
            "phone": "+1 (555) 234-5678",
            "address": "742 Evergreen Terrace, Springfield, IL",
            "status": "active",
            "email_verified_at": "2026-10-27 12:00:00",
            "kyc_status": "approved",
            "kyc_document_type": "Passport",
            "kyc_submitted_at": "2026-10-27 11:00:00",
            "kyc_reviewed_at": "2026-10-27 12:30:00",
            "kyc_rejection_reason": None,
            "suspended_reason": None,
            "suspended_at": None,
            "created_at": "2026-10-20 09:30:00"
        },
        {
            "id": 3,
            "first_name": "Sarah",
            "last_name": "Connor",
            "email": "sarah@bnkfx.com",
            "role": "customer",
            "country": "United Kingdom",
            "phone": "+44 20 7946 0912",
            "address": "10 Downing Street, London",
            "status": "active",
            "email_verified_at": None,
            "kyc_status": "pending_review",
            "kyc_document_type": "Driver's License",
            "kyc_submitted_at": "2026-10-26 14:15:00",
            "kyc_reviewed_at": None,
            "kyc_rejection_reason": None,
            "suspended_reason": None,
            "suspended_at": None,
            "created_at": "2026-10-22 15:00:00"
        },
        {
            "id": 4,
            "first_name": "Marcus",
            "last_name": "Vance",
            "email": "marcus.v@bnkfx.com",
            "role": "customer",
            "country": "Canada",
            "phone": "+1 (416) 555-0182",
            "address": "123 King St W, Toronto, ON",
            "status": "suspended",
            "email_verified_at": "2026-10-21 10:00:00",
            "kyc_status": "rejected",
            "kyc_document_type": "National ID",
            "kyc_submitted_at": "2026-10-23 08:30:00",
            "kyc_reviewed_at": "2026-10-23 11:00:00",
            "kyc_rejection_reason": "National ID card expired in 2024",
            "suspended_reason": "Multiple KYC verification failures and suspicious IP activity",
            "suspended_at": "2026-10-24 16:45:00",
            "created_at": "2026-10-21 08:00:00"
        }
    ],
    "payment_methods": [
        {
            "id": 1,
            "name": "USD Coin (Solana)",
            "code": "USDC",
            "network": "SOL",
            "icon_url": "/assets/images/crypto/usdc.svg",
            "wallet_address": "7XawRvyqYmqG6XWnL2G73G5d5pQoM4wN7VnZkL8tC4mK",
            "min_deposit": 50.00,
            "max_deposit": 100000.00,
            "required_confirmations": 12,
            "processing_fee_pct": 0.00,
            "instructions": "Send only USDC via Solana network. Instant processing.",
            "status": "active",
            "sort_order": 1
        },
        {
            "id": 2,
            "name": "USD Coin (Ethereum ERC-20)",
            "code": "USDC",
            "network": "ERC20",
            "icon_url": "/assets/images/crypto/usdc.svg",
            "wallet_address": "0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db",
            "min_deposit": 50.00,
            "max_deposit": 100000.00,
            "required_confirmations": 12,
            "processing_fee_pct": 0.00,
            "instructions": "Send only ERC-20 USDC. Standard Ethereum network fees apply.",
            "status": "active",
            "sort_order": 2
        },
        {
            "id": 3,
            "name": "USD Coin (Tron TRC-20)",
            "code": "USDC",
            "network": "TRC20",
            "icon_url": "/assets/images/crypto/usdc.svg",
            "wallet_address": "TQn9Y2khEsLJW1ChVWFMSMeSTow5K3GW5B",
            "min_deposit": 50.00,
            "max_deposit": 100000.00,
            "required_confirmations": 19,
            "processing_fee_pct": 0.00,
            "instructions": "Send only TRC-20 USDC. Low cost network transfer.",
            "status": "active",
            "sort_order": 3
        },
        {
            "id": 4,
            "name": "Bitcoin (Native SegWit)",
            "code": "BTC",
            "network": "BTC",
            "icon_url": "/assets/images/crypto/btc.svg",
            "wallet_address": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
            "min_deposit": 100.00,
            "max_deposit": 250000.00,
            "required_confirmations": 3,
            "processing_fee_pct": 0.00,
            "instructions": "Send native Bitcoin (BTC). Requires 3 network confirmations.",
            "status": "active",
            "sort_order": 4
        },
        {
            "id": 5,
            "name": "Ethereum (ERC-20)",
            "code": "ETH",
            "network": "ERC20",
            "icon_url": "/assets/images/crypto/eth.svg",
            "wallet_address": "0x71C8360f3E4249a5b3a3C7b38d3568c07e0541C5",
            "min_deposit": 100.00,
            "max_deposit": 250000.00,
            "required_confirmations": 12,
            "processing_fee_pct": 0.00,
            "instructions": "Send native ETH to this official receiving address.",
            "status": "active",
            "sort_order": 5
        }
    ],
    "wallet_address_history": [],
    "audit_logs": [],
    "accounts": [
        {
            "id": 1,
            "user_id": 2,
            "account_number": "0515705231",
            "account_type": "Savings",
            "currency": "USD",
            "balance": 0.00,
            "status": "active"
        },
        {
            "id": 2,
            "user_id": 2,
            "account_number": "8047291636",
            "currency": "USDC",
            "balance": 0.00,
            "status": "active"
        }
    ],
    "cards": [],
    "card_orders": [],
    "deposits": [],
    "transfers": [],
    "card_products": [
        {
            "id": 1,
            "name": "Monveracu Obsidian Virtual",
            "slug": "monveracu-obsidian-virtual",
            "type": "virtual",
            "card_type": "virtual",
            "network": "Monveracu Pay",
            "design": "obsidian",
            "card_design": "obsidian",
            "fee": 0.00,
            "issuance_fee": 0.00,
            "min_balance_required": 0.00,
            "limit": 5000.00,
            "daily_limit": 5000.00,
            "monthly_limit": 25000.00,
            "description": "Zero issuance fee virtual card tailored for secure digital subscriptions and mobile payments.",
            "features": ["Instant Virtual Issuance", "Apple Pay & Google Pay", "Zero Foreign FX Fees", "Dynamic Security CVV"],
            "is_active": 1
        },
        {
            "id": 2,
            "name": "Monveracu Midnight Blue Platinum",
            "slug": "monveracu-midnight-blue-platinum",
            "type": "physical",
            "card_type": "physical",
            "network": "Monveracu Pay",
            "design": "midnight_blue",
            "card_design": "midnight_blue",
            "fee": 25.00,
            "issuance_fee": 25.00,
            "min_balance_required": 100.00,
            "limit": 15000.00,
            "daily_limit": 15000.00,
            "monthly_limit": 50000.00,
            "description": "High-durability contactless card with international ATM privileges and travel protection.",
            "features": ["Premium Touch NFC Chip", "Global ATM Withdrawals", "Contactless Payments", "Cardholder Travel Insurance"],
            "is_active": 1
        },
        {
            "id": 3,
            "name": "Monveracu Titanium Gold Edition",
            "slug": "monveracu-titanium-gold-edition",
            "type": "metal",
            "card_type": "metal",
            "network": "Monveracu Pay",
            "design": "titanium_gold",
            "card_design": "titanium_gold",
            "fee": 75.00,
            "issuance_fee": 75.00,
            "min_balance_required": 500.00,
            "limit": 50000.00,
            "daily_limit": 50000.00,
            "monthly_limit": 150000.00,
            "description": "Solid brushed stainless steel payment card engineered for executive limits and airport lounge access.",
            "features": ["18g Solid Stainless Steel Core", "Airport Lounge Access", "Dedicated Concierge", "1% Cashback on Global Purchases"],
            "is_active": 1
        },
        {
            "id": 4,
            "name": "Monveracu Crypto Black VIP",
            "slug": "monveracu-crypto-black-vip",
            "type": "crypto_black",
            "card_type": "crypto_black",
            "network": "Monveracu VIP",
            "design": "crypto_black",
            "card_design": "crypto_black",
            "fee": 150.00,
            "issuance_fee": 150.00,
            "min_balance_required": 1000.00,
            "limit": 100000.00,
            "daily_limit": 100000.00,
            "monthly_limit": 500000.00,
            "description": "Ultra-matte ceramic card with bespoke private banking benefits, 2% crypto rewards, and high liquidity caps.",
            "features": ["Ultra-Matte Black Ceramic Finish", "2% Crypto Cashback", "High Daily Spend Limit", "Bespoke Wealth Manager"],
            "is_active": 1
        }
    ],
    "kyc_reminder_dismissed": False,
    "email_logs": [
        {
            "id": 1,
            "user_id": 2,
            "recipient": "elochukwu@bnkfx.com",
            "subject": "Welcome to Alliance Bank — Your Account Details",
            "template": "welcome",
            "status": "sent",
            "created_at": "2026-10-20 09:30:00"
        },
        {
            "id": 2,
            "user_id": 2,
            "recipient": "elochukwu@bnkfx.com",
            "subject": "Your Identity Verification Is Complete",
            "template": "kyc_approved",
            "status": "sent",
            "created_at": "2026-10-27 12:30:00"
        }
    ],
    "kyc_verifications": [
        {
            "id": 1,
            "user_id": 3,
            "first_name": "Sarah",
            "last_name": "Connor",
            "email": "sarah@bnkfx.com",
            "account_number": "4910283746",
            "document_type": "Driver's License",
            "id_number": "DL-98234-UK",
            "document_path": "/storage/kyc/sample_license.jpg",
            "status": "pending_review",
            "notes": None,
            "rejection_reason": None,
            "submitted_at": "2026-10-26 14:15:00",
            "updated_at": "2026-10-26 14:15:00",
            "reviewed_by": None,
            "reviewed_at": None
        },
        {
            "id": 2,
            "user_id": 4,
            "first_name": "Marcus",
            "last_name": "Vance",
            "email": "marcus.v@bnkfx.com",
            "account_number": "5819204812",
            "document_type": "National ID Card",
            "id_number": "ID-CAN-49102",
            "document_path": "/storage/kyc/sample_id.jpg",
            "status": "rejected",
            "notes": "Card expired",
            "rejection_reason": "National ID card expired in 2024",
            "submitted_at": "2026-10-23 08:30:00",
            "updated_at": "2026-10-23 11:00:00",
            "reviewed_by": 1,
            "reviewed_at": "2026-10-23 11:00:00"
        },
        {
            "id": 3,
            "user_id": 2,
            "first_name": "Elochukwu",
            "last_name": "Elom",
            "email": "elochukwu@bnkfx.com",
            "account_number": "8047291635",
            "document_type": "Passport",
            "id_number": "USA-90123841",
            "document_path": "/storage/kyc/sample_passport.jpg",
            "status": "approved",
            "notes": "Verified passport bio-data and facial match.",
            "rejection_reason": None,
            "submitted_at": "2026-10-27 11:00:00",
            "updated_at": "2026-10-27 12:30:00",
            "reviewed_by": 1,
            "reviewed_at": "2026-10-27 12:30:00"
        }
    ],
    "investment_plans": [
        {
            "id": 1,
            "name": "Starter Plan",
            "slug": "starter",
            "description": "Short duration, low commitment starter tier for new capital allocations.",
            "min_amount": 50.00,
            "max_amount": 99.00,
            "is_unlimited": False,
            "duration_hours": 48,
            "return_percentage": 20.00,
            "is_recommended": False,
            "status": "active",
            "display_order": 1
        },
        {
            "id": 2,
            "name": "Regular Plan",
            "slug": "regular",
            "description": "Standard institutional portfolio tier offering balanced yield and moderate term.",
            "min_amount": 100.00,
            "max_amount": 499.00,
            "is_unlimited": False,
            "duration_hours": 72,
            "return_percentage": 50.00,
            "is_recommended": False,
            "status": "active",
            "display_order": 2
        },
        {
            "id": 3,
            "name": "Pro Plan",
            "slug": "pro",
            "description": "Institutional growth tier featuring 100% contractual return across 96 hours.",
            "min_amount": 500.00,
            "max_amount": 4999.00,
            "is_unlimited": False,
            "duration_hours": 96,
            "return_percentage": 100.00,
            "is_recommended": True,
            "status": "active",
            "display_order": 3
        },
        {
            "id": 4,
            "name": "Premium Plan",
            "slug": "premium",
            "description": "Elite wealth management tier with unlimited allocation and 150% fixed yield.",
            "min_amount": 5000.00,
            "max_amount": None,
            "is_unlimited": True,
            "duration_hours": 120,
            "return_percentage": 150.00,
            "is_recommended": False,
            "status": "active",
            "display_order": 4
        }
    ],
    "stocks": [
        {
            "id": 1,
            "name": "Microsoft Corporation",
            "ticker": "MSFT",
            "category": "Technology",
            "short_description": "Global enterprise software, Azure cloud computing, and AI systems leader.",
            "default_plan_id": 3,
            "status": "active",
            "logo_url": "/assets/images/stocks/msft.svg",
            "display_order": 1,
            "notes": "Verified institutional asset"
        },
        {
            "id": 2,
            "name": "Netflix, Inc.",
            "ticker": "NFLX",
            "category": "Entertainment",
            "short_description": "World leading subscription streaming entertainment service.",
            "default_plan_id": 2,
            "status": "active",
            "logo_url": "/assets/images/stocks/nflx.svg",
            "display_order": 2,
            "notes": "Verified institutional asset"
        },
        {
            "id": 3,
            "name": "Apple Inc.",
            "ticker": "AAPL",
            "category": "Consumer Tech",
            "short_description": "Consumer technology hardware, iOS ecosystem, and digital services powerhouse.",
            "default_plan_id": 3,
            "status": "active",
            "logo_url": "/assets/images/stocks/aapl.svg",
            "display_order": 3,
            "notes": "Verified institutional asset"
        },
        {
            "id": 4,
            "name": "NVIDIA Corporation",
            "ticker": "NVDA",
            "category": "Semiconductors",
            "short_description": "Pioneer in accelerated computing, GPU architecture, and AI datacenter hardware.",
            "default_plan_id": 4,
            "status": "active",
            "logo_url": "/assets/images/stocks/nvda.svg",
            "display_order": 4,
            "notes": "Verified institutional asset"
        },
        {
            "id": 5,
            "name": "Amazon.com, Inc.",
            "ticker": "AMZN",
            "category": "E-Commerce",
            "short_description": "Global e-commerce marketplace, AWS cloud infrastructure, and logistics network.",
            "default_plan_id": 3,
            "status": "active",
            "logo_url": "/assets/images/stocks/amzn.svg",
            "display_order": 5,
            "notes": "Verified institutional asset"
        },
        {
            "id": 6,
            "name": "Alphabet Inc.",
            "ticker": "GOOGL",
            "category": "Internet Services",
            "short_description": "Google search engine, YouTube video platform, Android OS, and cloud platform.",
            "default_plan_id": 2,
            "status": "active",
            "logo_url": "/assets/images/stocks/googl.svg",
            "display_order": 6,
            "notes": "Verified institutional asset"
        }
    ],
    "investments": [],
    "investment_redemptions": [],
    "email_settings": {
        "smtp_host": "smtp.mailgun.org",
        "smtp_port": 587,
        "smtp_username": "postmaster@bnkfx.com",
        "smtp_password": "encrypted_app_secret",
        "encryption": "tls",
        "from_name": "Alliance Bank Operations",
        "from_address": "notifications@bnkfx.com",
        "require_email_verification": True,
        "notify_welcome": True,
        "notify_transactions": True,
        "notify_security": True,
        "notify_password_reset": True,
        "notify_deposits": True,
        "notify_withdrawals": True,
        "notify_cards": True
    },
    "password_resets": [],
    "email_verifications": [],
    "platform_settings": dict(platform_settings_service.DEFAULT_PLATFORM_SETTINGS)
}

def generate_svg_qr(data, size=180):
    hash_val = hashlib.sha256(data.encode('utf-8')).hexdigest()
    grid = 25
    cell_size = size / grid

    svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {size} {size}" width="{size}" height="{size}" class="rounded-xl shadow-inner bg-white p-2">'
    svg += '<rect width="100%" height="100%" fill="#FFFFFF" rx="8"/>'

    def draw_corner(sx, sy):
        nonlocal svg
        x = sx * cell_size
        y = sy * cell_size
        w = 7 * cell_size
        svg += f'<rect x="{x}" y="{y}" width="{w}" height="{w}" fill="#0B0D10" rx="2"/>'
        xi = (sx + 1) * cell_size
        yi = (sy + 1) * cell_size
        wi = 5 * cell_size
        svg += f'<rect x="{xi}" y="{yi}" width="{wi}" height="{wi}" fill="#FFFFFF" rx="1"/>'
        xc = (sx + 2) * cell_size
        yc = (sy + 2) * cell_size
        wc = 3 * cell_size
        svg += f'<rect x="{xc}" y="{yc}" width="{wc}" height="{wc}" fill="#246BFD" rx="1"/>'

    draw_corner(1, 1)
    draw_corner(17, 1)
    draw_corner(1, 17)

    for r in range(grid):
        for c in range(grid):
            if (r < 9 and c < 9) or (r < 9 and c > 15) or (r > 15 and c < 9):
                continue
            idx = (r * grid + c) % len(hash_val)
            val = int(hash_val[idx], 16)
            if r == 7 or c == 7:
                if (r + c) % 2 == 0:
                    svg += f'<rect x="{c * cell_size}" y="{r * cell_size}" width="{cell_size}" height="{cell_size}" fill="#0B0D10"/>'
                continue
            if val % 2 == 0:
                color = '#171A21' if val > 8 else '#246BFD'
                svg += f'<rect x="{c * cell_size}" y="{r * cell_size}" width="{cell_size}" height="{cell_size}" fill="{color}" rx="0.5"/>'

    svg += '</svg>'
    return svg

def build_app_layout(content, title="Monveracu Online Banking", current_path="/dashboard"):
    user = STATE["user"]
    initials = f"{user['first_name'][0]}{user['last_name'][0]}".upper()
    settings = platform_settings_service.get_platform_settings(STATE)
    brand_css = platform_settings_service.generate_brand_css(settings)
    platform_name = settings.get("platform_name", "Monveracu")
    short_name = settings.get("short_name", "Monveracu")
    page_title = title if title != "Monveracu Online Banking" else f"{platform_name} Online Banking"
    favicon_url = settings.get("favicon_url", "/assets/images/logo/favicon.ico")

    def nav_link(url, label, icon):
        active = (current_path == url or (url != "/dashboard" and current_path.startswith(url)))
        classes = "bg-[#246BFD]/10 text-[#246BFD] font-semibold border-l-4 border-[#246BFD]" if active else "text-[#9CA6BA] hover:text-[#F8FAFC] hover:bg-[#171A21]"
        return f'''<a href="{url}" class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm transition-all {classes}">
                    <i class="fa-solid {icon} w-5 text-center text-base"></i>
                    <span>{label}</span>
                </a>'''

    def mobile_link(url, label, icon):
        active = (current_path == url or (url != "/dashboard" and current_path.startswith(url)))
        color = "text-[#246BFD] font-bold" if active else "text-[#737D90] hover:text-[#9CA6BA]"
        return f'''<a href="{url}" class="flex flex-col items-center justify-center py-1 flex-1 text-center {color} transition-colors">
                    <i class="fa-solid {icon} text-lg mb-1"></i>
                    <span class="text-[10px] tracking-tight">{label}</span>
                </a>'''

    impersonation_banner = ""
    if STATE.get("impersonation"):
        imp = STATE["impersonation"]
        impersonation_banner = f'''
        <div class="bg-gradient-to-r from-amber-500 via-amber-400 to-amber-500 text-slate-950 px-4 py-2.5 text-xs md:text-sm font-semibold flex items-center justify-between shadow-xl sticky top-0 z-50 border-b border-amber-600">
            <div class="flex items-center gap-2.5">
                <i class="fa-solid fa-triangle-exclamation text-slate-950 text-base"></i>
                <span>
                    <strong>Support Mode Active:</strong> Logged in as 
                    <span class="underline font-bold">{user['first_name']} {user['last_name']}</span> 
                    ({user['email']}). Administrator: {imp.get('original_admin_email', 'admin@bnkfx.com')}. All actions are recorded.
                </span>
            </div>
            <a href="/admin/impersonate/exit" class="inline-flex items-center gap-1.5 px-3 py-1 bg-slate-950 text-amber-300 hover:text-white rounded-lg hover:bg-slate-900 transition-colors shadow text-xs font-bold whitespace-nowrap">
                <i class="fa-solid fa-right-from-bracket text-[11px]"></i>
                Exit Support Mode
            </a>
        </div>
        '''

    return f'''<!DOCTYPE html>
<html lang="en" class="h-full bg-[#0B0D10]">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>{page_title}</title>
    <link rel="icon" href="{favicon_url}">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {{
            darkMode: 'class',
            theme: {{
                extend: {{
                    colors: {{
                        darkBg: '#0B0D10',
                        darkSecondary: '#12151B',
                        darkCard: '#171A21',
                        elevated: '#20242D',
                        darkBorder: '#292E38',
                        primaryText: '#F8FAFC',
                        secondaryText: '#9CA6BA',
                        mutedText: '#737D90',
                        primary: '{settings.get("primary_color", "#246BFD")}',
                        darkBlue: '#1748A8',
                        primaryHover: '{settings.get("primary_hover", "#1858D8")}',
                        lightBlue: '#E7F0FF',
                        purpleAccent: '#8054F6',
                        successGreen: '#20C997',
                        warningAmber: '#F5B942',
                        errorRed: '#F05D6C'
                    }}
                }}
            }}
        }}
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/main.css">
    {brand_css}
</head>
<body class="h-full bg-[#0B0D10] text-[#F8FAFC] font-sans antialiased selection:bg-[#246BFD] selection:text-white pb-28 md:pb-8">
    <div class="min-h-full flex flex-col md:flex-row">
        <!-- Desktop Sidebar -->
        <aside class="hidden md:flex md:w-64 md:flex-col md:fixed md:inset-y-0 bg-[#12151B] border-r border-[#292E38] z-30">
            <div class="flex items-center justify-between h-16 px-6 border-b border-[#292E38]">
                <a href="/dashboard" class="flex items-center gap-3">
                    <div class="w-9 h-9 rounded-xl bg-gradient-to-tr from-[#246BFD] to-[#4D8CFF] flex items-center justify-center shadow-lg shadow-blue-500/20">
                        <i class="fa-solid fa-shield-halved text-white text-base"></i>
                    </div>
                    <span class="text-xl font-bold tracking-tight text-white font-mono">{short_name}</span>
                </a>
            </div>

            <div class="flex-1 flex flex-col overflow-y-auto px-4 py-6 space-y-1">
                <div class="text-[11px] font-semibold uppercase tracking-wider text-[#737D90] px-3 mb-2">Core Banking</div>
                {nav_link('/dashboard', 'Overview', 'fa-house')}
                {nav_link('/accounts', 'Accounts', 'fa-wallet')}
                {nav_link('/deposits', 'Fund Account', 'fa-circle-arrow-down text-[#20C997]')}
                {nav_link('/transfers/send', 'Transfer', 'fa-paper-plane text-[#246BFD]')}
                {nav_link('/transfers/receive', 'Receive Funds', 'fa-qrcode text-[#8054F6]')}
                {nav_link('/exchange', 'Currency Exchange', 'fa-arrow-right-arrow-left text-[#F5B942]')}
                {nav_link('/investments', 'Investments', 'fa-arrow-trend-up text-[#38BDF8]')}

                <div class="text-[11px] font-semibold uppercase tracking-wider text-[#737D90] px-3 mt-6 mb-2">Cards & History</div>
                {nav_link('/cards', 'Payment Cards', 'fa-credit-card')}
                {nav_link('/activity', 'Transaction History', 'fa-clock-rotate-left')}
                {nav_link('/notifications', 'Notifications', 'fa-bell')}

                <div class="text-[11px] font-semibold uppercase tracking-wider text-[#737D90] px-3 mt-6 mb-2">Preferences</div>
                {nav_link('/profile', 'Settings & Security', 'fa-gear')}
                {nav_link('/support', 'Support', 'fa-circle-question')}

                <div class="text-[11px] font-semibold uppercase tracking-wider text-[#F05D6C] px-3 mt-6 mb-2">System</div>
                <a href="/admin" class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-[#F05D6C] hover:bg-red-500/10 transition-all font-semibold">
                    <i class="fa-solid fa-user-shield w-5 text-center"></i>
                    <span>Admin Portal</span>
                </a>
            </div>

            <div class="p-4 border-t border-[#292E38] bg-[#0E1015]">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <div class="w-9 h-9 rounded-full bg-[#246BFD]/20 text-[#246BFD] flex items-center justify-center font-bold text-sm">
                            {initials}
                        </div>
                        <div class="overflow-hidden">
                            <p class="text-sm font-medium text-white truncate">{user['first_name']} {user['last_name']}</p>
                            <p class="text-xs text-[#737D90] truncate">{user['email']}</p>
                        </div>
                    </div>
                    <a href="/login" title="Sign out" class="text-[#737D90] hover:text-[#F05D6C] p-2 rounded-lg transition-colors">
                        <i class="fa-solid fa-arrow-right-from-bracket"></i>
                    </a>
                </div>
            </div>
        </aside>

        <!-- Main Content Area -->
        <div class="md:pl-64 flex flex-col flex-1">
            {impersonation_banner}
            <header class="sticky top-0 z-20 flex items-center justify-between h-16 px-4 md:px-8 bg-[#0B0D10]/90 backdrop-blur-md border-b border-[#292E38]">
                <div class="flex items-center gap-3">
                    <a href="/dashboard" class="md:hidden flex items-center gap-2">
                        <div class="w-8 h-8 rounded-lg bg-gradient-to-tr from-[#246BFD] to-[#4D8CFF] flex items-center justify-center">
                            <i class="fa-solid fa-shield-halved text-white text-sm"></i>
                        </div>
                        <span class="font-bold text-lg text-white font-mono">{short_name}</span>
                    </a>
                    <div class="hidden md:flex items-center gap-2 text-sm text-[#9CA6BA]">
                        <span>Welcome,</span>
                        <span class="text-[#F8FAFC] font-semibold">{user['first_name']} {user['last_name']}</span>
                    </div>
                </div>

                <div class="flex items-center gap-2 md:gap-3">
                    <a href="/notifications" class="relative p-2.5 rounded-full text-[#9CA6BA] hover:text-white hover:bg-[#171A21] transition-all">
                        <i class="fa-regular fa-bell text-lg"></i>
                        <span class="absolute top-1.5 right-1.5 w-2.5 h-2.5 rounded-full bg-[#246BFD] ring-2 ring-[#0B0D10]"></span>
                    </a>
                    <a href="/support" class="p-2.5 rounded-full text-[#9CA6BA] hover:text-white hover:bg-[#171A21] transition-all" title="Support">
                        <i class="fa-regular fa-circle-question text-lg"></i>
                    </a>
                    <!-- In-App Language Selector -->
                    <div class="relative inline-block text-left">
                        <button type="button" onclick="const m=this.nextElementSibling;m.classList.toggle('hidden')" 
                            class="p-2 px-2.5 rounded-xl bg-[#171A21] border border-[#292E38] text-xs text-gray-300 hover:text-white flex items-center gap-1.5 transition-colors cursor-pointer"
                            title="Switch Language">
                            <span class="current-lang-flag text-sm">🇺🇸</span>
                            <span class="current-lang-code font-mono uppercase text-[11px] text-gray-300 hidden sm:inline">EN</span>
                        </button>
                        <div class="lang-dropdown-menu hidden absolute right-0 mt-2 w-36 rounded-xl bg-[#171A21] border border-[#292E38] shadow-2xl py-1.5 z-50 text-xs font-medium">
                            <a href="javascript:void(0)" data-lang-select="en" class="flex items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-[#20242D] hover:text-white transition-colors">
                                <span>🇺🇸</span> <span>English</span>
                            </a>
                            <a href="javascript:void(0)" data-lang-select="es" class="flex items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-[#20242D] hover:text-white transition-colors">
                                <span>🇪🇸</span> <span>Español</span>
                            </a>
                            <a href="javascript:void(0)" data-lang-select="fr" class="flex items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-[#20242D] hover:text-white transition-colors">
                                <span>🇫🇷</span> <span>Français</span>
                            </a>
                            <a href="javascript:void(0)" data-lang-select="pt" class="flex items-center gap-2 px-3 py-1.5 text-gray-300 hover:bg-[#20242D] hover:text-white transition-colors">
                                <span>🇧🇷</span> <span>Português</span>
                            </a>
                        </div>
                    </div>
                    <a href="/profile" class="flex items-center gap-2 pl-2">
                        <div class="w-8 h-8 rounded-full bg-gradient-to-tr from-[#246BFD] to-[#8054F6] flex items-center justify-center text-xs font-bold text-white shadow-md">
                            {initials}
                        </div>
                    </a>
                </div>
            </header>

            <main class="flex-1 px-4 md:px-8 py-6">
                {content}
            </main>
        </div>
    </div>

    <!-- Mobile Fixed Bottom Navigation -->
    <nav class="md:hidden fixed bottom-0 inset-x-0 bg-[#12151B]/95 backdrop-blur-lg border-t border-[#292E38] z-30 px-3 py-2">
        <div class="flex items-center justify-around">
            {mobile_link('/dashboard', 'Home', 'fa-house')}
            {mobile_link('/accounts', 'Accounts', 'fa-wallet')}
            {mobile_link('/cards', 'Cards', 'fa-credit-card')}
            {mobile_link('/activity', 'Activity', 'fa-clock-rotate-left')}
            {mobile_link('/profile', 'Profile', 'fa-user')}
        </div>
    </nav>

    <div id="toast-container" class="fixed top-5 right-5 z-50 flex flex-col gap-2 max-w-sm pointer-events-none"></div>
    <script src="/assets/js/translator.js"></script>
    <script src="/assets/js/app.js"></script>
</body>
</html>'''

def build_admin_layout(content, title="Monveracu Admin Portal", current_path="/admin"):
    settings = platform_settings_service.get_platform_settings(STATE)
    brand_css = platform_settings_service.generate_brand_css(settings)
    short_name = settings.get("short_name", "Monveracu")
    platform_name = settings.get("platform_name", "Monveracu")
    admin_title = title if title != "Monveracu Admin Portal" else f"{short_name} Admin Portal"
    favicon_url = settings.get("favicon_url", "/assets/images/logo/favicon.ico")

    def admin_link(url, label, icon):
        active = (current_path == url or (url != "/admin" and current_path.startswith(url)))
        classes = "bg-[#F05D6C]/10 text-[#F05D6C] font-semibold border-l-4 border-[#F05D6C]" if active else "text-[#9CA6BA] hover:text-white hover:bg-[#171A21]"
        return f'''<a href="{url}" class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm transition-all {classes}">
                    <i class="fa-solid {icon} w-5 text-center"></i>
                    <span>{label}</span>
                </a>'''

    return f'''<!DOCTYPE html>
<html lang="en" class="h-full bg-[#0B0D10]">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{admin_title}</title>
    <link rel="icon" href="{favicon_url}">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {{
            darkMode: 'class',
            theme: {{
                extend: {{
                    colors: {{
                        darkBg: '#0B0D10',
                        darkSecondary: '#12151B',
                        darkCard: '#171A21',
                        elevated: '#20242D',
                        darkBorder: '#292E38',
                        primaryText: '#F8FAFC',
                        secondaryText: '#9CA6BA',
                        mutedText: '#737D90',
                        primary: '{settings.get("primary_color", "#246BFD")}',
                        darkBlue: '#1748A8',
                        primaryHover: '{settings.get("primary_hover", "#1858D8")}',
                        lightBlue: '#E7F0FF',
                        purpleAccent: '#8054F6',
                        successGreen: '#20C997',
                        warningAmber: '#F5B942',
                        errorRed: '#F05D6C'
                    }}
                }}
            }}
        }}
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/main.css">
    {brand_css}
</head>
<body class="h-full bg-[#0B0D10] text-[#F8FAFC] font-sans antialiased selection:bg-[#F05D6C] selection:text-white">
    <div class="min-h-full flex flex-col md:flex-row">
        <!-- Admin Sidebar -->
        <aside class="w-full md:w-64 bg-[#12151B] border-r border-[#292E38] flex flex-col">
            <div class="h-16 px-6 border-b border-[#292E38] flex items-center justify-between">
                <a href="/admin" class="flex items-center gap-2.5">
                    <div class="w-8 h-8 rounded-lg bg-[#F05D6C] flex items-center justify-center shadow-lg shadow-red-600/30">
                        <i class="fa-solid fa-user-shield text-white text-sm"></i>
                    </div>
                    <span class="font-bold text-lg text-white font-mono tracking-tight">{short_name} Admin</span>
                </a>
                <span class="px-2 py-0.5 rounded text-[10px] font-bold uppercase bg-[#F05D6C]/20 text-[#F05D6C] border border-[#F05D6C]/30">Admin</span>
            </div>

            <div class="flex-1 px-4 py-6 space-y-1">
                <div class="text-[11px] font-semibold uppercase tracking-wider text-[#737D90] px-3 mb-2">Platform Administration</div>
                {admin_link('/admin', 'Dashboard Overview', 'fa-gauge-high')}
                {admin_link('/admin/payment-methods', 'Payment Methods', 'fa-wallet')}
                {admin_link('/admin/users', 'Customer Accounts', 'fa-users')}
                {admin_link('/admin/kyc', 'KYC Management', 'fa-id-card')}
                {admin_link('/admin/transfers', 'Internal Transfers', 'fa-money-bill-transfer')}
                {admin_link('/admin/deposits', 'Crypto Deposits', 'fa-coins')}
                {admin_link('/admin/cards', 'Card Marketplace', 'fa-credit-card')}
                {admin_link('/admin/stocks', 'Stock Assets', 'fa-arrow-trend-up')}
                {admin_link('/admin/plans', 'Investment Plans', 'fa-layer-group')}
                {admin_link('/admin/investments', 'User Investments', 'fa-chart-pie')}

                <div class="text-[11px] font-semibold uppercase tracking-wider text-[#737D90] px-3 mt-6 mb-2">Audit & Financials</div>
                {admin_link('/admin/reports', 'Ledger Reconciliation', 'fa-scale-balanced')}
                {admin_link('/admin/audit', 'Security Audit Logs', 'fa-file-shield')}

                <div class="text-[11px] font-semibold uppercase tracking-wider text-[#737D90] px-3 mt-6 mb-2">Communications</div>
                {admin_link('/admin/settings/email', 'Email Settings', 'fa-envelope-open-text')}
                {admin_link('/admin/email-logs', 'Email Delivery Logs', 'fa-paper-plane')}

                <div class="text-[11px] font-semibold uppercase tracking-wider text-[#737D90] px-3 mt-6 mb-2">Platform & Identity</div>
                {admin_link('/admin/settings/platform', 'Platform Settings', 'fa-sliders')}

                <div class="text-[11px] font-semibold uppercase tracking-wider text-[#737D90] px-3 mt-6 mb-2">Shortcuts</div>
                <a href="/dashboard" class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-[#246BFD] hover:bg-blue-500/10 transition-all font-medium">
                    <i class="fa-solid fa-arrow-left w-5 text-center"></i>
                    <span>Customer App</span>
                </a>
            </div>

            <div class="p-4 border-t border-[#292E38] bg-[#0E1015] flex items-center justify-between">
                <div class="flex items-center gap-2 overflow-hidden">
                    <div class="w-8 h-8 rounded-full bg-[#F05D6C]/20 text-[#F05D6C] flex items-center justify-center font-bold text-xs">
                        AD
                    </div>
                    <div class="overflow-hidden">
                        <p class="text-xs font-semibold text-white truncate">admin@bnkfx.com</p>
                        <p class="text-[10px] text-[#737D90] uppercase tracking-wider">Super Administrator</p>
                    </div>
                </div>
                <a href="/login" class="text-[#737D90] hover:text-[#F05D6C] p-2" title="Sign Out">
                    <i class="fa-solid fa-power-off"></i>
                </a>
            </div>
        </aside>

        <!-- Admin Main Area -->
        <div class="flex-1 flex flex-col overflow-y-auto">
            <header class="h-16 px-6 border-b border-[#292E38] bg-[#0B0D10]/80 backdrop-blur-md flex items-center justify-between">
                <h1 class="text-lg font-bold text-white">{title}</h1>
                <div class="flex items-center gap-3 text-xs text-[#9CA6BA]">
                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-[#20C997]/10 text-[#20C997] border border-[#20C997]/20 font-medium">
                        <span class="w-1.5 h-1.5 rounded-full bg-[#20C997] animate-pulse"></span>
                        Ledger Synchronized
                    </span>
                    <span class="hidden sm:inline">Active</span>
                </div>
            </header>

            <main class="flex-1 p-6">
                {content}
            </main>
        </div>
    </div>
    <script src="/assets/js/translator.js"></script>
</body>
</html>'''

class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True
    allow_reuse_address = True

class BnkfxHandler(http.server.SimpleHTTPRequestHandler):
    def translate_path(self, path):
        if path.startswith("/assets/"):
            rel_path = path[len("/assets/"):]
            return os.path.join(PUBLIC_DIR, "assets", rel_path)
        return super().translate_path(path)

    def do_POST(self):
        parsed = urllib.parse.urlparse(self.path)
        content_length = int(self.headers.get('Content-Length', 0))
        post_data = self.rfile.read(content_length)
        content_type = self.headers.get('Content-Type', '')

        data = parse_request_body(post_data, content_type)

        # Check Admin Actions First
        import preview_admin
        if preview_admin.handle_admin_post(self, parsed, data, STATE):
            return

        # Maintenance Mode Check for non-admin mutations
        if platform_settings_service.is_maintenance_mode(STATE, user=STATE.get("user"), path=parsed.path):
            settings = platform_settings_service.get_platform_settings(STATE)
            self.send_response(503)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.end_headers()
            self.wfile.write(json.dumps({
                "success": False,
                "error": "Platform is currently undergoing scheduled maintenance. Financial operations are temporarily suspended.",
                "maintenance_mode": True,
                "message": settings.get("maintenance_mode_message")
            }).encode("utf-8"))
            return

        # 0. User Authentication Login
        if parsed.path == "/login":
            email_val = str(data.get("email", "")).lower().strip()
            # If admin, switch session to Super Admin and redirect to /admin
            if "admin" in email_val:
                admin_user = next((u for u in STATE.get("users", []) if u.get("role") in ["admin", "super_admin"]), None)
                if admin_user:
                    STATE["user"] = admin_user
                self.send_response(302)
                self.send_header("Location", "/admin")
                self.end_headers()
                return
            elif email_val:
                matched_user = next((u for u in STATE.get("users", []) if u.get("email", "").lower() == email_val), None)
                if matched_user:
                    STATE["user"] = matched_user
            self.send_response(302)
            self.send_header("Location", "/dashboard")
            self.end_headers()
            return

        # 0.05 User Language Preference
        if parsed.path == "/api/user/language":
            lang = str(data.get("language", "en")).lower().strip()
            if lang in ["en", "es", "fr", "pt"]:
                if STATE.get("user"):
                    STATE["user"]["preferred_language"] = lang
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"success": True, "language": lang}).encode('utf-8'))
                return
            self.send_response(400)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"success": False, "error": "Unsupported language"}).encode('utf-8'))
            return

        # 0. User Registration
        if parsed.path == "/register":
            cfg = platform_settings_service.get_platform_settings(STATE)
            if not cfg.get("allow_registrations", True):
                self.send_response(403)
                self.send_header("Content-Type", "application/json; charset=utf-8")
                self.end_headers()
                self.wfile.write(json.dumps({"success": False, "error": "New user registrations are currently disabled by the administrator."}).encode("utf-8"))
                return

            email_lower = data.get("email", "").lower().strip()
            first_name = data.get("first_name", "Abraham").strip()
            last_name = data.get("last_name", "Elom").strip()
            username = data.get("username", "abraham").strip()
            country = data.get("country", "United States").strip()
            account_type = data.get("account_type", "Checking Account").strip()

            if not email_lower or "@" not in email_lower:
                self.send_response(400)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"error": "A valid email address is required."}).encode('utf-8'))
                return

            # Prevent duplicate email registration
            existing = next((u for u in STATE.get("users", []) if u["email"].lower() == email_lower), None)
            if existing and existing["id"] != STATE["user"].get("id"):
                self.send_response(400)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"error": "An account with this email address already exists."}).encode('utf-8'))
                return

            new_acc_num = "".join([str(random.randint(0, 9)) for _ in range(10)])
            while any(a.get("account_number") == new_acc_num for a in STATE.get("accounts", [])):
                new_acc_num = "".join([str(random.randint(0, 9)) for _ in range(10)])

            new_user_id = max([u["id"] for u in STATE.get("users", [])] + [10]) + 1
            new_user = {
                "id": new_user_id,
                "first_name": first_name,
                "last_name": last_name,
                "username": username,
                "email": email_lower,
                "country": country,
                "phone": data.get("phone", "+1 555-0199"),
                "address": data.get("address", "742 Evergreen Terrace, Suite 100"),
                "status": "active",
                "kyc_status": "not_submitted",
                "email_verified_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "kyc_document_type": None,
                "kyc_submitted_at": None,
                "kyc_reviewed_at": None,
                "kyc_rejection_reason": None,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            STATE.setdefault("users", []).append(new_user)
            STATE["registered_user"] = new_user
            STATE["_last_welcome_resend"] = time.time()

            # Transactional Welcome Email Log
            welcome_email = {
                "id": len(STATE.get("email_logs", [])) + 1,
                "user_id": new_user_id,
                "recipient": email_lower,
                "subject": "Welcome to Alliance Bank — Your Account Details",
                "template": "welcome",
                "status": "sent",
                "metadata": {
                    "account_number": new_acc_num,
                    "account_type": account_type,
                    "currency": "USD"
                },
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            STATE.setdefault("email_logs", []).append(welcome_email)

            try:
                os.makedirs(os.path.join(WORKSPACE, "storage", "logs"), exist_ok=True)
                with open(os.path.join(WORKSPACE, "storage", "logs", "mail.log"), "a") as mf:
                    mf.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] [TEMPLATE: welcome] TO: {email_lower} | SUBJECT: Welcome to Alliance Bank — Your Account Details | ACC: {new_acc_num}\n")
            except Exception:
                pass

            STATE["registration_success"] = {
                "first_name": first_name,
                "last_name": last_name,
                "email": email_lower,
                "account_number": new_acc_num,
                "account_type": account_type,
                "currency": "USD",
                "email_sent": True
            }

            self.send_response(302)
            self.send_header("Location", "/register/success")
            self.end_headers()
            return

        # 0.1 Resend Welcome Email
        if parsed.path == "/register/resend-welcome":
            now = time.time()
            last_resend = STATE.get("_last_welcome_resend", 0)
            if now - last_resend < 60:
                self.send_response(429)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({
                    "success": False,
                    "message": "A welcome email was recently dispatched. Please wait before requesting another.",
                    "retry_after": int(60 - (now - last_resend))
                }).encode('utf-8'))
                return
            STATE["_last_welcome_resend"] = now
            target_email = data.get("email") or STATE.get("registration_success", {}).get("email") or STATE["user"]["email"]
            STATE.setdefault("email_logs", []).append({
                "id": len(STATE.get("email_logs", [])) + 1,
                "user_id": STATE["user"]["id"],
                "recipient": target_email,
                "subject": "Welcome to Alliance Bank — Your Account Details",
                "template": "welcome",
                "status": "sent",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            })
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({
                "success": True,
                "message": "Welcome email resent successfully. Please check your inbox."
            }).encode('utf-8'))
            return

        # 0.11 Customer Forgot Password Request
        if parsed.path == "/forgot-password":
            cfg = platform_settings_service.get_platform_settings(STATE)
            if not cfg.get("allow_password_reset", True):
                self.send_response(403)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"success": False, "error": "Password resets are temporarily disabled by the administrator."}).encode('utf-8'))
                return

            email_val = str(data.get("email", "")).lower().strip()
            generic_response = {
                "success": True,
                "message": "If an account is associated with that email address, password reset instructions have been dispatched to your inbox."
            }
            if not email_val or "@" not in email_val:
                self.send_response(400)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"success": False, "error": "A valid email address is required."}).encode('utf-8'))
                return

            # Rate limiting check: max 1 per 30 seconds for same email
            now = time.time()
            resets = STATE.get("password_resets", [])
            recent = [r for r in resets if r.get("email") == email_val and (now - r.get("_timestamp", 0)) < 30]
            if recent:
                self.send_response(429)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({
                    "success": False,
                    "error": "A password reset link was recently requested. Please check your inbox or wait before requesting another."
                }).encode('utf-8'))
                return

            user = next((u for u in STATE.get("users", []) if u.get("email", "").lower() == email_val), None)
            if user:
                token = secrets.token_urlsafe(32)
                reset_record = {
                    "id": len(STATE.setdefault("password_resets", [])) + 1,
                    "user_id": user["id"],
                    "email": email_val,
                    "token": token,
                    "_timestamp": now,
                    "expires_at": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(now + 3600)),
                    "used_at": None,
                    "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
                }
                STATE["password_resets"].append(reset_record)

                try:
                    mail_service.send_notification_email(
                        recipient=email_val,
                        template="password_reset",
                        context={
                            "first_name": user.get("first_name", "Customer"),
                            "token": token
                        },
                        user_id=user["id"],
                        idempotency_key=f"pwd_reset_{token}",
                        STATE=STATE
                    )
                except Exception:
                    pass

            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(generic_response).encode('utf-8'))
            return

        # 0.12 Customer Reset Password Submission
        if parsed.path == "/reset-password":
            token = str(data.get("token", "")).strip()
            new_pass = str(data.get("password", ""))
            confirm_pass = str(data.get("password_confirmation", ""))

            if not token:
                self.send_response(400)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"success": False, "error": "A valid password reset token is required."}).encode('utf-8'))
                return

            if not new_pass or len(new_pass) < 8:
                self.send_response(400)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"success": False, "error": "Password must be at least 8 characters in length."}).encode('utf-8'))
                return

            if new_pass != confirm_pass:
                self.send_response(400)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"success": False, "error": "Passwords do not match."}).encode('utf-8'))
                return

            reset_record = next((r for r in STATE.get("password_resets", []) if r.get("token") == token), None)
            now_str = time.strftime("%Y-%m-%d %H:%M:%S")

            if not reset_record or reset_record.get("used_at") is not None or reset_record.get("expires_at", "") < now_str:
                self.send_response(400)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({
                    "success": False,
                    "error": "This password reset link is invalid or has expired. Please request a new link."
                }).encode('utf-8'))
                return

            reset_record["used_at"] = now_str

            target_user = next((u for u in STATE.get("users", []) if u.get("id") == reset_record.get("user_id")), None)
            if target_user:
                target_user["password"] = new_pass
                STATE.setdefault("audit_logs", []).append({
                    "action": "user_password_reset_completed",
                    "user_id": target_user["id"],
                    "created_at": now_str,
                    "details": f"Password reset successfully executed for user {target_user['email']} via verified single-use token."
                })
                try:
                    mail_service.send_notification_email(
                        recipient=target_user["email"],
                        template="security_alert",
                        context={
                            "first_name": target_user.get("first_name", "Customer"),
                            "event_title": "Password Reset Successfully",
                            "details": "Your Alliance Bank password has been updated. If you did not initiate this change, freeze your account immediately.",
                            "ip_address": "127.0.0.1",
                            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S UTC")
                        },
                        user_id=target_user["id"],
                        idempotency_key=f"sec_alert_pwd_{token}",
                        STATE=STATE
                    )
                except Exception:
                    pass

            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({
                "success": True,
                "message": "Your password has been reset successfully. You may now sign in with your new credentials."
            }).encode('utf-8'))
            return

        # 0.13 Customer Resend Email Verification
        if parsed.path == "/resend-verification":
            email_val = str(data.get("email") or STATE.get("user", {}).get("email", "")).lower().strip()
            target_user = next((u for u in STATE.get("users", []) if u.get("email", "").lower() == email_val), None) or STATE.get("user")

            verif_token = secrets.token_urlsafe(32)
            STATE.setdefault("email_verifications", []).append({
                "user_id": target_user.get("id", 2),
                "email": email_val,
                "token": verif_token,
                "expires_at": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time() + 86400)),
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            })

            try:
                mail_service.send_notification_email(
                    recipient=email_val,
                    template="email_verification",
                    context={
                        "first_name": target_user.get("first_name", "Customer"),
                        "token": verif_token
                    },
                    user_id=target_user.get("id", 2),
                    idempotency_key=f"verif_resend_{verif_token}",
                    STATE=STATE
                )
            except Exception:
                pass

            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({
                "success": True,
                "message": f"Verification email dispatched to {email_val}. Please check your inbox."
            }).encode('utf-8'))
            return

        # 0.2 Customer KYC Submission
        if parsed.path == "/kyc":
            doc_type = data.get("document_type", "Passport")
            id_num = data.get("id_number", "VERIFIED-ID-99")
            notes = data.get("notes", "")
            new_sub_id = len(STATE.get("kyc_verifications", [])) + 1
            new_sub = {
                "id": new_sub_id,
                "user_id": STATE["user"]["id"],
                "first_name": STATE["user"]["first_name"],
                "last_name": STATE["user"]["last_name"],
                "email": STATE["user"]["email"],
                "account_number": STATE["accounts"][0]["account_number"],
                "document_type": doc_type,
                "id_number": id_num,
                "document_path": f"/storage/kyc/kyc_{new_sub_id}.jpg",
                "status": "pending_review",
                "notes": notes,
                "rejection_reason": None,
                "submitted_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "reviewed_by": None,
                "reviewed_at": None
            }
            STATE.setdefault("kyc_verifications", []).append(new_sub)
            STATE["user"]["kyc_status"] = "pending_review"
            STATE["user"]["kyc_document_type"] = doc_type
            STATE["user"]["kyc_submitted_at"] = new_sub["submitted_at"]

            match_user = next((u for u in STATE.get("users", []) if u["id"] == STATE["user"]["id"]), None)
            if match_user:
                match_user["kyc_status"] = "pending_review"
                match_user["kyc_document_type"] = doc_type
                match_user["kyc_submitted_at"] = new_sub["submitted_at"]

            STATE.setdefault("email_logs", []).append({
                "id": len(STATE.get("email_logs", [])) + 1,
                "user_id": STATE["user"]["id"],
                "recipient": STATE["user"]["email"],
                "subject": "Identity Verification Documents Received — Alliance Bank",
                "template": "kyc_submitted",
                "status": "sent",
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            })

            self.send_response(302)
            self.send_header("Location", "/kyc")
            self.end_headers()
            return

        # 0.3 Dismiss KYC Notice
        if parsed.path == "/kyc/dismiss-notice":
            STATE["kyc_reminder_dismissed"] = True
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"success": True}).encode('utf-8'))
            return

        # 1. Recipient Lookup API
        if parsed.path == "/transfers/find-recipient":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            query = data.get("query", "").strip()
            lookup_type = data.get("type", "email")

            if lookup_type == "email" and ("abraham" in query.lower() or "elochukwu" in query.lower() or query == STATE["user"]["email"]):
                res = {"success": False, "error": "You cannot transfer funds to yourself."}
            elif lookup_type == "account_number" and ("8047291635" in query or "0515705231" in query or STATE["accounts"][0]["account_number"] in query):
                res = {"success": False, "error": "You cannot transfer funds to your own account number."}
            elif lookup_type == "email" and ("sarah" in query.lower() or query == "sarah@bnkfx.com" or "@" in query):
                res = {
                    "success": True,
                    "recipient": {
                        "id": 3,
                        "name": "Sarah Connor",
                        "email": query if ("@" in query and "sarah" not in query.lower()) else "sarah@bnkfx.com",
                        "account_id": 3,
                        "account_number": "4910283746",
                        "masked_account_number": "••••••3746",
                        "currency": "USD",
                        "status": "Eligible"
                    }
                }
            elif lookup_type == "account_number" and ("4910283746" in query or "3746" in query or len(query.replace("-", "").replace(" ", "")) >= 8):
                clean_acc = query.replace("-", "").replace(" ", "")
                res = {
                    "success": True,
                    "recipient": {
                        "id": 3,
                        "name": "Sarah Connor",
                        "email": "sarah@bnkfx.com",
                        "account_id": 3,
                        "account_number": clean_acc if len(clean_acc) >= 8 else "4910283746",
                        "masked_account_number": f"••••••{clean_acc[-4:]}" if len(clean_acc) >= 4 else "••••••3746",
                        "currency": "USD",
                        "status": "Eligible"
                    }
                }
            else:
                res = {
                    "success": False,
                    "error": "We couldn't find an eligible account with those details. (Hint: Try 'sarah@bnkfx.com' or '4910283746')"
                }
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 2. Execute Transfer API
        if parsed.path == "/transfers/send":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            if STATE.get("user", {}).get("status") == "suspended":
                res = {"success": False, "error": f"Account suspended: {STATE['user'].get('suspended_reason', 'Compliance hold')}. Transfers are disabled."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return
            amt = float(data.get("amount", 100))
            if amt <= 0:
                res = {"success": False, "error": "Transfer amount must be greater than zero."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return
            if amt > STATE["accounts"][0]["balance"]:
                res = {"success": False, "error": f"Insufficient available balance. You currently have ${STATE['accounts'][0]['balance']:.2f} USD."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return

            ref = "TXN-20261027-" + hashlib.sha256(str(time.time()).encode()).hexdigest()[:8].upper()
            STATE["accounts"][0]["balance"] -= amt
            new_tx = {
                "ref": ref,
                "direction": "sent",
                "sender": f"{STATE['user']['first_name']} {STATE['user']['last_name']}",
                "sender_email": STATE['user']['email'],
                "sender_acc": STATE['accounts'][0]['account_number'],
                "recipient": "Sarah Connor",
                "recipient_email": "sarah@bnkfx.com",
                "recipient_acc": "4910283746",
                "amount": amt,
                "currency": "USD",
                "fee": 0.00,
                "total": amt,
                "status": "Completed",
                "date": "Just now"
            }
            STATE["transfers"].insert(0, new_tx)

            # Decoupled Non-blocking Notification Dispatch
            try:
                mail_service.send_notification_email(
                    recipient=STATE["user"]["email"],
                    template="transaction",
                    context={
                        "role": "debit",
                        "first_name": STATE["user"]["first_name"],
                        "reference": ref,
                        "amount": amt,
                        "currency": "USD",
                        "counterparty": "Sarah Connor",
                        "type": "Internal Transfer Out",
                        "timestamp": time.strftime("%Y-%m-%d %H:%M:%S UTC"),
                        "balance": STATE["accounts"][0]["balance"]
                    },
                    user_id=STATE["user"]["id"],
                    idempotency_key=f"tx_debit_{ref}",
                    STATE=STATE
                )
                mail_service.send_notification_email(
                    recipient="sarah@bnkfx.com",
                    template="transaction",
                    context={
                        "role": "credit",
                        "first_name": "Sarah",
                        "reference": ref,
                        "amount": amt,
                        "currency": "USD",
                        "counterparty": f"{STATE['user']['first_name']} {STATE['user']['last_name']}",
                        "type": "Internal Transfer In",
                        "timestamp": time.strftime("%Y-%m-%d %H:%M:%S UTC"),
                        "balance": None
                    },
                    user_id=3,
                    idempotency_key=f"tx_credit_{ref}",
                    STATE=STATE
                )
            except Exception:
                pass

            res = {
                "success": True,
                "transfer": {
                    "reference": ref,
                    "amount": amt,
                    "currency": "USD",
                    "status": "completed"
                }
            }
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 3. Crypto Deposit API (Initiate)
        if parsed.path == "/deposits/initiate":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            if STATE.get("user", {}).get("status") == "suspended":
                res = {"success": False, "error": f"Account suspended: {STATE['user'].get('suspended_reason', 'Compliance hold')}. Deposits are disabled."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return

            asset = str(data.get("asset", "USDC")).upper()
            net = str(data.get("network", "ERC20")).upper()
            amt = float(data.get("amount", 500))

            matching_pm = None
            for pm in STATE.get("payment_methods", []):
                if pm.get("status") == "active" and str(pm.get("code", "")).upper() == asset:
                    if str(pm.get("network", "")).upper() == net or (asset == "BTC" and str(pm.get("network", "")).upper() == "BTC") or (asset == "ETH" and str(pm.get("network", "")).upper() == "ERC20"):
                        matching_pm = pm
                        break

            if not matching_pm:
                res = {"success": False, "error": f"The deposit method for {asset} on {net} network is currently disabled or unavailable."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return

            addr = matching_pm["wallet_address"]
            net_name = matching_pm["name"]
            confs = int(matching_pm.get("required_confirmations", 12))
            min_dep = float(matching_pm.get("min_deposit", 50.0))
            max_dep = float(matching_pm.get("max_deposit", 100000.0))

            if amt < min_dep or amt > max_dep:
                res = {"success": False, "error": f"Deposit amount must be between ${min_dep:,.2f} and ${max_dep:,.2f} USD."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return

            if asset == "BTC":
                rate = 68500.0
                crypto_amt = round(amt / rate, 8)
            elif asset == "ETH":
                rate = 2650.0
                crypto_amt = round(amt / rate, 6)
            else:
                rate = 1.0
                crypto_amt = amt

            new_id = len(STATE["deposits"]) + 1
            ref = "DEP-" + hashlib.sha256(str(time.time()).encode()).hexdigest()[:8].upper()
            new_dep = {
                "id": new_id,
                "reference": ref,
                "user_id": STATE["user"]["id"],
                "customer_name": f"{STATE['user']['first_name']} {STATE['user']['last_name']}",
                "customer_email": STATE["user"]["email"],
                "account_number": STATE["accounts"][0]["account_number"],
                "asset": asset,
                "network": net_name,
                "deposit_address": addr,
                "tx_hash": None,
                "amount": amt,
                "credited_amount": 0.0,
                "confirmations": 0,
                "required_confirmations": confs,
                "status": "awaiting_deposit",
                "created_at": "Just now"
            }
            STATE["deposits"].insert(0, new_dep)

            res = {
                "success": True,
                "data": {
                    "deposit": new_dep,
                    "reference": ref,
                    "address": addr,
                    "qr_svg": generate_svg_qr(addr, 200),
                    "asset": asset,
                    "network": net,
                    "network_name": net_name,
                    "required_confirmations": confs,
                    "min_deposit": min_dep,
                    "max_deposit": max_dep,
                    "requested_amount": amt,
                    "estimated_crypto_amount": crypto_amt,
                    "exchange_rate": rate,
                    "fee": 0.0,
                    "estimated_account_credit": amt,
                    "status": "awaiting_deposit",
                    "date_initiated": "Just now"
                }
            }
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 3.1. Customer Confirms Sent Funds (Transitions to pending_review, DOES NOT credit ledger)
        if parsed.path == "/deposits/confirm-sent":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            ref = data.get("reference")
            dep_id = data.get("deposit_id")
            dep = None
            if dep_id:
                dep = next((d for d in STATE["deposits"] if d["id"] == int(dep_id)), None)
            if not dep and ref:
                dep = next((d for d in STATE["deposits"] if d["reference"] == ref), None)
            if not dep and STATE["deposits"]:
                dep = STATE["deposits"][0]

            if dep:
                if dep["status"] in ["awaiting_deposit", "awaiting_payment"]:
                    dep["status"] = "pending_review"
                tx_hash = data.get("tx_hash")
                if tx_hash:
                    dep["tx_hash"] = tx_hash
                res = {
                    "success": True,
                    "status": dep["status"],
                    "deposit": dep,
                    "message": "Your deposit confirmation has been received. Your transaction is awaiting verification and review. Your account will be credited once the deposit has been verified and approved."
                }
            else:
                res = {"success": False, "error": "Deposit record not found."}

            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 3.2. Administrator Deposit Approval API
        if parsed.path.startswith("/admin/deposits/") and parsed.path.endswith("/approve"):
            parts = parsed.path.strip("/").split("/")
            dep_id = int(parts[2])
            dep = next((d for d in STATE["deposits"] if d["id"] == dep_id), None)
            if dep and dep["status"] != "credited":
                amt = float(data.get("amount", dep["amount"]))
                STATE["accounts"][0]["balance"] += amt
                dep["status"] = "credited"
                dep["credited_amount"] = amt
                dep["tx_hash"] = data.get("tx_hash") or f"0x{hashlib.sha256(str(time.time()).encode()).hexdigest()}"
                
                # Decoupled Deposit Credited Notification
                try:
                    target_user = STATE.get("user", {})
                    mail_service.send_notification_email(
                        recipient=target_user.get("email", "customer@bnkfx.com"),
                        template="deposit_update",
                        context={
                            "status": "credited",
                            "first_name": target_user.get("first_name", "Customer"),
                            "reference": dep.get("reference", f"DEP-{dep_id}"),
                            "amount": amt,
                            "currency": dep.get("currency", "USD"),
                            "network": dep.get("network", "Base"),
                            "wallet_address": dep.get("wallet_address", ""),
                            "tx_hash": dep.get("tx_hash", ""),
                            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S UTC")
                        },
                        user_id=target_user.get("id", 2),
                        idempotency_key=f"dep_credit_{dep_id}",
                        STATE=STATE
                    )
                except Exception:
                    pass

                res = {"success": True, "message": f"Deposit #{dep['reference']} credited ${amt:.2f} to customer account."}
            elif dep and dep["status"] == "credited":
                res = {"success": True, "already_credited": True, "message": "Deposit already credited."}
            else:
                res = {"success": False, "error": "Deposit not found."}

            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 3.3. Administrator Deposit Rejection API
        if parsed.path.startswith("/admin/deposits/") and parsed.path.endswith("/reject"):
            parts = parsed.path.strip("/").split("/")
            dep_id = int(parts[2])
            dep = next((d for d in STATE["deposits"] if d["id"] == dep_id), None)
            if dep and dep["status"] != "credited":
                dep["status"] = "rejected"
                rej_reason = data.get("reason", "Administrative compliance review")
                dep["rejection_reason"] = rej_reason

                try:
                    target_user = STATE.get("user", {})
                    mail_service.send_notification_email(
                        recipient=target_user.get("email", "customer@bnkfx.com"),
                        template="deposit_update",
                        context={
                            "status": "rejected",
                            "first_name": target_user.get("first_name", "Customer"),
                            "reference": dep.get("reference", f"DEP-{dep_id}"),
                            "amount": dep.get("amount", 0.0),
                            "currency": dep.get("currency", "USD"),
                            "network": dep.get("network", "Base"),
                            "wallet_address": dep.get("wallet_address", ""),
                            "reason": rej_reason,
                            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S UTC")
                        },
                        user_id=target_user.get("id", 2),
                        idempotency_key=f"dep_reject_{dep_id}",
                        STATE=STATE
                    )
                except Exception:
                    pass

                res = {"success": True, "message": f"Deposit #{dep['reference']} rejected."}
            elif dep and dep["status"] == "credited":
                res = {"success": False, "error": "Cannot reject an already credited deposit."}
            else:
                res = {"success": False, "error": "Deposit not found."}

            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 4. Simulate Credit API (Testing)
        if parsed.path == "/deposits/simulate-credit":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            amt = float(data.get("amount", 250))
            STATE["accounts"][0]["balance"] += amt
            res = {"success": True, "message": f"Successfully credited ${amt:.2f} via double-entry ledger!"}
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 4.8. Apply for Card API
        if parsed.path == "/cards/apply":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            if STATE.get("user", {}).get("status") == "suspended":
                res = {"success": False, "error": "Your account is suspended. Card applications are disabled."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return

            prod_id = int(data.get("product_id", 1))
            prod = next((p for p in STATE.get("card_products", []) if p["id"] == prod_id), None)
            if not prod or prod.get("is_active", 1) != 1:
                res = {"success": False, "error": "Selected card tier is currently unavailable."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return

            user_bal = float(STATE["accounts"][0]["balance"])
            fee = float(prod.get("issuance_fee", prod.get("fee", 0.0)))
            min_bal = float(prod.get("min_balance_required", 0.0))

            if user_bal < min_bal:
                res = {"success": False, "error": f"Minimum balance requirement not met. This card tier requires at least ${min_bal:,.2f} in available funds (current: ${user_bal:,.2f})."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return

            if user_bal < fee:
                res = {"success": False, "error": f"Insufficient available balance to cover the ${fee:,.2f} issuance fee (current: ${user_bal:,.2f})."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return

            if fee > 0:
                STATE["accounts"][0]["balance"] -= fee
                STATE.setdefault("transactions", []).insert(0, {
                    "id": len(STATE.get("transactions", [])) + 1,
                    "type": "debit",
                    "category": "card_issuance_fee",
                    "amount": -fee,
                    "currency": "USD",
                    "status": "completed",
                    "reference": f"FEE-CRD-{random.randint(10000, 99999)}",
                    "description": f"Card Issuance Fee - {prod['name']}",
                    "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
                })

            new_order_id = max([o["id"] for o in STATE.get("card_orders", [])] + [0]) + 1
            order_ref = f"ORD-CRD-{random.randint(10000, 99999)}"
            user_name = f"{STATE.get('user', {}).get('first_name', 'Elochukwu')} {STATE.get('user', {}).get('last_name', 'Elom')}".strip()

            new_order = {
                "id": new_order_id,
                "reference": order_ref,
                "user_id": STATE.get("user", {}).get("id", 2),
                "user_name": user_name,
                "email": STATE.get("user", {}).get("email", "customer@bnkfx.com"),
                "product_id": prod["id"],
                "product_name": prod["name"],
                "card_type": prod.get("card_type", prod.get("type", "virtual")),
                "network": prod.get("network", "Monveracu Pay"),
                "card_design": prod.get("card_design", prod.get("design", "obsidian")),
                "payment_amount": fee,
                "min_balance_required": min_bal,
                "status": "pending",
                "rejection_reason": None,
                "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            STATE.setdefault("card_orders", []).insert(0, new_order)

            res = {
                "success": True,
                "message": f"Application for {prod['name']} submitted successfully! It is now pending administrator review.",
                "order": new_order,
                "available_balance": STATE["accounts"][0]["balance"]
            }
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 5. Purchase Card API
        if parsed.path == "/cards/purchase":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            if STATE.get("user", {}).get("status") == "suspended":
                res = {"success": False, "error": "Your account is suspended. Card issuance is disabled."}
                self.wfile.write(json.dumps(res).encode('utf-8'))
                return
            prod_id = int(data.get("product_id", 1))
            prod = next((p for p in STATE["card_products"] if p["id"] == prod_id), STATE["card_products"][0])
            if STATE["accounts"][0]["balance"] < prod["fee"]:
                res = {"success": False, "error": f"Insufficient USD balance. You need ${prod['fee']:.2f}."}
            else:
                STATE["accounts"][0]["balance"] -= prod["fee"]
                new_id = len(STATE["cards"]) + 1
                last_4 = str(random.randint(1000, 9999))
                holder_name = f"{STATE['user']['first_name']} {STATE['user']['last_name']}".upper()
                new_card = {
                    "id": new_id,
                    "name": prod["name"],
                    "product_name": prod["name"],
                    "type": prod.get("type", "virtual"),
                    "card_type": prod.get("type", "virtual"),
                    "network": prod.get("network", "Monveracu Pay"),
                    "design": prod.get("design", "obsidian"),
                    "card_design": prod.get("design", "obsidian"),
                    "masked_number": f"•••• •••• •••• {last_4}",
                    "card_number_masked": f"•••• •••• •••• {last_4}",
                    "last_four": last_4,
                    "exp": f"{random.randint(1, 12):02d}/31",
                    "expiry_month": 10,
                    "expiry_year": 2031,
                    "holder": holder_name,
                    "card_holder_name": holder_name,
                    "status": "active",
                    "daily_limit": prod["limit"],
                    "spent_today": 0.0,
                    "currency": "USD"
                }
                STATE["cards"].append(new_card)

                # Record completed order
                order_ref = f"ORD-CRD-{random.randint(10000, 99999)}"
                new_order = {
                    "id": len(STATE.setdefault("card_orders", [])) + 1,
                    "reference": order_ref,
                    "user_id": STATE.get("user", {}).get("id", 2),
                    "user_name": f"{STATE['user']['first_name']} {STATE['user']['last_name']}",
                    "email": STATE["user"]["email"],
                    "product_id": prod["id"],
                    "product_name": prod["name"],
                    "card_type": prod.get("type", "virtual"),
                    "network": prod.get("network", "Monveracu Pay"),
                    "card_design": prod.get("design", "obsidian"),
                    "payment_amount": prod["fee"],
                    "min_balance_required": prod.get("min_balance_required", 0.0),
                    "status": "completed",
                    "rejection_reason": None,
                    "created_at": time.strftime("%Y-%m-%d %H:%M:%S")
                }
                STATE["card_orders"].insert(0, new_order)

                res = {"success": True, "message": f"Successfully purchased {prod['name']}! Card is active and ready to use.", "card": new_card}
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 6. Toggle Card Freeze API
        if parsed.path == "/cards/toggle-freeze":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            card_id = int(data.get("card_id", 1))
            card = next((c for c in STATE["cards"] if c["id"] == card_id), STATE["cards"][0])
            card["status"] = "frozen" if card["status"] == "active" else "active"
            res = {"success": True, "status": card["status"], "message": f"{card['name']} is now {card['status']}."}
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 7. Exchange Quote API
        if parsed.path == "/exchange/quote":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            amt = float(data.get("amount", 100))
            from_curr = data.get("from_currency", "USD")
            to_curr = data.get("to_currency", "USDC")

            # Reasonable demo exchange rates
            rates = {
                ("USD", "USDC"): 1.0,
                ("USDC", "USD"): 1.0,
                ("USD", "EUR"): 0.92,
                ("EUR", "USD"): 1.087,
                ("USD", "BTC"): 0.0000147,
                ("BTC", "USD"): 68000.0,
                ("USD", "ETH"): 0.000384,
                ("ETH", "USD"): 2600.0,
            }
            rate = rates.get((from_curr, to_curr), 1.0)
            gross = amt * rate
            fee = gross * 0.005
            net = gross - fee

            res = {
                "success": True,
                "quote": {
                    "exchange_rate": rate,
                    "gross_to_amount": gross,
                    "fee_amount": fee,
                    "net_to_amount": net
                }
            }
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 8. Execute Exchange API
        if parsed.path == "/exchange/execute":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            amt = float(data.get("amount", 100))
            from_curr = data.get("from_currency", "USD")
            to_curr = data.get("to_currency", "USDC")

            if from_curr == "USD":
                if STATE["accounts"][0]["balance"] < amt:
                    res = {"success": False, "error": f"Insufficient available USD balance."}
                else:
                    STATE["accounts"][0]["balance"] -= amt
                    STATE["accounts"][1]["balance"] += (amt * 0.995)
                    res = {"success": True, "message": f"Successfully exchanged ${amt:.2f} USD to {(amt * 0.995):.2f} USDC!"}
            elif from_curr == "USDC":
                if STATE["accounts"][1]["balance"] < amt:
                    res = {"success": False, "error": f"Insufficient available USDC balance."}
                else:
                    STATE["accounts"][1]["balance"] -= amt
                    STATE["accounts"][0]["balance"] += (amt * 0.995)
                    res = {"success": True, "message": f"Successfully exchanged {amt:.2f} USDC to ${(amt * 0.995):.2f} USD!"}
            else:
                res = {"success": True, "message": f"Conversion from {from_curr} to {to_curr} processed via double-entry ledger!"}
            self.wfile.write(json.dumps(res).encode('utf-8'))
            return

        # 8. Create Investment API
        if parsed.path in ["/investments", "/investments/create"]:
            is_json = self.headers.get("Content-Type", "").startswith("application/json") or self.headers.get("X-Requested-With") == "XMLHttpRequest"
            if STATE.get("user", {}).get("status") == "suspended":
                err = "Account is suspended. Investment operations are disabled."
                if is_json:
                    self.send_response(400)
                    self.send_header("Content-Type", "application/json")
                    self.end_headers()
                    self.wfile.write(json.dumps({"success": False, "error": err}).encode('utf-8'))
                else:
                    self.send_response(302)
                    self.send_header("Location", "/investments?error=" + urllib.parse.quote(err))
                    self.end_headers()
                return

            try:
                stock_id = int(data.get("stock_id", 0))
                plan_id = int(data.get("plan_id", 0))
                amt = float(data.get("amount", 0))
                acc_id = int(data.get("account_id") or STATE["accounts"][0]["id"])
            except Exception:
                amt = 0.0
                stock_id = 0
                plan_id = 0
                acc_id = 1

            stock = next((s for s in STATE.get("stocks", []) if s["id"] == stock_id), None)
            plan = next((p for p in STATE.get("investment_plans", []) if p["id"] == plan_id), None)
            account = next((a for a in STATE.get("accounts", []) if a["id"] == acc_id), STATE["accounts"][0])

            err = None
            if not stock or stock.get("status") != "active":
                err = "Selected stock opportunity is not active or invalid."
            elif not plan or plan.get("status") != "active":
                err = "Selected investment plan is invalid or inactive."
            elif amt <= 0:
                err = "Investment amount must be greater than zero."
            elif amt < plan.get("min_amount", 50.0):
                err = f"Minimum investment for {plan['name']} is ${plan['min_amount']:,.2f}."
            elif not (plan.get("is_unlimited") or plan.get("max_amount") is None) and amt > plan.get("max_amount", 100000.0):
                err = f"Maximum investment for {plan['name']} is ${plan['max_amount']:,.2f}."
            elif account["balance"] < amt:
                err = f"Insufficient available balance in {account['currency']} account. Current balance: ${account['balance']:,.2f}."

            if err:
                if is_json:
                    self.send_response(400)
                    self.send_header("Content-Type", "application/json")
                    self.end_headers()
                    self.wfile.write(json.dumps({"success": False, "error": err}).encode('utf-8'))
                else:
                    self.send_response(302)
                    self.send_header("Location", "/investments?error=" + urllib.parse.quote(err))
                    self.end_headers()
                return

            # Debit account balance atomically
            account["balance"] -= amt
            ret_pct = float(plan["return_percentage"])
            profit = amt * (ret_pct / 100.0)
            expected_payout = amt + profit
            duration = int(plan["duration_hours"])
            ref = "INV-" + hashlib.sha256(f"{time.time()}_{stock_id}_{amt}".encode()).hexdigest()[:8].upper()

            now_ts = time.time()
            now_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now_ts))
            maturity_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now_ts + (duration * 3600)))

            new_inv = {
                "id": len(STATE.get("investments", [])) + 1,
                "user_id": STATE.get("user", {}).get("id", 2),
                "stock_id": stock["id"],
                "plan_id": plan["id"],
                "account_id": account["id"],
                "reference": ref,
                "stock_ticker": stock["ticker"],
                "stock_name": stock["name"],
                "stock_logo_url": stock.get("logo_url") or f"/assets/images/stocks/{stock['ticker'].lower()}.svg",
                "plan_name": plan["name"],
                "amount": amt,
                "return_percentage": ret_pct,
                "duration_hours": duration,
                "expected_payout": expected_payout,
                "started_at": now_str,
                "maturity_at": maturity_str,
                "status": "active",
                "created_at": now_str
            }
            STATE.setdefault("investments", []).append(new_inv)

            # Record in transfer ledger activity
            new_tx = {
                "type": "transfer",
                "direction": "sent",
                "title": f"Stock Investment: {stock['ticker']} ({plan['name']})",
                "amount": amt,
                "total": amt,
                "currency": "USD",
                "status": "Completed",
                "date": "Just now",
                "reference": ref
            }
            STATE.setdefault("transfers", []).insert(0, new_tx)

            if is_json:
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"success": True, "message": f"Successfully allocated ${amt:,.2f} into {stock['ticker']}.", "investment": new_inv}).encode('utf-8'))
            else:
                self.send_response(302)
                self.send_header("Location", "/investments")
                self.end_headers()
            return

        # 9. Redeem Investment API
        if parsed.path.startswith("/investments/") and parsed.path.endswith("/redeem"):
            parts = parsed.path.strip("/").split("/")
            inv_id = parts[1]
            inv = next((i for i in STATE.get("investments", []) if str(i["id"]) == str(inv_id) or i.get("reference") == inv_id), None)
            is_json = self.headers.get("Content-Type", "").startswith("application/json") or self.headers.get("X-Requested-With") == "XMLHttpRequest"

            if not inv:
                err = "Investment record not found."
                code = 404
            elif inv.get("status") == "redeemed":
                err = "Investment has already been redeemed."
                code = 400
            else:
                # Check maturity
                now_str = time.strftime("%Y-%m-%d %H:%M:%S")
                if inv.get("status") != "matured" and now_str < inv.get("maturity_at", "9999"):
                    err = f"Investment has not reached maturity date yet. Matures at {inv.get('maturity_at')}."
                    code = 400
                else:
                    err = None

            if err:
                if is_json:
                    self.send_response(code)
                    self.send_header("Content-Type", "application/json")
                    self.end_headers()
                    self.wfile.write(json.dumps({"success": False, "error": err}).encode('utf-8'))
                else:
                    self.send_response(302)
                    self.send_header("Location", "/investments?error=" + urllib.parse.quote(err))
                    self.end_headers()
                return

            payout = float(inv.get("expected_payout", inv.get("amount", 0)))
            acc = next((a for a in STATE.get("accounts", []) if a["id"] == inv.get("account_id")), STATE["accounts"][0])
            acc["balance"] += payout

            inv["status"] = "redeemed"
            inv["redeemed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")

            redemption_rec = {
                "id": len(STATE.get("investment_redemptions", [])) + 1,
                "investment_id": inv["id"],
                "reference": inv.get("reference"),
                "principal_amount": inv.get("amount"),
                "profit_amount": payout - inv.get("amount"),
                "total_payout": payout,
                "redeemed_at": inv["redeemed_at"]
            }
            STATE.setdefault("investment_redemptions", []).append(redemption_rec)

            # Record credit in activity
            new_tx = {
                "type": "transfer",
                "direction": "received",
                "title": f"Maturity Proceeds: {inv['stock_ticker']}",
                "amount": payout,
                "total": payout,
                "currency": "USD",
                "status": "Completed",
                "date": "Just now",
                "reference": "RED-" + inv.get("reference", "")
            }
            STATE.setdefault("transfers", []).insert(0, new_tx)

            if is_json:
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"success": True, "message": f"Successfully redeemed ${payout:,.2f} USD.", "data": redemption_rec}).encode('utf-8'))
            else:
                self.send_response(302)
                self.send_header("Location", "/investments")
                self.end_headers()
            return

        # Fallback
        self.send_response(302)
        self.send_header("Location", "/dashboard")
        self.end_headers()

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        path = parsed.path

        # User Language API
        if path == "/api/user/language":
            lang = STATE.get("user", {}).get("preferred_language", "en")
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(json.dumps({"language": lang}).encode('utf-8'))
            return

        # 1. Static Assets (CSS, JS, Fonts)
        if path.startswith("/assets/"):
            return super().do_GET()

        # Public Settings API (JSON)
        if path in ["/api/settings/public", "/settings/public"]:
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            pub = platform_settings_service.get_public_settings(STATE)
            self.wfile.write(json.dumps(pub, indent=2).encode('utf-8'))
            return

        # Maintenance Mode Interception
        if platform_settings_service.is_maintenance_mode(STATE, user=STATE.get("user"), path=path):
            settings = platform_settings_service.get_platform_settings(STATE)
            if path.startswith("/api/") or "application/json" in self.headers.get("Accept", ""):
                self.send_response(503)
                self.send_header("Content-Type", "application/json; charset=utf-8")
                self.end_headers()
                self.wfile.write(json.dumps({
                    "success": False,
                    "error": "System is currently undergoing scheduled maintenance.",
                    "maintenance_mode": True,
                    "message": settings.get("maintenance_mode_message")
                }).encode("utf-8"))
                return
            else:
                self.send_response(503)
                self.send_header("Content-Type", "text/html; charset=utf-8")
                self.end_headers()
                self.wfile.write(platform_settings_service.render_maintenance_page(settings).encode("utf-8"))
                return

        if path == "/admin/impersonate/exit" or path.startswith("/admin/uploads/"):
            import preview_admin
            if preview_admin.handle_admin_get(self, parsed, path, STATE, build_admin_layout):
                return

        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.end_headers()

        # 2. Public Landing Page ("Your Money. Your World.")
        if path == "/":
            view_path = os.path.join(VIEWS_DIR, "home", "index.php")
            with open(view_path, 'r', encoding='utf-8') as f:
                body = f.read().replace("<?= csrf_field() ?>", "")
            layout_path = os.path.join(VIEWS_DIR, "layouts", "main.php")
            with open(layout_path, 'r', encoding='utf-8') as f:
                layout = f.read()
            settings = platform_settings_service.get_platform_settings(STATE)
            brand_css = platform_settings_service.generate_brand_css(settings)
            platform_name = settings.get("platform_name", "Monveracu")
            html = layout.replace("<?= $content ?>", body)
            html = html.replace("<?= e($pageTitle ?? 'Monveracu | Smart Global Digital Banking') ?>", f"{platform_name} | Your Money. Your World.")
            html = html.replace("<!-- BRAND_CSS -->", brand_css)
            html = re.sub(r"<\?php.*?\?>", "", html, flags=re.DOTALL)
            html = re.sub(r"<\?=.*?\?>", "", html, flags=re.DOTALL)
            self.wfile.write(html.encode('utf-8'))
            return

        # 3. Authentication Pages (Login & Register)
        if path == "/login":
            view_path = os.path.join(VIEWS_DIR, "auth", "login.php")
            with open(view_path, 'r', encoding='utf-8') as f:
                html = f.read().replace("<?= csrf_field() ?>", "")
            settings = platform_settings_service.get_platform_settings(STATE)
            brand_css = platform_settings_service.generate_brand_css(settings)
            platform_name = settings.get("platform_name", "Alliance Bank")
            short_name = settings.get("short_name", "Alliance")
            html = html.replace("<?= e($platformName ?? 'Alliance Bank') ?>", platform_name)
            html = html.replace("<?= e($shortName ?? 'Alliance') ?>", short_name)
            html = html.replace("<?= e($pageTitle ?? 'Alliance Bank') ?>", f"{platform_name} | Log In")
            html = html.replace("<!-- BRAND_CSS -->", brand_css)
            html = re.sub(r"<\?php.*?\?>", "", html, flags=re.DOTALL)
            html = re.sub(r"<\?=.*?\?>", "", html, flags=re.DOTALL)
            self.wfile.write(html.encode('utf-8'))
            return

        if path == "/register":
            view_path = os.path.join(VIEWS_DIR, "auth", "register.php")
            with open(view_path, 'r', encoding='utf-8') as f:
                html = f.read().replace("<?= csrf_field() ?>", "")
            html = re.sub(r"<\?php.*?\?>", "", html, flags=re.DOTALL)
            html = re.sub(r"<\?=.*?\?>", "", html, flags=re.DOTALL)
            self.wfile.write(html.encode('utf-8'))
            return

        # 3.1 Registration Success Page (Module 3)
        if path == "/register/success":
            reg = STATE.get("registration_success", {})
            first_name = reg.get("first_name") or STATE["user"].get("first_name", "Customer")
            account_number = reg.get("account_number") or STATE["accounts"][0].get("account_number", "8047291635")
            account_type = reg.get("account_type") or STATE["accounts"][0].get("account_type", "Checking Account")
            currency = reg.get("currency", "USD")
            email = reg.get("email") or STATE["user"].get("email", "customer@bnkfx.com")

            html = f'''<!DOCTYPE html>
<html lang="en" class="h-full bg-[#0B0E14]">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome Aboard! | Alliance Bank</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/main.css">
</head>
<body class="min-h-full bg-[#0B0E14] text-white font-sans antialiased selection:bg-[#246BFD] selection:text-white flex flex-col justify-center items-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-xl w-full space-y-6">
        <div class="text-center">
            <a href="/" class="inline-flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-[#246BFD] to-[#60A5FA] flex items-center justify-center shadow-lg shadow-blue-500/25">
                    <i class="fa-solid fa-building-columns text-white text-lg"></i>
                </div>
                <span class="text-2xl font-bold tracking-tight text-white font-mono">ALLIANCE BANK</span>
            </a>
        </div>

        <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl p-6 sm:p-8 shadow-2xl relative overflow-hidden backdrop-blur-xl">
            <div class="absolute -top-24 left-1/2 -translate-x-1/2 w-72 h-72 bg-[#246BFD]/15 rounded-full blur-3xl pointer-events-none"></div>

            <div class="text-center relative z-10 space-y-3">
                <div class="w-16 h-16 rounded-full bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center mx-auto text-emerald-400">
                    <i class="fa-solid fa-check text-2xl"></i>
                </div>
                <h1 class="text-2xl sm:text-3xl font-extrabold text-white tracking-tight">Welcome Aboard!</h1>
                <p class="text-sm sm:text-base text-[#8F9CAE] max-w-md mx-auto leading-relaxed">
                    Hello <span class="text-white font-semibold">{first_name}</span>, your account has been created successfully. Your account details have been sent to your registered email address.
                </p>
            </div>

            <div class="mt-8 bg-[#0F131A] border border-[#282E3E] rounded-xl p-5 relative z-10 space-y-4">
                <div class="flex items-center justify-between pb-3 border-b border-[#282E3E]">
                    <div class="flex items-center gap-2">
                        <span class="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span>
                        <span class="text-xs font-bold uppercase tracking-wider text-[#246BFD]">Assigned Bank Account</span>
                    </div>
                    <span class="inline-flex items-center px-2 py-0.5 rounded text-[11px] font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                        Active & Provisioned
                    </span>
                </div>

                <div>
                    <label class="block text-xs font-medium text-[#8F9CAE] mb-1">Bank Account Number</label>
                    <div class="flex items-center justify-between bg-[#161A22] border border-[#282E3E] rounded-lg px-4 py-3">
                        <span id="account-number-text" class="font-mono text-lg sm:text-xl font-bold tracking-wider text-white">
                            {account_number}
                        </span>
                        <button id="copy-btn" onclick="copyAccountNumber()" class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium bg-[#246BFD]/10 text-[#246BFD] hover:bg-[#246BFD]/20 transition-all border border-[#246BFD]/20">
                            <i class="fa-regular fa-copy"></i>
                            <span id="copy-btn-label">Copy</span>
                        </button>
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4 pt-1">
                    <div>
                        <span class="block text-xs text-[#8F9CAE]">Account Type</span>
                        <span class="text-sm font-medium text-white">{account_type}</span>
                    </div>
                    <div>
                        <span class="block text-xs text-[#8F9CAE]">Primary Currency</span>
                        <span class="text-sm font-semibold text-emerald-400">{currency} (US Dollar)</span>
                    </div>
                </div>
            </div>

            <div class="mt-6 bg-[#246BFD]/5 border border-[#246BFD]/20 rounded-xl p-4 relative z-10 flex items-start gap-3.5">
                <div class="p-2 rounded-lg bg-[#246BFD]/10 text-[#246BFD] shrink-0 mt-0.5">
                    <i class="fa-regular fa-envelope text-base"></i>
                </div>
                <div class="space-y-1">
                    <h3 class="text-sm font-semibold text-white">Check Your Inbox</h3>
                    <p class="text-xs text-[#8F9CAE] leading-relaxed">
                        We've sent a welcome email containing your account details and information about getting started to <strong class="text-white">{email}</strong>. If you don't see it, please check your spam or junk folder.
                    </p>
                    <div class="inline-flex items-center gap-1.5 text-[11px] text-emerald-400 font-medium pt-1">
                        <i class="fa-solid fa-circle-check"></i> Delivery dispatched to mail service
                    </div>
                </div>
            </div>

            <div id="resend-feedback" class="hidden mt-4 p-3 rounded-lg text-xs font-medium"></div>

            <div class="mt-8 space-y-3 relative z-10">
                <a href="/login" class="w-full flex items-center justify-center gap-2 py-3.5 px-4 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-sm font-semibold shadow-lg shadow-blue-500/20 transition-all">
                    <span>Log In to Your Account</span>
                    <i class="fa-solid fa-arrow-right"></i>
                </a>
                <button id="resend-btn" onclick="resendWelcomeEmail()" class="w-full flex items-center justify-center gap-2 py-3 px-4 rounded-xl bg-[#0F131A] hover:bg-[#1a202c] border border-[#282E3E] text-[#8F9CAE] hover:text-white text-xs font-medium transition-all">
                    <i class="fa-solid fa-rotate-right"></i>
                    <span id="resend-btn-label">Resend Welcome Email</span>
                </button>
            </div>

            <div class="mt-6 pt-4 border-t border-[#282E3E] text-center text-[11px] text-[#5C6779]">
                Alliance Bank accounts are held with our FDIC-insured custodial partners. Never share your security credentials.
            </div>
        </div>
    </div>

    <script>
    function copyAccountNumber() {{
        const text = document.getElementById('account-number-text').innerText.trim();
        navigator.clipboard.writeText(text).then(() => {{
            const label = document.getElementById('copy-btn-label');
            label.innerText = 'Copied!';
            setTimeout(() => label.innerText = 'Copy', 2000);
        }});
    }}

    function resendWelcomeEmail() {{
        const btn = document.getElementById('resend-btn');
        const label = document.getElementById('resend-btn-label');
        const feedback = document.getElementById('resend-feedback');
        label.innerText = 'Dispatching email...';
        btn.disabled = true;

        fetch('/register/resend-welcome', {{
            method: 'POST',
            headers: {{ 'Content-Type': 'application/json' }},
            body: JSON.stringify({{ email: '{email}' }})
        }})
        .then(res => res.json())
        .then(data => {{
            feedback.classList.remove('hidden');
            if (data.success) {{
                feedback.className = 'mt-4 p-3 rounded-lg text-xs font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20';
                feedback.innerText = data.message || 'Welcome email resent successfully. Please check your inbox.';
            }} else {{
                feedback.className = 'mt-4 p-3 rounded-lg text-xs font-medium bg-rose-500/10 text-rose-400 border border-rose-500/20';
                feedback.innerText = data.message || 'Could not resend email.';
            }}
            label.innerText = 'Resend Welcome Email';
            btn.disabled = false;
        }})
        .catch(err => {{
            feedback.classList.remove('hidden');
            feedback.className = 'mt-4 p-3 rounded-lg text-xs font-medium bg-rose-500/10 text-rose-400 border border-rose-500/20';
            feedback.innerText = 'A network error occurred. Please try again.';
            label.innerText = 'Resend Welcome Email';
            btn.disabled = false;
        }});
    }}
    </script>
</body>
</html>'''
            self.wfile.write(html.encode('utf-8'))
            return

        # 3.12 Customer Forgot Password Page
        if path == "/forgot-password":
            html = f'''<!DOCTYPE html>
<html lang="en" class="h-full bg-[#0B0E14]">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password | Alliance Bank</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/main.css">
</head>
<body class="min-h-full bg-[#0B0E14] text-white font-sans antialiased selection:bg-[#246BFD] selection:text-white flex flex-col justify-center items-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-6">
        <div class="text-center">
            <a href="/" class="inline-flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-[#246BFD] to-[#60A5FA] flex items-center justify-center shadow-lg shadow-blue-500/25">
                    <i class="fa-solid fa-building-columns text-white text-lg"></i>
                </div>
                <span class="text-2xl font-bold tracking-tight text-white font-mono">ALLIANCE BANK</span>
            </a>
            <h2 class="mt-6 text-2xl font-bold tracking-tight text-white">Reset your password</h2>
            <p class="mt-2 text-xs text-[#8F9CAE]">Enter your registered email address and we'll dispatch a secure recovery link.</p>
        </div>

        <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl p-6 sm:p-8 shadow-2xl relative overflow-hidden">
            <div id="reset-success-box" class="hidden mb-5 p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/25 text-emerald-400 text-xs flex items-start gap-3">
                <i class="fa-solid fa-circle-check text-base mt-0.5"></i>
                <div>
                    <div class="font-bold">Instructions Dispatched</div>
                    <div class="mt-0.5 text-emerald-400/80">If an account is associated with that email, a password reset link has been dispatched to your inbox. Please check your inbox.</div>
                </div>
            </div>

            <div id="reset-error-box" class="hidden mb-5 p-3 rounded-xl bg-red-500/10 border border-red-500/25 text-red-400 text-xs flex items-center gap-2">
                <i class="fa-solid fa-circle-exclamation"></i>
                <span id="reset-error-msg"></span>
            </div>

            <form id="forgot-password-form" onsubmit="submitForgotPassword(event)" class="space-y-4">
                <div>
                    <label for="email" class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Registered Email Address</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-[#737D90]">
                            <i class="fa-regular fa-envelope"></i>
                        </div>
                        <input id="email" name="email" type="email" required autocomplete="email" placeholder="name@example.com"
                            class="block w-full pl-10 pr-3 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white placeholder-[#737D90] text-sm focus:outline-none focus:border-[#246BFD] transition-all">
                    </div>
                </div>

                <button type="submit" id="submit-btn" class="w-full py-3 px-4 rounded-xl bg-[#246BFD] hover:bg-blue-600 text-white font-semibold text-sm shadow-lg shadow-blue-600/25 transition-all flex items-center justify-center gap-2">
                    <i class="fa-solid fa-paper-plane text-xs"></i>
                    <span>Send Reset Instructions</span>
                </button>
            </form>

            <div class="mt-6 pt-5 border-t border-[#282E3E] text-center">
                <a href="/login" class="text-xs text-[#8F9CAE] hover:text-white flex items-center justify-center gap-2">
                    <i class="fa-solid fa-arrow-left text-[10px]"></i>
                    <span>Back to Sign In</span>
                </a>
            </div>
        </div>
    </div>

    <script>
    async function submitForgotPassword(e) {{
        e.preventDefault();
        const form = e.target;
        const btn = document.getElementById('submit-btn');
        const errBox = document.getElementById('reset-error-box');
        const errMsg = document.getElementById('reset-error-msg');
        const successBox = document.getElementById('reset-success-box');
        const email = document.getElementById('email').value.trim();

        errBox.classList.add('hidden');
        btn.disabled = true;
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin text-xs"></i><span>Dispatching Secure Link...</span>';

        try {{
            const res = await fetch('/forgot-password', {{
                method: 'POST',
                headers: {{ 'Content-Type': 'application/json', 'Accept': 'application/json' }},
                body: JSON.stringify({{ email: email }})
            }});
            const data = await res.json();
            if (res.ok) {{
                successBox.classList.remove('hidden');
                form.classList.add('hidden');
            }} else {{
                errMsg.textContent = data.error || 'Failed to dispatch password reset link.';
                errBox.classList.remove('hidden');
            }}
        }} catch (err) {{
            errMsg.textContent = 'A network error occurred. Please try again.';
            errBox.classList.remove('hidden');
        }} finally {{
            btn.disabled = false;
            btn.innerHTML = '<i class="fa-solid fa-paper-plane text-xs"></i><span>Send Reset Instructions</span>';
        }}
    }}
    </script>
</body>
</html>'''
            self.wfile.write(html.encode('utf-8'))
            return

        # 3.13 Customer Reset Password Page
        if path == "/reset-password":
            query = urllib.parse.parse_qs(parsed.query)
            token = query.get("token", [""])[0]

            # Validate token in STATE["password_resets"]
            now_str = time.strftime("%Y-%m-%d %H:%M:%S")
            reset_record = next((r for r in STATE.get("password_resets", []) if r.get("token") == token), None)
            is_valid = bool(reset_record and reset_record.get("used_at") is None and reset_record.get("expires_at", "") >= now_str)

            if not is_valid:
                # Invalid or Expired Token View
                html = f'''<!DOCTYPE html>
<html lang="en" class="h-full bg-[#0B0E14]">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invalid Reset Link | Alliance Bank</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/main.css">
</head>
<body class="min-h-full bg-[#0B0E14] text-white font-sans antialiased selection:bg-[#246BFD] selection:text-white flex flex-col justify-center items-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-6">
        <div class="text-center">
            <a href="/" class="inline-flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-[#246BFD] to-[#60A5FA] flex items-center justify-center shadow-lg shadow-blue-500/25">
                    <i class="fa-solid fa-building-columns text-white text-lg"></i>
                </div>
                <span class="text-2xl font-bold tracking-tight text-white font-mono">ALLIANCE BANK</span>
            </a>
        </div>

        <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl p-6 sm:p-8 shadow-2xl text-center space-y-5">
            <div class="w-14 h-14 rounded-2xl bg-red-500/15 text-red-400 border border-red-500/30 flex items-center justify-center mx-auto text-2xl">
                <i class="fa-solid fa-link-slash"></i>
            </div>
            <div>
                <h2 class="text-xl font-bold text-white">Reset Link Invalid or Expired</h2>
                <p class="text-xs text-[#8F9CAE] mt-2 leading-relaxed">
                    This password reset link is invalid, has already been used, or has expired after the 60-minute security window.
                </p>
            </div>

            <div class="pt-2">
                <a href="/forgot-password" class="inline-flex items-center justify-center gap-2 w-full py-3 px-4 rounded-xl bg-[#246BFD] hover:bg-blue-600 text-white font-semibold text-sm shadow-lg shadow-blue-600/25 transition-all">
                    <span>Request a New Reset Link</span>
                    <i class="fa-solid fa-arrow-right text-xs"></i>
                </a>
            </div>

            <div class="border-t border-[#282E3E] pt-4">
                <a href="/login" class="text-xs text-[#8F9CAE] hover:text-white">
                    Back to Sign In
                </a>
            </div>
        </div>
    </div>
</body>
</html>'''
                self.wfile.write(html.encode('utf-8'))
                return

            # Valid Token: Render Create New Password Form
            html = f'''<!DOCTYPE html>
<html lang="en" class="h-full bg-[#0B0E14]">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create New Password | Alliance Bank</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/main.css">
</head>
<body class="min-h-full bg-[#0B0E14] text-white font-sans antialiased selection:bg-[#246BFD] selection:text-white flex flex-col justify-center items-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-6">
        <div class="text-center">
            <a href="/" class="inline-flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-[#246BFD] to-[#60A5FA] flex items-center justify-center shadow-lg shadow-blue-500/25">
                    <i class="fa-solid fa-building-columns text-white text-lg"></i>
                </div>
                <span class="text-2xl font-bold tracking-tight text-white font-mono">ALLIANCE BANK</span>
            </a>
            <h2 class="mt-6 text-2xl font-bold tracking-tight text-white">Create New Password</h2>
            <p class="mt-2 text-xs text-[#8F9CAE]">Choose a strong, unique password to protect your account.</p>
        </div>

        <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl p-6 sm:p-8 shadow-2xl relative">
            <div id="reset-error-box" class="hidden mb-5 p-3 rounded-xl bg-red-500/10 border border-red-500/25 text-red-400 text-xs flex items-center gap-2">
                <i class="fa-solid fa-circle-exclamation"></i>
                <span id="reset-error-msg"></span>
            </div>

            <div id="reset-success-box" class="hidden mb-5 p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/25 text-emerald-400 text-xs text-center space-y-3">
                <i class="fa-solid fa-circle-check text-2xl text-emerald-400"></i>
                <div class="font-bold text-sm">Password Updated Successfully!</div>
                <div class="text-xs text-emerald-400/80">Your security profile has been updated. Redirecting to sign in...</div>
                <div class="pt-2">
                    <a href="/login" class="inline-block px-4 py-2 rounded-lg bg-emerald-500 text-slate-950 font-bold text-xs">Sign In Now</a>
                </div>
            </div>

            <form id="reset-password-form" onsubmit="submitNewPassword(event)" class="space-y-4">
                <input type="hidden" id="token" value="{html_lib.escape(token)}">

                <div>
                    <label for="new_password" class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">New Password</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-[#737D90]">
                            <i class="fa-solid fa-lock"></i>
                        </div>
                        <input id="new_password" name="password" type="password" required minlength="8" placeholder="••••••••"
                            class="block w-full pl-10 pr-10 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white placeholder-[#737D90] text-sm focus:outline-none focus:border-[#246BFD] transition-all">
                        <button type="button" onclick="togglePassVisibility('new_password', this)" class="absolute inset-y-0 right-0 pr-3 flex items-center text-[#737D90] hover:text-white">
                            <i class="fa-regular fa-eye text-xs"></i>
                        </button>
                    </div>
                </div>

                <div>
                    <label for="confirm_password" class="block text-xs font-semibold uppercase tracking-wider text-[#8F9CAE] mb-1.5">Confirm New Password</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-[#737D90]">
                            <i class="fa-solid fa-lock"></i>
                        </div>
                        <input id="confirm_password" name="password_confirmation" type="password" required minlength="8" placeholder="••••••••"
                            class="block w-full pl-10 pr-10 py-2.5 bg-[#12151B] border border-[#292E38] rounded-xl text-white placeholder-[#737D90] text-sm focus:outline-none focus:border-[#246BFD] transition-all">
                        <button type="button" onclick="togglePassVisibility('confirm_password', this)" class="absolute inset-y-0 right-0 pr-3 flex items-center text-[#737D90] hover:text-white">
                            <i class="fa-regular fa-eye text-xs"></i>
                        </button>
                    </div>
                </div>

                <div class="text-[11px] text-[#737D90] space-y-1 pt-1">
                    <div class="flex items-center gap-1.5"><i class="fa-solid fa-shield-halved text-[#246BFD]"></i> Minimum 8 characters</div>
                    <div class="flex items-center gap-1.5"><i class="fa-solid fa-circle-check text-emerald-400"></i> Never reuse passwords from other sites</div>
                </div>

                <button type="submit" id="reset-submit-btn" class="w-full py-3 px-4 rounded-xl bg-[#246BFD] hover:bg-blue-600 text-white font-semibold text-sm shadow-lg shadow-blue-600/25 transition-all flex items-center justify-center gap-2 mt-2">
                    <i class="fa-solid fa-check text-xs"></i>
                    <span>Set New Password</span>
                </button>
            </form>
        </div>
    </div>

    <script>
    function togglePassVisibility(id, btn) {{
        const input = document.getElementById(id);
        const icon = btn.querySelector('i');
        if (input.type === 'password') {{
            input.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }} else {{
            input.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }}
    }}

    async function submitNewPassword(e) {{
        e.preventDefault();
        const btn = document.getElementById('reset-submit-btn');
        const errBox = document.getElementById('reset-error-box');
        const errMsg = document.getElementById('reset-error-msg');
        const successBox = document.getElementById('reset-success-box');
        const form = document.getElementById('reset-password-form');

        const token = document.getElementById('token').value;
        const pass = document.getElementById('new_password').value;
        const confirm = document.getElementById('confirm_password').value;

        if (pass !== confirm) {{
            errMsg.textContent = 'Passwords do not match.';
            errBox.classList.remove('hidden');
            return;
        }}

        errBox.classList.add('hidden');
        btn.disabled = true;
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin text-xs"></i><span>Updating Password...</span>';

        try {{
            const res = await fetch('/reset-password', {{
                method: 'POST',
                headers: {{ 'Content-Type': 'application/json', 'Accept': 'application/json' }},
                body: JSON.stringify({{ token: token, password: pass, password_confirmation: confirm }})
            }});
            const data = await res.json();
            if (res.ok) {{
                successBox.classList.remove('hidden');
                form.classList.add('hidden');
                setTimeout(() => {{ window.location.href = '/login?reset=1'; }}, 2500);
            }} else {{
                errMsg.textContent = data.error || 'Failed to reset password.';
                errBox.classList.remove('hidden');
            }}
        }} catch (err) {{
            errMsg.textContent = 'A network error occurred. Please try again.';
            errBox.classList.remove('hidden');
        }} finally {{
            btn.disabled = false;
            btn.innerHTML = '<i class="fa-solid fa-check text-xs"></i><span>Set New Password</span>';
        }}
    }}
    </script>
</body>
</html>'''
            self.wfile.write(html.encode('utf-8'))
            return

        # 3.14 Customer Email Verification Route
        if path == "/verify-email":
            query = urllib.parse.parse_qs(parsed.query)
            token = query.get("token", [""])[0]

            verif = next((v for v in STATE.get("email_verifications", []) if v.get("token") == token), None)
            if verif:
                # Mark verified
                now_str = time.strftime("%Y-%m-%d %H:%M:%S")
                verif["verified_at"] = now_str
                target_user = next((u for u in STATE.get("users", []) if u.get("id") == verif.get("user_id")), None) or STATE.get("user")
                if target_user:
                    target_user["email_verified_at"] = now_str

                html = f'''<!DOCTYPE html>
<html lang="en" class="h-full bg-[#0B0E14]">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Verified | Alliance Bank</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/main.css">
</head>
<body class="min-h-full bg-[#0B0E14] text-white font-sans antialiased selection:bg-[#246BFD] selection:text-white flex flex-col justify-center items-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-6">
        <div class="text-center">
            <a href="/" class="inline-flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-[#246BFD] to-[#60A5FA] flex items-center justify-center shadow-lg shadow-blue-500/25">
                    <i class="fa-solid fa-building-columns text-white text-lg"></i>
                </div>
                <span class="text-2xl font-bold tracking-tight text-white font-mono">ALLIANCE BANK</span>
            </a>
        </div>

        <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl p-6 sm:p-8 shadow-2xl text-center space-y-5">
            <div class="w-14 h-14 rounded-2xl bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 flex items-center justify-center mx-auto text-2xl">
                <i class="fa-solid fa-circle-check"></i>
            </div>
            <div>
                <h2 class="text-xl font-bold text-white">Email Verified Successfully</h2>
                <p class="text-xs text-[#8F9CAE] mt-2 leading-relaxed">
                    Thank you! Your email address has been verified. Your account limits and access levels are now unlocked.
                </p>
            </div>

            <div class="pt-2">
                <a href="/dashboard" class="inline-flex items-center justify-center gap-2 w-full py-3 px-4 rounded-xl bg-[#246BFD] hover:bg-blue-600 text-white font-semibold text-sm shadow-lg shadow-blue-600/25 transition-all">
                    <span>Continue to Dashboard</span>
                    <i class="fa-solid fa-arrow-right text-xs"></i>
                </a>
            </div>
        </div>
    </div>
</body>
</html>'''
            else:
                html = f'''<!DOCTYPE html>
<html lang="en" class="h-full bg-[#0B0E14]">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invalid Verification Link | Alliance Bank</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/main.css">
</head>
<body class="min-h-full bg-[#0B0E14] text-white font-sans antialiased selection:bg-[#246BFD] selection:text-white flex flex-col justify-center items-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-6">
        <div class="text-center">
            <a href="/" class="inline-flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-[#246BFD] to-[#60A5FA] flex items-center justify-center shadow-lg shadow-blue-500/25">
                    <i class="fa-solid fa-building-columns text-white text-lg"></i>
                </div>
                <span class="text-2xl font-bold tracking-tight text-white font-mono">ALLIANCE BANK</span>
            </a>
        </div>

        <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl p-6 sm:p-8 shadow-2xl text-center space-y-5">
            <div class="w-14 h-14 rounded-2xl bg-amber-500/15 text-amber-400 border border-amber-500/30 flex items-center justify-center mx-auto text-2xl">
                <i class="fa-solid fa-triangle-exclamation"></i>
            </div>
            <div>
                <h2 class="text-xl font-bold text-white">Verification Link Expired or Invalid</h2>
                <p class="text-xs text-[#8F9CAE] mt-2 leading-relaxed">
                    This verification link has expired or has already been used. You can request a fresh verification link from your profile.
                </p>
            </div>

            <div class="pt-2">
                <a href="/dashboard" class="inline-flex items-center justify-center gap-2 w-full py-3 px-4 rounded-xl bg-[#246BFD] hover:bg-blue-600 text-white font-semibold text-sm shadow-lg shadow-blue-600/25 transition-all">
                    <span>Return to Dashboard</span>
                </a>
            </div>
        </div>
    </div>
</body>
</html>'''
            self.wfile.write(html.encode('utf-8'))
            return

        # 3.2 Customer KYC Page (Module 7)
        if path == "/kyc":
            user_rec = STATE.get("user", {})
            kyc_status = user_rec.get("kyc_status", "not_submitted")
            doc_type = user_rec.get("kyc_document_type", "Passport")
            rejection_reason = user_rec.get("kyc_rejection_reason", "Document image was unclear or expired.")
            kyc_notes = user_rec.get("kyc_notes", "Please provide additional documentation.")

            status_badge = {
                "approved": '<span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"><i class="fa-solid fa-circle-check"></i> Verified Customer</span>',
                "pending_review": '<span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/20"><span class="w-2 h-2 rounded-full bg-amber-400 animate-pulse"></span> Pending Review</span>',
                "under_review": '<span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-blue-500/10 text-blue-400 border border-blue-500/20"><span class="w-2 h-2 rounded-full bg-blue-400 animate-pulse"></span> Under Review</span>',
                "rejected": '<span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-rose-500/10 text-rose-400 border border-rose-500/20"><i class="fa-solid fa-circle-exclamation"></i> Needs Attention</span>',
                "additional_info_required": '<span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-orange-500/10 text-orange-400 border border-orange-500/20">Action Required</span>'
            }.get(kyc_status, '<span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-white/10 text-[#8F9CAE] border border-white/10">Not Submitted</span>')

            status_content = ""
            if kyc_status == "approved":
                status_content = f'''
                <div class="bg-emerald-500/10 border border-emerald-500/30 rounded-2xl p-6 sm:p-8 flex items-start gap-4">
                    <div class="w-12 h-12 rounded-xl bg-emerald-500/20 text-emerald-400 flex items-center justify-center shrink-0">
                        <i class="fa-solid fa-shield-check text-2xl"></i>
                    </div>
                    <div class="space-y-2">
                        <h3 class="text-lg font-bold text-white">Identity Verification Complete</h3>
                        <p class="text-sm text-[#C2C9D6] leading-relaxed">
                            Your identity has been fully verified and approved by Alliance Bank compliance. You now have unrestricted access to institutional transfer limits, international wire transactions, and payment card ordering.
                        </p>
                        <div class="flex items-center gap-4 pt-2 text-xs text-[#8F9CAE]">
                            <span>Verified Document: <strong class="text-white">{doc_type}</strong></span>
                            <span>&bull;</span>
                            <span>Status: <strong class="text-emerald-400">Approved & Verified</strong></span>
                        </div>
                    </div>
                </div>'''
            elif kyc_status in ["pending_review", "under_review"]:
                st_title = "Identity Verification Under Review" if kyc_status == "under_review" else "Verification Submitted — Awaiting Review"
                status_content = f'''
                <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl p-6 sm:p-8 space-y-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-xl bg-amber-500/10 border border-amber-500/20 flex items-center justify-center text-amber-400">
                            <i class="fa-solid fa-spinner fa-spin text-lg"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-white">{st_title}</h3>
                            <p class="text-xs text-[#8F9CAE]">Submitted on {user_rec.get("kyc_submitted_at", "Just now")}</p>
                        </div>
                    </div>
                    <p class="text-sm text-[#C2C9D6] leading-relaxed">
                        Your identity documents have been submitted successfully and are awaiting review. You can continue using the permitted features of your account while we review your submission. Compliance reviews typically complete within 15–30 minutes during standard business hours.
                    </p>
                    <div class="bg-[#0F131A] border border-[#282E3E] rounded-xl p-4 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs">
                        <div class="flex items-center gap-3">
                            <div class="w-8 h-8 rounded-lg bg-[#246BFD]/10 text-[#246BFD] flex items-center justify-center">
                                <i class="fa-solid fa-file-shield"></i>
                            </div>
                            <div>
                                <div class="font-semibold text-white">Document: {doc_type}</div>
                                <div class="text-[#8F9CAE]">In Queue for Compliance Review</div>
                            </div>
                        </div>
                        <span class="px-2.5 py-1 rounded text-[11px] font-medium bg-[#246BFD]/10 text-[#246BFD] border border-[#246BFD]/20">
                            Status: {'Under Review' if kyc_status == 'under_review' else 'Awaiting Review'}
                        </span>
                    </div>
                </div>'''
            elif kyc_status in ["rejected", "additional_info_required"]:
                alert_class = "bg-rose-500/10 border-rose-500/30 text-rose-400" if kyc_status == "rejected" else "bg-orange-500/10 border-orange-500/30 text-orange-400"
                alert_title = "Identity Verification Requires Attention" if kyc_status == "rejected" else "Additional Information Required"
                alert_msg = rejection_reason if kyc_status == "rejected" else kyc_notes
                status_content = f'''
                <div class="{alert_class} border rounded-2xl p-6 sm:p-8 space-y-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center">
                            <i class="fa-solid fa-triangle-exclamation text-lg"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-white">{alert_title}</h3>
                            <p class="text-xs text-[#8F9CAE]">Feedback from compliance officer</p>
                        </div>
                    </div>
                    <div class="bg-[#0F131A] border border-[#282E3E] rounded-xl p-4 text-xs space-y-1">
                        <div class="font-bold uppercase tracking-wider text-rose-400">Compliance Reason:</div>
                        <div class="text-[#C2C9D6]">{alert_msg}</div>
                    </div>
                </div>'''

            form_content = ""
            if kyc_status != "approved" and kyc_status not in ["pending_review", "under_review"]:
                form_content = f'''
                <div class="bg-[#161A22] border border-[#282E3E] rounded-2xl p-6 sm:p-8 space-y-6">
                    <div class="border-b border-[#282E3E] pb-4">
                        <h2 class="text-lg font-bold text-white">Submit Identity Documents</h2>
                        <p class="text-xs text-[#8F9CAE] mt-1">Please ensure your document is valid, unexpired, and clearly legible without glare.</p>
                    </div>
                    <form id="kyc-form" method="POST" action="/kyc" class="space-y-6">
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-medium text-[#8F9CAE] mb-1.5">Legal First Name</label>
                                <input type="text" value="{user_rec.get('first_name', 'Abraham')}" disabled class="w-full bg-[#0F131A] border border-[#282E3E] rounded-xl px-4 py-2.5 text-sm text-[#8F9CAE] cursor-not-allowed">
                            </div>
                            <div>
                                <label class="block text-xs font-medium text-[#8F9CAE] mb-1.5">Legal Last Name</label>
                                <input type="text" value="{user_rec.get('last_name', 'Elom')}" disabled class="w-full bg-[#0F131A] border border-[#282E3E] rounded-xl px-4 py-2.5 text-sm text-[#8F9CAE] cursor-not-allowed">
                            </div>
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label for="document_type" class="block text-xs font-medium text-[#8F9CAE] mb-1.5">Document Type *</label>
                                <select id="document_type" name="document_type" required class="w-full bg-[#0F131A] border border-[#282E3E] rounded-xl px-4 py-2.5 text-sm text-white">
                                    <option value="Passport">International Passport</option>
                                    <option value="Driver's License">Driver's License</option>
                                    <option value="National ID Card">National Identity Card</option>
                                    <option value="Residence Permit">Residence Permit</option>
                                </select>
                            </div>
                            <div>
                                <label for="id_number" class="block text-xs font-medium text-[#8F9CAE] mb-1.5">Document / ID Number *</label>
                                <input type="text" id="id_number" name="id_number" required placeholder="e.g. A12345678" class="w-full bg-[#0F131A] border border-[#282E3E] rounded-xl px-4 py-2.5 text-sm text-white">
                            </div>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-[#8F9CAE] mb-1.5">Upload Identity Document (Front / Bio-data) *</label>
                            <div class="border-2 border-dashed border-[#282E3E] hover:border-[#246BFD] rounded-2xl p-6 text-center transition-all bg-[#0F131A] cursor-pointer">
                                <div class="w-12 h-12 rounded-full bg-[#246BFD]/10 text-[#246BFD] flex items-center justify-center mx-auto mb-3">
                                    <i class="fa-solid fa-cloud-arrow-up text-xl"></i>
                                </div>
                                <div class="text-sm font-semibold text-white">Sample document auto-selected for submission</div>
                                <div class="text-xs text-[#8F9CAE] mt-1">Supported formats: JPG, PNG, PDF (Max 5 MB)</div>
                            </div>
                        </div>
                        <div>
                            <label for="notes" class="block text-xs font-medium text-[#8F9CAE] mb-1.5">Additional Notes for Compliance Officer (Optional)</label>
                            <textarea id="notes" name="notes" rows="2" placeholder="Any additional context regarding your identity document or address..." class="w-full bg-[#0F131A] border border-[#282E3E] rounded-xl px-4 py-2.5 text-sm text-white"></textarea>
                        </div>
                        <div>
                            <button type="submit" id="btn-submit-kyc" class="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-6 py-3 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-sm font-semibold shadow-lg shadow-blue-500/20 transition-all">
                                <span>Submit for Verification</span>
                                <i class="fa-solid fa-arrow-right"></i>
                            </button>
                        </div>
                    </form>
                </div>'''

            body = f'''<div class="max-w-4xl mx-auto space-y-6 pb-12">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <div class="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-[#246BFD] mb-1">
                            <span>Compliance & Safety</span>
                            <span>&bull;</span>
                            <span>Tier 2 Verification</span>
                        </div>
                        <h1 class="text-2xl sm:text-3xl font-extrabold text-white tracking-tight">Identity Verification</h1>
                        <p class="text-sm text-[#8F9CAE] mt-1">Submit government-issued identification to unlock institutional limits and card ordering.</p>
                    </div>
                    <div>{status_badge}</div>
                </div>
                {status_content}
                {form_content}
            </div>'''
            html = build_app_layout(body, "Identity Verification (KYC) | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 4. Customer Banking Dashboard
        if path == "/dashboard":
            user_rec = STATE.get("user", {})
            first_name = user_rec.get("first_name", "Elochukwu")
            account_number = STATE["accounts"][0].get("account_number", "0515705231")
            account_type = STATE["accounts"][0].get("account_type", "Savings")
            kyc_status = user_rec.get("kyc_status", "approved")
            kyc_dismissed = STATE.get("kyc_reminder_dismissed", False)

            kyc_banner_html = ""
            if kyc_status == "not_submitted" and not kyc_dismissed:
                kyc_banner_html = '''
                <div id="kyc-notice-banner" class="bg-gradient-to-r from-[#171A21] via-[#1A1F2B] to-[#13161C] border border-[#246BFD]/40 rounded-2xl p-4 sm:p-5 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 shadow-lg shadow-blue-500/10 relative overflow-hidden mb-6">
                    <div class="flex items-start gap-3.5">
                        <div class="w-10 h-10 rounded-xl bg-[#246BFD]/15 text-[#246BFD] flex items-center justify-center shrink-0 mt-0.5 border border-[#246BFD]/30">
                            <i class="fa-solid fa-shield-halved text-lg"></i>
                        </div>
                        <div class="space-y-1">
                            <h4 class="text-sm font-bold text-white flex items-center gap-2">
                                Verify Your Identity
                                <span class="text-[10px] uppercase font-bold tracking-wider px-2 py-0.5 rounded bg-[#246BFD]/20 text-[#246BFD] border border-[#246BFD]/30">Recommended</span>
                            </h4>
                            <p class="text-xs text-[#8F9CAE] max-w-xl leading-relaxed">
                                Complete identity verification to help secure your account and unlock features that may require verification.
                            </p>
                        </div>
                    </div>
                    <div class="flex items-center gap-3 w-full sm:w-auto shrink-0 justify-end">
                        <button type="button" onclick="dismissKycReminder()" class="text-xs text-[#8F9CAE] hover:text-white px-3 py-2 rounded-lg hover:bg-white/5 transition-all">
                            Remind Me Later
                        </button>
                        <a href="/kyc" class="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-semibold shadow-md shadow-blue-500/20 transition-all">
                            <span>Verify Now</span>
                            <i class="fa-solid fa-arrow-right"></i>
                        </a>
                    </div>
                </div>'''
            elif kyc_status == "pending_review":
                kyc_banner_html = '''
                <div class="bg-amber-500/10 border border-amber-500/30 rounded-2xl p-4 sm:p-5 flex items-center justify-between gap-4 mb-6">
                    <div class="flex items-center gap-3.5">
                        <div class="w-9 h-9 rounded-xl bg-amber-500/20 text-amber-400 flex items-center justify-center shrink-0">
                            <i class="fa-solid fa-spinner fa-spin text-base"></i>
                        </div>
                        <div>
                            <h4 class="text-sm font-bold text-white">Identity Verification In Progress — Awaiting Review</h4>
                            <p class="text-xs text-[#8F9CAE]">Your identity documents have been submitted and are currently in queue for review by our compliance team.</p>
                        </div>
                    </div>
                    <a href="/kyc" class="text-xs font-medium text-amber-400 hover:text-amber-300 underline shrink-0">View Status</a>
                </div>'''
            elif kyc_status == "under_review":
                kyc_banner_html = '''
                <div class="bg-blue-500/10 border border-blue-500/30 rounded-2xl p-4 sm:p-5 flex items-center justify-between gap-4 mb-6">
                    <div class="flex items-center gap-3.5">
                        <div class="w-9 h-9 rounded-xl bg-blue-500/20 text-blue-400 flex items-center justify-center shrink-0">
                            <i class="fa-solid fa-circle-notch fa-spin text-base"></i>
                        </div>
                        <div>
                            <h4 class="text-sm font-bold text-white">Identity Verification Under Review</h4>
                            <p class="text-xs text-[#8F9CAE]">A compliance officer is currently reviewing your identity documents. This typically takes 15–30 minutes.</p>
                        </div>
                    </div>
                    <a href="/kyc" class="text-xs font-medium text-blue-400 hover:text-blue-300 underline shrink-0">View Status</a>
                </div>'''
            elif kyc_status == "additional_info_required":
                notes_msg = user_rec.get("kyc_notes", "Please provide additional identity documentation.")
                kyc_banner_html = f'''
                <div class="bg-orange-500/10 border border-orange-500/30 rounded-2xl p-4 sm:p-5 flex items-center justify-between gap-4 mb-6">
                    <div class="flex items-center gap-3.5">
                        <div class="w-9 h-9 rounded-xl bg-orange-500/20 text-orange-400 flex items-center justify-center shrink-0">
                            <i class="fa-solid fa-triangle-exclamation text-base"></i>
                        </div>
                        <div>
                            <h4 class="text-sm font-bold text-white">Additional Information Required</h4>
                            <p class="text-xs text-[#8F9CAE]">{notes_msg}</p>
                        </div>
                    </div>
                    <a href="/kyc" class="px-3 py-1.5 rounded-lg bg-orange-500 hover:bg-orange-600 text-white text-xs font-semibold shrink-0">Provide Information</a>
                </div>'''
            elif kyc_status == "rejected":
                reason_msg = user_rec.get("kyc_rejection_reason", "Document could not be verified.")
                kyc_banner_html = f'''
                <div class="bg-rose-500/10 border border-rose-500/30 rounded-2xl p-4 sm:p-5 flex items-center justify-between gap-4 mb-6">
                    <div class="flex items-center gap-3.5">
                        <div class="w-9 h-9 rounded-xl bg-rose-500/20 text-rose-400 flex items-center justify-center shrink-0">
                            <i class="fa-solid fa-triangle-exclamation text-base"></i>
                        </div>
                        <div>
                            <h4 class="text-sm font-bold text-white">Identity Verification Requires Attention</h4>
                            <p class="text-xs text-[#8F9CAE]">Reason: {reason_msg}</p>
                        </div>
                    </div>
                    <a href="/kyc" class="px-3 py-1.5 rounded-lg bg-rose-500 hover:bg-rose-600 text-white text-xs font-semibold shrink-0">Resubmit Documents</a>
                </div>'''

            verified_badge_html = '''<span class="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-2 py-0.5 rounded-full ml-2" title="Identity Verified"><i class="fa-solid fa-circle-check text-[10px]"></i> Verified</span>''' if kyc_status == "approved" else ""

            usd_bal = STATE["accounts"][0]["balance"]
            usdc_bal = STATE["accounts"][1]["balance"]
            total_bal = usd_bal
            book_bal = total_bal

            int_part = f"{int(total_bal):,}"
            dec_part = f"{total_bal % 1:.2f}"[2:]

            # Generate dynamic transaction rows (from both transfers and deposits)
            all_activity = []
            for t in STATE.get("transfers", []):
                is_sender = (t["direction"] == "sent")
                all_activity.append({
                    "date": t.get("date", "Today"),
                    "title": f"Sent to {t['recipient']}" if is_sender else f"Received from {t['sender']}",
                    "ref": t["ref"],
                    "amount": t["amount"],
                    "sign": "-" if is_sender else "+",
                    "color": "text-red-400 bg-red-500/10" if is_sender else "text-emerald-400 bg-emerald-500/10",
                    "amt_color": "text-red-400" if is_sender else "text-emerald-400",
                    "icon": "fa-arrow-up" if is_sender else "fa-arrow-down",
                    "status": "Completed Transaction",
                    "link": f"/transfers/receipt/{t['ref']}"
                })
            for d in STATE.get("deposits", []):
                st = str(d.get("status", "pending")).lower()
                is_credited = (st == "credited")
                is_pending = st in ["pending_review", "confirming", "pending_confirmation", "awaiting_deposit", "awaiting_payment"]
                st_label = "Credited" if is_credited else ("Pending Review" if st == "pending_review" else ("Awaiting Deposit" if "awaiting" in st else st.title()))
                dep_asset = d.get('asset') or d.get('currency') or 'USD'
                dep_ref = d.get('reference') or f"DEP-{d.get('id', '000')}"
                dep_amt = d.get('amount', 0.0)
                all_activity.append({
                    "date": d.get("created_at", "Just now"),
                    "title": f"Crypto Deposit ({dep_asset})",
                    "ref": dep_ref,
                    "amount": dep_amt,
                    "sign": "+",
                    "color": "text-emerald-400 bg-emerald-500/10" if is_credited else ("text-amber-400 bg-amber-500/10" if is_pending else "text-red-400 bg-red-500/10"),
                    "amt_color": "text-emerald-400" if is_credited else ("text-amber-400" if is_pending else "text-gray-400"),
                    "icon": "fa-arrow-down-long",
                    "status": st_label,
                    "link": "/deposits"
                })

            tx_rows = ""
            for a in all_activity:
                tx_rows += f'''
                <a href="{a['link']}" class="flex items-center justify-between p-4 hover:bg-[#1F2430]/70 transition-colors">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-xl {a['color']} flex items-center justify-center text-sm">
                            <i class="fa-solid {a['icon']}"></i>
                        </div>
                        <div>
                            <h4 class="text-sm font-bold text-white">{a['title']}</h4>
                            <p class="text-xs text-gray-500 font-mono">{a['date']} • Ref: {a['ref']}</p>
                        </div>
                    </div>
                    <div class="text-right">
                        <div class="text-sm font-mono font-bold {a['amt_color']} balance-amount" data-raw-amount="{a['sign']}${a['amount']:.2f}">{a['sign']}${a['amount']:.2f}</div>
                        <span class="text-[10px] uppercase font-semibold text-gray-400">{a['status']}</span>
                    </div>
                </a>'''

            if not tx_rows:
                tx_section_html = '''
                <div class="p-8 rounded-2xl bg-[#171A21] border border-[#292E38] text-center space-y-2">
                    <p class="text-sm font-semibold text-white">No account activity yet.</p>
                    <p class="text-xs text-gray-400">Your deposits, transfers, and card transactions will appear here.</p>
                </div>'''
            else:
                tx_section_html = f'''
                <div class="rounded-2xl bg-[#171A21] border border-[#292E38] divide-y divide-[#292E38] overflow-hidden">
                    {tx_rows}
                </div>'''

            # Generate dynamic cards carousel
            cards_list = STATE.get("cards", [])
            has_multiple_cards = len(cards_list) > 1

            cards_html = ""
            dots_html = ""
            for idx, c in enumerate(cards_list):
                c_id = c["id"]
                c_name = c.get("product_name") or c.get("name", "Monveracu Card")
                c_status = str(c.get("status", "active")).lower()
                is_frozen = (c_status == "frozen")
                is_pending = (c_status == "pending")

                badge_style = "bg-[#261E0F] text-amber-400 border-amber-500/30" if is_frozen else ("bg-[#0F1E29] text-blue-400 border-blue-500/30" if is_pending else "bg-[#0F291E] text-emerald-400 border-emerald-500/30")
                design = c.get("card_design") or c.get("design", "obsidian")

                c_network = '''<div class="flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-white/10 text-white border border-white/20 backdrop-blur-xs">
                    <i class="fa-solid fa-building-columns text-[10px]"></i>
                    <span class="text-[10px] font-bold font-mono tracking-wider">MONVERACU</span>
                </div>'''

                if design == "midnight_blue":
                    c_bg = "bg-gradient-to-br from-[#101D38] via-[#0E172B] to-[#0A0F1A]"
                    c_border = "border-[#1E3A6E]"
                    c_sheen = "bg-blue-400/10"
                elif design == "titanium_gold":
                    c_bg = "bg-gradient-to-br from-[#262015] via-[#1C170F] to-[#110E0A]"
                    c_border = "border-[#59441E]"
                    c_sheen = "bg-amber-400/10"
                elif design == "crypto_black":
                    c_bg = "bg-gradient-to-br from-[#121418] via-[#0C0D10] to-[#050607]"
                    c_border = "border-[#3A404E]"
                    c_sheen = "bg-cyan-400/10"
                else: # obsidian
                    c_bg = "bg-gradient-to-br from-[#1C2028] via-[#15181F] to-[#0E1015]"
                    c_border = "border-[#2B303C]"
                    c_sheen = "bg-white/5"

                last_four = c.get("last_four") or str(c.get("masked_number", "4829"))[-4:]
                holder = str(c.get("card_holder_name") or c.get("holder", "ELOCHUKWU ELOM")).upper()
                exp_date = c.get("exp") or f"{c.get('expiry_month', 12):02d}/{str(c.get('expiry_year', 2029))[-2:]}"
                c_json = json.dumps(c).replace("'", "&#39;")
                slide_class = "w-[88%] sm:w-[420px] shrink-0 snap-center" if has_multiple_cards else "w-full max-w-lg mx-auto sm:mx-0"

                cards_html += f'''
                <div class="card-slide {slide_class}" data-card-index="{idx}">
                    <div class="relative overflow-hidden rounded-3xl {c_bg} border {c_border} shadow-2xl p-6 sm:p-7 flex flex-col justify-between transition-all duration-200 hover:border-gray-500/60 cursor-pointer active:scale-[0.98] group aspect-[1.586/1] min-h-[210px] sm:min-h-[235px]"
                         data-card-id="{c_id}"
                         onclick='openCardDetailsModal({c_json})'>
                        <div class="absolute -top-16 -right-16 w-44 h-44 {c_sheen} rounded-full blur-2xl pointer-events-none"></div>
                        <div class="flex items-center justify-between relative z-10">
                            <h4 class="text-sm sm:text-base font-bold text-white tracking-wide truncate max-w-[210px] sm:max-w-[260px]">{c_name}</h4>
                            <span data-card-badge-id="{c_id}" class="px-2.5 py-1 rounded-lg text-[10px] font-extrabold tracking-wider uppercase border {badge_style} shrink-0">
                                {c_status.upper()}
                            </span>
                        </div>
                        <div class="my-auto py-3 relative z-10 flex items-center justify-between">
                            <div class="text-xl sm:text-2xl md:text-[26px] font-mono font-bold tracking-[0.22em] sm:tracking-[0.25em] text-white">
                                •••• &nbsp;•••• &nbsp;•••• &nbsp;{last_four}
                            </div>
                        </div>
                        <div class="border-t border-[#2B303C]/70 pt-3 sm:pt-4 flex items-center justify-between relative z-10">
                            <div class="truncate max-w-[200px] sm:max-w-[240px]">
                                <span class="text-xs sm:text-sm font-semibold text-gray-200 tracking-wider uppercase truncate block">{holder}</span>
                            </div>
                            <div class="flex items-center gap-3 shrink-0">
                                <span class="text-xs sm:text-sm font-mono font-medium text-gray-300">Exp: {exp_date}</span>
                                <div class="shrink-0 flex items-center">{c_network}</div>
                            </div>
                        </div>
                    </div>
                </div>'''

                dot_class = "bg-[#246BFD] w-5" if idx == 0 else "bg-gray-600 w-2 hover:bg-gray-400"
                dots_html += f'''<button type="button" onclick="scrollCardTo({idx})" class="card-dot h-2 rounded-full transition-all {dot_class}" data-index="{idx}" title="Go to card {idx+1}"></button>'''

            # Generate Stock Investment Cards for Dashboard
            stock_cards_html = ""
            active_stocks = [s for s in STATE.get("stocks", []) if s.get("status") == "active"]
            for stk in active_stocks:
                plan_id = stk.get("default_plan_id", 3)
                plan = next((p for p in STATE.get("investment_plans", []) if p["id"] == plan_id), None)
                if not plan and STATE.get("investment_plans"):
                    plan = STATE["investment_plans"][0]

                plan_name = plan["name"] if plan else "Pro Plan"
                min_amt = plan["min_amount"] if plan else 500.0
                max_amt = plan.get("max_amount")
                is_unlimited = plan.get("is_unlimited", False) or (max_amt is None)
                duration = plan["duration_hours"] if plan else 96
                return_pct = plan["return_percentage"] if plan else 100.0

                limits_str = f"${min_amt:,.0f} - Unlimited" if (is_unlimited or max_amt is None) else f"${min_amt:,.0f} - ${max_amt:,.0f}"

                stock_cards_html += f'''
                <div class="min-w-[270px] sm:min-w-[300px] max-w-[320px] rounded-3xl bg-[#171A21] border border-[#292E38] p-5 flex flex-col justify-between hover:border-gray-600 transition-all shadow-xl snap-start group">
                    <div>
                        <div class="flex items-start justify-between mb-4">
                            <div class="flex items-center gap-3">
                                <div class="w-12 h-12 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-center p-2 shrink-0 group-hover:border-[#246BFD]/50 transition-colors">
                                    <img src="{stk.get('logo_url') or '/assets/images/stocks/' + stk['ticker'].lower() + '.svg'}" 
                                         alt="{stk['ticker']}" 
                                         class="w-full h-full object-contain"
                                         onerror="this.src='/assets/images/stocks/default.svg';">
                                </div>
                                <div>
                                    <div class="flex items-center gap-1.5">
                                        <h4 class="text-base font-bold text-white">{stk['ticker']}</h4>
                                        <span class="text-[10px] font-mono px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400 font-semibold border border-blue-500/20">STOCK</span>
                                    </div>
                                    <p class="text-xs text-gray-400 truncate max-w-[150px]">{stk['name']}</p>
                                </div>
                            </div>
                            <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Active</span>
                        </div>
                        <p class="text-xs text-gray-400 line-clamp-2 mb-4 leading-relaxed">{stk.get('short_description', '')}</p>
                        <div class="rounded-2xl bg-[#12151B] border border-[#292E38] p-3 space-y-2 mb-4 text-xs">
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 text-[11px]">Investment Product</span>
                                <span class="font-bold text-white">{plan_name}</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 text-[11px]">Allocation Range</span>
                                <span class="font-mono font-semibold text-white">{limits_str}</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 text-[11px]">Duration</span>
                                <span class="font-mono text-gray-300">{duration} hours</span>
                            </div>
                            <div class="pt-1.5 border-t border-[#292E38] flex items-center justify-between">
                                <span class="text-gray-400 text-[11px] font-semibold">Contractual Return</span>
                                <span class="font-mono font-bold text-emerald-400">+{return_pct:g}%</span>
                            </div>
                        </div>
                    </div>
                    <button type="button" 
                            onclick='openInvestModal({json.dumps(stk)})'
                            class="w-full py-3 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold text-xs shadow-lg shadow-blue-500/20 transition-all flex items-center justify-center gap-2 active:scale-95">
                        <span>View Investment</span>
                        <i class="fa-solid fa-arrow-right text-[10px]"></i>
                    </button>
                </div>
                '''

            dash_plans_opts = ""
            for p in STATE.get("investment_plans", []):
                if p.get("status") == "active":
                    m_val = f"{p['max_amount']}" if p.get("max_amount") is not None else ""
                    unl = "1" if p.get("is_unlimited") or p.get("max_amount") is None else "0"
                    dash_plans_opts += f'''<option value="{p['id']}" data-min="{p['min_amount']}" data-max="{m_val}" data-unlimited="{unl}" data-duration="{p['duration_hours']}" data-return="{p['return_percentage']}">{p['name']} ({p['duration_hours']}h, +{p['return_percentage']:g}% Return)</option>'''

            dash_acc_opts = ""
            for acc in STATE.get("accounts", []):
                dash_acc_opts += f'''<option value="{acc['id']}">{acc['currency']} Account ({acc['account_number']}) · Available: ${acc['balance']:,.2f}</option>'''

            card_counter_html = f'''<span id="card-carousel-counter" class="text-[11px] font-mono font-bold px-2 py-0.5 rounded-full bg-[#1C2028] border border-[#2B303C] text-gray-300">1 of {len(cards_list)}</span>''' if has_multiple_cards else ""
            carousel_controls_html = '''<div class="hidden sm:flex items-center gap-1.5">
                <button type="button" id="cards-prev-btn" onclick="scrollCardCarousel(-1)" class="w-7 h-7 rounded-lg bg-[#1C2028] hover:bg-[#252B3B] border border-[#2B303C] text-gray-300 hover:text-white flex items-center justify-center text-xs transition-colors" title="Previous card">
                    <i class="fa-solid fa-chevron-left"></i>
                </button>
                <button type="button" id="cards-next-btn" onclick="scrollCardCarousel(1)" class="w-7 h-7 rounded-lg bg-[#1C2028] hover:bg-[#252B3B] border border-[#2B303C] text-gray-300 hover:text-white flex items-center justify-center text-xs transition-colors" title="Next card">
                    <i class="fa-solid fa-chevron-right"></i>
                </button>
            </div>''' if has_multiple_cards else ""

            if cards_list:
                cards_section_content = f'''
                <div class="relative">
                    <div id="cards-carousel-container" class="flex gap-4 overflow-x-auto no-scrollbar scroll-smooth snap-x snap-mandatory py-2 px-1 -mx-2 sm:mx-0 {'cursor-grab' if has_multiple_cards else ''}">
                        {cards_html}
                    </div>
                    {f'<div class="flex items-center justify-center gap-1.5 mt-3">{dots_html}</div>' if has_multiple_cards else ''}
                </div>'''
            else:
                cards_section_content = '''
                <div class="p-8 rounded-3xl bg-[#171A21] border border-[#292E38] text-center space-y-3">
                    <div class="w-12 h-12 rounded-2xl bg-[#246BFD]/10 text-[#246BFD] flex items-center justify-center mx-auto text-xl">
                        <i class="fa-solid fa-credit-card"></i>
                    </div>
                    <h4 class="text-sm font-bold text-white">You don't have any payment cards yet</h4>
                    <p class="text-xs text-gray-400 max-w-sm mx-auto">Instant virtual cards and platinum metal payment cards are available in our marketplace.</p>
                    <div class="pt-2">
                        <a href="/cards" class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-semibold shadow-lg shadow-blue-500/20 transition-all active:scale-95">
                            <i class="fa-solid fa-plus text-xs"></i>
                            <span>Get a Card</span>
                        </a>
                    </div>
                </div>'''

            body = f'''<div class="max-w-5xl mx-auto space-y-6">

                <!-- Dynamic KYC Banner -->
                {kyc_banner_html}

                <!-- Primary Account Hero Card (Exact Structure from Reference Design) -->
                <div class="p-6 sm:p-8 rounded-3xl bg-gradient-to-b from-[#171A21] via-[#14171E] to-[#111318] border border-[#2B303C] shadow-2xl relative overflow-hidden">
                    
                    <!-- Ambient Blue Glow -->
                    <div class="absolute -top-20 -right-20 w-64 h-64 bg-[#246BFD]/10 rounded-full blur-3xl pointer-events-none"></div>

                    <!-- 1. Personalized Greeting with Avatar -->
                    <div class="flex items-center gap-3 mb-5">
                        <div class="w-10 h-10 rounded-full bg-[#1C2028] border border-[#2B303C] flex items-center justify-center text-gray-300 text-base shadow-sm shrink-0">
                            <i class="fa-regular fa-user"></i>
                        </div>
                        <div>
                            <h1 class="text-xl sm:text-2xl font-bold text-white tracking-tight flex items-center gap-2">
                                Hello, {first_name}!
                                {verified_badge_html}
                            </h1>
                        </div>
                    </div>

                    <!-- 2. Account Information Row: Account Type (Left) & Account Number with Copy (Right) -->
                    <div class="flex items-center justify-between gap-3 mb-6">
                        <div class="px-3.5 py-1.5 rounded-xl bg-[#1C2028] border border-[#2B303C] text-xs font-semibold text-gray-300 tracking-wide">
                            {account_type}
                        </div>
                        
                        <button type="button" 
                                onclick="copyToClipboard('{account_number}', this)" 
                                class="px-3.5 py-1.5 rounded-xl bg-[#1C2028] border border-[#2B303C] hover:border-[#246BFD]/60 text-xs sm:text-sm font-mono font-bold text-gray-200 tracking-wider inline-flex items-center gap-2 transition-all cursor-pointer group"
                                title="Click to copy account number">
                            <span id="account-num-text">{account_number}</span>
                            <i class="fa-regular fa-copy text-[#246BFD] group-hover:scale-110 transition-transform"></i>
                        </button>
                    </div>

                    <!-- 3. Prominent Available Balance & Book Balance Display -->
                    <div class="mb-7 space-y-1.5">
                        <div class="flex items-center gap-2">
                            <div class="text-3xl sm:text-4xl md:text-5xl font-extrabold text-white tracking-tight flex items-baseline">
                                <span class="text-2xl sm:text-3xl md:text-4xl font-bold text-gray-300 mr-1">$</span>
                                <span class="balance-amount font-mono" data-raw-amount="{int_part}.<span class='text-2xl sm:text-3xl font-bold text-gray-300'>{dec_part}</span>">
                                    {int_part}.<span class="text-2xl sm:text-3xl font-bold text-gray-300">{dec_part}</span>
                                </span>
                            </div>
                            <button type="button" 
                                    onclick="toggleBalanceVisibility()" 
                                    id="balance-toggle-btn" 
                                    class="text-gray-400 hover:text-white transition-colors p-1.5 rounded-lg active:scale-90" 
                                    title="Toggle balance privacy">
                                <i class="fa-regular fa-eye text-lg text-gray-400"></i>
                            </button>
                        </div>

                        <!-- Book Balance Line -->
                        <div class="flex items-center gap-2 text-xs sm:text-sm text-gray-400 font-medium">
                            <span>Book balance</span>
                            <span class="text-gray-300 font-mono font-semibold balance-amount" data-raw-amount="${book_bal:,.2f}">
                                ${book_bal:,.2f}
                            </span>
                        </div>
                    </div>

                    <!-- 4. Horizontally Scrollable Action Carousel -->
                    <div class="pt-2 border-t border-[#292E38]/60">
                        <div class="flex items-center gap-3 overflow-x-auto no-scrollbar scroll-smooth snap-x py-2 px-0.5 -mx-2 sm:mx-0 sm:overflow-visible sm:grid sm:grid-cols-5">
                            
                            <!-- 1. Fund Account (Opens cryptocurrency deposit flow) -->
                            <a href="/deposits" class="shrink-0 snap-start flex items-center justify-center gap-2.5 px-5 py-3 rounded-full bg-[#1C2028] hover:bg-[#222733] border border-[#2B303C] hover:border-[#246BFD]/60 text-white shadow-md transition-all active:scale-95 group">
                                <i class="fa-solid fa-circle-plus text-base text-[#246BFD] group-hover:scale-110 transition-transform"></i>
                                <span class="text-sm font-semibold tracking-tight whitespace-nowrap">Fund account</span>
                            </a>

                            <!-- 2. Transfer (Opens transfer interface) -->
                            <a href="/transfers/send" class="shrink-0 snap-start flex items-center justify-center gap-2.5 px-5 py-3 rounded-full bg-[#1C2028] hover:bg-[#222733] border border-[#2B303C] hover:border-[#246BFD]/60 text-white shadow-md transition-all active:scale-95 group">
                                <i class="fa-solid fa-angles-right text-base text-[#246BFD] group-hover:scale-110 transition-transform"></i>
                                <span class="text-sm font-semibold tracking-tight whitespace-nowrap">Transfer</span>
                            </a>

                            <!-- 3. Transactions (Opens transaction history) -->
                            <a href="/activity" class="shrink-0 snap-start flex items-center justify-center gap-2.5 px-5 py-3 rounded-full bg-[#1C2028] hover:bg-[#222733] border border-[#2B303C] hover:border-[#246BFD]/60 text-white shadow-md transition-all active:scale-95 group">
                                <i class="fa-solid fa-bars-staggered text-base text-[#246BFD] group-hover:scale-110 transition-transform"></i>
                                <span class="text-sm font-semibold tracking-tight whitespace-nowrap">Transactions</span>
                            </a>

                            <!-- 4. Cards (Opens card management section) -->
                            <a href="/cards" class="shrink-0 snap-start flex items-center justify-center gap-2.5 px-5 py-3 rounded-full bg-[#1C2028] hover:bg-[#222733] border border-[#2B303C] hover:border-[#246BFD]/60 text-white shadow-md transition-all active:scale-95 group">
                                <i class="fa-regular fa-credit-card text-base text-[#246BFD] group-hover:scale-110 transition-transform"></i>
                                <span class="text-sm font-semibold tracking-tight whitespace-nowrap">Cards</span>
                            </a>

                            <!-- 5. More (Displays other available banking services) -->
                            <button type="button" 
                                    onclick="openMoreServicesModal()" 
                                    class="shrink-0 snap-start flex items-center justify-center gap-2.5 px-5 py-3 rounded-full bg-[#1C2028] hover:bg-[#222733] border border-[#2B303C] hover:border-[#246BFD]/60 text-white shadow-md transition-all active:scale-95 group">
                                <i class="fa-solid fa-ellipsis text-base text-[#246BFD] group-hover:scale-110 transition-transform"></i>
                                <span class="text-sm font-semibold tracking-tight whitespace-nowrap">More</span>
                            </button>
                        </div>
                    </div>

                </div>

                <!-- 5. Explore Investment Opportunities Carousel -->
                <div>
                    <div class="flex items-center justify-between mb-3 px-1">
                        <div class="flex items-center gap-2">
                            <h3 class="text-xs font-bold uppercase tracking-wider text-gray-400">Explore Investment Opportunities</h3>
                            <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase bg-blue-500/10 text-blue-400 border border-blue-500/20">Institutional</span>
                        </div>
                        <div class="flex items-center gap-3">
                            <div class="hidden sm:flex items-center gap-1.5">
                                <button type="button" onclick="scrollStockCarousel(-1)" class="w-7 h-7 rounded-lg bg-[#1C2028] hover:bg-[#252B3B] border border-[#2B303C] text-gray-300 hover:text-white flex items-center justify-center text-xs transition-colors" title="Previous stocks">
                                    <i class="fa-solid fa-chevron-left"></i>
                                </button>
                                <button type="button" onclick="scrollStockCarousel(1)" class="w-7 h-7 rounded-lg bg-[#1C2028] hover:bg-[#252B3B] border border-[#2B303C] text-gray-300 hover:text-white flex items-center justify-center text-xs transition-colors" title="Next stocks">
                                    <i class="fa-solid fa-chevron-right"></i>
                                </button>
                            </div>
                            <a href="/investments" class="text-xs font-semibold text-[#246BFD] hover:text-blue-400 transition-colors flex items-center gap-1">
                                <span>Explore All Stocks &rarr;</span>
                            </a>
                        </div>
                    </div>
                    <div id="stock-carousel" class="flex gap-4 overflow-x-auto pb-2 scroll-smooth snap-x snap-mandatory no-scrollbar">
                        {stock_cards_html if stock_cards_html else '<div class="w-full p-8 rounded-3xl bg-[#171A21] border border-[#292E38] text-center text-gray-400">No stock opportunities currently active.</div>'}
                    </div>
                </div>

                <!-- 6. Premium Payment Cards Section (Exact Layout & Proportions from Reference Design) -->
                <div>
                    <div class="flex items-center justify-between mb-3 px-1">
                        <div class="flex items-center gap-2.5">
                            <h3 class="text-xs font-bold uppercase tracking-wider text-gray-400">PAYMENT CARDS</h3>
                            {card_counter_html}
                        </div>
                        <div class="flex items-center gap-3">
                            {carousel_controls_html}
                            <a href="/cards" class="text-xs font-semibold text-[#246BFD] hover:text-blue-400 transition-colors flex items-center gap-1">
                                <span>Card Marketplace</span>
                            </a>
                        </div>
                    </div>

                    {cards_section_content}
                </div>

                <!-- 7. Recent Transactions Section -->
                <div>
                    <div class="flex items-center justify-between mb-3 px-1">
                        <h3 class="text-xs font-bold uppercase tracking-wider text-gray-400">Recent Transactions</h3>
                        <a href="/activity" class="text-xs font-semibold text-[#246BFD] hover:underline">Transaction History</a>
                    </div>
                    {tx_section_html}
                </div>

                <!-- Dedicated Card Details & Management Modal -->
                <div id="card-details-modal" class="fixed inset-0 z-50 hidden bg-black/80 backdrop-blur-sm flex items-end sm:items-center justify-center p-0 sm:p-4 animate-fade-in">
                    <div class="w-full sm:max-w-md bg-[#171A21] border border-[#2B303C] rounded-t-3xl sm:rounded-3xl p-6 sm:p-7 space-y-5 shadow-2xl">
                        <div class="flex items-center justify-between border-b border-[#292E38] pb-3.5">
                            <div class="flex items-center gap-2.5">
                                <div class="w-8 h-8 rounded-lg bg-[#246BFD]/10 text-[#246BFD] flex items-center justify-center text-sm">
                                    <i class="fa-solid fa-credit-card"></i>
                                </div>
                                <h3 class="text-base font-bold text-white" id="modal-card-name">Card Details</h3>
                            </div>
                            <button type="button" onclick="closeCardDetailsModal()" class="w-8 h-8 rounded-full bg-[#1F2430] hover:bg-[#252B3B] text-gray-400 hover:text-white flex items-center justify-center transition-colors">
                                <i class="fa-solid fa-xmark"></i>
                            </button>
                        </div>

                        <!-- Rendered Card Preview Container in Modal -->
                        <div id="modal-card-preview-container" class="w-full">
                            <!-- Dynamically cloned card preview -->
                        </div>

                        <!-- Card Specifications List -->
                        <div class="rounded-2xl bg-[#12151B] border border-[#292E38] divide-y divide-[#292E38] text-xs">
                            <div class="p-3 flex justify-between items-center">
                                <span class="text-gray-400">Card Status</span>
                                <span id="modal-card-status-badge" class="font-extrabold uppercase px-2.5 py-0.5 rounded-md text-[10px] border"></span>
                            </div>
                            <div class="p-3 flex justify-between items-center">
                                <span class="text-gray-400">Card Type</span>
                                <span id="modal-card-type" class="font-semibold text-white"></span>
                            </div>
                            <div class="p-3 flex justify-between items-center">
                                <span class="text-gray-400">Masked Card Number</span>
                                <div class="flex items-center gap-2">
                                    <span id="modal-card-number" class="font-mono font-bold text-white"></span>
                                    <button type="button" onclick="copyCardNumberFromModal(this)" class="text-gray-400 hover:text-[#246BFD] p-1" title="Copy Number">
                                        <i class="fa-regular fa-copy"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="p-3 flex justify-between items-center">
                                <span class="text-gray-400">Cardholder Name</span>
                                <span id="modal-card-holder" class="font-bold text-white uppercase tracking-wider"></span>
                            </div>
                            <div class="p-3 flex justify-between items-center">
                                <span class="text-gray-400">Expiration</span>
                                <span id="modal-card-expiry" class="font-mono font-semibold text-white"></span>
                            </div>
                            <div class="p-3 flex justify-between items-center">
                                <span class="text-gray-400">Daily Spending Limit</span>
                                <span id="modal-card-limit" class="font-mono font-semibold text-white">$5,000.00 / day</span>
                            </div>
                            <div class="p-3 flex justify-between items-center">
                                <span class="text-gray-400">Linked Account</span>
                                <span class="font-semibold text-blue-400">Primary USD Account</span>
                            </div>
                        </div>

                        <!-- Interactive Actions -->
                        <div class="grid grid-cols-2 gap-3 pt-1">
                            <button type="button" 
                                    id="modal-toggle-freeze-btn"
                                    onclick="handleCardFreezeToggle()"
                                    class="w-full py-3 rounded-xl font-bold text-xs flex items-center justify-center gap-2 shadow-lg transition-all active:scale-95">
                                <i id="modal-freeze-icon" class="fa-solid fa-snowflake"></i>
                                <span id="modal-freeze-text">Freeze Card</span>
                            </button>
                            <a href="/cards" class="w-full py-3 rounded-xl bg-[#1F2430] hover:bg-[#252B3B] border border-[#2B303C] text-gray-200 hover:text-white font-semibold text-xs flex items-center justify-center gap-2 transition-all">
                                <i class="fa-solid fa-store text-xs"></i>
                                <span>Marketplace</span>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Interactive "More" Banking Services Modal -->
                <div id="more-services-modal" class="fixed inset-0 z-50 hidden bg-black/70 backdrop-blur-sm flex items-end sm:items-center justify-center p-0 sm:p-4 animate-fade-in">
                    <div class="w-full sm:max-w-md bg-[#171A21] border border-[#2B303C] rounded-t-3xl sm:rounded-3xl p-6 space-y-5 shadow-2xl">
                        <div class="flex items-center justify-between border-b border-[#292E38] pb-3">
                            <h3 class="text-base font-bold text-white">More Banking Services</h3>
                            <button type="button" onclick="closeMoreServicesModal()" class="w-8 h-8 rounded-full bg-[#1F2430] hover:bg-[#252B3B] text-gray-400 hover:text-white flex items-center justify-center transition-colors">
                                <i class="fa-solid fa-xmark"></i>
                            </button>
                        </div>

                        <div class="grid grid-cols-1 gap-2.5">
                            <a href="/exchange" class="flex items-center gap-3 p-3.5 rounded-2xl bg-[#12151B] hover:bg-[#1E232E] border border-[#292E38] transition-colors">
                                <div class="w-10 h-10 rounded-xl bg-amber-500/10 text-amber-400 flex items-center justify-center text-base shrink-0">
                                    <i class="fa-solid fa-arrow-right-arrow-left"></i>
                                </div>
                                <div>
                                    <h4 class="text-sm font-bold text-white">Currency Exchange</h4>
                                    <p class="text-xs text-gray-400">Convert balances between USD, USDC, EUR, BTC, ETH</p>
                                </div>
                            </a>

                            <a href="/activity" class="flex items-center gap-3 p-3.5 rounded-2xl bg-[#12151B] hover:bg-[#1E232E] border border-[#292E38] transition-colors">
                                <div class="w-10 h-10 rounded-xl bg-[#246BFD]/10 text-[#246BFD] flex items-center justify-center text-base shrink-0">
                                    <i class="fa-solid fa-file-invoice"></i>
                                </div>
                                <div>
                                    <h4 class="text-sm font-bold text-white">Account Statements</h4>
                                    <p class="text-xs text-gray-400">View and download transaction history and receipts</p>
                                </div>
                            </a>

                            <a href="/transfers/receive" class="flex items-center gap-3 p-3.5 rounded-2xl bg-[#12151B] hover:bg-[#1E232E] border border-[#292E38] transition-colors">
                                <div class="w-10 h-10 rounded-xl bg-purple-500/10 text-purple-400 flex items-center justify-center text-base shrink-0">
                                    <i class="fa-solid fa-qrcode"></i>
                                </div>
                                <div>
                                    <h4 class="text-sm font-bold text-white">Receive Funds</h4>
                                    <p class="text-xs text-gray-400">Account QR code and platform transfer details</p>
                                </div>
                            </a>

                            <a href="/cards" class="flex items-center gap-3 p-3.5 rounded-2xl bg-[#12151B] hover:bg-[#1E232E] border border-[#292E38] transition-colors">
                                <div class="w-10 h-10 rounded-xl bg-emerald-500/10 text-emerald-400 flex items-center justify-center text-base shrink-0">
                                    <i class="fa-regular fa-credit-card"></i>
                                </div>
                                <div>
                                    <h4 class="text-sm font-bold text-white">Card Marketplace</h4>
                                    <p class="text-xs text-gray-400">Order virtual or physical metal payment cards</p>
                                </div>
                            </a>

                            <a href="/support" class="flex items-center gap-3 p-3.5 rounded-2xl bg-[#12151B] hover:bg-[#1E232E] border border-[#292E38] transition-colors">
                                <div class="w-10 h-10 rounded-xl bg-cyan-500/10 text-cyan-400 flex items-center justify-center text-base shrink-0">
                                    <i class="fa-solid fa-headset"></i>
                                </div>
                                <div>
                                    <h4 class="text-sm font-bold text-white">Customer Support</h4>
                                    <p class="text-xs text-gray-400">24/7 dedicated banking assistance & ticket desk</p>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>

                <script>
                // --- Payment Cards Carousel & Modal Logic ---
                let currentModalCard = null;

                function scrollCardCarousel(direction) {{
                    const container = document.getElementById('cards-carousel-container');
                    if (!container) return;
                    const firstCard = container.querySelector('.card-slide');
                    const scrollAmount = firstCard ? (firstCard.offsetWidth + 16) : 340;
                    container.scrollBy({{ left: direction * scrollAmount, behavior: 'smooth' }});
                }}

                function scrollCardTo(index) {{
                    const container = document.getElementById('cards-carousel-container');
                    if (!container) return;
                    const cards = container.querySelectorAll('.card-slide');
                    if (cards[index]) {{
                        cards[index].scrollIntoView({{ behavior: 'smooth', inline: 'center', block: 'nearest' }});
                    }}
                }}

                function updateCardCarouselState() {{
                    const container = document.getElementById('cards-carousel-container');
                    if (!container) return;
                    const cards = container.querySelectorAll('.card-slide');
                    if (cards.length <= 1) return;

                    const scrollLeft = container.scrollLeft;
                    const cardWidth = cards[0].offsetWidth + 16;
                    const activeIndex = Math.min(Math.max(Math.round(scrollLeft / cardWidth), 0), cards.length - 1);

                    const counter = document.getElementById('card-carousel-counter');
                    if (counter) {{
                        counter.textContent = `${{activeIndex + 1}} of ${{cards.length}}`;
                    }}

                    const dots = document.querySelectorAll('.card-dot');
                    dots.forEach((dot, idx) => {{
                        if (idx === activeIndex) {{
                            dot.className = 'card-dot h-2 rounded-full transition-all bg-[#246BFD] w-5';
                        }} else {{
                            dot.className = 'card-dot h-2 rounded-full transition-all bg-gray-600 w-2 hover:bg-gray-400';
                        }}
                    }});
                }}

                document.getElementById('cards-carousel-container')?.addEventListener('scroll', () => {{
                    updateCardCarouselState();
                }}, {{ passive: true }});

                function openCardDetailsModal(card) {{
                    currentModalCard = card;
                    document.getElementById('modal-card-name').textContent = card.product_name || card.name || 'Payment Card';
                    document.getElementById('modal-card-type').textContent = ((card.card_type || card.type || 'Virtual') + ' CARD').toUpperCase();
                    document.getElementById('modal-card-number').textContent = card.card_number_masked || card.masked_number || '•••• •••• •••• 4829';
                    document.getElementById('modal-card-holder').textContent = (card.card_holder_name || card.holder || 'ELOCHUKWU ELOM').toUpperCase();

                    const expM = String(card.expiry_month || 12).padStart(2, '0');
                    const expY = String(card.expiry_year || 2029).slice(-2);
                    document.getElementById('modal-card-expiry').textContent = `${{expM}}/${{expY}}`;

                    const limit = parseFloat(card.daily_limit || card.limit || 5000);
                    document.getElementById('modal-card-limit').textContent = `$${{limit.toLocaleString('en-US', {{minimumFractionDigits: 2}})}} / day`;

                    updateModalStatusView(card.status || 'active');

                    const originalCardEl = document.querySelector(`[data-card-id="${{card.id}}"]`);
                    const previewContainer = document.getElementById('modal-card-preview-container');
                    if (originalCardEl && previewContainer) {{
                        previewContainer.innerHTML = '';
                        const clone = originalCardEl.cloneNode(true);
                        clone.classList.remove('shrink-0', 'snap-center', 'w-[88%]', 'sm:w-[420px]', 'cursor-pointer');
                        clone.classList.add('w-full', 'shadow-xl');
                        clone.removeAttribute('onclick');
                        previewContainer.appendChild(clone);
                    }}

                    document.getElementById('card-details-modal').classList.remove('hidden');
                }}

                function closeCardDetailsModal() {{
                    document.getElementById('card-details-modal')?.classList.add('hidden');
                }}

                function updateModalStatusView(status) {{
                    const isFrozen = (status === 'frozen');
                    const badge = document.getElementById('modal-card-status-badge');
                    const btn = document.getElementById('modal-toggle-freeze-btn');
                    const icon = document.getElementById('modal-freeze-icon');
                    const text = document.getElementById('modal-freeze-text');

                    if (badge) {{
                        badge.textContent = status.toUpperCase();
                        badge.className = isFrozen 
                            ? 'font-extrabold uppercase px-2.5 py-0.5 rounded-md text-[10px] border bg-[#261E0F] text-amber-400 border-amber-500/30'
                            : 'font-extrabold uppercase px-2.5 py-0.5 rounded-md text-[10px] border bg-[#0F291E] text-emerald-400 border-emerald-500/30';
                    }}

                    if (btn) {{
                        if (isFrozen) {{
                            btn.className = 'w-full py-3 rounded-xl font-bold text-xs flex items-center justify-center gap-2 shadow-lg transition-all active:scale-95 bg-emerald-600 hover:bg-emerald-700 text-white';
                            icon.className = 'fa-solid fa-lock-open';
                            text.textContent = 'Unfreeze Card';
                        }} else {{
                            btn.className = 'w-full py-3 rounded-xl font-bold text-xs flex items-center justify-center gap-2 shadow-lg transition-all active:scale-95 bg-amber-600 hover:bg-amber-700 text-white';
                            icon.className = 'fa-solid fa-snowflake';
                            text.textContent = 'Freeze Card';
                        }}
                    }}
                }}

                async function handleCardFreezeToggle() {{
                    if (!currentModalCard) return;
                    const btn = document.getElementById('modal-toggle-freeze-btn');
                    btn.disabled = true;

                    try {{
                        const response = await fetch('/cards/toggle-freeze', {{
                            method: 'POST',
                            headers: {{ 'Content-Type': 'application/json' }},
                            body: JSON.stringify({{ card_id: currentModalCard.id }})
                        }});
                        const res = await response.json();
                        if (res.success) {{
                            currentModalCard.status = res.status;
                            updateModalStatusView(res.status);

                            const cardBadge = document.querySelector(`[data-card-badge-id="${{currentModalCard.id}}"]`);
                            if (cardBadge) {{
                                const isFrozen = (res.status === 'frozen');
                                cardBadge.textContent = res.status.toUpperCase();
                                cardBadge.className = isFrozen 
                                    ? 'px-2.5 py-1 rounded-lg text-[10px] font-extrabold tracking-wider uppercase border bg-[#261E0F] text-amber-400 border-amber-500/30 shrink-0'
                                    : 'px-2.5 py-1 rounded-lg text-[10px] font-extrabold tracking-wider uppercase border bg-[#0F291E] text-emerald-400 border-emerald-500/30 shrink-0';
                            }}

                            const previewBadge = document.querySelector('#modal-card-preview-container [data-card-badge-id]');
                            if (previewBadge) {{
                                const isFrozen = (res.status === 'frozen');
                                previewBadge.textContent = res.status.toUpperCase();
                                previewBadge.className = isFrozen 
                                    ? 'px-2.5 py-1 rounded-lg text-[10px] font-extrabold tracking-wider uppercase border bg-[#261E0F] text-amber-400 border-amber-500/30 shrink-0'
                                    : 'px-2.5 py-1 rounded-lg text-[10px] font-extrabold tracking-wider uppercase border bg-[#0F291E] text-emerald-400 border-emerald-500/30 shrink-0';
                            }}

                            showToast(res.message || `Card status updated to ${{res.status}}`, res.status === 'frozen' ? 'warning' : 'success');
                        }} else {{
                            showToast(res.error || 'Failed to update card status', 'error');
                        }}
                    }} catch (err) {{
                        showToast('Network error updating card status', 'error');
                    }} finally {{
                        btn.disabled = false;
                    }}
                }}

                function copyCardNumberFromModal(btn) {{
                    if (!currentModalCard) return;
                    const num = currentModalCard.card_number_masked || currentModalCard.masked_number;
                    copyToClipboard(num, btn);
                }}

                document.getElementById('card-details-modal')?.addEventListener('click', (e) => {{
                    if (e.target.id === 'card-details-modal') closeCardDetailsModal();
                }});

                // --- More Services Modal Logic ---
                function openMoreServicesModal() {{
                    const modal = document.getElementById('more-services-modal');
                    if (modal) modal.classList.remove('hidden');
                }}
                function closeMoreServicesModal() {{
                    const modal = document.getElementById('more-services-modal');
                    if (modal) modal.classList.add('hidden');
                }}
                document.getElementById('more-services-modal')?.addEventListener('click', (e) => {{
                    if (e.target.id === 'more-services-modal') closeMoreServicesModal();
                }});

                function dismissKycReminder() {{
                    const banner = document.getElementById('kyc-notice-banner');
                    if (banner) {{
                        banner.style.transition = 'opacity 0.2s ease-out, transform 0.2s ease-out';
                        banner.style.opacity = '0';
                        banner.style.transform = 'translateY(-10px)';
                        setTimeout(() => banner.remove(), 200);
                    }}
                    fetch('/kyc/dismiss-notice', {{
                        method: 'POST',
                        headers: {{ 'Content-Type': 'application/json' }}
                    }});
                function scrollStockCarousel(direction) {{
                    const container = document.getElementById('stock-carousel');
                    if (!container) return;
                    container.scrollBy({{ left: direction * 320, behavior: 'smooth' }});
                }}

                function openInvestModal(stock) {{
                    if (!stock) return;
                    document.getElementById('dash-modal-stock-id').value = stock.id;
                    document.getElementById('dash-modal-stock-title').textContent = stock.ticker + ' Investment Opportunity';
                    document.getElementById('dash-modal-stock-sub').textContent = stock.name;
                    document.getElementById('dash-modal-stock-logo').src = stock.logo_url || ('/assets/images/stocks/' + stock.ticker.toLowerCase() + '.svg');

                    const planSelect = document.getElementById('dash-modal-plan-select');
                    if (stock.default_plan_id) {{
                        planSelect.value = stock.default_plan_id;
                    }}
                    onDashPlanChange();
                    document.getElementById('dashboard-invest-modal').classList.remove('hidden');
                }}

                function closeDashboardInvestModal() {{
                    document.getElementById('dashboard-invest-modal').classList.add('hidden');
                }}

                function onDashPlanChange() {{
                    const planSelect = document.getElementById('dash-modal-plan-select');
                    const opt = planSelect.options[planSelect.selectedIndex];
                    if (!opt) return;

                    document.getElementById('dash-modal-plan-id').value = opt.value;
                    const min = parseFloat(opt.getAttribute('data-min')) || 50;
                    const max = parseFloat(opt.getAttribute('data-max'));
                    const isUnlimited = opt.getAttribute('data-unlimited') === '1' || isNaN(max);

                    document.getElementById('dash-modal-limits').textContent = '$' + min.toLocaleString() + ' - ' + (isUnlimited ? 'Unlimited' : '$' + max.toLocaleString());

                    const amountInput = document.getElementById('dash-modal-amount');
                    if (!amountInput.value || parseFloat(amountInput.value) < min) {{
                        amountInput.value = min;
                    }}
                    recalcDashPayout();
                }}

                function recalcDashPayout() {{
                    const planSelect = document.getElementById('dash-modal-plan-select');
                    const opt = planSelect.options[planSelect.selectedIndex];
                    if (!opt) return;

                    const returnPct = parseFloat(opt.getAttribute('data-return')) || 0;
                    const duration = parseInt(opt.getAttribute('data-duration')) || 0;
                    const amount = parseFloat(document.getElementById('dash-modal-amount').value) || 0;

                    const profit = amount * (returnPct / 100);
                    const total = amount + profit;

                    document.getElementById('dash-calc-principal').textContent = '$' + amount.toLocaleString(undefined, {{minimumFractionDigits: 2, maximumFractionDigits: 2}});
                    document.getElementById('dash-calc-return').textContent = '+' + returnPct + '%';
                    document.getElementById('dash-calc-profit').textContent = '+$' + profit.toLocaleString(undefined, {{minimumFractionDigits: 2, maximumFractionDigits: 2}});
                    document.getElementById('dash-calc-duration').textContent = duration + ' hours';
                    document.getElementById('dash-calc-payout').textContent = '$' + total.toLocaleString(undefined, {{minimumFractionDigits: 2, maximumFractionDigits: 2}});
                }}

                document.getElementById('dashboard-invest-modal')?.addEventListener('click', (e) => {{
                    if (e.target.id === 'dashboard-invest-modal') closeDashboardInvestModal();
                }});
                </script>

                <!-- Quick Investment Modal for Dashboard -->
                <div id="dashboard-invest-modal" class="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm hidden flex items-center justify-center p-4">
                    <div class="w-full max-w-lg rounded-3xl bg-[#171A21] border border-[#292E38] shadow-2xl p-6 sm:p-8 space-y-6">
                        <div class="flex items-center justify-between pb-4 border-b border-[#292E38]">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-center p-2">
                                    <img id="dash-modal-stock-logo" src="/assets/images/stocks/default.svg" alt="Stock" class="w-full h-full object-contain">
                                </div>
                                <div>
                                    <h3 id="dash-modal-stock-title" class="text-base font-bold text-white">Stock Investment</h3>
                                    <p id="dash-modal-stock-sub" class="text-xs text-gray-400">Fixed Yield Allocation</p>
                                </div>
                            </div>
                            <button type="button" onclick="closeDashboardInvestModal()" class="text-gray-400 hover:text-white">
                                <i class="fa-solid fa-xmark"></i>
                            </button>
                        </div>

                        <form action="/investments" method="POST" class="space-y-4">
                            <input type="hidden" name="stock_id" id="dash-modal-stock-id" value="">
                            <input type="hidden" name="plan_id" id="dash-modal-plan-id" value="">

                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Select Investment Plan</label>
                                <select id="dash-modal-plan-select" onchange="onDashPlanChange()" class="w-full px-4 py-3 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs font-semibold focus:outline-none focus:border-[#246BFD]">
                                    {dash_plans_opts}
                                </select>
                            </div>

                            <div>
                                <div class="flex items-center justify-between mb-1.5">
                                    <label class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Allocation Amount ($ USD)</label>
                                    <span id="dash-modal-limits" class="text-[11px] font-mono text-gray-400">$50 - $99</span>
                                </div>
                                <div class="relative">
                                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 font-mono font-bold">$</span>
                                    <input type="number" 
                                           id="dash-modal-amount" 
                                           name="amount" 
                                           step="any" 
                                           placeholder="500.00" 
                                           oninput="recalcDashPayout()" 
                                           required 
                                           class="w-full pl-8 pr-4 py-3 rounded-xl bg-[#12151B] border border-[#292E38] text-white font-mono font-bold text-sm focus:outline-none focus:border-[#246BFD]">
                                </div>
                            </div>

                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Funding Account</label>
                                <select name="account_id" class="w-full px-4 py-3 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs font-semibold focus:outline-none focus:border-[#246BFD]">
                                    {dash_acc_opts}
                                </select>
                            </div>

                            <div class="rounded-2xl bg-[#12151B] border border-[#292E38] p-4 space-y-2 text-xs">
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-400">Principal:</span>
                                    <span id="dash-calc-principal" class="font-mono font-bold text-white">$0.00</span>
                                </div>
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-400">Yield Rate:</span>
                                    <span id="dash-calc-return" class="font-mono font-bold text-emerald-400">+0%</span>
                                </div>
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-400">Profit:</span>
                                    <span id="dash-calc-profit" class="font-mono font-bold text-emerald-400">+$0.00</span>
                                </div>
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-400">Duration:</span>
                                    <span id="dash-calc-duration" class="font-mono text-gray-300">0 hours</span>
                                </div>
                                <div class="pt-2 border-t border-[#292E38] flex items-center justify-between">
                                    <span class="text-white font-bold">Total Payout:</span>
                                    <span id="dash-calc-payout" class="font-mono font-bold text-base text-emerald-400">$0.00</span>
                                </div>
                            </div>

                            <button type="submit" class="w-full py-3.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold text-sm shadow-xl shadow-blue-500/25 transition-all">
                                Lock Investment Now
                            </button>
                        </form>
                    </div>
                </div>

            </div>'''
            html = build_app_layout(body, "Dashboard | Monveracu Online Banking", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 5. Accounts Page
        if path == "/accounts":
            usd_bal = STATE["accounts"][0]["balance"]
            usdc_bal = STATE["accounts"][1]["balance"]
            body = f'''<div class="max-w-5xl mx-auto space-y-6">
                <div class="flex items-center justify-between">
                    <div>
                        <h2 class="text-2xl font-bold text-white tracking-tight">Accounts & Balances</h2>
                        <p class="text-sm text-gray-400 mt-1">Review currency balances backed by double-entry ledger entries.</p>
                    </div>
                    <a href="/deposits" class="px-4 py-2.5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-semibold text-xs shadow-lg flex items-center gap-2">
                        <i class="fa-solid fa-circle-plus text-xs"></i> Fund Account
                    </a>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-xl space-y-4">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-3">
                                <div class="w-11 h-11 rounded-2xl bg-blue-600/20 text-blue-400 flex items-center justify-center font-bold text-base">USD</div>
                                <div>
                                    <h3 class="text-base font-bold text-white">US Dollars</h3>
                                    <p class="text-xs font-mono text-gray-500">Acc: 8047291635</p>
                                </div>
                            </div>
                            <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Verified</span>
                        </div>
                        <div class="pt-2">
                            <div class="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Ledger Balance</div>
                            <div class="text-3xl font-extrabold font-mono text-white pt-1">${usd_bal:.2f}</div>
                        </div>
                        <div class="pt-4 border-t border-[#292E38] flex items-center justify-between">
                            <button onclick="copyToClipboard('8047291635', this)" class="text-xs font-semibold text-gray-400 hover:text-white flex items-center gap-1.5">
                                <i class="fa-regular fa-copy"></i> Copy Number
                            </button>
                            <a href="/transfers/send" class="px-3 py-1.5 rounded-lg bg-[#1F2430] hover:bg-blue-600 text-white text-xs font-semibold">Send</a>
                        </div>
                    </div>

                    <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-xl space-y-4">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-3">
                                <div class="w-11 h-11 rounded-2xl bg-emerald-600/20 text-emerald-400 flex items-center justify-center font-bold text-base">USDC</div>
                                <div>
                                    <h3 class="text-base font-bold text-white">USD Coin</h3>
                                    <p class="text-xs font-mono text-gray-500">Acc: 8047291636</p>
                                </div>
                            </div>
                            <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Verified</span>
                        </div>
                        <div class="pt-2">
                            <div class="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Ledger Balance</div>
                            <div class="text-3xl font-extrabold font-mono text-white pt-1">{usdc_bal:.2f} USDC</div>
                        </div>
                        <div class="pt-4 border-t border-[#292E38] flex items-center justify-between">
                            <button onclick="copyToClipboard('8047291636', this)" class="text-xs font-semibold text-gray-400 hover:text-white flex items-center gap-1.5">
                                <i class="fa-regular fa-copy"></i> Copy Number
                            </button>
                            <a href="/exchange" class="px-3 py-1.5 rounded-lg bg-[#1F2430] hover:bg-amber-600 text-white text-xs font-semibold">Convert</a>
                        </div>
                    </div>
                </div>
            </div>'''
            html = build_app_layout(body, "My Accounts | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 6. Send Money Page
        if path == "/transfers/send":
            view_path = os.path.join(VIEWS_DIR, "transfers", "send.php")
            with open(view_path, 'r', encoding='utf-8') as f:
                body = f.read()
            body = body.replace("<?= (float)($primaryAccount['cached_balance'] ?? 0) ?>", str(STATE["accounts"][0]["balance"]))
            body = body.replace("<?= format_money($primaryAccount['cached_balance'] ?? 0, 'USD') ?>", f"${STATE['accounts'][0]['balance']:.2f}")
            body = body.replace("<?= (float)env('TRANSFER_DEFAULT_FEE_PCT', 0.00) * 100 ?>", "0.0")
            body = body.replace("<?= (float)env('TRANSFER_DEFAULT_FEE_PCT', 0.00) ?>", "0.00")
            body = body.replace("<?= csrf_token() ?>", "preview_token")
            body = re.sub(r"<\?php.*?\?>", "", body, flags=re.DOTALL)
            body = re.sub(r"<\?=.*?\?>", "", body, flags=re.DOTALL)
            html = build_app_layout(body, "Send Money | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 7. Receive Money Page
        if path == "/transfers/receive":
            user = STATE["user"]
            qr_svg = generate_svg_qr("8047291635", 180)
            body = f'''<div class="max-w-xl mx-auto space-y-6">
                <div class="text-center sm:text-left">
                    <h2 class="text-2xl font-bold text-white tracking-tight">Receive Money</h2>
                    <p class="text-sm text-gray-400 mt-1">Share your account number or registered email with another platform user to receive funds instantly.</p>
                </div>
                <div class="p-6 sm:p-8 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-2xl text-center space-y-6">
                    <div class="inline-block p-4 rounded-2xl bg-white shadow-xl mx-auto">
                        {qr_svg}
                    </div>
                    <div class="space-y-1">
                        <h3 class="text-xl font-bold text-white">{user['first_name']} {user['last_name']}</h3>
                        <p class="text-xs text-gray-400">Verified Platform Account</p>
                    </div>
                    <div class="space-y-3 max-w-md mx-auto text-left">
                        <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-between">
                            <div>
                                <div class="text-[10px] font-semibold uppercase tracking-wider text-gray-400">Platform Account Number</div>
                                <div class="text-base font-mono font-bold text-blue-400 tracking-wider">8047291635</div>
                            </div>
                            <button onclick="copyToClipboard('8047291635', this)" class="px-3 py-1.5 rounded-lg bg-[#1F2430] hover:bg-blue-600 text-xs font-semibold text-gray-300">Copy</button>
                        </div>
                        <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-between">
                            <div>
                                <div class="text-[10px] font-semibold uppercase tracking-wider text-gray-400">Registered Email Address</div>
                                <div class="text-sm font-semibold text-white">{user['email']}</div>
                            </div>
                            <button onclick="copyToClipboard('{user['email']}', this)" class="px-3 py-1.5 rounded-lg bg-[#1F2430] hover:bg-blue-600 text-xs font-semibold text-gray-300">Copy</button>
                        </div>
                    </div>
                </div>
            </div>'''
            html = build_app_layout(body, "Receive Money | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 8. Transfer Receipt
        if path.startswith("/transfers/receipt/"):
            ref = path.split("/")[-1]
            tx = next((t for t in STATE["transfers"] if t["ref"] == ref), STATE["transfers"][0])
            body = f'''<div class="max-w-md mx-auto space-y-6">
                <div class="p-6 sm:p-8 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-2xl text-center space-y-6">
                    <div class="w-16 h-16 rounded-full bg-emerald-500/20 text-emerald-400 flex items-center justify-center mx-auto text-2xl shadow-lg ring-4 ring-emerald-500/10">
                        <i class="fa-solid fa-check"></i>
                    </div>
                    <div class="space-y-1">
                        <h2 class="text-xs font-bold uppercase tracking-wider text-emerald-400">TRANSFER SUCCESSFUL</h2>
                        <div class="text-3xl font-extrabold font-mono text-white pt-1">${tx['amount']:.2f} {tx['currency']}</div>
                        <p class="text-sm text-gray-400 pt-1">You sent funds to {tx['recipient']}</p>
                    </div>
                    <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38] space-y-3 text-xs text-left">
                        <div class="flex justify-between"><span class="text-gray-400">Reference:</span> <span class="font-mono font-bold text-blue-400">{tx['ref']}</span></div>
                        <div class="flex justify-between"><span class="text-gray-400">Date:</span> <span class="text-white">{tx['date']}</span></div>
                        <div class="flex justify-between"><span class="text-gray-400">Sender:</span> <span class="text-white">{tx['sender']}</span></div>
                        <div class="flex justify-between"><span class="text-gray-400">Recipient Account:</span> <span class="font-mono text-white">••••••3746</span></div>
                        <div class="flex justify-between font-bold text-sm pt-2 border-t border-[#292E38]"><span class="text-white">Total Debit:</span> <span class="font-mono text-emerald-400">${tx['total']:.2f}</span></div>
                    </div>
                    <div class="space-y-2">
                        <a href="/transfers/send" class="block w-full py-3.5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-bold text-sm shadow-xl">Send Another Transfer</a>
                        <a href="/dashboard" class="block w-full py-2.5 rounded-xl bg-[#1F2430] text-gray-300 text-xs font-semibold">Back to Dashboard</a>
                    </div>
                </div>
            </div>'''
            html = build_app_layout(body, f"Receipt {ref} | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 9. Deposits (Fund Account)
        if path == "/deposits":
            acc_bal = STATE["accounts"][0]["balance"]
            acc_num = STATE["accounts"][0]["account_number"]
            acc_type = STATE["accounts"][0].get("account_type", "Checking Account")
            acc_curr = STATE["accounts"][0]["currency"]

            rates_dict = {
                "USDC": 1.00,
                "BTC": 68500.00,
                "ETH": 2650.00,
                "SOL": 178.50
            }

            assets_dict = {}
            for pm in STATE.get("payment_methods", []):
                if pm.get("status") != "active":
                    continue
                code = str(pm.get("code", "USDC")).upper()
                if code not in assets_dict:
                    clean_name = pm.get("name", code).split(" (")[0]
                    assets_dict[code] = {
                        "name": clean_name if clean_name else code,
                        "symbol": code,
                        "decimals": 8 if code == "BTC" else (18 if code == "ETH" else 6),
                        "min_deposit": float(pm.get("min_deposit", 50.0)),
                        "max_deposit": float(pm.get("max_deposit", 100000.0)),
                        "exchange_rate": rates_dict.get(code, 1.0),
                        "icon_url": pm.get("icon_url", f"/assets/images/crypto/{code.lower()}.svg"),
                        "networks": []
                    }
                assets_dict[code]["networks"].append({
                    "id": str(pm.get("network", "ERC20")).upper(),
                    "name": pm.get("name", f"{code} ({pm.get('network')})"),
                    "required_confirmations": int(pm.get("required_confirmations", 12)),
                    "estimated_time": pm.get("processing_time") or "3 - 8 mins",
                    "default_address": pm.get("wallet_address", ""),
                    "min_deposit": float(pm.get("min_deposit", 50.0)),
                    "max_deposit": float(pm.get("max_deposit", 100000.0)),
                    "instructions": pm.get("instructions", ""),
                    "method_id": pm.get("id")
                })

            if not assets_dict:
                assets_dict = {
                    "USDC": {
                        "name": "USD Coin",
                        "symbol": "USDC",
                        "decimals": 6,
                        "min_deposit": 50.0,
                        "max_deposit": 100000.0,
                        "networks": []
                    }
                }

            dep_rows = ""
            for d in STATE.get("deposits", []):
                st = d["status"].lower()
                is_credited = (st == "credited")
                is_pending = st in ["pending_review", "confirming", "pending_confirmation", "approved"]
                is_rejected = st in ["rejected", "failed"]

                badge_class = "bg-[#0F291E] text-emerald-400 border border-emerald-500/30" if is_credited else ("bg-[#261E0F] text-amber-400 border border-amber-500/30" if is_pending else ("bg-[#291212] text-red-400 border border-red-500/30" if is_rejected else "bg-[#0F1E29] text-blue-400 border border-blue-500/30"))

                status_label = "Credited" if is_credited else ("Pending Review" if st == "pending_review" else ("Awaiting Deposit" if "awaiting" in st else st.replace("_", " ").title()))

                dep_rows += f'''
                <div class="p-4 sm:p-5 flex items-center justify-between hover:bg-[#1C2028]/40 transition-colors">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-center text-blue-400 shrink-0">
                            <i class="fa-solid fa-arrow-down-long"></i>
                        </div>
                        <div>
                            <div class="flex items-center gap-2">
                                <span class="text-sm font-bold text-white font-mono">${d['amount']:,.2f} USD</span>
                                <span class="text-xs text-gray-400">({d['asset']} • {d['network']})</span>
                            </div>
                            <div class="flex items-center gap-2 mt-0.5">
                                <span class="font-mono text-[11px] text-gray-500">{d['reference']}</span>
                                <span class="text-gray-600">•</span>
                                <span class="text-[11px] text-gray-500">{d['created_at']}</span>
                            </div>
                        </div>
                    </div>
                    <div class="text-right flex items-center gap-3">
                        <span class="px-2.5 py-1 rounded-full text-[10px] font-extrabold tracking-wider uppercase {badge_class}">
                            {status_label}
                        </span>
                    </div>
                </div>'''

            view_path = os.path.join(VIEWS_DIR, "deposits", "index.php")
            with open(view_path, 'r', encoding='utf-8') as f:
                body = f.read()

            # Substitute PHP tags with live variables
            body = body.replace("<?= number_format($accBal, 2) ?>", f"{acc_bal:,.2f}")
            body = body.replace("<?= e($accNum) ?>", acc_num)
            body = body.replace("<?= e($accType) ?>", acc_type)
            body = body.replace("<?= e($accCurr) ?>", acc_curr)
            body = body.replace("<?= json_encode($assets) ?>", json.dumps(assets_dict))
            body = body.replace("<?= json_encode($rates) ?>", json.dumps(rates_dict))
            body = body.replace("<?= csrf_token() ?>", "preview_token")

            # Replace the recent deposits PHP foreach block with pre-rendered rows or empty state
            if dep_rows:
                recent_dep_html = f'<div class="rounded-3xl bg-[#171A21] border border-[#292E38] divide-y divide-[#292E38]/60 overflow-hidden shadow-xl">{dep_rows}</div>'
            else:
                recent_dep_html = '''<div class="p-8 rounded-3xl bg-[#171A21] border border-[#292E38] text-center space-y-2">
                    <p class="text-sm text-gray-400">No deposit records yet.</p>
                    <p class="text-xs text-gray-500">Fund your account above to post your first ledger deposit credit.</p>
                </div>'''

            body = re.sub(
                r'<\?php if \(!empty\(\$recentDeposits\)\): \?>.*?<\?php endif; \?>',
                recent_dep_html,
                body,
                flags=re.DOTALL
            )

            # Strip any remaining PHP tags cleanly
            body = re.sub(r'<\?php.*?\?>', '', body, flags=re.DOTALL)
            body = re.sub(r'<\?=.*?\?>', '', body, flags=re.DOTALL)

            html = build_app_layout(body, "Fund Account | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 10. Cards Marketplace & Virtual Cards Hub
        if path == "/cards":
            usd_bal = float(STATE["accounts"][0]["balance"])
            my_cards = STATE.get("cards", [])
            my_orders = STATE.get("card_orders", [])

            active_cards_count = len([c for c in my_cards if c.get("status") == "active"])
            pending_count = sum(1 for o in my_orders if o.get("status") in ["pending", "processing"])
            total_card_limit = sum(float(c.get("daily_limit", 5000.0)) for c in my_cards if c.get("status") == "active")

            # 1. Active Cards Grid
            my_cards_html = ""
            if my_cards:
                cards_list_html = ""
                for my_card in my_cards:
                    c_id = my_card["id"]
                    c_st = my_card.get("status", "active")
                    is_active = (c_st == "active")
                    freeze_text = "Freeze Card" if is_active else "Unfreeze Card"
                    btn_bg = "bg-[#1F2430] hover:bg-amber-500/20 text-gray-300 hover:text-amber-400 border border-[#292E38]" if is_active else "bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400 border border-emerald-500/30"

                    c_design = my_card.get("card_design", my_card.get("design", "obsidian"))
                    if c_design == "midnight_blue":
                        bg_front = "from-[#0B2545] via-[#133E7C] to-[#1E3A8A]"
                        bg_back = "from-[#081B33] via-[#0E2D5A] to-[#162C66]"
                    elif c_design == "titanium_gold":
                        bg_front = "from-[#3A2207] via-[#854D0E] to-[#D97706]"
                        bg_back = "from-[#2A1805] via-[#5F370A] to-[#92400E]"
                    elif c_design == "crypto_black":
                        bg_front = "from-[#000000] via-[#111827] to-[#1F2937]"
                        bg_back = "from-[#050505] via-[#0A0D14] to-[#151922]"
                    else:
                        bg_front = "from-[#0F1318] via-[#161B22] to-[#21262D]"
                        bg_back = "from-[#0A0D10] via-[#10141A] to-[#171B22]"

                    c_network = my_card.get("network", "Monveracu Pay")
                    c_json = html_lib.escape(json.dumps(my_card), quote=True)

                    cards_list_html += f'''
                    <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-xl flex flex-col justify-between space-y-5">
                        <!-- 3D Interactive Flip Card for Issued Card -->
                        <div class="card-container w-full h-52 cursor-pointer perspective-1000" onclick="this.classList.toggle('is-flipped')">
                            <div class="card-inner relative w-full h-full transform-style-preserve-3d transition-transform duration-700">
                                <!-- FRONT FACE -->
                                <div class="card-front absolute inset-0 w-full h-full rounded-2xl bg-gradient-to-tr {bg_front} p-5 text-white flex flex-col justify-between border border-white/10 shadow-2xl backface-hidden overflow-hidden">
                                    <div class="absolute -right-8 -bottom-8 w-36 h-36 bg-white/5 rounded-full blur-2xl pointer-events-none"></div>
                                    <div class="flex justify-between items-start relative z-10">
                                        <div class="flex items-center gap-2">
                                            <div class="emv-chip"></div>
                                            <i class="fa-solid fa-wifi text-white/70 text-xs rotate-90"></i>
                                        </div>
                                        <div class="text-right">
                                            <span class="font-bold tracking-wide text-xs block">{my_card.get('name', 'Monveracu Card')}</span>
                                            <span class="inline-block mt-0.5 px-2 py-0.5 rounded bg-white/10 text-[9px] font-mono uppercase text-gray-200 font-bold tracking-wider">MONVERACU</span>
                                        </div>
                                    </div>
                                    <div class="py-2 relative z-10">
                                        <div class="text-xl sm:text-2xl font-mono tracking-widest text-white font-bold drop-shadow">
                                            {my_card.get('masked_number', '•••• •••• •••• 0000')}
                                        </div>
                                    </div>
                                    <div class="flex justify-between items-end text-xs relative z-10">
                                        <div>
                                            <div class="text-[8px] uppercase tracking-wider text-gray-400">Cardholder</div>
                                            <div class="font-bold text-white tracking-wide text-[11px] truncate max-w-[150px]">{my_card.get('holder', 'Elochukwu Elom')}</div>
                                        </div>
                                        <div class="text-center">
                                            <div class="text-[8px] uppercase tracking-wider text-gray-400">Expires</div>
                                            <div class="font-mono text-white font-bold text-[11px]">{my_card.get('exp', '10/31')}</div>
                                        </div>
                                        <div>
                                            <span class="px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider {'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30' if is_active else 'bg-amber-500/20 text-amber-300 border border-amber-500/30'}">
                                                {'● Active' if is_active else '○ Frozen'}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <!-- BACK FACE -->
                                <div class="card-back absolute inset-0 w-full h-full rounded-2xl bg-gradient-to-tr {bg_back} text-white flex flex-col justify-between border border-white/10 shadow-2xl backface-hidden rotate-y-180 overflow-hidden">
                                    <div class="w-full h-10 bg-black/90 mt-4"></div>
                                    <div class="px-5 space-y-2">
                                        <div class="flex items-center justify-between">
                                            <div class="h-7 flex-1 bg-white/20 rounded flex items-center justify-end px-3 font-mono text-black font-bold text-xs tracking-widest">
                                                ••• <span class="text-[9px] text-gray-800 ml-1 font-sans">CVV</span>
                                            </div>
                                            <div class="px-2.5 py-1 ml-3 rounded bg-white/10 flex items-center gap-1 font-mono text-[9px] text-gray-200 font-bold uppercase">
                                                <i class="fa-solid fa-building-columns text-[8px]"></i> MONVERACU
                                            </div>
                                        </div>
                                        <p class="text-[8px] text-gray-400 leading-tight">This virtual card is issued for verified online purchases and contactless transactions. Authorised use only.</p>
                                    </div>
                                    <div class="px-5 pb-3 flex justify-between items-center text-[9px] text-gray-400 font-mono">
                                        <span>Monveracu Secured</span>
                                        <span>Tap card to flip back</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Card Controls & Metadata -->
                        <div class="space-y-3 pt-2">
                            <div class="grid grid-cols-2 gap-2 text-xs">
                                <div class="p-2.5 rounded-xl bg-[#12151B] border border-[#292E38]">
                                    <span class="text-[9px] text-gray-500 uppercase block font-semibold">Daily Limit</span>
                                    <span class="font-mono font-bold text-white">${float(my_card.get('daily_limit', 5000)):,.2f}</span>
                                </div>
                                <div class="p-2.5 rounded-xl bg-[#12151B] border border-[#292E38]">
                                    <span class="text-[9px] text-gray-500 uppercase block font-semibold">Spend Today</span>
                                    <span class="font-mono font-bold text-blue-400">${float(my_card.get('spent_today', 0.0)):,.2f}</span>
                                </div>
                            </div>
                            <div class="flex items-center gap-2">
                                <button type="button" onclick="openCardSpecsModal({c_json})"
                                    class="flex-1 py-2 rounded-xl bg-[#1F2430] hover:bg-[#252B3B] text-white text-xs font-semibold transition-all">
                                    <i class="fa-solid fa-eye mr-1 text-[11px]"></i> Card Specs
                                </button>
                                <button type="button" onclick="toggleCardFreeze({c_id}, this)"
                                    class="flex-1 py-2 rounded-xl {btn_bg} text-xs font-semibold transition-all">
                                    <i class="fa-solid {'fa-snowflake' if is_active else 'fa-sun'} mr-1 text-[11px]"></i> {freeze_text}
                                </button>
                            </div>
                        </div>
                    </div>'''
                my_cards_html = f'<div class="grid grid-cols-1 md:grid-cols-2 gap-6">{cards_list_html}</div>'
            else:
                my_cards_html = '''
                <div class="p-10 rounded-3xl bg-[#171A21] border border-[#292E38] text-center space-y-4">
                    <div class="w-14 h-14 rounded-2xl bg-[#246BFD]/10 text-[#246BFD] flex items-center justify-center mx-auto text-2xl">
                        <i class="fa-solid fa-credit-card"></i>
                    </div>
                    <div>
                        <h4 class="text-base font-bold text-white">No active cards yet</h4>
                        <p class="text-xs text-gray-400 max-w-md mx-auto mt-1">Select a card from our marketplace catalog below to apply for your primary payment card.</p>
                    </div>
                    <div class="pt-2">
                        <a href="#available-catalog" class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-xs font-semibold shadow-lg shadow-blue-500/20 transition-all">
                            Browse Card Catalog <i class="fa-solid fa-arrow-down text-[10px]"></i>
                        </a>
                    </div>
                </div>'''

            # 2. Applications Table HTML
            app_rows_html = ""
            for o in my_orders:
                o_st = str(o.get("status", "pending")).lower()
                is_p = o_st in ["pending", "processing"]
                is_appr = o_st in ["completed", "approved", "active"]
                is_rej = (o_st == "rejected")

                o_fee = float(o.get("payment_amount", 0.0))
                o_ref = o.get("reference", f"ORD-CRD-{o['id']}")

                if is_p:
                    st_badge = '<span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase bg-amber-500/10 text-amber-300 border border-amber-500/20"><i class="fa-solid fa-spinner fa-spin text-[9px]"></i> Pending Review</span>'
                elif is_appr:
                    st_badge = '<span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"><i class="fa-solid fa-check text-[9px]"></i> Approved & Issued</span>'
                elif is_rej:
                    rej_msg = html_lib.escape(str(o.get("rejection_reason", "Compliance criteria not met")))
                    st_badge = f'''<div class="space-y-1">
                        <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase bg-rose-500/10 text-rose-400 border border-rose-500/20"><i class="fa-solid fa-xmark text-[9px]"></i> Rejected (Fee Refunded)</span>
                        <p class="text-[10px] text-gray-400 italic">"{rej_msg}"</p>
                    </div>'''
                else:
                    st_badge = f'<span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase bg-gray-500/10 text-gray-400">{o_st}</span>'

                app_rows_html += f'''
                <tr class="hover:bg-white/[0.02] transition-colors">
                    <td class="py-4 font-mono font-bold text-blue-400">{o_ref}</td>
                    <td class="py-4 font-medium text-white">{o.get('product_name', 'Virtual Card')}</td>
                    <td class="py-4 font-mono font-bold {'text-white' if o_fee > 0 else 'text-emerald-400'}">{f'${o_fee:.2f}' if o_fee > 0 else 'Free ($0.00)'}</td>
                    <td class="py-4 font-mono text-gray-400 text-[11px]">{o.get('created_at', time.strftime('%Y-%m-%d %H:%M'))}</td>
                    <td class="py-4">{st_badge}</td>
                </tr>'''

            # 3. Available Catalog Cards with 3D Flip Visuals
            catalog_items_html = ""
            active_prods = [p for p in STATE["card_products"] if p.get("is_active", 1) == 1]
            for p in active_prods:
                p_fee = float(p.get("fee", p.get("issuance_fee", 0.0)))
                p_min_bal = float(p.get("min_balance_required", 0.0))
                p_daily_lim = float(p.get("limit", p.get("daily_limit", 5000.0)))
                p_monthly_lim = float(p.get("monthly_limit", 25000.0))
                p_design = p.get("design", p.get("card_design", "obsidian"))

                if p_design == "midnight_blue":
                    bg_front = "from-[#0B2545] via-[#133E7C] to-[#1E3A8A]"
                    bg_back = "from-[#081B33] via-[#0E2D5A] to-[#162C66]"
                elif p_design == "titanium_gold":
                    bg_front = "from-[#3A2207] via-[#854D0E] to-[#D97706]"
                    bg_back = "from-[#2A1805] via-[#5F370A] to-[#92400E]"
                elif p_design == "crypto_black":
                    bg_front = "from-[#000000] via-[#111827] to-[#1F2937]"
                    bg_back = "from-[#050505] via-[#0A0D14] to-[#151922]"
                else:
                    bg_front = "from-[#0F1318] via-[#161B22] to-[#21262D]"
                    bg_back = "from-[#0A0D10] via-[#10141A] to-[#171B22]"

                price_tag = "Free" if p_fee == 0.0 else f"${p_fee:,.2f}"
                features_li = "".join([f'<li class="flex items-center gap-2"><i class="fa-solid fa-check text-emerald-400 text-[10px]"></i><span>{feat}</span></li>' for feat in p.get("features", [])[:4]])

                can_apply = (usd_bal >= p_fee) and (usd_bal >= p_min_bal)
                p_json_str = html_lib.escape(json.dumps(p), quote=True)

                catalog_items_html += f'''
                <div class="rounded-3xl bg-[#171A21] border border-[#292E38] overflow-hidden flex flex-col justify-between hover:border-gray-500 transition-all shadow-xl group">
                    <div class="p-5 pb-3">
                        <!-- 3D Flip Card Container on hover or click -->
                        <div class="card-container w-full h-44 cursor-pointer perspective-1000" onclick="this.classList.toggle('is-flipped')">
                            <div class="card-inner relative w-full h-full transform-style-preserve-3d transition-transform duration-700">
                                <!-- FRONT -->
                                <div class="card-front absolute inset-0 w-full h-full rounded-2xl bg-gradient-to-tr {bg_front} p-4 text-white flex flex-col justify-between border border-white/10 shadow-lg backface-hidden overflow-hidden">
                                    <div class="absolute -right-6 -bottom-6 w-28 h-28 bg-white/5 rounded-full blur-xl pointer-events-none"></div>
                                    <div class="flex justify-between items-start relative z-10">
                                        <div class="flex items-center gap-2">
                                            <div class="emv-chip"></div>
                                            <i class="fa-solid fa-wifi text-white/70 text-[10px] rotate-90"></i>
                                        </div>
                                        <div class="text-right">
                                            <span class="font-bold text-[11px] block">{p['name']}</span>
                                            <span class="inline-block mt-0.5 px-2 py-0.5 rounded bg-white/10 text-[9px] font-mono uppercase text-gray-200 font-bold tracking-wider">MONVERACU</span>
                                        </div>
                                    </div>
                                    <div class="text-base font-mono tracking-widest text-white font-bold opacity-80 py-1 relative z-10">
                                        •••• •••• •••• 0000
                                    </div>
                                    <div class="flex justify-between items-end text-[9px] uppercase tracking-wider opacity-80 relative z-10">
                                        <div>
                                            <span class="block text-[8px] text-gray-400">Card Tier</span>
                                            <span class="font-semibold text-white">{p.get('type', 'virtual').upper()}</span>
                                        </div>
                                        <span class="px-2 py-0.5 rounded font-mono text-[8px] bg-white/10 font-bold">{p.get('design', 'obsidian').upper()}</span>
                                    </div>
                                </div>
                                <!-- BACK -->
                                <div class="card-back absolute inset-0 w-full h-full rounded-2xl bg-gradient-to-tr {bg_back} text-white flex flex-col justify-between border border-white/10 shadow-lg backface-hidden rotate-y-180 overflow-hidden">
                                    <div class="w-full h-8 bg-black/90 mt-3"></div>
                                    <div class="px-4 space-y-1">
                                        <div class="flex items-center justify-between">
                                            <div class="h-6 flex-1 bg-white/20 rounded flex items-center justify-end px-2 font-mono text-black font-bold text-[10px] tracking-widest">
                                                ••• <span class="text-[8px] text-gray-800 ml-1 font-sans">CVV</span>
                                            </div>
                                            <div class="px-2 py-0.5 ml-2 rounded bg-white/10 flex items-center gap-1 font-mono text-[8px] text-gray-200 font-bold uppercase">
                                                <i class="fa-solid fa-building-columns text-[7px]"></i> MONVERACU
                                            </div>
                                        </div>
                                        <p class="text-[8px] text-gray-400 leading-tight">Virtual spending card powered by Monveracu core ledger.</p>
                                    </div>
                                    <div class="px-4 pb-2 flex justify-between items-center text-[8px] text-gray-400 font-mono">
                                        <span>Click to flip</span>
                                        <span>Monveracu 3D Secure</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="px-5 pb-5 flex-1 flex flex-col justify-between space-y-4">
                        <div>
                            <div class="flex justify-between items-baseline mb-1">
                                <h4 class="text-base font-bold text-white">{p['name']}</h4>
                                <div class="text-sm font-mono font-bold text-blue-400">{price_tag}</div>
                            </div>
                            <div class="flex items-center gap-2 text-xs text-gray-400">
                                <span>Daily Limit: <strong class="text-white">${p_daily_lim:,.0f}</strong></span>
                                {f'<span>• Min Bal: <strong class="text-white">${p_min_bal:,.0f}</strong></span>' if p_min_bal > 0 else ''}
                            </div>
                            <ul class="mt-3 space-y-1.5 text-xs text-gray-300">
                                {features_li}
                            </ul>
                        </div>

                        <div class="space-y-2 pt-2 border-t border-[#292E38]/80">
                            <div class="grid grid-cols-2 gap-2">
                                <button type="button" onclick="openProductDetailsModal({p_json_str})"
                                    class="w-full py-2.5 rounded-xl bg-[#1F2430] hover:bg-[#252B3B] text-gray-300 hover:text-white font-semibold text-xs transition-all">
                                    View Details
                                </button>
                                <button type="button" onclick="openApplyModal({p_json_str})"
                                    class="w-full py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold text-xs shadow-lg shadow-blue-500/20 transition-all active:scale-95">
                                    Apply Now
                                </button>
                            </div>
                        </div>
                    </div>
                </div>'''

            body = f'''
            <style>
            .perspective-1000 {{ perspective: 1000px; }}
            .transform-style-preserve-3d {{ transform-style: preserve-3d; }}
            .backface-hidden {{ backface-visibility: hidden; -webkit-backface-visibility: hidden; }}
            .rotate-y-180 {{ transform: rotateY(180deg); }}
            .card-inner {{ transition: transform 0.7s cubic-bezier(0.4, 0.2, 0.2, 1); }}
            .card-container:hover .card-inner, .card-container.is-flipped .card-inner {{ transform: rotateY(180deg); }}
            </style>

            <div class="max-w-6xl mx-auto space-y-10">

                <!-- 1. Header & Breadcrumb -->
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <div class="flex items-center gap-2 text-xs text-gray-400 mb-1">
                            <a href="/dashboard" class="hover:text-white transition-colors">Dashboard</a>
                            <i class="fa-solid fa-chevron-right text-[10px]"></i>
                            <span class="text-white">Virtual Cards</span>
                        </div>
                        <h1 class="text-2xl sm:text-3xl font-bold text-white tracking-tight">Virtual Cards & Marketplace</h1>
                        <p class="text-xs sm:text-sm text-gray-400 mt-1">Manage your virtual cards, track applications, and access your card details securely.</p>
                    </div>
                    <div>
                        <a href="#available-catalog" class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white text-sm font-semibold shadow-lg shadow-blue-500/20 transition-all">
                            <i class="fa-solid fa-plus text-xs"></i>
                            <span>Apply for Card</span>
                        </a>
                    </div>
                </div>

                <!-- 2. Summary Statistics (4 KPI Cards) -->
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <!-- Active Cards -->
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-2">
                        <div class="flex items-center justify-between text-xs text-gray-400">
                            <span class="font-medium">Active Cards</span>
                            <div class="w-8 h-8 rounded-lg bg-[#20C997]/10 text-[#20C997] flex items-center justify-center text-sm">
                                <i class="fa-solid fa-credit-card"></i>
                            </div>
                        </div>
                        <div class="text-2xl font-bold text-white font-mono">{active_cards_count}</div>
                        <p class="text-[11px] text-gray-500">Issued and ready for use</p>
                    </div>

                    <!-- Pending Applications -->
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-2">
                        <div class="flex items-center justify-between text-xs text-gray-400">
                            <span class="font-medium">Pending Applications</span>
                            <div class="w-8 h-8 rounded-lg bg-amber-500/10 text-amber-400 flex items-center justify-center text-sm">
                                <i class="fa-solid fa-clock-rotate-left"></i>
                            </div>
                        </div>
                        <div class="text-2xl font-bold text-white font-mono">{pending_count}</div>
                        <p class="text-[11px] text-gray-500">Awaiting administrator review</p>
                    </div>

                    <!-- Total Card Limit -->
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-2">
                        <div class="flex items-center justify-between text-xs text-gray-400">
                            <span class="font-medium">Total Card Limit</span>
                            <div class="w-8 h-8 rounded-lg bg-[#246BFD]/10 text-[#246BFD] flex items-center justify-center text-sm">
                                <i class="fa-solid fa-gauge-high"></i>
                            </div>
                        </div>
                        <div class="text-2xl font-bold text-white font-mono">${total_card_limit:,.2f}</div>
                        <p class="text-[11px] text-gray-500">Combined daily limit</p>
                    </div>

                    <!-- Available Balance -->
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-2">
                        <div class="flex items-center justify-between text-xs text-gray-400">
                            <span class="font-medium">Available Balance</span>
                            <div class="w-8 h-8 rounded-lg bg-emerald-500/10 text-emerald-400 flex items-center justify-center text-sm">
                                <i class="fa-solid fa-wallet"></i>
                            </div>
                        </div>
                        <div class="text-2xl font-bold text-white font-mono">${usd_bal:,.2f}</div>
                        <p class="text-[11px] text-gray-500">USD available balance</p>
                    </div>
                </div>

                <!-- 3. Virtual Card Introduction Section -->
                <div class="p-6 sm:p-8 rounded-3xl bg-gradient-to-r from-[#171A21] via-[#1A1F29] to-[#12151B] border border-[#292E38] shadow-2xl relative overflow-hidden">
                    <div class="absolute -right-16 -top-16 w-64 h-64 bg-blue-600/10 rounded-full blur-3xl pointer-events-none"></div>
                    <div class="max-w-2xl space-y-3 relative z-10">
                        <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-[#246BFD]/10 text-[#246BFD] border border-[#246BFD]/20">
                            <i class="fa-solid fa-shield-halved text-[10px]"></i> Enterprise-Grade Cards
                        </span>
                        <h2 class="text-xl sm:text-2xl font-bold text-white tracking-tight">Virtual Cards Made Easy</h2>
                        <p class="text-xs sm:text-sm text-gray-300 leading-relaxed">
                            Apply for virtual cards for eligible online payments, subscription management, and other supported spending needs. Manage your card applications, review spending limits, and access issued card details directly from your dashboard.
                        </p>
                    </div>

                    <!-- 4 Feature Highlights -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-6 pt-6 border-t border-[#292E38]">
                        <div class="space-y-1.5">
                            <div class="flex items-center gap-2 text-white font-semibold text-xs">
                                <i class="fa-solid fa-lock text-[#246BFD]"></i>
                                <span>Secure Payments</span>
                            </div>
                            <p class="text-[11px] text-gray-400 leading-snug">Use separate virtual cards for eligible transactions without exposing your primary card details unnecessarily.</p>
                        </div>
                        <div class="space-y-1.5">
                            <div class="flex items-center gap-2 text-white font-semibold text-xs">
                                <i class="fa-solid fa-globe text-[#20C997]"></i>
                                <span>Global Acceptance</span>
                            </div>
                            <p class="text-[11px] text-gray-400 leading-snug">Use supported virtual cards with online merchants and digital terminals worldwide for everyday subscriptions and transactions.</p>
                        </div>
                        <div class="space-y-1.5">
                            <div class="flex items-center gap-2 text-white font-semibold text-xs">
                                <i class="fa-solid fa-sliders text-amber-400"></i>
                                <span>Spending Controls</span>
                            </div>
                            <p class="text-[11px] text-gray-400 leading-snug">Review your card spending limits and manage instant freeze/unfreeze controls from your dashboard.</p>
                        </div>
                        <div class="space-y-1.5">
                            <div class="flex items-center gap-2 text-white font-semibold text-xs">
                                <i class="fa-solid fa-bolt text-purple-400"></i>
                                <span>Digital Issuance</span>
                            </div>
                            <p class="text-[11px] text-gray-400 leading-snug">Track your application and access card details once your card has been approved and successfully issued.</p>
                        </div>
                    </div>

                    <div class="mt-6 flex items-center gap-3">
                        <a href="#available-catalog" class="px-5 py-2.5 rounded-xl bg-white hover:bg-gray-100 text-black text-xs font-bold transition-colors">
                            Apply Now
                        </a>
                        <a href="#how-cards-work" class="px-4 py-2.5 rounded-xl bg-transparent hover:bg-white/5 text-gray-400 hover:text-white text-xs font-medium transition-colors">
                            How It Works <i class="fa-solid fa-arrow-down ml-1 text-[10px]"></i>
                        </a>
                    </div>
                </div>

                <!-- 4. Your Cards & Applications Section -->
                <div class="space-y-6">
                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 border-b border-[#292E38] pb-3">
                        <div>
                            <h3 class="text-lg font-bold text-white tracking-tight">Your Cards & Applications</h3>
                            <p class="text-xs text-gray-400">View your active virtual cards and review application progress.</p>
                        </div>
                        <!-- Sub-Tabs Navigation -->
                        <div class="inline-flex p-1 rounded-xl bg-[#12151B] border border-[#292E38] text-xs">
                            <button type="button" onclick="switchCustomerCardTab('active')" id="tab-btn-active" class="px-3 py-1.5 rounded-lg font-semibold bg-[#246BFD] text-white transition-all">
                                Active Cards ({len(my_cards)})
                            </button>
                            <button type="button" onclick="switchCustomerCardTab('pending')" id="tab-btn-pending" class="px-3 py-1.5 rounded-lg font-semibold text-gray-400 hover:text-white transition-all">
                                Applications ({len(my_orders)})
                            </button>
                        </div>
                    </div>

                    <!-- 4A. Active Cards Tab Content -->
                    <div id="card-tab-active" class="space-y-4">
                        {my_cards_html}
                    </div>

                    <!-- 4B. Pending Applications Tab Content -->
                    <div id="card-tab-pending" class="hidden space-y-4">
                        <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] overflow-hidden">
                            <div class="overflow-x-auto">
                                <table class="w-full text-left text-xs">
                                    <thead>
                                        <tr class="border-b border-[#292E38] text-gray-400 uppercase font-semibold text-[11px]">
                                            <th class="pb-3">Order Ref</th>
                                            <th class="pb-3">Card Tier</th>
                                            <th class="pb-3">Issuance Fee</th>
                                            <th class="pb-3">Submitted Date</th>
                                            <th class="pb-3">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-[#292E38]/60">
                                        {app_rows_html if app_rows_html else '<tr><td colspan="5" class="py-12 text-center text-gray-500"><div class="w-12 h-12 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-center mx-auto mb-2 text-gray-400"><i class="fa-solid fa-inbox text-lg"></i></div><p class="font-medium text-gray-300">No card applications yet</p><p class="text-[11px] text-gray-500">Apply for a virtual card below to track application status.</p></td></tr>'}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 5. Available Cards Catalog -->
                <div id="available-catalog" class="space-y-6 pt-4">
                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
                        <div>
                            <h3 class="text-xl font-bold text-white tracking-tight">Card Marketplace Catalog</h3>
                            <p class="text-xs text-gray-400">Select an approved card tier designed for your spending requirements.</p>
                        </div>
                        <div class="text-xs text-gray-400">
                            Available USD: <strong class="text-white font-mono">${usd_bal:,.2f}</strong>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                        {catalog_items_html if catalog_items_html else '<div class="col-span-full p-12 text-center text-gray-500">No cards currently active in the marketplace.</div>'}
                    </div>
                </div>

                <!-- 6. How Virtual Cards Work (3-Step Guide) -->
                <div id="how-cards-work" class="p-8 rounded-3xl bg-[#171A21] border border-[#292E38] space-y-6">
                    <div class="text-center max-w-xl mx-auto space-y-2">
                        <h3 class="text-xl font-bold text-white">How Virtual Cards Work</h3>
                        <p class="text-xs text-gray-400">Three simple steps to obtain and manage enterprise-grade virtual cards.</p>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 pt-2">
                        <div class="p-5 rounded-2xl bg-[#12151B] border border-[#292E38] space-y-3">
                            <div class="w-10 h-10 rounded-xl bg-blue-500/10 text-blue-400 flex items-center justify-center font-bold font-mono text-sm">
                                01
                            </div>
                            <h4 class="text-sm font-bold text-white">Select Your Tier & Apply</h4>
                            <p class="text-xs text-gray-400 leading-relaxed">Choose the card tier matching your daily spend limit and required network features. Submit your application directly from your dashboard.</p>
                        </div>

                        <div class="p-5 rounded-2xl bg-[#12151B] border border-[#292E38] space-y-3">
                            <div class="w-10 h-10 rounded-xl bg-purple-500/10 text-purple-400 flex items-center justify-center font-bold font-mono text-sm">
                                02
                            </div>
                            <h4 class="text-sm font-bold text-white">Administrator Compliance Review</h4>
                            <p class="text-xs text-gray-400 leading-relaxed">Your application is reviewed by our operations team against account verification criteria. Once verified, credentials are generated and issued.</p>
                        </div>

                        <div class="p-5 rounded-2xl bg-[#12151B] border border-[#292E38] space-y-3">
                            <div class="w-10 h-10 rounded-xl bg-emerald-500/10 text-emerald-400 flex items-center justify-center font-bold font-mono text-sm">
                                03
                            </div>
                            <h4 class="text-sm font-bold text-white">Spend Online & Manage Controls</h4>
                            <p class="text-xs text-gray-400 leading-relaxed">Use your card details with merchants, point-of-sale systems, and subscriptions. Freeze or unfreeze your card instantly whenever needed.</p>
                        </div>
                    </div>
                </div>

            </div>

            <!-- Apply Modal -->
            <div id="apply-card-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md">
                <div class="w-full max-w-md p-6 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-2xl space-y-5">
                    <div class="flex items-center justify-between pb-3 border-b border-[#292E38]">
                        <h3 class="text-lg font-bold text-white">Apply for Virtual Card</h3>
                        <button type="button" onclick="closeApplyModal()" class="w-8 h-8 rounded-full bg-[#12151B] text-gray-400 hover:text-white flex items-center justify-center">
                            <i class="fa-solid fa-xmark"></i>
                        </button>
                    </div>

                    <div class="space-y-4 text-xs">
                        <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38] space-y-2">
                            <div class="flex justify-between"><span class="text-gray-400">Selected Card Tier:</span> <span id="apply-prod-name" class="font-bold text-white"></span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Card Type / Network:</span> <span id="apply-prod-type" class="text-white"></span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Daily Spend Limit:</span> <span id="apply-prod-limit" class="font-mono text-white"></span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Required Available Balance:</span> <span id="apply-prod-minbal" class="font-mono text-white"></span></div>
                            <div class="flex justify-between pt-2 border-t border-[#292E38]"><span class="text-gray-400">One-Time Issuance Fee:</span> <span id="apply-prod-fee" class="font-mono font-bold text-blue-400"></span></div>
                        </div>

                        <div id="apply-validation-box" class="p-3 rounded-xl text-[11px] space-y-1"></div>

                        <div class="grid grid-cols-2 gap-3 pt-2">
                            <button type="button" onclick="closeApplyModal()" class="py-2.5 rounded-xl bg-[#1F2430] hover:bg-[#252B3B] text-gray-300 font-semibold text-xs">
                                Cancel
                            </button>
                            <button type="button" id="confirm-apply-btn" onclick="submitCardApplication()" class="py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold text-xs shadow-lg shadow-blue-500/20">
                                Confirm & Submit
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Product Details Modal -->
            <div id="product-details-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md">
                <div class="w-full max-w-lg p-6 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-2xl space-y-5 max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between pb-3 border-b border-[#292E38]">
                        <h3 class="text-lg font-bold text-white" id="modal-spec-name">Card Specifications</h3>
                        <button type="button" onclick="closeProductDetailsModal()" class="w-8 h-8 rounded-full bg-[#12151B] text-gray-400 hover:text-white flex items-center justify-center">
                            <i class="fa-solid fa-xmark"></i>
                        </button>
                    </div>

                    <div class="space-y-4 text-xs">
                        <p class="text-gray-400" id="modal-spec-desc"></p>

                        <div class="grid grid-cols-2 gap-3">
                            <div class="p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                                <span class="text-[10px] text-gray-500 block uppercase">Issuance Fee</span>
                                <span id="modal-spec-fee" class="font-mono font-bold text-white"></span>
                            </div>
                            <div class="p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                                <span class="text-[10px] text-gray-500 block uppercase">Min Balance Required</span>
                                <span id="modal-spec-minbal" class="font-mono font-bold text-white"></span>
                            </div>
                            <div class="p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                                <span class="text-[10px] text-gray-500 block uppercase">Daily Spend Limit</span>
                                <span id="modal-spec-daily" class="font-mono font-bold text-white"></span>
                            </div>
                            <div class="p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                                <span class="text-[10px] text-gray-500 block uppercase">Monthly Limit</span>
                                <span id="modal-spec-monthly" class="font-mono font-bold text-white"></span>
                            </div>
                        </div>

                        <div>
                            <h5 class="font-bold text-white mb-2">Features & Benefits</h5>
                            <ul id="modal-spec-features" class="space-y-2 text-gray-300"></ul>
                        </div>

                        <div class="pt-3 border-t border-[#292E38] flex justify-end">
                            <button type="button" onclick="closeProductDetailsModal(); openApplyModal(activeSpecProd);" class="px-5 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold text-xs shadow-lg shadow-blue-500/20">
                                Apply for this Card
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Card Specs Modal for Issued Card -->
            <div id="card-specs-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md">
                <div class="w-full max-w-md p-6 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-2xl space-y-4">
                    <div class="flex items-center justify-between pb-3 border-b border-[#292E38]">
                        <h3 class="text-lg font-bold text-white">Card Credentials</h3>
                        <button type="button" onclick="closeCardSpecsModal()" class="w-8 h-8 rounded-full bg-[#12151B] text-gray-400 hover:text-white flex items-center justify-center">
                            <i class="fa-solid fa-xmark"></i>
                        </button>
                    </div>

                    <div class="space-y-3 text-xs">
                        <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38] space-y-2.5">
                            <div class="flex justify-between"><span class="text-gray-400">Card Name:</span> <span id="cs-name" class="font-bold text-white"></span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Card Number:</span> <span id="cs-num" class="font-mono font-bold text-blue-400"></span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Expires:</span> <span id="cs-exp" class="font-mono text-white"></span></div>
                            <div class="flex justify-between"><span class="text-gray-400">CVV:</span> <span class="font-mono text-emerald-400 font-bold">••• (Protected)</span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Cardholder:</span> <span id="cs-holder" class="font-bold text-white"></span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Status:</span> <span id="cs-status" class="uppercase font-bold"></span></div>
                        </div>

                        <p class="text-[11px] text-gray-400">For security compliance, card credentials remain protected under end-to-end tokenization.</p>

                        <div class="pt-2">
                            <button type="button" onclick="closeCardSpecsModal()" class="w-full py-2.5 rounded-xl bg-[#1F2430] hover:bg-[#252B3B] text-white text-xs font-semibold">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <script>
            let selectedApplyProd = null;
            let activeSpecProd = null;
            const userUsdBalance = {usd_bal};

            function switchCustomerCardTab(tab) {{
                const actSec = document.getElementById('card-tab-active');
                const pendSec = document.getElementById('card-tab-pending');
                const actBtn = document.getElementById('tab-btn-active');
                const pendBtn = document.getElementById('tab-btn-pending');

                if (tab === 'active') {{
                    actSec.classList.remove('hidden');
                    pendSec.classList.add('hidden');
                    actBtn.className = 'px-3 py-1.5 rounded-lg font-semibold bg-[#246BFD] text-white transition-all';
                    pendBtn.className = 'px-3 py-1.5 rounded-lg font-semibold text-gray-400 hover:text-white transition-all';
                }} else {{
                    pendSec.classList.remove('hidden');
                    actSec.classList.add('hidden');
                    pendBtn.className = 'px-3 py-1.5 rounded-lg font-semibold bg-[#246BFD] text-white transition-all';
                    actBtn.className = 'px-3 py-1.5 rounded-lg font-semibold text-gray-400 hover:text-white transition-all';
                }}
            }}

            function openApplyModal(p) {{
                selectedApplyProd = p;
                const fee = parseFloat(p.issuance_fee || p.fee || 0);
                const minBal = parseFloat(p.min_balance_required || 0);
                const limit = parseFloat(p.daily_limit || p.limit || 5000);

                document.getElementById('apply-prod-name').textContent = p.name;
                document.getElementById('apply-prod-type').textContent = (p.type || 'Virtual') + ' Card • ' + (p.network || 'Monveracu Pay');
                document.getElementById('apply-prod-limit').textContent = '$' + limit.toLocaleString('en-US', {{ minimumFractionDigits: 2 }});
                document.getElementById('apply-prod-minbal').textContent = minBal > 0 ? '$' + minBal.toLocaleString('en-US', {{ minimumFractionDigits: 2 }}) : 'None ($0.00)';
                document.getElementById('apply-prod-fee').textContent = fee > 0 ? '$' + fee.toFixed(2) : 'Free ($0.00)';

                const vBox = document.getElementById('apply-validation-box');
                const confirmBtn = document.getElementById('confirm-apply-btn');

                let errors = [];
                if (userUsdBalance < minBal) {{
                    errors.push('Minimum balance required is $' + minBal.toFixed(2) + ' (Available: $' + userUsdBalance.toFixed(2) + ').');
                }}
                if (userUsdBalance < fee) {{
                    errors.push('Insufficient available balance to cover issuance fee of $' + fee.toFixed(2) + ' (Available: $' + userUsdBalance.toFixed(2) + ').');
                }}

                if (errors.length > 0) {{
                    vBox.className = 'p-3 rounded-xl text-[11px] space-y-1 bg-red-500/10 border border-red-500/20 text-red-300';
                    vBox.innerHTML = '<p class="font-bold"><i class="fa-solid fa-circle-exclamation mr-1"></i> Eligibility Requirements Not Met:</p><p>' + errors.join('<br>') + '</p><p class="text-[10px] text-gray-400 pt-1">Please deposit crypto to fund your account before applying.</p>';
                    confirmBtn.disabled = true;
                    confirmBtn.className = 'py-2.5 rounded-xl bg-gray-700 text-gray-400 font-bold text-xs cursor-not-allowed';
                }} else {{
                    vBox.className = 'p-3 rounded-xl text-[11px] space-y-1 bg-emerald-500/10 border border-emerald-500/20 text-emerald-300';
                    vBox.innerHTML = '<p class="font-bold"><i class="fa-solid fa-circle-check mr-1"></i> Balance Verified:</p><p>You are eligible to apply. ' + (fee > 0 ? ('An issuance fee of $' + fee.toFixed(2) + ' will be debited on submission.') : 'No issuance fee will be charged.') + '</p>';
                    confirmBtn.disabled = false;
                    confirmBtn.className = 'py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold text-xs shadow-lg shadow-blue-500/20';
                }}

                document.getElementById('apply-card-modal').classList.remove('hidden');
            }}

            function closeApplyModal() {{
                document.getElementById('apply-card-modal').classList.add('hidden');
            }}

            async function submitCardApplication() {{
                if (!selectedApplyProd) return;
                const btn = document.getElementById('confirm-apply-btn');
                btn.disabled = true;
                btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-1"></i> Submitting...';

                try {{
                    const res = await (await fetch('/cards/apply', {{
                        method: 'POST',
                        headers: {{ 'Content-Type': 'application/json' }},
                        body: JSON.stringify({{ product_id: selectedApplyProd.id }})
                    }})).json();

                    if (res.success) {{
                        alert(res.message);
                        window.location.reload();
                    }} else {{
                        alert(res.error || 'Failed to submit card application.');
                        btn.disabled = false;
                        btn.textContent = 'Confirm & Submit';
                    }}
                }} catch (e) {{
                    alert('Network error. Please try again.');
                    btn.disabled = false;
                    btn.textContent = 'Confirm & Submit';
                }}
            }}

            function openProductDetailsModal(p) {{
                activeSpecProd = p;
                document.getElementById('modal-spec-name').textContent = p.name;
                document.getElementById('modal-spec-desc').textContent = p.description || 'Enterprise-grade payment card connected to your Monveracu USD balance.';
                document.getElementById('modal-spec-fee').textContent = (parseFloat(p.issuance_fee || p.fee || 0) > 0 ? '$' + parseFloat(p.issuance_fee || p.fee).toFixed(2) : 'Free ($0.00)');
                document.getElementById('modal-spec-minbal').textContent = (parseFloat(p.min_balance_required || 0) > 0 ? '$' + parseFloat(p.min_balance_required).toFixed(2) : 'None');
                document.getElementById('modal-spec-daily').textContent = '$' + parseFloat(p.daily_limit || p.limit || 5000).toLocaleString('en-US', {{ minimumFractionDigits: 2 }});
                document.getElementById('modal-spec-monthly').textContent = '$' + parseFloat(p.monthly_limit || 25000).toLocaleString('en-US', {{ minimumFractionDigits: 2 }});

                const feats = p.features || [];
                document.getElementById('modal-spec-features').innerHTML = feats.map(f => `<li class="flex items-center gap-2"><i class="fa-solid fa-check text-emerald-400 text-[10px]"></i><span>${{f}}</span></li>`).join('');

                document.getElementById('product-details-modal').classList.remove('hidden');
            }}

            function closeProductDetailsModal() {{
                document.getElementById('product-details-modal').classList.add('hidden');
            }}

            function openCardSpecsModal(c) {{
                document.getElementById('cs-name').textContent = c.name || 'Monveracu Card';
                document.getElementById('cs-num').textContent = c.masked_number || '•••• •••• •••• 0000';
                document.getElementById('cs-exp').textContent = c.exp || '10/31';
                document.getElementById('cs-holder').textContent = c.holder || 'Elochukwu Elom';

                const isAct = (c.status === 'active');
                const stEl = document.getElementById('cs-status');
                stEl.textContent = isAct ? 'Active' : 'Frozen';
                stEl.className = isAct ? 'font-mono text-emerald-400 font-bold' : 'font-mono text-amber-400 font-bold';

                document.getElementById('card-specs-modal').classList.remove('hidden');
            }}

            function closeCardSpecsModal() {{
                document.getElementById('card-specs-modal').classList.add('hidden');
            }}

            async function toggleCardFreeze(id, btn) {{
                btn.disabled = true;
                try {{
                    const res = await (await fetch('/cards/toggle-freeze', {{
                        method: 'POST',
                        headers: {{ 'Content-Type': 'application/json' }},
                        body: JSON.stringify({{ card_id: id }})
                    }})).json();
                    if (res.success) {{
                        alert(res.message);
                        window.location.reload();
                    }} else {{
                        alert(res.error || 'Failed to toggle freeze.');
                        btn.disabled = false;
                    }}
                }} catch (e) {{
                    alert('Network error.');
                    btn.disabled = false;
                }}
            }}
            </script>'''
            html = build_app_layout(body, "Cards & Marketplace | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 10.5. Customer Investments Hub
        if path.startswith("/investments"):
            # Update matured investments
            now_str = time.strftime("%Y-%m-%d %H:%M:%S")
            for inv in STATE.get("investments", []):
                if inv.get("status") == "active" and inv.get("maturity_at") and now_str >= inv.get("maturity_at"):
                    inv["status"] = "matured"

            # Check single investment view
            parts = path.strip("/").split("/")
            if len(parts) == 2 and parts[1].isdigit():
                inv_id = int(parts[1])
                inv = next((i for i in STATE.get("investments", []) if i["id"] == inv_id), None)
                if not inv:
                    self.send_response(302)
                    self.send_header("Location", "/investments")
                    self.end_headers()
                    return

                st = inv.get("status", "active")
                badge_class = "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" if st == "matured" else ("bg-purple-500/10 text-purple-400 border-purple-500/20" if st == "redeemed" else "bg-blue-500/10 text-blue-400 border-blue-500/20")

                status_banner = ""
                if st == "active":
                    status_banner = f'''
                    <div class="p-5 rounded-2xl bg-gradient-to-r from-blue-900/20 to-blue-600/10 border border-blue-500/30 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-xl bg-blue-500/20 text-blue-400 flex items-center justify-center text-lg shrink-0">
                                <i class="fa-solid fa-hourglass-half"></i>
                            </div>
                            <div>
                                <div class="text-sm font-bold text-white">Investment Growth in Progress</div>
                                <div class="text-xs text-gray-400">Funds locked until maturity date: <span class="font-mono text-gray-300">{inv.get('maturity_at')}</span></div>
                            </div>
                        </div>
                        <div class="text-right">
                            <div class="text-[10px] text-gray-400 uppercase tracking-wider">Maturity Status</div>
                            <div class="text-base font-mono font-bold text-white tracking-wider">Active Cycle</div>
                        </div>
                    </div>
                    '''
                elif st == "matured":
                    status_banner = f'''
                    <div class="p-5 rounded-2xl bg-gradient-to-r from-emerald-900/30 to-emerald-600/10 border border-emerald-500/40 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-xl bg-emerald-500/20 text-emerald-400 flex items-center justify-center text-lg shrink-0">
                                <i class="fa-solid fa-circle-check"></i>
                            </div>
                            <div>
                                <div class="text-sm font-bold text-white">Investment Cycle Complete!</div>
                                <div class="text-xs text-gray-300">Principal and guaranteed contractual returns are ready for instant redemption.</div>
                            </div>
                        </div>
                        <div>
                            <form action="/investments/{inv['id']}/redeem" method="POST">
                                <button type="submit" class="px-5 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs shadow-lg shadow-emerald-500/30 transition-all">
                                    Redeem ${float(inv.get('expected_payout', 0)):,.2f} USD
                                </button>
                            </form>
                        </div>
                    </div>
                    '''
                else:
                    status_banner = f'''
                    <div class="p-5 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center gap-3">
                        <div class="w-10 h-10 rounded-xl bg-purple-500/20 text-purple-400 flex items-center justify-center text-lg shrink-0">
                            <i class="fa-solid fa-check-double"></i>
                        </div>
                        <div>
                            <div class="text-sm font-bold text-white">Investment Redeemed</div>
                            <div class="text-xs text-gray-400">Total proceeds of ${float(inv.get('expected_payout', 0)):,.2f} USD were credited to your account balance.</div>
                        </div>
                    </div>
                    '''

                body = f'''
                <div class="max-w-4xl mx-auto space-y-6">
                    <div>
                        <a href="/investments" class="inline-flex items-center gap-2 text-xs font-semibold text-[#246BFD] hover:underline">
                            <i class="fa-solid fa-arrow-left"></i>
                            <span>Back to All Investments</span>
                        </a>
                    </div>

                    <div class="p-6 sm:p-8 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-2xl space-y-8">
                        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pb-6 border-b border-[#292E38]">
                            <div class="flex items-center gap-4">
                                <div class="w-14 h-14 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-center p-2.5">
                                    <img src="{inv.get('stock_logo_url') or '/assets/images/stocks/' + inv['stock_ticker'].lower() + '.svg'}" 
                                         alt="{inv['stock_ticker']}" class="w-full h-full object-contain" onerror="this.src='/assets/images/stocks/default.svg';">
                                </div>
                                <div>
                                    <div class="flex items-center gap-2">
                                        <h2 class="text-xl font-bold text-white">{inv.get('stock_name')}</h2>
                                        <span class="px-2 py-0.5 rounded text-[11px] font-mono font-bold bg-blue-500/10 text-blue-400 border border-blue-500/20">{inv.get('stock_ticker')}</span>
                                    </div>
                                    <p class="text-xs text-gray-400 mt-0.5">Position Reference: <span class="font-mono text-gray-300">{inv.get('reference')}</span></p>
                                </div>
                            </div>
                            <div>
                                <span class="px-3 py-1 rounded-full text-xs font-bold uppercase border {badge_class}">
                                    {st.upper()}
                                </span>
                            </div>
                        </div>

                        <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                            <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38]">
                                <div class="text-[11px] text-gray-400 uppercase tracking-wider">Allocated Capital</div>
                                <div class="text-lg font-bold font-mono text-white mt-1">${float(inv.get('amount', 0)):,.2f}</div>
                            </div>
                            <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38]">
                                <div class="text-[11px] text-gray-400 uppercase tracking-wider">Contractual Yield</div>
                                <div class="text-lg font-bold font-mono text-emerald-400 mt-1">+{float(inv.get('return_percentage', 0)):g}%</div>
                            </div>
                            <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38]">
                                <div class="text-[11px] text-gray-400 uppercase tracking-wider">Expected Payout</div>
                                <div class="text-lg font-bold font-mono text-emerald-400 mt-1">${float(inv.get('expected_payout', 0)):,.2f}</div>
                            </div>
                            <div class="p-4 rounded-2xl bg-[#12151B] border border-[#292E38]">
                                <div class="text-[11px] text-gray-400 uppercase tracking-wider">Lock Duration</div>
                                <div class="text-lg font-bold font-mono text-gray-300 mt-1">{inv.get('duration_hours')} Hours</div>
                            </div>
                        </div>

                        {status_banner}

                        <div class="space-y-3 pt-4 border-t border-[#292E38] text-xs">
                            <h4 class="text-xs font-bold uppercase tracking-wider text-gray-400">Immutable Contract Terms</h4>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div class="flex items-center justify-between p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                                    <span class="text-gray-400">Plan Tier:</span>
                                    <span class="font-bold text-white">{inv.get('plan_name')}</span>
                                </div>
                                <div class="flex items-center justify-between p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                                    <span class="text-gray-400">Started At:</span>
                                    <span class="font-mono text-gray-300">{inv.get('started_at')}</span>
                                </div>
                                <div class="flex items-center justify-between p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                                    <span class="text-gray-400">Maturity At:</span>
                                    <span class="font-mono text-gray-300">{inv.get('maturity_at')}</span>
                                </div>
                                <div class="flex items-center justify-between p-3 rounded-xl bg-[#12151B] border border-[#292E38]">
                                    <span class="text-gray-400">Settlement Status:</span>
                                    <span class="font-mono text-gray-300">{st.upper()}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                '''
                html = build_app_layout(body, f"Investment {inv.get('reference')} | Monveracu", "/investments")
                self.wfile.write(html.encode('utf-8'))
                return

            # Main Hub View
            stocks = [s for s in STATE.get("stocks", []) if s.get("status") == "active"]
            plans = [p for p in STATE.get("investment_plans", []) if p.get("status") == "active"]
            investments = STATE.get("investments", [])

            total_invested = sum(float(i.get("amount", 0)) for i in investments if i.get("status") == "active")
            total_matured = sum(float(i.get("expected_payout", 0)) for i in investments if i.get("status") == "matured")
            total_redeemed = sum(float(i.get("expected_payout", 0)) for i in investments if i.get("status") == "redeemed")
            usd_bal = STATE["accounts"][0]["balance"]

            # Stock catalog grid HTML
            catalog_cards_html = ""
            for stk in stocks:
                plan_id = stk.get("default_plan_id", 3)
                plan = next((p for p in plans if p["id"] == plan_id), None) or (plans[0] if plans else None)
                plan_name = plan["name"] if plan else "Pro Plan"
                min_amt = plan["min_amount"] if plan else 500.0
                max_amt = plan.get("max_amount")
                is_unlimited = plan.get("is_unlimited", False) or (max_amt is None)
                duration = plan["duration_hours"] if plan else 96
                return_pct = plan["return_percentage"] if plan else 100.0
                limits_str = f"${min_amt:,.0f} - Unlimited" if (is_unlimited or max_amt is None) else f"${min_amt:,.0f} - ${max_amt:,.0f}"

                catalog_cards_html += f'''
                <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] flex flex-col justify-between hover:border-gray-500 transition-all shadow-xl group">
                    <div>
                        <div class="flex items-start justify-between mb-4">
                            <div class="flex items-center gap-3">
                                <div class="w-12 h-12 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-center p-2 group-hover:border-[#246BFD]/50 transition-colors">
                                    <img src="{stk.get('logo_url') or '/assets/images/stocks/' + stk['ticker'].lower() + '.svg'}" 
                                         alt="{stk['ticker']}" class="w-full h-full object-contain" onerror="this.src='/assets/images/stocks/default.svg';">
                                </div>
                                <div>
                                    <div class="flex items-center gap-1.5">
                                        <h4 class="text-base font-bold text-white">{stk['ticker']}</h4>
                                        <span class="text-[10px] font-mono px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400 font-semibold border border-blue-500/20">STOCK</span>
                                    </div>
                                    <p class="text-xs text-gray-400">{stk['name']}</p>
                                </div>
                            </div>
                            <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Active</span>
                        </div>
                        <p class="text-xs text-gray-400 line-clamp-2 mb-4 leading-relaxed">{stk.get('short_description', '')}</p>
                        <div class="rounded-2xl bg-[#12151B] border border-[#292E38] p-3.5 space-y-2.5 mb-5 text-xs">
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 text-[11px]">Investment Plan</span>
                                <span class="font-bold text-white">{plan_name}</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 text-[11px]">Allocation Range</span>
                                <span class="font-mono font-semibold text-white">{limits_str}</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 text-[11px]">Lock Duration</span>
                                <span class="font-mono text-gray-300">{duration} hours</span>
                            </div>
                            <div class="pt-2 border-t border-[#292E38] flex items-center justify-between">
                                <span class="text-gray-400 text-[11px] font-semibold">Contractual Return</span>
                                <span class="font-mono font-bold text-emerald-400 text-sm">+{return_pct:g}%</span>
                            </div>
                        </div>
                    </div>
                    <button type="button" onclick="openInvestModal({json.dumps(stk)})" class="w-full py-3 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold text-xs shadow-lg shadow-blue-500/20 transition-all flex items-center justify-center gap-2 active:scale-95">
                        <i class="fa-solid fa-bolt text-xs"></i>
                        <span>Invest in {stk['ticker']}</span>
                    </button>
                </div>
                '''

            # Portfolio table rows
            portfolio_rows_html = ""
            for inv in investments:
                st = inv.get("status", "active")
                is_matured = (st == "matured")
                is_redeemed = (st == "redeemed")
                badge_class = "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20" if is_matured else ("bg-purple-500/10 text-purple-400 border border-purple-500/20" if is_redeemed else "bg-blue-500/10 text-blue-400 border border-blue-500/20")

                action_html = f'''<form action="/investments/{inv['id']}/redeem" method="POST" class="inline"><button type="submit" class="px-3.5 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs shadow-md shadow-emerald-500/20 transition-all">Redeem Funds</button></form>''' if is_matured else (f'<span class="text-xs text-gray-500 font-mono">Credited</span>' if is_redeemed else f'''<a href="/investments/{inv['id']}" class="text-xs text-[#246BFD] hover:underline font-semibold">View Details</a>''')

                portfolio_rows_html += f'''
                <tr class="hover:bg-[#1C2028] transition-colors">
                    <td class="py-4 px-5 font-mono font-bold text-blue-400">
                        <a href="/investments/{inv['id']}" class="hover:underline">{inv.get('reference')}</a>
                    </td>
                    <td class="py-4 px-5">
                        <div class="font-bold text-white">{inv.get('stock_ticker')} · {inv.get('stock_name')}</div>
                        <div class="text-[11px] text-gray-400">{inv.get('plan_name')} ({inv.get('duration_hours')}h)</div>
                    </td>
                    <td class="py-4 px-5 font-mono font-semibold text-white">${float(inv.get('amount', 0)):,.2f}</td>
                    <td class="py-4 px-5 font-mono font-bold text-emerald-400">+{float(inv.get('return_percentage', 0)):g}%</td>
                    <td class="py-4 px-5 font-mono font-bold text-white">${float(inv.get('expected_payout', 0)):,.2f}</td>
                    <td class="py-4 px-5 font-mono text-gray-300">{inv.get('maturity_at')}</td>
                    <td class="py-4 px-5">
                        <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase border {badge_class}">
                            {st.upper()}
                        </span>
                    </td>
                    <td class="py-4 px-5 text-right">{action_html}</td>
                </tr>
                '''

            plans_opts = "".join([f'<option value="{p["id"]}" data-min="{p["min_amount"]}" data-max="{p["max_amount"] if p.get("max_amount") is not None else ""}" data-unlimited="{"1" if p.get("is_unlimited") or p.get("max_amount") is None else "0"}" data-duration="{p["duration_hours"]}" data-return="{p["return_percentage"]}">{p["name"]} ({p["duration_hours"]}h, +{p["return_percentage"]:g}% Return)</option>' for p in plans])
            acc_opts = "".join([f'<option value="{a["id"]}">{a["currency"]} Account ({a["account_number"]}) · Available: ${a["balance"]:,.2f}</option>' for a in STATE["accounts"]])

            body = f'''
            <div class="max-w-6xl mx-auto space-y-8">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <div class="flex items-center gap-2">
                            <h2 class="text-2xl font-bold text-white tracking-tight">Investments & Opportunities</h2>
                            <span class="px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-blue-500/10 text-blue-400 border border-blue-500/20">High Yield</span>
                        </div>
                        <p class="text-sm text-gray-400 mt-1">Explore institutional-grade stock opportunities with guaranteed contractual returns.</p>
                    </div>
                    <div class="flex items-center gap-3">
                        <div class="p-3 rounded-2xl bg-[#171A21] border border-[#292E38] text-xs">
                            <span class="text-gray-400">Available USD:</span>
                            <span class="font-mono font-bold text-white ml-1">${usd_bal:,.2f}</span>
                        </div>
                        <button type="button" onclick="openInvestModal({json.dumps(stocks[0]) if stocks else '{}'})" class="px-4 py-2.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold text-xs shadow-lg shadow-blue-500/20 transition-all flex items-center gap-2">
                            <i class="fa-solid fa-plus text-xs"></i>
                            <span>New Investment</span>
                        </button>
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div class="p-5 rounded-3xl bg-[#171A21] border border-[#292E38] flex flex-col justify-between">
                        <div class="flex items-center justify-between">
                            <span class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Active Capital</span>
                            <div class="w-8 h-8 rounded-xl bg-blue-500/10 text-blue-400 flex items-center justify-center text-xs"><i class="fa-solid fa-lock"></i></div>
                        </div>
                        <div class="mt-4">
                            <div class="text-2xl font-bold font-mono text-white">${total_invested:,.2f}</div>
                            <div class="text-xs text-gray-500 mt-1">Currently locked in growth cycles</div>
                        </div>
                    </div>

                    <div class="p-5 rounded-3xl bg-[#171A21] border border-[#292E38] flex flex-col justify-between">
                        <div class="flex items-center justify-between">
                            <span class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Ready to Redeem</span>
                            <div class="w-8 h-8 rounded-xl bg-emerald-500/10 text-emerald-400 flex items-center justify-center text-xs"><i class="fa-solid fa-circle-check"></i></div>
                        </div>
                        <div class="mt-4">
                            <div class="text-2xl font-bold font-mono text-emerald-400">${total_matured:,.2f}</div>
                            <div class="text-xs text-gray-500 mt-1">Matured principal + contractual yield</div>
                        </div>
                    </div>

                    <div class="p-5 rounded-3xl bg-[#171A21] border border-[#292E38] flex flex-col justify-between">
                        <div class="flex items-center justify-between">
                            <span class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Total Redeemed</span>
                            <div class="w-8 h-8 rounded-xl bg-purple-500/10 text-purple-400 flex items-center justify-center text-xs"><i class="fa-solid fa-wallet"></i></div>
                        </div>
                        <div class="mt-4">
                            <div class="text-2xl font-bold font-mono text-purple-400">${total_redeemed:,.2f}</div>
                            <div class="text-xs text-gray-500 mt-1">Total credited back to your balance</div>
                        </div>
                    </div>
                </div>

                <div class="flex border-b border-[#292E38] gap-6 text-sm font-semibold">
                    <button type="button" id="tab-btn-catalog" onclick="switchTab('catalog')" class="pb-3 border-b-2 border-[#246BFD] text-white flex items-center gap-2">
                        <i class="fa-solid fa-arrow-trend-up text-[#246BFD]"></i>
                        <span>Explore Opportunities</span>
                        <span class="px-2 py-0.5 rounded-full text-[10px] bg-[#1F2430] text-gray-300 font-mono">{len(stocks)}</span>
                    </button>
                    <button type="button" id="tab-btn-portfolio" onclick="switchTab('portfolio')" class="pb-3 border-b-2 border-transparent text-gray-400 hover:text-white flex items-center gap-2">
                        <i class="fa-solid fa-briefcase"></i>
                        <span>My Portfolio</span>
                        <span class="px-2 py-0.5 rounded-full text-[10px] bg-[#1F2430] text-gray-300 font-mono">{len(investments)}</span>
                    </button>
                </div>

                <div id="tab-content-catalog" class="space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        {catalog_cards_html if catalog_cards_html else '<div class="col-span-full p-12 text-center text-gray-400">No opportunities available.</div>'}
                    </div>
                </div>

                <div id="tab-content-portfolio" class="hidden space-y-6">
                    <div class="rounded-3xl bg-[#171A21] border border-[#292E38] overflow-hidden shadow-xl">
                        <div class="p-5 border-b border-[#292E38]">
                            <h3 class="text-sm font-bold uppercase tracking-wider text-white">Investment Positions</h3>
                            <p class="text-xs text-gray-400 mt-0.5">Track growth, maturity countdowns, and execute contractual redemptions.</p>
                        </div>
                        <div class="overflow-x-auto">
                            <table class="w-full text-left text-xs">
                                <thead class="bg-[#12151B] text-gray-400 uppercase font-semibold text-[10px] tracking-wider border-b border-[#292E38]">
                                    <tr>
                                        <th class="py-3.5 px-5">Reference</th>
                                        <th class="py-3.5 px-5">Asset / Plan</th>
                                        <th class="py-3.5 px-5">Invested Amount</th>
                                        <th class="py-3.5 px-5">Contractual Return</th>
                                        <th class="py-3.5 px-5">Expected Payout</th>
                                        <th class="py-3.5 px-5">Maturity Date</th>
                                        <th class="py-3.5 px-5">Status</th>
                                        <th class="py-3.5 px-5 text-right">Action</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-[#292E38]">
                                    {portfolio_rows_html if portfolio_rows_html else '<tr><td colspan="8" class="py-12 text-center text-gray-500">No investment records found.</td></tr>'}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Investment Modal -->
                <div id="invest-modal" class="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm hidden flex items-center justify-center p-4">
                    <div class="w-full max-w-lg rounded-3xl bg-[#171A21] border border-[#292E38] shadow-2xl overflow-hidden p-6 sm:p-8 space-y-6">
                        <div class="flex items-center justify-between pb-4 border-b border-[#292E38]">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-2xl bg-[#12151B] border border-[#292E38] flex items-center justify-center p-2">
                                    <img id="modal-stock-logo" src="/assets/images/stocks/default.svg" alt="Stock" class="w-full h-full object-contain">
                                </div>
                                <div>
                                    <h3 id="modal-stock-title" class="text-base font-bold text-white">Create Stock Investment</h3>
                                    <p id="modal-stock-ticker" class="text-xs text-gray-400">Select terms & allocate capital</p>
                                </div>
                            </div>
                            <button type="button" onclick="closeInvestModal()" class="w-8 h-8 rounded-full bg-[#12151B] hover:bg-[#1C2028] text-gray-400 hover:text-white flex items-center justify-center transition-colors">
                                <i class="fa-solid fa-xmark"></i>
                            </button>
                        </div>

                        <form id="invest-form" action="/investments" method="POST" class="space-y-4">
                            <input type="hidden" name="stock_id" id="modal-stock-id" value="">
                            <input type="hidden" name="plan_id" id="modal-plan-id" value="">

                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Investment Tier / Plan</label>
                                <select id="modal-plan-select" onchange="onPlanChange()" class="w-full px-4 py-3 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs font-semibold focus:outline-none focus:border-[#246BFD]">
                                    {plans_opts}
                                </select>
                            </div>

                            <div>
                                <div class="flex items-center justify-between mb-1.5">
                                    <label class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Investment Amount ($ USD)</label>
                                    <span id="modal-tier-limits" class="text-[11px] font-mono text-gray-400">$500 - $4,999</span>
                                </div>
                                <div class="relative">
                                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 font-mono font-bold">$</span>
                                    <input type="number" id="modal-amount-input" name="amount" step="any" placeholder="500.00" oninput="recalculatePayout()" required class="w-full pl-8 pr-4 py-3 rounded-xl bg-[#12151B] border border-[#292E38] text-white font-mono font-bold text-sm focus:outline-none focus:border-[#246BFD]">
                                </div>
                            </div>

                            <div>
                                <label class="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Funding Source Account</label>
                                <select name="account_id" id="modal-account-select" class="w-full px-4 py-3 rounded-xl bg-[#12151B] border border-[#292E38] text-white text-xs font-semibold focus:outline-none focus:border-[#246BFD]">
                                    {acc_opts}
                                </select>
                            </div>

                            <div class="rounded-2xl bg-[#12151B] border border-[#292E38] p-4 space-y-2 text-xs">
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-400">Principal Allocation:</span>
                                    <span id="calc-principal" class="font-mono font-bold text-white">$0.00</span>
                                </div>
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-400">Contractual Yield:</span>
                                    <span id="calc-return-rate" class="font-mono font-bold text-emerald-400">+0%</span>
                                </div>
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-400">Estimated Net Profit:</span>
                                    <span id="calc-profit" class="font-mono font-bold text-emerald-400">+$0.00</span>
                                </div>
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-400">Maturity Duration:</span>
                                    <span id="calc-duration" class="font-mono text-gray-300">0 hours</span>
                                </div>
                                <div class="pt-2 border-t border-[#292E38] flex items-center justify-between">
                                    <span class="text-white font-bold">Total Maturity Payout:</span>
                                    <span id="calc-payout" class="font-mono font-bold text-base text-emerald-400">$0.00</span>
                                </div>
                            </div>

                            <div class="pt-2">
                                <button type="submit" id="modal-submit-btn" class="w-full py-3.5 rounded-xl bg-[#246BFD] hover:bg-[#1858D8] text-white font-bold text-sm shadow-xl shadow-blue-500/25 transition-all flex items-center justify-center gap-2">
                                    <i class="fa-solid fa-lock text-xs"></i>
                                    <span>Confirm & Lock Investment</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <script>
                function switchTab(tab) {{
                    const catContent = document.getElementById('tab-content-catalog');
                    const portContent = document.getElementById('tab-content-portfolio');
                    const catBtn = document.getElementById('tab-btn-catalog');
                    const portBtn = document.getElementById('tab-btn-portfolio');

                    if (tab === 'catalog') {{
                        catContent.classList.remove('hidden');
                        portContent.classList.add('hidden');
                        catBtn.className = "pb-3 border-b-2 border-[#246BFD] text-white flex items-center gap-2 font-semibold";
                        portBtn.className = "pb-3 border-b-2 border-transparent text-gray-400 hover:text-white flex items-center gap-2 font-semibold";
                    }} else {{
                        catContent.classList.add('hidden');
                        portContent.classList.remove('hidden');
                        portBtn.className = "pb-3 border-b-2 border-[#246BFD] text-white flex items-center gap-2 font-semibold";
                        catBtn.className = "pb-3 border-b-2 border-transparent text-gray-400 hover:text-white flex items-center gap-2 font-semibold";
                    }}
                }}

                function openInvestModal(stock) {{
                    if (!stock) return;
                    document.getElementById('modal-stock-id').value = stock.id;
                    document.getElementById('modal-stock-title').textContent = stock.ticker + ' Investment';
                    document.getElementById('modal-stock-ticker').textContent = stock.name;
                    document.getElementById('modal-stock-logo').src = stock.logo_url || ('/assets/images/stocks/' + stock.ticker.toLowerCase() + '.svg');

                    const planSelect = document.getElementById('modal-plan-select');
                    if (stock.default_plan_id) {{
                        planSelect.value = stock.default_plan_id;
                    }}
                    onPlanChange();
                    document.getElementById('invest-modal').classList.remove('hidden');
                }}

                function closeInvestModal() {{
                    document.getElementById('invest-modal').classList.add('hidden');
                }}

                function onPlanChange() {{
                    const planSelect = document.getElementById('modal-plan-select');
                    const opt = planSelect.options[planSelect.selectedIndex];
                    if (!opt) return;

                    document.getElementById('modal-plan-id').value = opt.value;
                    const min = parseFloat(opt.getAttribute('data-min')) || 0;
                    const max = parseFloat(opt.getAttribute('data-max'));
                    const isUnlimited = opt.getAttribute('data-unlimited') === '1' || isNaN(max);

                    document.getElementById('modal-tier-limits').textContent = '$' + min.toLocaleString() + ' - ' + (isUnlimited ? 'Unlimited' : '$' + max.toLocaleString());

                    const amountInput = document.getElementById('modal-amount-input');
                    if (!amountInput.value || parseFloat(amountInput.value) < min) {{
                        amountInput.value = min;
                    }}
                    recalculatePayout();
                }}

                function recalculatePayout() {{
                    const planSelect = document.getElementById('modal-plan-select');
                    const opt = planSelect.options[planSelect.selectedIndex];
                    if (!opt) return;

                    const returnPct = parseFloat(opt.getAttribute('data-return')) || 0;
                    const durationHours = parseInt(opt.getAttribute('data-duration')) || 0;
                    const amount = parseFloat(document.getElementById('modal-amount-input').value) || 0;

                    const profit = amount * (returnPct / 100);
                    const totalPayout = amount + profit;

                    document.getElementById('calc-principal').textContent = '$' + amount.toLocaleString(undefined, {{minimumFractionDigits: 2, maximumFractionDigits: 2}});
                    document.getElementById('calc-return-rate').textContent = '+' + returnPct + '%';
                    document.getElementById('calc-profit').textContent = '+$' + profit.toLocaleString(undefined, {{minimumFractionDigits: 2, maximumFractionDigits: 2}});
                    document.getElementById('calc-duration').textContent = durationHours + ' hours';
                    document.getElementById('calc-payout').textContent = '$' + totalPayout.toLocaleString(undefined, {{minimumFractionDigits: 2, maximumFractionDigits: 2}});
                }}

                document.getElementById('invest-modal')?.addEventListener('click', (e) => {{
                    if (e.target.id === 'invest-modal') closeInvestModal();
                }});
                </script>
            </div>
            '''
            html = build_app_layout(body, "Investments & Opportunities | Monveracu", "/investments")
            self.wfile.write(html.encode('utf-8'))
            return

        # 11. Currency Exchange (Convert)
        if path == "/exchange":
            view_path = os.path.join(VIEWS_DIR, "exchange", "index.php")
            with open(view_path, 'r', encoding='utf-8') as f:
                body = f.read()
            body = re.sub(r"<\?php.*?\?>", "", body, flags=re.DOTALL)
            body = re.sub(r"<\?=.*?\?>", "", body, flags=re.DOTALL)
            html = build_app_layout(body, "Currency Exchange | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 12. Activity & Transactions
        if path == "/activity/export":
            csv_lines = ["Reference,Date,Type,Counterparty,Amount,Currency,Status"]
            for t in STATE["transfers"]:
                is_sender = (t["direction"] == "sent")
                cparty = t['recipient'] if is_sender else t['sender']
                ttype = "Debit (Sent)" if is_sender else "Credit (Received)"
                csv_lines.append(f"{t['ref']},{t['date']},{ttype},{cparty},{t['amount']},{t['currency']},{t['status']}")
            csv_data = "\n".join(csv_lines)

            self.send_response(200)
            self.send_header("Content-Type", "text/csv")
            self.send_header("Content-Disposition", "attachment; filename=bnkfx_transactions.csv")
            self.end_headers()
            self.wfile.write(csv_data.encode('utf-8'))
            return

        if path == "/activity":
            all_activity = []
            for t in STATE.get("transfers", []):
                is_sender = (t["direction"] == "sent")
                all_activity.append({
                    "date": t.get("date", "Today"),
                    "title": f"Money Sent to {t['recipient']}" if is_sender else f"Money Received from {t['sender']}",
                    "ref": t["ref"],
                    "amount": t["amount"],
                    "sign": "-" if is_sender else "+",
                    "color": "text-red-400 bg-red-500/10" if is_sender else "text-emerald-400 bg-emerald-500/10",
                    "amt_color": "text-red-400" if is_sender else "text-emerald-400",
                    "icon": "fa-arrow-up" if is_sender else "fa-arrow-down",
                    "status": t["status"],
                    "link": f"/transfers/receipt/{t['ref']}"
                })
            for d in STATE.get("deposits", []):
                st = str(d.get("status", "pending")).lower()
                is_credited = (st == "credited")
                is_pending = st in ["pending_review", "confirming", "pending_confirmation", "awaiting_deposit", "awaiting_payment"]
                st_label = "Credited" if is_credited else ("Pending Review" if st == "pending_review" else ("Awaiting Deposit" if "awaiting" in st else st.title()))
                dep_asset = d.get('asset') or d.get('currency') or 'USD'
                dep_ref = d.get('reference') or f"DEP-{d.get('id', '000')}"
                dep_amt = d.get('amount', 0.0)
                all_activity.append({
                    "date": d.get("created_at", "Just now"),
                    "title": f"Crypto Deposit ({dep_asset})",
                    "ref": dep_ref,
                    "amount": dep_amt,
                    "sign": "+",
                    "color": "text-emerald-400 bg-emerald-500/10" if is_credited else ("text-amber-400 bg-amber-500/10" if is_pending else "text-red-400 bg-red-500/10"),
                    "amt_color": "text-emerald-400" if is_credited else ("text-amber-400" if is_pending else "text-gray-400"),
                    "icon": "fa-arrow-down-long",
                    "status": st_label,
                    "link": "/deposits"
                })

            tx_rows = ""
            for a in all_activity:
                tx_rows += f'''
                <a href="{a['link']}" class="flex items-center justify-between p-4 sm:p-5 hover:bg-[#1F2430]/70 transition-colors">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-2xl {a['color']} flex items-center justify-center text-sm shrink-0">
                            <i class="fa-solid {a['icon']}"></i>
                        </div>
                        <div>
                            <h4 class="text-sm font-bold text-white">{a['title']}</h4>
                            <div class="flex items-center gap-2 text-xs text-gray-500 mt-0.5">
                                <span class="font-mono">{a['ref']}</span>
                                <span>•</span>
                                <span>{a['date']}</span>
                            </div>
                        </div>
                    </div>
                    <div class="text-right">
                        <div class="text-sm sm:text-base font-mono font-bold {a['amt_color']}">{a['sign']}${a['amount']:.2f} USD</div>
                        <span class="inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 mt-1">{a['status']}</span>
                    </div>
                </a>'''

            if tx_rows:
                activity_content = f'''
                <div class="rounded-3xl bg-[#171A21] border border-[#292E38] divide-y divide-[#292E38] overflow-hidden shadow-xl">
                    {tx_rows}
                </div>'''
            else:
                activity_content = '''
                <div class="rounded-3xl bg-[#171A21] border border-[#292E38] p-12 text-center text-gray-400 space-y-3 shadow-xl">
                    <div class="w-12 h-12 rounded-2xl bg-[#246BFD]/10 text-[#246BFD] flex items-center justify-center mx-auto text-xl">
                        <i class="fa-solid fa-receipt"></i>
                    </div>
                    <h4 class="text-sm font-bold text-white">No account activity yet.</h4>
                    <p class="text-xs text-gray-400 max-w-sm mx-auto">Your verified deposits, transfers, and card transactions will appear here.</p>
                </div>'''

            body = f'''<div class="max-w-5xl mx-auto space-y-6">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <h2 class="text-2xl font-bold text-white tracking-tight">Account Activity</h2>
                        <p class="text-sm text-gray-400 mt-1">Review all verified transactions, deposits, and account movements.</p>
                    </div>
                    <a href="/activity/export" class="px-4 py-2 rounded-xl bg-[#171A21] hover:bg-[#1F2430] text-gray-300 hover:text-white font-semibold text-xs border border-[#292E38] transition-all flex items-center gap-2 self-start sm:self-auto">
                        <i class="fa-solid fa-download text-xs"></i>
                        <span>Export CSV</span>
                    </a>
                </div>
                {activity_content}
            </div>'''
            html = build_app_layout(body, "Account Activity | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 13. Notifications
        if path == "/notifications":
            view_path = os.path.join(VIEWS_DIR, "notifications", "index.php")
            with open(view_path, 'r', encoding='utf-8') as f:
                body = f.read()
            body = re.sub(r"<\?php.*?\?>", "", body, flags=re.DOTALL)
            body = re.sub(r"<\?=.*?\?>", "", body, flags=re.DOTALL)
            html = build_app_layout(body, "Notifications | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 14. Profile & Security
        if path == "/profile":
            user = STATE["user"]
            body = f'''<div class="max-w-2xl mx-auto space-y-6">
                <div>
                    <h2 class="text-2xl font-bold text-white tracking-tight">Profile & Security Settings</h2>
                    <p class="text-sm text-gray-400 mt-1">Manage your identity information, authentication credentials, and security controls.</p>
                </div>
                <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-xl space-y-5">
                    <h3 class="text-sm font-bold uppercase tracking-wider text-gray-400 flex items-center gap-2">
                        <i class="fa-solid fa-user-circle text-blue-500"></i> Personal Information
                    </h3>
                    <div class="grid grid-cols-2 gap-3 text-xs">
                        <div><span class="text-gray-400">First Name:</span> <div class="font-bold text-white text-sm pt-1">{user['first_name']}</div></div>
                        <div><span class="text-gray-400">Last Name:</span> <div class="font-bold text-white text-sm pt-1">{user['last_name']}</div></div>
                    </div>
                    <div class="text-xs pt-2">
                        <span class="text-gray-400">Registered Email Address:</span>
                        <div class="font-mono text-white text-sm pt-1">{user['email']}</div>
                    </div>
                </div>
                <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-xl space-y-4">
                    <h3 class="text-sm font-bold uppercase tracking-wider text-gray-400 flex items-center gap-2">
                        <i class="fa-solid fa-shield-halved text-blue-500"></i> Security & Two-Factor Authentication
                    </h3>
                    <div class="flex items-center justify-between p-4 rounded-2xl bg-[#12151B] border border-[#292E38]">
                        <div>
                            <h4 class="text-sm font-bold text-white">Two-Factor Authentication (2FA)</h4>
                            <p class="text-xs text-gray-400 mt-0.5">Protect high-value internal transfers and card operations</p>
                        </div>
                        <span class="px-3 py-1 rounded-xl bg-emerald-600 text-white text-xs font-bold">Enabled</span>
                    </div>
                </div>
            </div>'''
            html = build_app_layout(body, "Profile & Security | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 15. Support
        if path == "/support":
            view_path = os.path.join(VIEWS_DIR, "support", "index.php")
            with open(view_path, 'r', encoding='utf-8') as f:
                body = f.read()
            body = re.sub(r"<\?php.*?\?>", "", body, flags=re.DOTALL)
            body = re.sub(r"<\?=.*?\?>", "", body, flags=re.DOTALL)
            html = build_app_layout(body, "Customer Support | Monveracu", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 16. Legal
        if path in ["/terms", "/privacy", "/risk"]:
            sub = path.strip("/")
            view_path = os.path.join(VIEWS_DIR, "legal", f"{sub}.php")
            with open(view_path, 'r', encoding='utf-8') as f:
                body = f.read()
            legal_cfg = platform_settings_service.get_platform_settings(STATE).get("legal", {})
            legal_key_map = {"terms": "terms_of_service", "privacy": "privacy_policy", "risk": "risk_disclosure"}
            if sub in legal_key_map and legal_cfg.get(legal_key_map[sub]):
                custom_legal = f"""
                <div class="py-8 space-y-4">
                    <div class="p-6 rounded-2xl bg-[#171A21] border border-[#292E38] text-slate-300 leading-relaxed">
                        <p class="whitespace-pre-line">{html_lib.escape(legal_cfg[legal_key_map[sub]])}</p>
                    </div>
                </div>
                """
                body = re.sub(r'<div class="prose[^"]*">.*?</div>', custom_legal, body, flags=re.DOTALL) or body
            layout_path = os.path.join(VIEWS_DIR, "layouts", "main.php")
            with open(layout_path, 'r', encoding='utf-8') as f:
                layout = f.read()
            platform_name = platform_settings_service.get_platform_settings(STATE).get("platform_name", "Monveracu")
            html_out = layout.replace("<?= $content ?>", body).replace("<?= e($pageTitle ?? 'Bnkfx | Your Money. Your World.') ?>", f"{sub.capitalize()} | {platform_name}")
            html_out = re.sub(r"<\?php.*?\?>", "", html_out, flags=re.DOTALL)
            html_out = re.sub(r"<\?=.*?\?>", "", html_out, flags=re.DOTALL)
            self.wfile.write(html_out.encode('utf-8'))
            return

        # 17. Administrator Portal Dashboard & Subsections
        if path.startswith("/admin"):
            import preview_admin
            if preview_admin.handle_admin_get(self, parsed, path, STATE, build_admin_layout):
                return

            if path == "/admin/login":
                view_path = os.path.join(VIEWS_DIR, "admin", "login.php")
                with open(view_path, 'r', encoding='utf-8') as f:
                    body = f.read().replace("<?= csrf_field() ?>", "")
                layout_path = os.path.join(VIEWS_DIR, "layouts", "auth.php")
                with open(layout_path, 'r', encoding='utf-8') as f:
                    layout = f.read()
                html = layout.replace("<?= $content ?>", body).replace("<?= e($pageTitle ?? 'Authentication | Monveracu') ?>", "Admin Portal Login | Monveracu")
                html = re.sub(r"<\?php.*?\?>", "", html, flags=re.DOTALL)
                html = re.sub(r"<\?=.*?\?>", "", html, flags=re.DOTALL)
                self.wfile.write(html.encode('utf-8'))
                return

            if path == "/admin/users":
                body = f'''<div class="space-y-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <h2 class="text-xl font-bold text-white">Customer Account Management</h2>
                            <p class="text-xs text-gray-400 mt-0.5">Search, monitor and manage registered banking customers.</p>
                        </div>
                    </div>
                    <div class="rounded-3xl bg-[#171A21] border border-[#292E38] overflow-hidden shadow-xl">
                        <table class="w-full text-left text-xs">
                            <thead>
                                <tr class="border-b border-[#292E38] bg-[#12151B] text-gray-400 uppercase font-semibold">
                                    <th class="p-4">Customer</th>
                                    <th class="p-4">Country</th>
                                    <th class="p-4">Role</th>
                                    <th class="p-4">USD Balance</th>
                                    <th class="p-4">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-[#292E38]/60">
                                <tr>
                                    <td class="p-4"><div class="font-bold text-white">Abraham Elom</div><div class="text-gray-400">abraham@bnkfx.com</div></td>
                                    <td class="p-4 text-gray-300">United States</td>
                                    <td class="p-4"><span class="px-2 py-0.5 rounded text-[10px] font-bold uppercase bg-blue-500/10 text-blue-400">Customer</span></td>
                                    <td class="p-4 font-mono font-bold text-white">${STATE['accounts'][0]['balance']:.2f}</td>
                                    <td class="p-4"><span class="px-2 py-0.5 rounded text-[10px] font-bold uppercase bg-emerald-500/10 text-emerald-400">Active</span></td>
                                </tr>
                                <tr>
                                    <td class="p-4"><div class="font-bold text-white">Sarah Connor</div><div class="text-gray-400">sarah@bnkfx.com</div></td>
                                    <td class="p-4 text-gray-300">United Kingdom</td>
                                    <td class="p-4"><span class="px-2 py-0.5 rounded text-[10px] font-bold uppercase bg-blue-500/10 text-blue-400">Customer</span></td>
                                    <td class="p-4 font-mono font-bold text-white">$950.00</td>
                                    <td class="p-4"><span class="px-2 py-0.5 rounded text-[10px] font-bold uppercase bg-emerald-500/10 text-emerald-400">Active</span></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>'''
                html = build_admin_layout(body, "Customer Accounts | Monveracu Admin", path)
                self.wfile.write(html.encode('utf-8'))
                return

            if path == "/admin/transfers":
                qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
                type_filter = qs.get("type", ["all"])[0].lower()

                # Build unified transaction list from all sources
                unified = []
                for t in STATE.get("transfers", []):
                    is_adj = t.get("direction") in ["credit", "debit"]
                    tx_type = "adjustment" if is_adj else "transfer"
                    if type_filter not in ["all", tx_type]:
                        continue
                    is_credit = t.get("direction") in ["received", "credit"]
                    unified.append({
                        "ref": t["ref"],
                        "type": "Admin Adjustment" if is_adj else "Internal Transfer",
                        "type_badge": "bg-purple-500/10 text-purple-400 border-purple-500/20" if is_adj else "bg-blue-500/10 text-blue-400 border-blue-500/20",
                        "from": t.get("sender_email", t.get("sender", "N/A")),
                        "to": t.get("recipient_email", t.get("recipient", "N/A")),
                        "amount": float(t["amount"]),
                        "fee": float(t.get("fee", 0)),
                        "is_credit": is_credit,
                        "status": t.get("status", "Completed"),
                        "date": t.get("date", "N/A"),
                    })
                for d in STATE.get("deposits", []):
                    if type_filter not in ["all", "deposit"]:
                        continue
                    st = d.get("status", "").lower()
                    st_label = "Credited" if st == "credited" else ("Pending" if "pending" in st or "awaiting" in st else st.replace("_", " ").title())
                    unified.append({
                        "ref": d["reference"],
                        "type": "Crypto Deposit",
                        "type_badge": "bg-emerald-500/10 text-emerald-400 border-emerald-500/20",
                        "from": f"{d['asset']} ({d['network']})",
                        "to": d.get("customer_email", STATE.get("user", {}).get("email", "customer")),
                        "amount": float(d["amount"]),
                        "fee": 0.0,
                        "is_credit": True,
                        "status": st_label,
                        "date": d.get("created_at", "N/A"),
                    })

                # Stats
                total_count = len(unified)
                transfer_count = sum(1 for u in unified if u["type"] == "Internal Transfer")
                deposit_count = sum(1 for u in unified if u["type"] == "Crypto Deposit")
                adjustment_count = sum(1 for u in unified if u["type"] == "Admin Adjustment")

                tx_rows = ""
                for u in unified:
                    amt_color = "text-emerald-400" if u["is_credit"] else "text-red-400"
                    sign = "+" if u["is_credit"] else "-"
                    st_lower = u["status"].lower()
                    if st_lower in ["completed", "credited"]:
                        st_badge_cls = "bg-emerald-500/10 text-emerald-400"
                    elif "pending" in st_lower or "awaiting" in st_lower:
                        st_badge_cls = "bg-amber-500/10 text-amber-400"
                    elif st_lower in ["rejected", "failed"]:
                        st_badge_cls = "bg-red-500/10 text-red-400"
                    else:
                        st_badge_cls = "bg-gray-500/10 text-gray-400"
                    tx_rows += f'''
                    <tr class="hover:bg-[#12151B]/50 transition-colors">
                        <td class="p-4 font-mono font-bold text-blue-400 text-[11px]">{u['ref']}</td>
                        <td class="p-4"><span class="px-2 py-0.5 rounded text-[10px] font-bold uppercase {u['type_badge']} border">{u['type']}</span></td>
                        <td class="p-4 text-white text-[11px] truncate max-w-[140px]">{u['from']}</td>
                        <td class="p-4 text-white text-[11px] truncate max-w-[140px]">{u['to']}</td>
                        <td class="p-4 font-mono font-bold {amt_color}">{sign}${u['amount']:,.2f}</td>
                        <td class="p-4 font-mono text-gray-400">${u['fee']:.2f}</td>
                        <td class="p-4"><span class="px-2 py-0.5 rounded text-[10px] font-bold uppercase {st_badge_cls}">{u['status']}</span></td>
                        <td class="p-4 text-[11px] text-[#737D90]">{u['date']}</td>
                    </tr>'''

                if not tx_rows:
                    tx_rows = '<tr><td colspan="8" class="p-8 text-center text-[#737D90]">No transactions recorded yet.</td></tr>'

                active_cls = lambda t: "bg-[#246BFD] text-white" if type_filter == t else "bg-[#171A21] text-[#9CA6BA] hover:text-white border border-[#292E38]"

                body = f'''<div class="space-y-6">
                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                        <div>
                            <h2 class="text-xl font-bold text-white">Transfer Management</h2>
                            <p class="text-xs text-gray-400 mt-0.5">Unified view of all platform financial movements — transfers, deposits, and admin adjustments.</p>
                        </div>
                        <div class="flex gap-2">
                            <a href="/admin/transfers-export" class="px-3 py-2 bg-[#171A21] hover:bg-[#1F2430] text-gray-300 text-xs font-semibold rounded-xl border border-[#292E38] flex items-center gap-1.5">
                                <i class="fa-solid fa-download"></i><span>Export CSV</span>
                            </a>
                        </div>
                    </div>

                    <div class="flex flex-wrap gap-2">
                        <a href="/admin/transfers?type=all" class="px-3 py-1.5 rounded-lg text-xs font-semibold {active_cls('all')}">All ({total_count})</a>
                        <a href="/admin/transfers?type=transfer" class="px-3 py-1.5 rounded-lg text-xs font-semibold {active_cls('transfer')}">Transfers ({transfer_count})</a>
                        <a href="/admin/transfers?type=deposit" class="px-3 py-1.5 rounded-lg text-xs font-semibold {active_cls('deposit')}">Deposits ({deposit_count})</a>
                        <a href="/admin/transfers?type=adjustment" class="px-3 py-1.5 rounded-lg text-xs font-semibold {active_cls('adjustment')}">Adjustments ({adjustment_count})</a>
                    </div>

                    <div class="rounded-3xl bg-[#171A21] border border-[#292E38] overflow-hidden shadow-xl">
                        <div class="overflow-x-auto">
                            <table class="w-full text-left text-xs">
                                <thead>
                                    <tr class="border-b border-[#292E38] bg-[#12151B] text-gray-400 uppercase font-semibold">
                                        <th class="p-4">Reference</th>
                                        <th class="p-4">Type</th>
                                        <th class="p-4">From</th>
                                        <th class="p-4">To</th>
                                        <th class="p-4">Amount</th>
                                        <th class="p-4">Fee</th>
                                        <th class="p-4">Status</th>
                                        <th class="p-4">Date</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-[#292E38]/60">
                                    {tx_rows}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>'''
                html = build_admin_layout(body, "Transfer Management | Monveracu Admin", path)
                self.wfile.write(html.encode('utf-8'))
                return

            if path == "/admin/deposits":
                deposits_list = STATE.get("deposits", [])
                awaiting_count = sum(1 for d in deposits_list if d.get("status") in ["pending_review", "pending_confirmation", "awaiting_deposit", "awaiting_payment"])
                credited_count = sum(1 for d in deposits_list if d.get("status") == "credited")
                rejected_count = sum(1 for d in deposits_list if d.get("status") in ["rejected", "failed"])
                total_volume = sum(d.get("credited_amount", 0.0) for d in deposits_list if d.get("status") == "credited")

                dep_table_rows = ""
                for d in deposits_list:
                    st = d["status"].lower()
                    is_credited = (st == "credited")
                    is_pending = st in ["pending_review", "confirming", "pending_confirmation", "approved"]
                    is_rejected = st in ["rejected", "failed"]

                    badge_class = "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20" if is_credited else ("bg-amber-500/10 text-amber-400 border border-amber-500/20" if is_pending else ("bg-red-500/10 text-red-400 border border-red-500/20" if is_rejected else "bg-blue-500/10 text-blue-400 border border-blue-500/20"))
                    status_label = "Credited" if is_credited else ("Pending Review" if st == "pending_review" else ("Awaiting Deposit" if "awaiting" in st else st.replace("_", " ").title()))

                    dep_table_rows += f'''
                    <tr class="hover:bg-[#12151B]/50 transition-colors">
                        <td class="p-4 font-mono font-bold text-blue-400">{d['reference']}</td>
                        <td class="p-4 text-white">
                            <div class="font-semibold">{d.get('customer_name', 'Elochukwu Elom')}</div>
                            <div class="text-[11px] text-gray-400">{d.get('customer_email', 'elochukwu@bnkfx.com')}</div>
                        </td>
                        <td class="p-4">
                            <span class="font-bold text-white">{d['asset']}</span>
                            <span class="text-gray-400 text-[11px]">({d['network']})</span>
                        </td>
                        <td class="p-4 font-mono font-bold text-white">${d['amount']:,.2f} USD</td>
                        <td class="p-4 font-mono text-gray-300">{d.get('confirmations', 0)} / {d.get('required_confirmations', 12)}</td>
                        <td class="p-4">
                            <span class="px-2.5 py-1 rounded text-[10px] font-bold uppercase {badge_class}">
                                {status_label}
                            </span>
                        </td>
                        <td class="p-4 text-right">
                            <a href="/admin/deposits/{d['id']}" class="px-3.5 py-1.5 rounded-lg bg-[#1F2430] hover:bg-[#246BFD] hover:text-white text-gray-300 text-xs font-semibold transition-all">
                                Review
                            </a>
                        </td>
                    </tr>'''

                if not dep_table_rows:
                    dep_table_rows = '''
                    <tr>
                        <td colspan="7" class="p-12 text-center text-gray-400 space-y-2">
                            <i class="fa-solid fa-inbox text-3xl text-gray-600 block"></i>
                            <p class="text-sm font-medium">No deposit records found.</p>
                            <p class="text-xs text-gray-500">Deposit requests submitted by customers will appear here for review.</p>
                        </td>
                    </tr>'''

                body = f'''<div class="space-y-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <h2 class="text-xl font-bold text-white">Cryptocurrency Deposits</h2>
                            <p class="text-xs text-gray-400 mt-0.5">Monitor blockchain confirmations and review deposit funding requests.</p>
                        </div>
                    </div>

                    <!-- 4 KPI Summary Cards -->
                    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
                        <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1.5">
                            <div class="flex items-center justify-between">
                                <span class="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Awaiting Review</span>
                                <span class="w-7 h-7 rounded-lg bg-amber-500/10 text-amber-400 flex items-center justify-center text-xs">
                                    <i class="fa-solid fa-clock"></i>
                                </span>
                            </div>
                            <div class="text-2xl font-bold font-mono text-amber-400">{awaiting_count}</div>
                            <p class="text-[10px] text-gray-500">Deposits requiring manual verification</p>
                        </div>

                        <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1.5">
                            <div class="flex items-center justify-between">
                                <span class="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Credited</span>
                                <span class="w-7 h-7 rounded-lg bg-emerald-500/10 text-emerald-400 flex items-center justify-center text-xs">
                                    <i class="fa-solid fa-check"></i>
                                </span>
                            </div>
                            <div class="text-2xl font-bold font-mono text-emerald-400">{credited_count}</div>
                            <p class="text-[10px] text-gray-500">Posted ledger credits</p>
                        </div>

                        <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1.5">
                            <div class="flex items-center justify-between">
                                <span class="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Rejected</span>
                                <span class="w-7 h-7 rounded-lg bg-red-500/10 text-red-400 flex items-center justify-center text-xs">
                                    <i class="fa-solid fa-ban"></i>
                                </span>
                            </div>
                            <div class="text-2xl font-bold font-mono text-red-400">{rejected_count}</div>
                            <p class="text-[10px] text-gray-500">Denied or invalid transfers</p>
                        </div>

                        <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-1.5">
                            <div class="flex items-center justify-between">
                                <span class="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Total Volume</span>
                                <span class="w-7 h-7 rounded-lg bg-blue-500/10 text-blue-400 flex items-center justify-center text-xs">
                                    <i class="fa-solid fa-dollar-sign"></i>
                                </span>
                            </div>
                            <div class="text-2xl font-bold font-mono text-white">${total_volume:,.2f}</div>
                            <p class="text-[10px] text-gray-500">Total credited vault balance</p>
                        </div>
                    </div>

                    <div class="rounded-3xl bg-[#171A21] border border-[#292E38] overflow-hidden shadow-xl">
                        <table class="w-full text-left text-xs">
                            <thead>
                                <tr class="border-b border-[#292E38] bg-[#12151B] text-gray-400 uppercase font-semibold">
                                    <th class="p-4">Reference</th>
                                    <th class="p-4">Customer</th>
                                    <th class="p-4">Asset & Network</th>
                                    <th class="p-4">Amount</th>
                                    <th class="p-4">Confirmations</th>
                                    <th class="p-4">Status</th>
                                    <th class="p-4 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-[#292E38]/60">
                                {dep_table_rows}
                            </tbody>
                        </table>
                    </div>
                </div>'''
                html = build_admin_layout(body, "Cryptocurrency Deposits | Monveracu Admin", path)
                self.wfile.write(html.encode('utf-8'))
                return

            if path.startswith("/admin/deposits/"):
                dep_id = int(path.split("/")[-1])
                dep = next((d for d in STATE.get("deposits", []) if d["id"] == dep_id), STATE["deposits"][0])
                st = dep["status"].lower()
                is_credited = (st == "credited")
                badge_class = "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20" if is_credited else "bg-amber-500/10 text-amber-400 border border-amber-500/20"
                status_label = "Credited" if is_credited else ("Pending Review" if st == "pending_review" else ("Awaiting Deposit" if "awaiting" in st else st.replace("_", " ").title()))

                admin_action_html = f'''
                <div class="p-6 rounded-3xl bg-[#171A21] border border-blue-500/30 shadow-xl space-y-4">
                    <h3 class="text-sm font-bold uppercase tracking-wider text-blue-400 flex items-center gap-2">
                        <i class="fa-solid fa-gavel"></i> Manual Credit Verification & Approval
                    </h3>
                    <p class="text-xs text-gray-400">
                        Authorizing this action will immediately execute a double-entry ledger debit on the Platform Vault Asset account and credit the customer's liability account with full audit logging.
                    </p>
                    <div class="grid grid-cols-2 gap-3 pt-2">
                        <button onclick="approveAdminDeposit({dep['id']}, {dep['amount']})" class="py-3.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs shadow-lg transition-all">
                            Approve & Credit Ledger
                        </button>
                        <button onclick="rejectAdminDeposit({dep['id']})" class="py-3.5 rounded-xl bg-red-600/20 hover:bg-red-600 text-red-400 hover:text-white font-bold text-xs border border-red-500/30 transition-all">
                            Reject Deposit
                        </button>
                    </div>
                </div>''' if not is_credited else f'''
                <div class="p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs flex items-center gap-2">
                    <i class="fa-solid fa-circle-check"></i>
                    <span>This deposit has been verified, approved, and posted to the customer ledger balance.</span>
                </div>'''

                body = f'''<div class="max-w-2xl mx-auto space-y-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <a href="/admin/deposits" class="text-xs text-blue-400 hover:text-blue-300 flex items-center gap-1.5 mb-1">
                                <i class="fa-solid fa-arrow-left"></i> Back to Deposits
                            </a>
                            <h2 class="text-xl font-bold font-mono text-white">{dep['reference']}</h2>
                            <p class="text-xs text-gray-400">Customer: {dep.get('customer_name', 'Elochukwu Elom')} ({dep.get('customer_email', 'elochukwu@bnkfx.com')})</p>
                        </div>
                        <span class="px-3 py-1 rounded-full text-xs font-bold uppercase {badge_class}">
                            {status_label}
                        </span>
                    </div>

                    <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] shadow-xl space-y-4 text-xs">
                        <h3 class="text-sm font-bold uppercase tracking-wider text-gray-400">Deposit Parameters</h3>
                        <div class="space-y-3">
                            <div class="flex justify-between"><span class="text-gray-400">Cryptocurrency:</span> <span class="font-bold text-white">{dep['asset']}</span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Network:</span> <span class="font-bold text-white">{dep['network']}</span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Deposit Address:</span> <span class="font-mono text-blue-400 break-all">{dep['deposit_address']}</span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Transaction Hash:</span> <span class="font-mono text-white break-all">{dep.get('tx_hash') or 'Pending detection'}</span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Deposit Amount (USD):</span> <span class="font-mono font-bold text-white">${dep['amount']:,.2f} USD</span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Credited Amount:</span> <span class="font-mono font-bold text-emerald-400">${dep['credited_amount']:,.2f} USD</span></div>
                            <div class="flex justify-between"><span class="text-gray-400">Confirmations:</span> <span class="font-mono text-white">{dep.get('confirmations', 0)} / {dep.get('required_confirmations', 12)}</span></div>
                        </div>
                    </div>

                    {admin_action_html}

                    <script>
                    async function approveAdminDeposit(id, amt) {{
                        if (!confirm('Authorize ledger credit of $' + amt.toFixed(2) + ' USD to customer account?')) return;
                        const res = await fetch('/admin/deposits/' + id + '/approve', {{
                            method: 'POST',
                            headers: {{ 'Content-Type': 'application/json' }},
                            body: JSON.stringify({{ amount: amt }})
                        }});
                        const data = await res.json();
                        if (data.success) {{
                            alert(data.message || 'Deposit approved and credited.');
                            window.location.reload();
                        }} else {{
                            alert(data.error || 'Failed to approve deposit.');
                        }}
                    }}

                    async function rejectAdminDeposit(id) {{
                        if (!confirm('Reject this deposit request? No funds will be credited.')) return;
                        const res = await fetch('/admin/deposits/' + id + '/reject', {{
                            method: 'POST',
                            headers: {{ 'Content-Type': 'application/json' }},
                            body: JSON.stringify({{ reason: 'Manual administrative rejection' }})
                        }});
                        const data = await res.json();
                        if (data.success) {{
                            alert(data.message || 'Deposit rejected.');
                            window.location.reload();
                        }} else {{
                            alert(data.error || 'Failed to reject deposit.');
                        }}
                    }}
                    </script>
                </div>'''
                html = build_admin_layout(body, f"Deposit {dep['reference']} | Monveracu Admin", path)
                self.wfile.write(html.encode('utf-8'))
                return

            if path == "/admin/cards":
                import preview_admin
                if preview_admin.handle_admin_get(self, parsed, path, STATE, build_admin_layout):
                    return

            if path == "/admin/reports":
                body = f'''<div class="space-y-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <h2 class="text-xl font-bold text-white">Ledger Reconciliation Report</h2>
                            <p class="text-xs text-gray-400 mt-0.5">Authoritative mathematical reconciliation of all platform debits and credits.</p>
                        </div>
                        <span class="px-3 py-1 rounded-full text-xs font-bold uppercase bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">
                            <i class="fa-solid fa-circle-check mr-1"></i> Ledger 100% Balanced
                        </span>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-2">
                            <div class="text-xs font-bold text-white">USD Currency Pool</div>
                            <div class="text-xs text-gray-400 pt-2 space-y-1 font-mono">
                                <div class="flex justify-between"><span>Total Debits:</span> <span class="text-white">2,100.0000</span></div>
                                <div class="flex justify-between"><span>Total Credits:</span> <span class="text-white">2,100.0000</span></div>
                                <div class="flex justify-between border-t border-[#292E38] pt-1 font-bold"><span class="text-emerald-400">Difference:</span> <span class="text-emerald-400">0.00000000</span></div>
                            </div>
                        </div>
                        <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38] space-y-2">
                            <div class="text-xs font-bold text-white">USDC Currency Pool</div>
                            <div class="text-xs text-gray-400 pt-2 space-y-1 font-mono">
                                <div class="flex justify-between"><span>Total Debits:</span> <span class="text-white">750.0000</span></div>
                                <div class="flex justify-between"><span>Total Credits:</span> <span class="text-white">750.0000</span></div>
                                <div class="flex justify-between border-t border-[#292E38] pt-1 font-bold"><span class="text-emerald-400">Difference:</span> <span class="text-emerald-400">0.00000000</span></div>
                            </div>
                        </div>
                    </div>
                </div>'''
                html = build_admin_layout(body, "Ledger Reconciliation | Monveracu Admin", path)
                self.wfile.write(html.encode('utf-8'))
                return

            if path == "/admin/audit":
                body = f'''<div class="space-y-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <h2 class="text-xl font-bold text-white">System Security Audit Logs</h2>
                            <p class="text-xs text-gray-400 mt-0.5">Immutable audit trail of administrator and customer actions.</p>
                        </div>
                    </div>
                    <div class="rounded-3xl bg-[#171A21] border border-[#292E38] overflow-hidden shadow-xl">
                        <table class="w-full text-left text-xs font-mono">
                            <thead>
                                <tr class="border-b border-[#292E38] bg-[#12151B] text-gray-400 uppercase font-semibold font-sans">
                                    <th class="p-4">Timestamp</th>
                                    <th class="p-4">Actor</th>
                                    <th class="p-4">Action</th>
                                    <th class="p-4">IP Address</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-[#292E38]/60">
                                <tr>
                                    <td class="p-4 text-gray-400">2026-10-27 22:30:12</td>
                                    <td class="p-4 text-white font-bold font-sans">admin@bnkfx.com</td>
                                    <td class="p-4 text-blue-400 font-bold">admin_login</td>
                                    <td class="p-4 text-gray-400">127.0.0.1</td>
                                </tr>
                                <tr>
                                    <td class="p-4 text-gray-400">2026-10-27 20:15:00</td>
                                    <td class="p-4 text-white font-bold font-sans">abraham@bnkfx.com</td>
                                    <td class="p-4 text-emerald-400 font-bold">transfer_completed</td>
                                    <td class="p-4 text-gray-400">127.0.0.1</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>'''
                html = build_admin_layout(body, "Security Audit Logs | Monveracu Admin", path)
                self.wfile.write(html.encode('utf-8'))
                return

            # Default Admin Dashboard — All statistics calculated from STATE
            num_users = len(STATE.get("users", []))
            active_users = sum(1 for u in STATE.get("users", []) if u.get("status") == "active")
            suspended_users = sum(1 for u in STATE.get("users", []) if u.get("status") == "suspended")

            # Total customer liabilities = sum of ALL account balances
            total_liabilities = sum(a["balance"] for a in STATE.get("accounts", []))

            # Platform fees collected from transfers
            total_fees = sum(float(t.get("fee", 0)) for t in STATE.get("transfers", []))

            # Deposit analytics
            all_deposits = STATE.get("deposits", [])
            credited_deposits = [d for d in all_deposits if d.get("status", "").lower() == "credited"]
            pending_deposits = [d for d in all_deposits if d.get("status", "").lower() in ["pending_review", "confirming", "pending_confirmation", "awaiting_deposit", "awaiting_payment"]]
            rejected_deposits = [d for d in all_deposits if d.get("status", "").lower() in ["rejected", "failed"]]
            total_credited_vol = sum(float(d.get("credited_amount", d.get("amount", 0))) for d in credited_deposits)
            total_pending_vol = sum(float(d.get("amount", 0)) for d in pending_deposits)

            # Transfer analytics — separate user P2P from admin adjustments
            all_transfers = STATE.get("transfers", [])
            p2p_sent = [t for t in all_transfers if t.get("direction") == "sent"]
            admin_adjustments = [t for t in all_transfers if t.get("direction") in ["credit", "debit"]]
            admin_credits = sum(float(t["amount"]) for t in admin_adjustments if t.get("direction") == "credit")
            admin_debits = sum(float(t["amount"]) for t in admin_adjustments if t.get("direction") == "debit")
            transfer_volume = sum(float(t["amount"]) for t in p2p_sent)

            # Total transactions
            total_tx_count = len(all_transfers) + len(all_deposits)

            # Build recent activity rows dynamically
            recent_items = []
            for t in all_transfers:
                is_adj = t.get("direction") in ["credit", "debit"]
                recent_items.append({
                    "ref": t["ref"],
                    "type": "Adjustment" if is_adj else "Transfer",
                    "type_color": "bg-purple-500/10 text-purple-400" if is_adj else "bg-blue-500/10 text-blue-400",
                    "from": t.get("sender_email", t.get("sender", "N/A")),
                    "to": t.get("recipient_email", t.get("recipient", "N/A")),
                    "amount": float(t["amount"]),
                    "is_credit": t.get("direction") in ["received", "credit"],
                    "status": t.get("status", "Completed"),
                    "date": t.get("date", "N/A")
                })
            for d in all_deposits:
                st = d.get("status", "").lower()
                st_label = "Credited" if st == "credited" else ("Pending" if "pending" in st or "awaiting" in st else st.replace("_", " ").title())
                st_color = "bg-emerald-500/10 text-emerald-400" if st == "credited" else ("bg-amber-500/10 text-amber-400" if "pending" in st or "awaiting" in st else "bg-red-500/10 text-red-400")
                recent_items.append({
                    "ref": d["reference"],
                    "type": "Deposit",
                    "type_color": "bg-emerald-500/10 text-emerald-400",
                    "from": d.get("customer_email", d.get("asset", "Crypto")),
                    "to": "Platform",
                    "amount": float(d["amount"]),
                    "is_credit": True,
                    "status": st_label,
                    "status_color": st_color,
                    "date": d.get("created_at", "N/A")
                })

            recent_tx_rows = ""
            for item in recent_items[:8]:
                amt_color = "text-emerald-400" if item["is_credit"] else "text-red-400"
                sign = "+" if item["is_credit"] else "-"
                s_color = item.get("status_color", "bg-emerald-500/10 text-emerald-400")
                recent_tx_rows += f'''<tr class="hover:bg-[#1C202A] transition-colors">
                    <td class="py-3 font-mono font-bold text-blue-400 text-[11px]">{item['ref']}</td>
                    <td class="py-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold uppercase {item['type_color']}">{item['type']}</span></td>
                    <td class="py-3 text-white truncate max-w-[120px]">{item['from']}</td>
                    <td class="py-3 text-white truncate max-w-[120px]">{item['to']}</td>
                    <td class="py-3 font-mono font-bold {amt_color}">{sign}${item['amount']:,.2f}</td>
                    <td class="py-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold uppercase {s_color}">{item['status']}</span></td>
                </tr>'''

            if not recent_tx_rows:
                recent_tx_rows = '<tr><td colspan="6" class="py-8 text-center text-[#737D90]">No platform activity recorded yet. Transactions will appear here as users deposit and transfer funds.</td></tr>'

            body = f'''<div class="space-y-6">
                <div>
                    <h1 class="text-2xl font-bold text-white tracking-tight">Administrator Overview</h1>
                    <p class="text-xs text-[#9CA6BA] mt-0.5">All statistics are calculated from real platform records in real time.</p>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                        <div class="flex justify-between text-xs text-gray-400 uppercase font-semibold"><span>Registered Customers</span> <i class="fa-solid fa-users text-blue-500"></i></div>
                        <div class="text-2xl font-bold font-mono text-white mt-3">{num_users}</div>
                        <div class="text-[11px] mt-2 border-t border-[#292E38] pt-2"><span class="text-emerald-400">{active_users} Active</span>{f' · <span class="text-red-400">{suspended_users} Suspended</span>' if suspended_users else ''}</div>
                    </div>
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                        <div class="flex justify-between text-xs text-gray-400 uppercase font-semibold"><span>Customer Liabilities (USD)</span> <i class="fa-solid fa-scale-balanced text-amber-500"></i></div>
                        <div class="text-2xl font-bold font-mono text-white mt-3">${total_liabilities:,.2f}</div>
                        <div class="text-[11px] text-gray-400 mt-2 border-t border-[#292E38] pt-2">Sum of all account balances</div>
                    </div>
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                        <div class="flex justify-between text-xs text-gray-400 uppercase font-semibold"><span>Credited Deposits</span> <i class="fa-solid fa-coins text-emerald-400"></i></div>
                        <div class="text-2xl font-bold font-mono text-emerald-400 mt-3">${total_credited_vol:,.2f}</div>
                        <div class="text-[11px] mt-2 border-t border-[#292E38] pt-2"><span class="text-emerald-400">{len(credited_deposits)} verified</span>{f' · <span class="text-amber-400">{len(pending_deposits)} pending</span>' if pending_deposits else ''}{f' · <span class="text-red-400">{len(rejected_deposits)} rejected</span>' if rejected_deposits else ''}</div>
                    </div>
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                        <div class="flex justify-between text-xs text-gray-400 uppercase font-semibold"><span>Total Transactions</span> <i class="fa-solid fa-receipt text-purple-400"></i></div>
                        <div class="text-2xl font-bold font-mono text-white mt-3">{total_tx_count}</div>
                        <div class="text-[11px] text-gray-400 mt-2 border-t border-[#292E38] pt-2">{len(all_transfers)} transfers · {len(all_deposits)} deposits</div>
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                        <div class="flex justify-between text-xs text-gray-400 uppercase font-semibold"><span>Pending Deposits</span> <i class="fa-solid fa-clock text-amber-400"></i></div>
                        <div class="text-2xl font-bold font-mono text-amber-400 mt-3">{len(pending_deposits)}</div>
                        <div class="text-[11px] text-gray-400 mt-2 border-t border-[#292E38] pt-2">${total_pending_vol:,.2f} awaiting verification</div>
                    </div>
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                        <div class="flex justify-between text-xs text-gray-400 uppercase font-semibold"><span>Transfer Volume</span> <i class="fa-solid fa-money-bill-transfer text-blue-400"></i></div>
                        <div class="text-2xl font-bold font-mono text-white mt-3">${transfer_volume:,.2f}</div>
                        <div class="text-[11px] text-gray-400 mt-2 border-t border-[#292E38] pt-2">{len(p2p_sent)} completed P2P transfers</div>
                    </div>
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-[#292E38]">
                        <div class="flex justify-between text-xs text-gray-400 uppercase font-semibold"><span>Admin Adjustments</span> <i class="fa-solid fa-sliders text-purple-400"></i></div>
                        <div class="text-2xl font-bold font-mono text-white mt-3">{len(admin_adjustments)}</div>
                        <div class="text-[11px] mt-2 border-t border-[#292E38] pt-2"><span class="text-emerald-400">+${admin_credits:,.2f}</span> · <span class="text-red-400">-${admin_debits:,.2f}</span></div>
                    </div>
                    <div class="p-5 rounded-2xl bg-[#171A21] border border-emerald-500/30">
                        <div class="flex justify-between text-xs text-emerald-400 uppercase font-semibold"><span>Platform Revenue (Fees)</span> <i class="fa-solid fa-sack-dollar text-emerald-400"></i></div>
                        <div class="text-2xl font-bold font-mono text-emerald-400 mt-3">${total_fees:,.2f}</div>
                        <div class="text-[11px] text-gray-400 mt-2 border-t border-[#292E38] pt-2">Separated from liabilities</div>
                    </div>
                </div>

                <div class="p-6 rounded-3xl bg-[#171A21] border border-[#292E38] space-y-4">
                    <div class="flex justify-between items-center">
                        <h3 class="text-sm font-bold uppercase tracking-wider text-gray-400">Recent Platform Activity</h3>
                        <a href="/admin/transfers" class="text-xs text-blue-400 font-semibold">View All Transactions</a>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left text-xs">
                            <thead>
                                <tr class="border-b border-[#292E38] text-gray-400 uppercase font-semibold">
                                    <th class="pb-2">Reference</th>
                                    <th class="pb-2">Type</th>
                                    <th class="pb-2">From</th>
                                    <th class="pb-2">To</th>
                                    <th class="pb-2">Amount</th>
                                    <th class="pb-2">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-[#292E38]/60">
                                {recent_tx_rows}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>'''
            html = build_admin_layout(body, "Administrator Overview | Monveracu Admin", path)
            self.wfile.write(html.encode('utf-8'))
            return

        # 18. Default 404
        self.wfile.write(b"<h1>404 Not Found</h1><p><a href='/dashboard'>Return to Dashboard</a></p>")

def start():
    # Bind to 0.0.0.0 so both localhost, 127.0.0.1, and browser IPv6 work without hindrance
    server_address = ("0.0.0.0", PORT)
    with ThreadedHTTPServer(server_address, BnkfxHandler) as httpd:
        print("==================================================================")
        print(f"      BNKFX BANKING PLATFORM - LOCALHOST SERVER ACTIVE            ")
        print("==================================================================")
        print(f"  [+] Local Server URL: http://localhost:{PORT}")
        print(f"  [+] Customer Dashboard: http://localhost:{PORT}/dashboard")
        print(f"  [+] Administrator Portal: http://localhost:{PORT}/admin")
        print("==================================================================")
        httpd.serve_forever()

if __name__ == "__main__":
    start()
